ngram
listlengths
0
82k
[ "poll = models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE) def __str__(self): return str(self.poll) class", "= True class AnonymousUserPollTelemetry(models.Model): \"\"\" To \"store\" the anonymous users", "Poll class BasePollTelemetry(models.Model): \"\"\" This Base class gives a hint", "models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE) def __str__(self): return str(self.poll) class Meta: abstract", "the future more Telemetry classes could be implemented. \"\"\" poll", "panel. \"\"\" anonymous_user = models.GenericIPAddressField(blank=True, null=True) def __str__(self): return self.anonymous_user", "could be implemented. \"\"\" poll = models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE) def", "It will NEVER be displayed outside the admin panel. \"\"\"", "Base class gives a hint that in the future more", "need to store their IP Addresses. It will NEVER be", "get_user_model from poll.models.poll_models import Poll class BasePollTelemetry(models.Model): \"\"\" This Base", "displayed outside the admin panel. \"\"\" anonymous_user = models.GenericIPAddressField(blank=True, null=True)", "self.anonymous_user class UsersPollTelemetry(BasePollTelemetry): users = models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users = models.ManyToManyField(db_index=True,", "to store their IP Addresses. It will NEVER be displayed", "= models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users = models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class Meta: verbose_name", "Telemetry classes could be implemented. \"\"\" poll = models.ForeignKey(db_index=True, to=Poll,", "django.contrib.auth import get_user_model from poll.models.poll_models import Poll class BasePollTelemetry(models.Model): \"\"\"", "gives a hint that in the future more Telemetry classes", "\"\"\" anonymous_user = models.GenericIPAddressField(blank=True, null=True) def __str__(self): return self.anonymous_user class", "= models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE) def __str__(self): return str(self.poll) class Meta:", "import models from django.contrib.auth import get_user_model from poll.models.poll_models import Poll", "classes could be implemented. \"\"\" poll = models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE)", "models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users = models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class Meta: verbose_name =", "return self.anonymous_user class UsersPollTelemetry(BasePollTelemetry): users = models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users =", "from django.contrib.auth import get_user_model from poll.models.poll_models import Poll class BasePollTelemetry(models.Model):", "from poll.models.poll_models import Poll class BasePollTelemetry(models.Model): \"\"\" This Base class", "import Poll class BasePollTelemetry(models.Model): \"\"\" This Base class gives a", "models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class Meta: verbose_name = 'PollTelemetry' verbose_name_plural = 'PollTelemetry'", "__str__(self): return self.anonymous_user class UsersPollTelemetry(BasePollTelemetry): users = models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users", "Poll, I need to store their IP Addresses. It will", "True class AnonymousUserPollTelemetry(models.Model): \"\"\" To \"store\" the anonymous users that", "anonymous_user = models.GenericIPAddressField(blank=True, null=True) def __str__(self): return self.anonymous_user class UsersPollTelemetry(BasePollTelemetry):", "the admin panel. \"\"\" anonymous_user = models.GenericIPAddressField(blank=True, null=True) def __str__(self):", "<filename>poll/models/telemetry_models.py from django.db import models from django.contrib.auth import get_user_model from", "\"store\" the anonymous users that have viewed the Poll, I", "that in the future more Telemetry classes could be implemented.", "BasePollTelemetry(models.Model): \"\"\" This Base class gives a hint that in", "in the future more Telemetry classes could be implemented. \"\"\"", "anonymous_users = models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class Meta: verbose_name = 'PollTelemetry' verbose_name_plural", "be implemented. \"\"\" poll = models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE) def __str__(self):", "have viewed the Poll, I need to store their IP", "the Poll, I need to store their IP Addresses. It", "abstract = True class AnonymousUserPollTelemetry(models.Model): \"\"\" To \"store\" the anonymous", "admin panel. \"\"\" anonymous_user = models.GenericIPAddressField(blank=True, null=True) def __str__(self): return", "be displayed outside the admin panel. \"\"\" anonymous_user = models.GenericIPAddressField(blank=True,", "future more Telemetry classes could be implemented. \"\"\" poll =", "will NEVER be displayed outside the admin panel. \"\"\" anonymous_user", "IP Addresses. It will NEVER be displayed outside the admin", "Meta: abstract = True class AnonymousUserPollTelemetry(models.Model): \"\"\" To \"store\" the", "import get_user_model from poll.models.poll_models import Poll class BasePollTelemetry(models.Model): \"\"\" This", "UsersPollTelemetry(BasePollTelemetry): users = models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users = models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class", "that have viewed the Poll, I need to store their", "return str(self.poll) class Meta: abstract = True class AnonymousUserPollTelemetry(models.Model): \"\"\"", "This Base class gives a hint that in the future", "their IP Addresses. It will NEVER be displayed outside the", "anonymous users that have viewed the Poll, I need to", "null=True) def __str__(self): return self.anonymous_user class UsersPollTelemetry(BasePollTelemetry): users = models.ManyToManyField(db_index=True,", "To \"store\" the anonymous users that have viewed the Poll,", "outside the admin panel. \"\"\" anonymous_user = models.GenericIPAddressField(blank=True, null=True) def", "class BasePollTelemetry(models.Model): \"\"\" This Base class gives a hint that", "on_delete=models.CASCADE) def __str__(self): return str(self.poll) class Meta: abstract = True", "__str__(self): return str(self.poll) class Meta: abstract = True class AnonymousUserPollTelemetry(models.Model):", "to=Poll, on_delete=models.CASCADE) def __str__(self): return str(self.poll) class Meta: abstract =", "more Telemetry classes could be implemented. \"\"\" poll = models.ForeignKey(db_index=True,", "class Meta: abstract = True class AnonymousUserPollTelemetry(models.Model): \"\"\" To \"store\"", "django.db import models from django.contrib.auth import get_user_model from poll.models.poll_models import", "users = models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users = models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class Meta:", "hint that in the future more Telemetry classes could be", "AnonymousUserPollTelemetry(models.Model): \"\"\" To \"store\" the anonymous users that have viewed", "def __str__(self): return self.anonymous_user class UsersPollTelemetry(BasePollTelemetry): users = models.ManyToManyField(db_index=True, to=get_user_model())", "implemented. \"\"\" poll = models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE) def __str__(self): return", "to=get_user_model()) anonymous_users = models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class Meta: verbose_name = 'PollTelemetry'", "I need to store their IP Addresses. It will NEVER", "str(self.poll) class Meta: abstract = True class AnonymousUserPollTelemetry(models.Model): \"\"\" To", "def __str__(self): return str(self.poll) class Meta: abstract = True class", "a hint that in the future more Telemetry classes could", "= models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry) class Meta: verbose_name = 'PollTelemetry' verbose_name_plural =", "models from django.contrib.auth import get_user_model from poll.models.poll_models import Poll class", "NEVER be displayed outside the admin panel. \"\"\" anonymous_user =", "class AnonymousUserPollTelemetry(models.Model): \"\"\" To \"store\" the anonymous users that have", "= models.GenericIPAddressField(blank=True, null=True) def __str__(self): return self.anonymous_user class UsersPollTelemetry(BasePollTelemetry): users", "Addresses. It will NEVER be displayed outside the admin panel.", "\"\"\" poll = models.ForeignKey(db_index=True, to=Poll, on_delete=models.CASCADE) def __str__(self): return str(self.poll)", "from django.db import models from django.contrib.auth import get_user_model from poll.models.poll_models", "\"\"\" This Base class gives a hint that in the", "class gives a hint that in the future more Telemetry", "models.GenericIPAddressField(blank=True, null=True) def __str__(self): return self.anonymous_user class UsersPollTelemetry(BasePollTelemetry): users =", "poll.models.poll_models import Poll class BasePollTelemetry(models.Model): \"\"\" This Base class gives", "\"\"\" To \"store\" the anonymous users that have viewed the", "the anonymous users that have viewed the Poll, I need", "viewed the Poll, I need to store their IP Addresses.", "store their IP Addresses. It will NEVER be displayed outside", "class UsersPollTelemetry(BasePollTelemetry): users = models.ManyToManyField(db_index=True, to=get_user_model()) anonymous_users = models.ManyToManyField(db_index=True, to=AnonymousUserPollTelemetry)", "users that have viewed the Poll, I need to store" ]
[ ".decouple_bev_backbone import DecoupledBEVBackbone __all__ = { 'BaseBEVBackbone': BaseBEVBackbone, 'DecoupledBEVBackbone': DecoupledBEVBackbone,", "from .decouple_bev_backbone import DecoupledBEVBackbone __all__ = { 'BaseBEVBackbone': BaseBEVBackbone, 'DecoupledBEVBackbone':", "from .base_bev_backbone import BaseBEVBackbone from .decouple_bev_backbone import DecoupledBEVBackbone __all__ =", "BaseBEVBackbone from .decouple_bev_backbone import DecoupledBEVBackbone __all__ = { 'BaseBEVBackbone': BaseBEVBackbone,", "import DecoupledBEVBackbone __all__ = { 'BaseBEVBackbone': BaseBEVBackbone, 'DecoupledBEVBackbone': DecoupledBEVBackbone, }", "import BaseBEVBackbone from .decouple_bev_backbone import DecoupledBEVBackbone __all__ = { 'BaseBEVBackbone':", ".base_bev_backbone import BaseBEVBackbone from .decouple_bev_backbone import DecoupledBEVBackbone __all__ = {" ]
[ "\"testpath3\"})) == 0 # TODO: Good deal of overlap here", "ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert self.param.from_json(\"42\", self.trans) == \"42\"", "ref=\"input_bam\" column=\"0\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\":", "self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert", "{\"input_bam\": \"testpath2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"})) == 0 # TODO:", "with DataToolParameterTestCase, # refactor. def setUp(self): super().setUp() self.test_history = model.History()", "False) in self.param.get_options(self.trans, {\"input_bam\": \"testname2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"})) ==", "self.options_xml data_ref_text = \"\" if self.set_data_ref: data_ref_text = 'data_ref=\"input_bam\"' template_xml", "assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname2\"}) assert len(self.param.get_options(self.trans,", "but no legal values defined\" def test_unvalidated_values(self): self.options_xml = \"\"\"<options><filter", "but filtering on a different column. self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter", "self._parameter_for(xml=param_str) return self._param class MockToolDataTable: def __init__(self): self.columns = dict(", "= \"\"\"<param name=\"my_name\" type=\"%s\" %s %s %s>%s</param>\"\"\" param_str = template_xml", "%s %s %s>%s</param>\"\"\" param_str = template_xml % (self.type, data_ref_text, multi_text,", "key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans, {\"input_bam\": model.HistoryDatasetAssociation()}) assert", "dict( name=0, value=1, ) self.missing_index_file = None def get_fields(self): return", "optional_text = \"\" if self.optional: optional_text = 'optional=\"True\"' options_text =", "Good deal of overlap here with DataToolParameterTestCase, # refactor. def", "values defined\" def test_unvalidated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\"", "ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans, {\"input_bam\": model.HistoryDatasetAssociation()})", "\"\" self._param = None @property def param(self): if not self._param:", "as exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": None}) assert str(exc_info.value) == \"parameter", "self.options_xml = \"\" self._param = None @property def param(self): if", "= \"\" if self.multiple: multi_text = 'multiple=\"True\"' optional_text = \"\"", "self.trans.workflow_building_mode = True assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation,", "len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"})) == 0 # TODO: Good deal of", "= \"\" if self.optional: optional_text = 'optional=\"True\"' options_text = self.options_xml", "param(self): if not self._param: multi_text = \"\" if self.multiple: multi_text", "as exc_info: self.param.from_json(\"42\", self.trans) assert str(exc_info.value) == \"parameter 'my_name': requires", "defined\" def test_validated_values_missing_dependency(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with", "import basic from .util import BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self):", "setUp(self): super().setUp() self.test_history = model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] = MockToolDataTable()", "self.app.tool_data_tables[\"test_table\"] = MockToolDataTable() self.trans = Mock( app=self.app, get_history=lambda: self.test_history, get_current_user_roles=lambda:", "from unittest.mock import Mock import pytest from galaxy import model", "# refactor. def setUp(self): super().setUp() self.test_history = model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush()", "data_ref_text = 'data_ref=\"input_bam\"' template_xml = \"\"\"<param name=\"my_name\" type=\"%s\" %s %s", "def test_unvalidated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode =", "\"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"}))", "\"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(),", "as above, but filtering on a different column. self.options_xml =", "0 # TODO: Good deal of overlap here with DataToolParameterTestCase,", "\"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans,", "self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": None}) assert str(exc_info.value) == \"parameter 'my_name': requires", "galaxy import model from galaxy.tools.parameters import basic from .util import", "False self.multiple = False self.optional = False self.options_xml = \"\"", "= self._parameter_for(xml=param_str) return self._param class MockToolDataTable: def __init__(self): self.columns =", "= self.options_xml data_ref_text = \"\" if self.set_data_ref: data_ref_text = 'data_ref=\"input_bam\"'", "type=\"param_value\" ref=\"input_bam\" column=\"1\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans,", "a value, but no legal values defined\" def test_unvalidated_values(self): self.options_xml", "import BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\"", "= \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert self.param.from_json(\"42\",", "False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"})) ==", "if self.optional: optional_text = 'optional=\"True\"' options_text = self.options_xml data_ref_text =", "= True assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation, )", "type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans,", "== 0 def test_filter_param_value2(self): # Same test as above, but", "requires a value, but no legal values defined\" def test_validated_values_missing_dependency(self):", "assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"}) assert len(self.param.get_options(self.trans,", "self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"})) == 0 #", "= True assert self.param.from_json(\"42\", self.trans) == \"42\" def test_validated_datasets(self): self.options_xml", "from galaxy import model from galaxy.tools.parameters import basic from .util", "\"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert self.param.from_json(\"42\", self.trans)", "deal of overlap here with DataToolParameterTestCase, # refactor. def setUp(self):", "refactor. def setUp(self): super().setUp() self.test_history = model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"]", "= \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\",", "value, but no legal values defined\" def test_validated_values_missing_dependency(self): self.options_xml =", "False self.options_xml = \"\" self._param = None @property def param(self):", "get_current_user_roles=lambda: [], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), ) self.type = \"select\" self.set_data_ref =", "'optional=\"True\"' options_text = self.options_xml data_ref_text = \"\" if self.set_data_ref: data_ref_text", "SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with", "= 'optional=\"True\"' options_text = self.options_xml data_ref_text = \"\" if self.set_data_ref:", "model.HistoryDatasetAssociation, ) def test_filter_param_value(self): self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\"", "assert len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"})) == 0 # TODO: Good deal", "{\"input_bam\": \"testname3\"})) == 0 def test_filter_param_value2(self): # Same test as", "def setUp(self): super().setUp() self.test_history = model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] =", "name=\"my_name\" type=\"%s\" %s %s %s>%s</param>\"\"\" param_str = template_xml % (self.type,", "from .util import BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self): self.options_xml =", "self.multiple: multi_text = 'multiple=\"True\"' optional_text = \"\" if self.optional: optional_text", "= Mock( app=self.app, get_history=lambda: self.test_history, get_current_user_roles=lambda: [], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), )", "but no legal values defined\" def test_unvalidated_datasets(self): self.options_xml = \"\"\"<options><filter", "type=\"%s\" %s %s %s>%s</param>\"\"\" param_str = template_xml % (self.type, data_ref_text,", "test_filter_param_value(self): self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"0\" /></options>\"\"\" assert", "test_unvalidated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True", "multi_text = 'multiple=\"True\"' optional_text = \"\" if self.optional: optional_text =", "type=\"param_value\" ref=\"input_bam\" column=\"0\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans,", "with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans) assert str(exc_info.value) == \"parameter", ") def test_filter_param_value(self): self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"0\"", "self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] = MockToolDataTable() self.trans = Mock( app=self.app, get_history=lambda:", "multi_text, optional_text, options_text) self._param = self._parameter_for(xml=param_str) return self._param class MockToolDataTable:", "self._param = self._parameter_for(xml=param_str) return self._param class MockToolDataTable: def __init__(self): self.columns", "== 0 # TODO: Good deal of overlap here with", "self.multiple = False self.optional = False self.options_xml = \"\" self._param", "not self._param: multi_text = \"\" if self.multiple: multi_text = 'multiple=\"True\"'", "column=\"1\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"})", "test_validated_values_missing_dependency(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as", "self.param.from_json(\"42\", self.trans) == \"42\" def test_validated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\"", "'my_name': requires a value, but no legal values defined\" def", "pytest.raises(ValueError) as exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": None}) assert str(exc_info.value) ==", "optional_text = 'optional=\"True\"' options_text = self.options_xml data_ref_text = \"\" if", "= \"select\" self.set_data_ref = False self.multiple = False self.optional =", "False) in self.param.get_options(self.trans, {\"input_bam\": \"testname1\"}) assert (\"testname2\", \"testpath2\", False) in", "\"testname2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"})) == 0 def test_filter_param_value2(self): #", "{\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation, ) def test_filter_param_value(self): self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter", "self._param class MockToolDataTable: def __init__(self): self.columns = dict( name=0, value=1,", "= template_xml % (self.type, data_ref_text, multi_text, optional_text, options_text) self._param =", "def test_filter_param_value2(self): # Same test as above, but filtering on", "as exc_info: self.param.from_json(\"42\", self.trans, {\"input_bam\": model.HistoryDatasetAssociation()}) assert str(exc_info.value) == \"parameter", "\"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"0\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False)", "test_filter_param_value2(self): # Same test as above, but filtering on a", "assert str(exc_info.value) == \"parameter 'my_name': requires a value, but no", "app=self.app, get_history=lambda: self.test_history, get_current_user_roles=lambda: [], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), ) self.type =", "%s>%s</param>\"\"\" param_str = template_xml % (self.type, data_ref_text, multi_text, optional_text, options_text)", "class SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\"", "def test_validated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError)", "filtering on a different column. self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\"", "column. self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"1\" /></options>\"\"\" assert", "type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\":", "assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"}) assert (\"testname2\",", "= model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] = MockToolDataTable() self.trans = Mock(", "(\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\":", ") self.type = \"select\" self.set_data_ref = False self.multiple = False", "a different column. self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"1\"", "defined\" def test_unvalidated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode", "defined\" def test_unvalidated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode", "ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\":", "\"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname1\"}) assert (\"testname2\", \"testpath2\", False)", "a value, but no legal values defined\" def test_validated_values_missing_dependency(self): self.options_xml", "self.trans, {\"input_bam\": model.HistoryDatasetAssociation()}) assert str(exc_info.value) == \"parameter 'my_name': requires a", ") self.missing_index_file = None def get_fields(self): return [[\"testname1\", \"testpath1\"], [\"testname2\",", "= MockToolDataTable() self.trans = Mock( app=self.app, get_history=lambda: self.test_history, get_current_user_roles=lambda: [],", "a value, but no legal values defined\" def test_unvalidated_datasets(self): self.options_xml", "model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] = MockToolDataTable() self.trans = Mock( app=self.app,", "options_text) self._param = self._parameter_for(xml=param_str) return self._param class MockToolDataTable: def __init__(self):", "\"testname3\"})) == 0 def test_filter_param_value2(self): # Same test as above,", "self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\":", "value, but no legal values defined\" def test_unvalidated_values(self): self.options_xml =", "multi_text = \"\" if self.multiple: multi_text = 'multiple=\"True\"' optional_text =", "if not self._param: multi_text = \"\" if self.multiple: multi_text =", "%s %s>%s</param>\"\"\" param_str = template_xml % (self.type, data_ref_text, multi_text, optional_text,", "key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": None}) assert", "import model from galaxy.tools.parameters import basic from .util import BaseParameterTestCase", "here with DataToolParameterTestCase, # refactor. def setUp(self): super().setUp() self.test_history =", "param_str = template_xml % (self.type, data_ref_text, multi_text, optional_text, options_text) self._param", "class MockToolDataTable: def __init__(self): self.columns = dict( name=0, value=1, )", "pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans) assert str(exc_info.value) == \"parameter 'my_name':", "MockToolDataTable() self.trans = Mock( app=self.app, get_history=lambda: self.test_history, get_current_user_roles=lambda: [], workflow_building_mode=False,", "= False self.optional = False self.options_xml = \"\" self._param =", "self.test_history, get_current_user_roles=lambda: [], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), ) self.type = \"select\" self.set_data_ref", "if self.set_data_ref: data_ref_text = 'data_ref=\"input_bam\"' template_xml = \"\"\"<param name=\"my_name\" type=\"%s\"", "exc_info: self.param.from_json(\"42\", self.trans, {\"input_bam\": model.HistoryDatasetAssociation()}) assert str(exc_info.value) == \"parameter 'my_name':", "pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans, {\"input_bam\": model.HistoryDatasetAssociation()}) assert str(exc_info.value) ==", "self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] = MockToolDataTable() self.trans = Mock( app=self.app, get_history=lambda: self.test_history,", "= \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"0\" /></options>\"\"\" assert (\"testname1\", \"testpath1\",", "self.columns = dict( name=0, value=1, ) self.missing_index_file = None def", "(self.type, data_ref_text, multi_text, optional_text, options_text) self._param = self._parameter_for(xml=param_str) return self._param", "data_ref_text, multi_text, optional_text, options_text) self._param = self._parameter_for(xml=param_str) return self._param class", "= \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"1\" /></options>\"\"\" assert (\"testname1\", \"testpath1\",", "(\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname1\"}) assert (\"testname2\", \"testpath2\",", "\"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"}))", "self.type = \"select\" self.set_data_ref = False self.multiple = False self.optional", "= dict( name=0, value=1, ) self.missing_index_file = None def get_fields(self):", "self.param.get_options(self.trans, {\"input_bam\": \"testname2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"})) == 0 def", "\"select\" self.set_data_ref = False self.multiple = False self.optional = False", "/></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"}) assert", "key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans) assert str(exc_info.value) ==", "# Same test as above, but filtering on a different", "test_unvalidated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True", "\"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans,", "0 def test_filter_param_value2(self): # Same test as above, but filtering", "= 'multiple=\"True\"' optional_text = \"\" if self.optional: optional_text = 'optional=\"True\"'", "\"\" if self.optional: optional_text = 'optional=\"True\"' options_text = self.options_xml data_ref_text", "no legal values defined\" def test_unvalidated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\"", "options_text = self.options_xml data_ref_text = \"\" if self.set_data_ref: data_ref_text =", "type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans, {\"input_bam\":", "exc_info: self.param.from_json(\"42\", self.trans) assert str(exc_info.value) == \"parameter 'my_name': requires a", "value, but no legal values defined\" def test_unvalidated_datasets(self): self.options_xml =", "BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\"", "None}) assert str(exc_info.value) == \"parameter 'my_name': requires a value, but", "__init__(self): self.columns = dict( name=0, value=1, ) self.missing_index_file = None", "self.trans) assert str(exc_info.value) == \"parameter 'my_name': requires a value, but", "self.missing_index_file = None def get_fields(self): return [[\"testname1\", \"testpath1\"], [\"testname2\", \"testpath2\"]]", "test_validated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as", "{\"input_bam\": \"testpath3\"})) == 0 # TODO: Good deal of overlap", "Mock( app=self.app, get_history=lambda: self.test_history, get_current_user_roles=lambda: [], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), ) self.type", "assert len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"})) == 0 def test_filter_param_value2(self): # Same", "{\"input_bam\": \"testpath1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"})", "self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"0\" /></options>\"\"\" assert (\"testname1\",", "self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info:", "'multiple=\"True\"' optional_text = \"\" if self.optional: optional_text = 'optional=\"True\"' options_text", "key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": basic.RuntimeValue()}),", "def test_validated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError)", "template_xml % (self.type, data_ref_text, multi_text, optional_text, options_text) self._param = self._parameter_for(xml=param_str)", "self.trans = Mock( app=self.app, get_history=lambda: self.test_history, get_current_user_roles=lambda: [], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"),", "False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"}) assert (\"testname2\", \"testpath2\", False) in", "{\"input_bam\": \"testname1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname2\"})", "in self.param.get_options(self.trans, {\"input_bam\": \"testname2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"})) == 0", "self._param: multi_text = \"\" if self.multiple: multi_text = 'multiple=\"True\"' optional_text", "from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"0\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in", "basic from .util import BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self): self.options_xml", "self.set_data_ref = False self.multiple = False self.optional = False self.options_xml", "ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": None})", "values defined\" def test_unvalidated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\"", "requires a value, but no legal values defined\" def test_unvalidated_datasets(self):", "different column. self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"1\" /></options>\"\"\"", "data_ref_text = \"\" if self.set_data_ref: data_ref_text = 'data_ref=\"input_bam\"' template_xml =", "assert self.param.from_json(\"42\", self.trans) == \"42\" def test_validated_datasets(self): self.options_xml = \"\"\"<options><filter", "value=1, ) self.missing_index_file = None def get_fields(self): return [[\"testname1\", \"testpath1\"],", "== \"42\" def test_validated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\"", "on a different column. self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\"", "\"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans)", "pytest from galaxy import model from galaxy.tools.parameters import basic from", "values defined\" def test_validated_values_missing_dependency(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\"", "unittest.mock import Mock import pytest from galaxy import model from", "no legal values defined\" def test_unvalidated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\"", "True assert self.param.from_json(\"42\", self.trans) == \"42\" def test_validated_datasets(self): self.options_xml =", "None @property def param(self): if not self._param: multi_text = \"\"", "ref=\"input_bam\" column=\"1\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\":", "\"parameter 'my_name': requires a value, but no legal values defined\"", "# TODO: Good deal of overlap here with DataToolParameterTestCase, #", "{\"input_bam\": model.HistoryDatasetAssociation()}) assert str(exc_info.value) == \"parameter 'my_name': requires a value,", "== \"parameter 'my_name': requires a value, but no legal values", "legal values defined\" def test_validated_values_missing_dependency(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\"", "def test_validated_values_missing_dependency(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError)", "\"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"1\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False)", "in self.param.get_options(self.trans, {\"input_bam\": \"testname1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans,", "= \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert isinstance(", "self.trans.workflow_building_mode = True assert self.param.from_json(\"42\", self.trans) == \"42\" def test_validated_datasets(self):", "self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"1\" /></options>\"\"\" assert (\"testname1\",", "\"testname1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname2\"}) assert", "name=0, value=1, ) self.missing_index_file = None def get_fields(self): return [[\"testname1\",", "DataToolParameterTestCase, # refactor. def setUp(self): super().setUp() self.test_history = model.History() self.app.model.context.add(self.test_history)", "Same test as above, but filtering on a different column.", "test_validated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as", "/></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname1\"}) assert", "super().setUp() self.test_history = model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] = MockToolDataTable() self.trans", "MockToolDataTable: def __init__(self): self.columns = dict( name=0, value=1, ) self.missing_index_file", "def test_unvalidated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode =", "template_xml = \"\"\"<param name=\"my_name\" type=\"%s\" %s %s %s>%s</param>\"\"\" param_str =", "assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname1\"}) assert (\"testname2\",", "\"42\" def test_validated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with", "= False self.multiple = False self.optional = False self.options_xml =", "with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans, {\"input_bam\": model.HistoryDatasetAssociation()}) assert str(exc_info.value)", "from galaxy.tools.parameters import basic from .util import BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase):", "Mock import pytest from galaxy import model from galaxy.tools.parameters import", "type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans) assert", "= False self.options_xml = \"\" self._param = None @property def", "of overlap here with DataToolParameterTestCase, # refactor. def setUp(self): super().setUp()", "requires a value, but no legal values defined\" def test_unvalidated_values(self):", "in self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans,", "import pytest from galaxy import model from galaxy.tools.parameters import basic", "\"testpath1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"}) assert", "from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"1\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in", "self.trans, {\"input_bam\": None}) assert str(exc_info.value) == \"parameter 'my_name': requires a", "self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation, ) def test_filter_param_value(self): self.options_xml =", "assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation, ) def test_filter_param_value(self):", "False self.optional = False self.options_xml = \"\" self._param = None", "= None @property def param(self): if not self._param: multi_text =", "len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"})) == 0 def test_filter_param_value2(self): # Same test", "self.optional: optional_text = 'optional=\"True\"' options_text = self.options_xml data_ref_text = \"\"", "ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(\"42\", self.trans) assert str(exc_info.value)", "get_history=lambda: self.test_history, get_current_user_roles=lambda: [], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), ) self.type = \"select\"", "self.optional = False self.options_xml = \"\" self._param = None @property", "model from galaxy.tools.parameters import basic from .util import BaseParameterTestCase class", "column=\"0\" /></options>\"\"\" assert (\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testname1\"})", "basic.RuntimeValue()}), model.HistoryDatasetAssociation, ) def test_filter_param_value(self): self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\"", "self.set_data_ref: data_ref_text = 'data_ref=\"input_bam\"' template_xml = \"\"\"<param name=\"my_name\" type=\"%s\" %s", "overlap here with DataToolParameterTestCase, # refactor. def setUp(self): super().setUp() self.test_history", "def test_filter_param_value(self): self.options_xml = \"\"\"<options from_data_table=\"test_table\"><filter type=\"param_value\" ref=\"input_bam\" column=\"0\" /></options>\"\"\"", "self.trans, {\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation, ) def test_filter_param_value(self): self.options_xml = \"\"\"<options", "(\"testname1\", \"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"}) assert (\"testname2\", \"testpath2\",", "legal values defined\" def test_unvalidated_values(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\"", "\"\" if self.set_data_ref: data_ref_text = 'data_ref=\"input_bam\"' template_xml = \"\"\"<param name=\"my_name\"", "(\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\":", "True assert isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation, ) def", "def param(self): if not self._param: multi_text = \"\" if self.multiple:", "galaxy.tools.parameters import basic from .util import BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase): def", "isinstance( self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": basic.RuntimeValue()}), model.HistoryDatasetAssociation, ) def test_filter_param_value(self): self.options_xml", "@property def param(self): if not self._param: multi_text = \"\" if", ".util import BaseParameterTestCase class SelectToolParameterTestCase(BaseParameterTestCase): def test_validated_values(self): self.options_xml = \"\"\"<options><filter", "= \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" with pytest.raises(ValueError) as exc_info: self.param.from_json(model.HistoryDatasetAssociation(),", "[], workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), ) self.type = \"select\" self.set_data_ref = False", "model.HistoryDatasetAssociation()}) assert str(exc_info.value) == \"parameter 'my_name': requires a value, but", "{\"input_bam\": None}) assert str(exc_info.value) == \"parameter 'my_name': requires a value,", "{\"input_bam\": \"testname2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testname3\"})) == 0 def test_filter_param_value2(self):", "self.param.from_json(\"42\", self.trans, {\"input_bam\": model.HistoryDatasetAssociation()}) assert str(exc_info.value) == \"parameter 'my_name': requires", "= \"\" if self.set_data_ref: data_ref_text = 'data_ref=\"input_bam\"' template_xml = \"\"\"<param", "with pytest.raises(ValueError) as exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": None}) assert str(exc_info.value)", "type=\"data_meta\" ref=\"input_bam\" key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert self.param.from_json(\"42\", self.trans) ==", "\"testpath1\", False) in self.param.get_options(self.trans, {\"input_bam\": \"testpath1\"}) assert (\"testname2\", \"testpath2\", False)", "webapp=Mock(name=\"galaxy\"), ) self.type = \"select\" self.set_data_ref = False self.multiple =", "self.trans) == \"42\" def test_validated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\"", "return self._param class MockToolDataTable: def __init__(self): self.columns = dict( name=0,", "def __init__(self): self.columns = dict( name=0, value=1, ) self.missing_index_file =", "\"\" if self.multiple: multi_text = 'multiple=\"True\"' optional_text = \"\" if", "TODO: Good deal of overlap here with DataToolParameterTestCase, # refactor.", "self.test_history = model.History() self.app.model.context.add(self.test_history) self.app.model.context.flush() self.app.tool_data_tables[\"test_table\"] = MockToolDataTable() self.trans =", "% (self.type, data_ref_text, multi_text, optional_text, options_text) self._param = self._parameter_for(xml=param_str) return", "workflow_building_mode=False, webapp=Mock(name=\"galaxy\"), ) self.type = \"select\" self.set_data_ref = False self.multiple", "\"testpath2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"})) == 0 # TODO: Good", "import Mock import pytest from galaxy import model from galaxy.tools.parameters", "no legal values defined\" def test_validated_values_missing_dependency(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\"", "in self.param.get_options(self.trans, {\"input_bam\": \"testpath2\"}) assert len(self.param.get_options(self.trans, {\"input_bam\": \"testpath3\"})) == 0", "but no legal values defined\" def test_validated_values_missing_dependency(self): self.options_xml = \"\"\"<options><filter", "= \"\" self._param = None @property def param(self): if not", "self._param = None @property def param(self): if not self._param: multi_text", "exc_info: self.param.from_json(model.HistoryDatasetAssociation(), self.trans, {\"input_bam\": None}) assert str(exc_info.value) == \"parameter 'my_name':", "legal values defined\" def test_unvalidated_datasets(self): self.options_xml = \"\"\"<options><filter type=\"data_meta\" ref=\"input_bam\"", "'data_ref=\"input_bam\"' template_xml = \"\"\"<param name=\"my_name\" type=\"%s\" %s %s %s>%s</param>\"\"\" param_str", "if self.multiple: multi_text = 'multiple=\"True\"' optional_text = \"\" if self.optional:", "str(exc_info.value) == \"parameter 'my_name': requires a value, but no legal", "optional_text, options_text) self._param = self._parameter_for(xml=param_str) return self._param class MockToolDataTable: def", "self.param.get_options(self.trans, {\"input_bam\": \"testname1\"}) assert (\"testname2\", \"testpath2\", False) in self.param.get_options(self.trans, {\"input_bam\":", "above, but filtering on a different column. self.options_xml = \"\"\"<options", "test as above, but filtering on a different column. self.options_xml", "self.param.from_json(\"42\", self.trans) assert str(exc_info.value) == \"parameter 'my_name': requires a value,", "key=\"dbkey\"/></options>\"\"\" self.trans.workflow_building_mode = True assert self.param.from_json(\"42\", self.trans) == \"42\" def", "= 'data_ref=\"input_bam\"' template_xml = \"\"\"<param name=\"my_name\" type=\"%s\" %s %s %s>%s</param>\"\"\"", "\"\"\"<param name=\"my_name\" type=\"%s\" %s %s %s>%s</param>\"\"\" param_str = template_xml %" ]
[ "<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\"recumpiler Recompile", "coding: utf-8 -*- \"\"\"recumpiler Recompile text to be semi-readable memey", "text to be semi-readable memey garbage. \"\"\" __version__ = (0,", "Recompile text to be semi-readable memey garbage. \"\"\" __version__ =", "utf-8 -*- \"\"\"recumpiler Recompile text to be semi-readable memey garbage.", "to be semi-readable memey garbage. \"\"\" __version__ = (0, 0,", "be semi-readable memey garbage. \"\"\" __version__ = (0, 0, 0)", "# -*- coding: utf-8 -*- \"\"\"recumpiler Recompile text to be", "-*- coding: utf-8 -*- \"\"\"recumpiler Recompile text to be semi-readable", "\"\"\"recumpiler Recompile text to be semi-readable memey garbage. \"\"\" __version__", "-*- \"\"\"recumpiler Recompile text to be semi-readable memey garbage. \"\"\"", "python # -*- coding: utf-8 -*- \"\"\"recumpiler Recompile text to", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\"recumpiler Recompile text" ]
[ "'posix_avoid_mmap%': 0, }], ['OS==\"ios\"', { # Websockets and socket stream", "'../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc',", "'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ], # TODO(jschuh):", "[ # These are the features Android doesn't support. 'ENABLE_MEDIA_CODEC_THEORA',", "'../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_test_support', ], 'sources': [ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc',", "'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc',", "'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc',", "'../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'certificate_mime_types_java', 'type': 'none', 'sources': [", "'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h',", "'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h',", "'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc',", "we need to exclude NSS specific tests. # TODO(bulach): Add", "'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc',", "\"android\" and OS != \"ios\"', { 'conditions': [ ['use_openssl==1', {", "a # toolchain bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', # These tests crash", "'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h',", "'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h',", "[ { 'action_name': 'net_resources', 'variables': { 'grit_grd_file': 'base/net_resources.grd', }, 'includes':", "'ENABLE_BUILT_IN_DNS', ] }, { # else 'sources!': [ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h',", "'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ], 'defines': [ 'NET_IMPLEMENTATION', ], 'export_dependent_settings':", "that mmap-ing the index would not hurt any # existing", "'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h',", "'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc',", "'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc',", "0, }, { 'enable_websockets%': 1, 'use_v8_in_net%': 1, 'enable_built_in_dns%': 1, }],", "'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc',", "'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h',", "{ 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'data/ssl/certificates/', 'data/url_request_unittest/', ],", "'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h',", "'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc',", "'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h',", "gnome-vfs? xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h',", "'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h',", "<reponame>codenote/chromium-test<gh_stars>0 # Copyright 2013 The Chromium Authors. All rights reserved.", "OpenSSL-internal header. 'include_dirs': [ '../third_party/openssl', ], }, { # else", "[4267, ], }, ], }], ['OS != \"ios\"', { 'targets':", "'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc',", "'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h',", "'net_test_support', ], 'sources': [ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc',", "'^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }], [ 'disable_ftp_support==1', { 'sources/': [", "'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h',", "These source files are excluded by default platform rules, but", "'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h',", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support', ], 'sources': [ 'tools/testserver/run_testserver.cc',", "}], ['OS == \"ios\"', { 'sources/': [ ['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include',", "'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h',", "], }, { # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_perftest.cc', ],", "'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h',", "'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_server',", "'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc',", "'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', # Needs GetAppOutput(). 'test/python_utils_unittest.cc', # The following", "file. { 'variables': { 'chromium_code': 1, 'linux_link_kerberos%': 0, 'conditions': [", "'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'cert_verify_result_android_java', 'type': 'none',", "'dependencies': [ 'net_java', 'net_javatests', 'net_unittests', ], 'variables': { 'test_suite_name': 'net_unittests',", "'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h',", "'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc',", "'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h',", "[ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ], }, ], [ 'OS == \"win\"',", "'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ], }, ], [ 'use_glib == 1',", "'net', 'net_test_support', ], 'sources': [ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc',", "'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h',", "'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ], },{ 'dependencies': [ '../build/linux/system.gyp:libresolv', ], }],", "'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc',", "[ 'disk_cache/stress_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc',", "'$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ] }, }, ], [ 'OS", "'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc',", "'includes': [ '../build/android/java_cpp_template.gypi' ], }, ], }], # Special target", "{ # else: OS != \"win\" 'sources!': [ 'base/winsock_init.cc', 'base/winsock_init.h',", "'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_errors_java', 'type': 'none',", "'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc',", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', ], 'export_dependent_settings': [", "'--result', '<@(_outputs)', '--isolate', 'net_unittests.isolate', ], }, ], }, ], }],", "'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', # These", "'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc',", "'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc', ], }, { 'target_name': 'flip_in_mem_edsm_server', 'type': 'executable',", "[ 'enable_built_in_dns!=1', { 'sources!': [ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ], }, ],", "'dependencies': [ '../third_party/nss/nss.gyp:nss', ], }], [ 'use_v8_in_net==1', { 'dependencies': [", "'../build/jni_generator.gypi' ], }, { 'target_name': 'net_java', 'type': 'none', 'variables': {", "'^websockets/'], ], 'sources!': [ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ], }], [ 'OS", "], 'conditions': [ [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ],", "'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc',", "0', { 'sources!': [ # These sources can't be built", "'defines': [ 'POSIX_AVOID_MMAP', ], }, 'sources!': [ 'disk_cache/mapped_file_posix.cc', ], },", "'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc',", "'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h',", "'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ], 'defines': [ 'NET_IMPLEMENTATION',", "'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ],", "'static_library', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc',", "'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc',", "'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ],", "'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc',", "], }, { # else OS != \"android\" 'defines': [", "is needed to trigger the dll copy step on windows.", "[ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc',", "the above list 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h',", "== 1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], 'conditions': [", "'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h',", "'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ], # TODO(jschuh): crbug.com/167187 fix", "'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h',", "'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc',", "'msvs_disabled_warnings': [4267, ], }, { # else: OS != \"win\"", "'net', 'quic_library', ], 'sources': [ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc',", "/etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h',", "}], ['OS==\"solaris\"', { 'link_settings': { 'ldflags': [ '-R/usr/lib/mps', ], },", "'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h',", "['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { # else", "'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc',", "'sources': [ 'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h',", "], }, { # else: OS != \"win\" 'sources!': [", "['OS == \"android\" and gtest_target_type == \"shared_library\"', { 'targets': [", "'base/dns_util.h', 'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc',", "'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc',", "'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc',", "'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc',", "'<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest',", "'sources!': [ 'proxy/proxy_resolver_perftest.cc', ], }, ], # This is needed", "'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h', 'base/address_family.h', 'base/address_list.cc', 'base/address_list.h',", "}], ['os_posix == 1 and OS != \"mac\" and OS", "'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h', ], # TODO(jschuh):", "'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h',", "[ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], }, ], ],", "'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc',", "}, { 'target_name': 'net_java', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/java',", "}, { 'target_name': 'dns_fuzz_stub', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net',", "'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h',", "'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc',", "'target_name': 'quic_client', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library',", "'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc',", "{ # else 'sources!': [ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc', ], }],", "['OS != \"ios\"', { 'targets': [ # iOS doesn't have", "'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h',", "'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc', 'http/md4.h', 'http/partial_data.cc',", "'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc',", "}], ['os_bsd==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ], },{", "0, }], ['OS==\"ios\"', { # Websockets and socket stream are", "'../build/java.gypi' ], }, { 'target_name': 'net_java_test_support', 'type': 'none', 'variables': {", "equivalent tests when the underlying # functionality is ported to", "'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc',", "'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ], 'conditions': [ ['chromeos==1', {", "'sources': [ 'tools/crash_cache/crash_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h',", "'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc',", "\"win\" and OS != \"mac\"', { 'sources!': [ 'cert/x509_cert_types_unittest.cc', ],", "], 'sources': [ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc',", "{ 'java_in_dir': '../net/android/javatests', }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java', ],", "'../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support', ], 'sources':", "'export_dependent_settings': [ '../base/base.gyp:base', ], 'conditions': [ ['chromeos==1', { 'sources!': [", "}, { 'target_name': 'net_javatests', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/javatests',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'gdig',", "[ 'tools/testserver/run_testserver.cc', ], }, { 'target_name': 'stress_cache', 'type': 'executable', 'dependencies':", "'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc',", "'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ],", "'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h',", "], 'sources': [ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ],", "'dependencies': [ 'net_with_v8', ], }, { # else: !use_v8_in_net 'sources!':", "'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc',", "], }, ], [ 'OS == \"win\"', { 'sources!': [", "'../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/get_server_time/get_server_time.cc', ], # TODO(jschuh):", "'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc',", "{ # else 'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }], ['disable_ftp_support==1', {", "'../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources',", "{ 'chromium_code': 1, 'linux_link_kerberos%': 0, 'conditions': [ ['chromeos==1 or OS==\"android\"", "'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc',", "flag is set, we hackily avoid using mmap() in the", "['os_bsd==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ], },{ 'dependencies':", "'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc',", "'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h',", "'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ], }], [ 'use_openssl==1', { # When building", "'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc',", "'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h',", "'OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], 'actions': [", "'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ], }], ['use_kerberos==1', { 'defines': [", "'none', 'variables': { 'java_in_dir': '../net/android/java', }, 'dependencies': [ '../base/base.gyp:base', 'cert_verify_result_android_java',", "Websockets and socket stream are not used on iOS. 'enable_websockets%':", "'conditions': [ ['inside_chromium_build==1 and OS != \"ios\"', { 'dependencies': [", "], 'includes': [ '../build/grit_target.gypi' ], }, { 'target_name': 'http_server', 'type':", "'enable_built_in_dns!=1', { 'sources!': [ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ], }, ], [", "[ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ], }], ['enable_built_in_dns==1', { 'defines':", "'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h',", "'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ], 'conditions': [ ['chromeos==1',", "'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc',", "}], ], }, { # use_kerberos == 0 'sources!': [", "], }], ['os_bsd==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ],", "this here shouldn't be necessary. [ 'OS == \"win\"', {", "'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc',", "'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc',", "'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h',", "'url_request/url_request_ftp_job_unittest.cc', ], }, ], [ 'enable_built_in_dns!=1', { 'sources!': [ 'dns/address_sorter_posix_unittest.cc',", "'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h',", "this flag is set, we hackily avoid using mmap() in", "], }, { 'target_name': 'http_server', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors':", "'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h',", "}, { 'target_name': 'http_server', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1,", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dump_cache', 'type': 'executable', 'dependencies':", "'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h',", "['exclude', '^ftp/'], ], 'sources!': [ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ],", "'net_java', ], }], [ 'OS == \"android\"', { 'dependencies': [", "[ '../build/linux/system.gyp:ssl', ], }], ], }], ['os_posix == 1 and", "'$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ], }, }, ], ['OS==\"android\" and", "'defines': [ 'ENABLE_BUILT_IN_DNS', ] }, { # else 'sources!': [", "'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h',", "# platform rules. ['OS == \"android\"', { 'sources/': [ ['include',", "'action': [ 'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)',", "'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc',", "definition is not used. The following files are needed though:", "'../base/base.gyp:base', 'net', ], 'sources': [ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ], }, {", "'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h',", "Android doesn't support. 'ENABLE_MEDIA_CODEC_THEORA', ], }, ], [ 'OS ==", "'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ], }, {", "'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc',", "], [ 'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ],", "'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc',", "'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h',", "'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc',", "0 'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ], }], [", "[ 'net_unittests', ], 'includes': [ 'net_unittests.isolate', ], 'actions': [ {", "'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc',", "'../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support', ], 'sources': [ 'tools/testserver/run_testserver.cc', ], }, {", "NSS specific tests. # TODO(bulach): Add equivalent tests when the", "existing x86 android devices, but we cannot be so sure", "'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc',", "'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc',", "'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc',", "'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc',", "'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h',", "'net_test_jni_headers', ], }], [ 'use_glib == 1', { 'dependencies': [", "# OS is not \"linux\" or \"freebsd\" or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc',", "'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h',", "'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h',", "'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h',", "'../net/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_javatests',", "'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h',", "'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h',", "{ 'target_name': 'tld_cleanup', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl',", "'../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', ], 'export_dependent_settings': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ],", "The iOS implementation only partially uses NSS and thus does", "'net_test_jni_headers', 'type': 'none', 'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables': { 'jni_gen_package':", "'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc',", "'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc',", "}, { 'enable_websockets%': 1, 'use_v8_in_net%': 1, 'enable_built_in_dns%': 1, }], ],", "'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ], }], [ 'OS == \"win\"', { 'sources!':", "'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ], }], [ 'enable_websockets != 1', {", "'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h',", "'variables': { 'java_in_dir': '../net/android/java', }, 'dependencies': [ '../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java',", "'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h',", "'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc',", "'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h',", "== 0: !posix || mac 'sources!': [ 'cert/nss_cert_database_unittest.cc', ], },", "'../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ], # TODO(jschuh): crbug.com/167187 fix size_t", "above list 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc',", "'../base/allocator/allocator.gyp:allocator', ], }], ], }], ['OS != \"android\"', { 'sources!':", "'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc',", "'../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources', ], 'sources': [ 'android/cert_verify_result_android.h',", "'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc',", "missing or incomplete. # KeygenHandler::GenKeyAndSignChallenge() is not ported to iOS.", "'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h',", "== \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], 'actions': [ {", "TODO(mark): Specifying this here shouldn't be necessary. [ 'OS ==", "}, ], 'conditions': [ ['use_v8_in_net == 1', { 'targets': [", "'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc',", "1', { 'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ], 'sources!':", "'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc',", "'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc',", "'quic_library', ], 'sources': [ 'tools/quic/quic_client_bin.cc', ], }, { 'target_name': 'quic_server',", "OS==\"android\" or OS==\"ios\"', { # Disable Kerberos on ChromeOS, Android", "\"android\" 'defines': [ # These are the features Android doesn't", "{ 'action_name': 'net_resources', 'variables': { 'grit_grd_file': 'base/net_resources.grd', }, 'includes': [", "'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ], 'dependencies':", "'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc',", "== \"win\"', { 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], # TODO(jschuh): crbug.com/167187", "[ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'data/ssl/certificates/', 'data/url_request_unittest/',", "'../third_party/protobuf/protobuf.gyp:py_proto', ], }], ['os_posix == 1 and OS != \"mac\"", "cache. # We are pretty confident that mmap-ing the index", "'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h',", "'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc',", "'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc',", "'../build/grit_action.gypi' ], }, ], 'includes': [ '../build/grit_target.gypi' ], }, {", "'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h',", "[ '../build/linux/system.gyp:gtk', ], }, ], [ 'os_posix == 1 and", "evaluated after the # platform rules. ['OS == \"android\"', {", "'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h',", "}, { 'target_name': 'cert_verify_result_android_java', 'type': 'none', 'sources': [ 'android/java/CertVerifyResultAndroid.template', ],", "'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h',", "'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc',", "], # The net/android/keystore_openssl.cc source file needs to # access", "'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc',", "'variables': { 'test_suite_name': 'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [ '../build/apk_test.gypi'", "'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc',", "'msvs_disabled_warnings': [4267, ], }, ], ], }, { 'target_name': 'net_test_support',", "{ 'target_name': 'net_unittests_run', 'type': 'none', 'dependencies': [ 'net_unittests', ], 'includes':", "], 'conditions': [ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], },", "'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc',", "[ '../third_party/openssl/openssl.gyp:openssl', ], }, { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }],", "'../testing/gtest.gyp:gtest', 'net', 'quic_library', ], 'sources': [ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h',", "'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc',", "'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc',", "], 'variables': { 'test_suite_name': 'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [", "'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc',", "'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h',", "'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc',", "dll copy step on windows. # TODO(mark): Specifying this here", "[ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc',", "'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc',", "OpenSSL, we need to exclude NSS specific tests. # TODO(bulach):", "'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_server_bin.cc',", "'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc',", "'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h',", "'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc',", "'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h',", "'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h',", "'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc',", "[ 'OS == \"mac\"', { 'sources!': [ 'ssl/client_cert_store_impl_nss.cc', ], 'dependencies':", "'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ],", "'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h',", "when run with coverage turned on: # http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ],", "'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h',", "'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h',", "specific cases on other platforms. Re-including them can # only", "these targets # can't be compiled on the platform. {", "pretty confident that mmap-ing the index would not hurt any", "'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ], }, ], [ 'use_glib", "{ 'target_name': 'dns_fuzz_stub', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ],", "'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], 'conditions': [ ['use_openssl==1', { 'dependencies':", "'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc',", "[ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h',", "(krb5.conf and so on). 'use_kerberos%': 0, }, { # chromeos", "}, 'actions': [ { 'action_name': 'net_resources', 'variables': { 'grit_grd_file': 'base/net_resources.grd',", "'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h',", "'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc',", "{ 'link_settings': { 'ldflags': [ '<!@(krb5-config --libs gssapi)', ], },", "rules, but they # are needed in specific cases on", "[ '../build/linux/system.gyp:ssl', ], }, { # else use_glib == 0:", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_client', 'type': 'executable',", "'tools/crl_set_dump/crl_set_dump.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "targets # can't be compiled on the platform. { 'target_name':", "'sources': [ 'tools/get_server_time/get_server_time.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "'target_name': 'crl_set_dump', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources':", "'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc',", "'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc',", "'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ], }, ], [ 'OS ==", "'template_deps': ['base/net_error_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name':", "'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h',", "\"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries':", "], 'action': [ 'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR',", "'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc',", "'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc',", "'server/web_socket.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h',", "'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc',", "'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc',", "'sources': [ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc',", "}, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'cert_verify_result_android_java', 'type':", "http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', # These tests crash when run with coverage", "'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h', ], # TODO(jschuh): crbug.com/167187", "[ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { #", "'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h',", "'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc',", "'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', ], }], ['OS == \"ios\"', { 'dependencies':", "{ 'ldflags': [ '-R/usr/lib/mps', ], }, }], ], }, {", "'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h',", "'sources!': [ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ], }], ['enable_built_in_dns==1', {", "'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc',", "[ 'tools/tld_cleanup/tld_cleanup.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h',", "'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc', 'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h',", "'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc', 'base/net_log.h',", "'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc',", "'type': 'none', 'variables': { 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions': [ {", "{ 'package_name': 'org/chromium/net', 'template_deps': ['base/net_error_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ],", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dump_cache', 'type': 'executable',", "], }, }], ], }, { # else: OS is", "'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc',", "'../build/linux/system.gyp:libresolv', ], }], ['OS==\"solaris\"', { 'link_settings': { 'ldflags': [ '-R/usr/lib/mps',", "'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h',", "== \"ios\"', { 'sources/': [ ['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include',", "'^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include',", "], }, { 'target_name': 'net_watcher', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "GetAppOutput(). 'test/python_utils_unittest.cc', # The following tests are disabled because they", "0: !posix || mac 'sources!': [ 'cert/nss_cert_database_unittest.cc', ], }, ],", "'../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_server_bin.cc', ], }, {", "], 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [", "for x86 only for now. 'posix_avoid_mmap%': 1, }, { 'posix_avoid_mmap%':", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'crl_set_dump', 'type': 'executable',", "# These are the features Android doesn't support. 'ENABLE_MEDIA_CODEC_THEORA', ],", "'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h',", "'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h',", "{ 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl',", "['OS == \"ios\"', { 'sources/': [ ['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'],", "'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc',", "], ['OS == \"android\" and gtest_target_type == \"shared_library\"', { 'dependencies':", "'targets': [ { 'target_name': 'net_unittests_apk', 'type': 'none', 'dependencies': [ 'net_java',", "}, { # else: OS != \"win\" 'sources!': [ 'base/winsock_init.cc',", "So enable it for x86 only for now. 'posix_avoid_mmap%': 1,", "'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc',", "'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h',", "1, }], ['OS==\"android\" and target_arch != \"ia32\"', { # The", "'../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_test_support', ], 'sources': [", "'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h',", "to an # issue with llvm_gcda_increment_indirect_counter: # http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h',", "done in target_conditions as it is evaluated after the #", "'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ], # TODO(jschuh): crbug.com/167187", "'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h',", "exclude NSS specific tests. # TODO(bulach): Add equivalent tests when", "'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc',", "'ssl/openssl_client_key_store_unittest.cc', ], }, ], [ 'enable_websockets != 1', { 'sources/':", "'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ], }], ['use_kerberos==1', {", "'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ], 'conditions': [ ['chromeos==1', { 'sources!':", "'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', #", "'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h',", "'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc',", "'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h',", "'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h',", "'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc', 'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc',", "'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, { # else !use_openssl: remove the", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'crl_set_dump',", "{ 'target_name': 'net_java_test_support', 'type': 'none', 'variables': { 'java_in_dir': '../net/test/android/javatests', },", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'tld_cleanup', 'type': 'executable',", "[ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h',", "files are needed though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'],", "'../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h',", "'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc',", "'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h',", "'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc',", "}, ], ], 'sources': [ 'tools/net_watcher/net_watcher.cc', ], }, { 'target_name':", "'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h',", "TODO(bulach): Add equivalent tests when the underlying # functionality is", "'sources': [ 'tools/quic/quic_client_bin.cc', ], }, { 'target_name': 'quic_server', 'type': 'executable',", "\"android\" and gtest_target_type == \"shared_library\"', { 'targets': [ { 'target_name':", "'gdig', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [", "'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc',", "'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc',", "'../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/quic/quic_client.cc',", "], 'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc',", "'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ], 'defines': [ 'NET_IMPLEMENTATION', ], 'export_dependent_settings': [", "{ 'target_name': 'quic_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest',", "this source code is governed by a BSD-style license that", "'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h', ], # TODO(jschuh): crbug.com/167187 fix", "|use_nss|. In particular the |USE_NSS| preprocessor # definition is not", "'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h',", "else use_openssl==0, use NSS 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ['os_bsd==1',", "1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], }, ], ],", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_with_v8', ], 'conditions': [", "], }], # Special target to wrap a gtest_target_type==shared_library #", "'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc',", "['OS==\"openbsd\"', { 'include_dirs': [ '/usr/include/kerberosV' ], }], ['linux_link_kerberos==1', { 'link_settings':", "[ '../third_party/icu/icu.gyp:icudata', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc',", "'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h',", "other platforms. Re-including them can # only be done in", "'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc',", "'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc',", "# only be done in target_conditions as it is evaluated", "{ 'sources!': [ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ], }], [ 'enable_websockets", "{ 'target_name': 'quic_server', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net',", "{ 'dependencies': [ 'net_java', ], }], [ 'OS == \"android\"',", "'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc',", "{ 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ], },", "'dependencies': [ '../build/linux/system.gyp:gtk', ], }, ], [ 'os_posix == 1", "'ENABLE_MEDIA_CODEC_THEORA', ], }, ], [ 'OS == \"linux\"', { 'dependencies':", "'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc',", "and OS != \"android\" and OS != \"ios\"', { 'conditions':", "'net_java', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/java', }, 'dependencies': [", "[ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/url_request_ftp_job_unittest.cc', ], }, ],", "'target_name': 'net_java_test_support', 'type': 'none', 'variables': { 'java_in_dir': '../net/test/android/javatests', }, 'includes':", "'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc',", "'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc',", "|| mac 'sources!': [ 'cert/nss_cert_database_unittest.cc', ], }, ], [ 'toolkit_uses_gtk", "# found in the LICENSE file. { 'variables': { 'chromium_code':", "use V8. 'use_v8_in_net%': 0, 'enable_built_in_dns%': 0, }, { 'enable_websockets%': 1,", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], }], ['OS", "make a lot of # sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies':", "'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc',", "'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc',", "'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc',", "'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc',", "file needs to # access an OpenSSL-internal header. 'include_dirs': [", "['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'],", "'proxy/proxy_resolver_perftest.cc', ], 'conditions': [ [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8',", "}, { 'target_name': 'net_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n',", "'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc',", "'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc',", "{ 'target_name': 'crl_set_dump', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ],", "['include', '^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'],", "}, 'dependencies': [ '../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java', ], 'includes':", "'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc',", "'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc',", "'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc',", "'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h',", "}, ], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], },", "'disk_cache/stress_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc',", "'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc',", "'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc',", "[ 'cert/nss_cert_database_unittest.cc', ], }, ], [ 'toolkit_uses_gtk == 1', {", "\"linux\" or \"freebsd\" or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions': [ ['coverage", "}, ], [ 'OS == \"win\"', { 'sources!': [ 'dns/dns_config_service_posix_unittest.cc',", "[ 'NET_IMPLEMENTATION', ], 'sources': [ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc',", "[ 'tools/net_watcher/net_watcher.cc', ], }, { 'target_name': 'run_testserver', 'type': 'executable', 'dependencies':", "doesn't make a lot of # sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ],", "'base/filter.h', 'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc',", "'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net', 'quic_library', ],", "'export_dependent_settings': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'base/capturing_net_log.cc', 'base/capturing_net_log.h',", "else: OS is not in the above list 'sources!': [", "[ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc',", "'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc',", "], 'actions': [ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [", "of this source code is governed by a BSD-style license", "'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h',", "bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', # These tests crash when run with", "using mmap() in the disk cache. # We are pretty", "'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h',", "'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc',", "'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h',", "'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h',", "reserved. # Use of this source code is governed by", "'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ], 'sources!': [ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc',", "'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h',", "}, { # else OS != \"android\" 'defines': [ #", "# defines |use_nss|. In particular the |USE_NSS| preprocessor # definition", "[ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_server_bin.cc', ],", "'net', 'net_test_support', ], 'sources': [ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ], 'conditions':", "'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], 'sources!': [ # TODO(droger):", "'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc',", "'private_key_types_java', 'type': 'none', 'sources': [ 'android/java/PrivateKeyType.template', ], 'variables': { 'package_name':", "'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc',", "'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc',", "'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h',", "'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc',", "'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc',", "'type': 'none', 'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ],", "'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc',", "found in the LICENSE file. { 'variables': { 'chromium_code': 1,", "'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc',", "[ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], }, { # else !use_openssl:", "the dll copy step on windows. # TODO(mark): Specifying this", "'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h',", "'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc',", "'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base',", "crash when run with coverage turned on due to an", "'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "[ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "{ 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ] }, },", "and socket stream are not used on iOS. 'enable_websockets%': 0,", "'type': 'none', 'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables': { 'jni_gen_package': 'net',", "'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_java', 'type': 'none',", "'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h',", "], 'conditions': [ ['OS==\"openbsd\"', { 'include_dirs': [ '/usr/include/kerberosV' ], }],", "# http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ], }], ], }], [ 'OS ==", "[ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ], }, ], [ 'use_v8_in_net==1', { 'dependencies':", "defines |use_nss|. In particular the |USE_NSS| preprocessor # definition is", "'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc',", "'../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources', ], 'sources':", "'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h',", "'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc',", "'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h',", "'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ], }, ], [ 'OS", "'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc',", "'third_party/nss/ssl.gyp:libssl', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'../third_party/nss/nss.gyp:nss', ], }], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ],", "'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc',", "used. The following files are needed though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include',", "'../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_test_support', ], 'sources': [ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc',", "'conditions': [ ['chromeos==1 or OS==\"android\" or OS==\"ios\"', { # Disable", "'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h',", "'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc',", "'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ], }, { 'target_name': 'get_server_time', 'type': 'executable', 'dependencies':", "'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc',", "'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h',", "'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h',", "}, { # else 'sources!': [ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc', ],", "], }, { 'target_name': 'cert_verify_result_android_java', 'type': 'none', 'sources': [ 'android/java/CertVerifyResultAndroid.template',", "'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ], 'defines': [ 'NET_IMPLEMENTATION', ], 'export_dependent_settings': [ '../base/base.gyp:base',", "xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc',", "'../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java', ], 'includes': [ '../build/java.gypi' ],", "] }], ['OS==\"android\"', { 'targets': [ { 'target_name': 'net_jni_headers', 'type':", "only partially uses NSS and thus does not # defines", "'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ], 'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux_unittest.cc',", "# iOS. # OS is not \"linux\" or \"freebsd\" or", "files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', # Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc',", "We are pretty confident that mmap-ing the index would not", "'../third_party/icu/icu.gyp:icudata', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "on due to an # issue with llvm_gcda_increment_indirect_counter: # http://crbug.com/156058", "}], ['use_openssl==1', { 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc',", "needed though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'],", "'dependencies': [ 'net_java', ], }], [ 'OS == \"android\"', {", "'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h',", "'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h',", "in specific cases on other platforms. Re-including them can #", "[ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ], # This is needed to trigger", "], 'sources': [ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ], 'conditions': [ [", "}], # Special target to wrap a gtest_target_type==shared_library # net_unittests", "'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc',", "{ 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ], # This is needed", "'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "default platform rules, but they # are needed in specific", "'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc',", "== 0 'use_kerberos%': 1, }], ['OS==\"android\" and target_arch != \"ia32\"',", "iOS does not use V8. 'use_v8_in_net%': 0, 'enable_built_in_dns%': 0, },", "'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc',", "], }], [ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:ssl',", "and OS != \"mac\" and OS != \"android\" and OS", "{ 'targets': [ # iOS doesn't have the concept of", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'gdig', 'type': 'executable', 'dependencies':", "'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', # Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc',", "would not hurt any # existing x86 android devices, but", "'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h',", "'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc',", "'type': 'none', 'variables': { 'java_in_dir': '../net/android/java', }, 'dependencies': [ '../base/base.gyp:base',", "'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc',", "'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr',", "on the platform. { 'target_name': 'crash_cache', 'type': 'executable', 'dependencies': [", "'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h',", "Add equivalent tests when the underlying # functionality is ported", "'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc',", "Android and iOS, at least for now. # It needs", "The net/android/keystore_openssl.cc source file needs to # access an OpenSSL-internal", "'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc',", "'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc',", "else !use_openssl: remove the unneeded files 'sources!': [ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc',", "and gtest_target_type == \"shared_library\"', { 'targets': [ { 'target_name': 'net_unittests_apk',", "], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries':", "'dns/dns_config_service_posix_unittest.cc', ], }, ], ['OS == \"android\" and gtest_target_type ==", "'../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ], 'sources!': [ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ],", "'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ] },", "'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc',", "\"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ], }, ], [", "'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc',", "'jni_gen_package': 'net', }, 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net', ], },", "'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc',", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources': [", "'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [", "'target_name': 'net_watcher', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_with_v8', ],", "], }], ['disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ], 'sources!':", "], }, ], [ 'OS == \"linux\"', { 'dependencies': [", "'net_unittests.isolate', '<@(isolate_dependency_tracked)', ], 'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated', ], 'action': [ 'python',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'tld_cleanup', 'type':", "'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h',", "[ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h',", "'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h',", "'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock',", "'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc',", "[ 'ENABLE_BUILT_IN_DNS', ] }, { # else 'sources!': [ 'dns/address_sorter_posix.cc',", "'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h',", "'conditions': [ [ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:gconf',", "], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'], }, 'includes': [", "'../third_party/zlib/zlib.gyp:zlib', 'net_resources', ], 'sources': [ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc',", "'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc',", "the # implementation is missing or incomplete. # KeygenHandler::GenKeyAndSignChallenge() is", "[ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc',", "is not \"linux\" or \"freebsd\" or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions':", "{ 'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/url_request_ftp_job_unittest.cc', ],", "'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h',", "'use_openssl==1', { # When building for OpenSSL, we need to", "'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h',", "# Websockets and socket stream are not used on iOS.", "'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc',", "execution. # See base.gyp for TODO(jrg)s about this strategy. ['OS", "'sources!': [ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ], }], [ 'OS == \"android\"',", "'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h',", "'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc',", "'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc',", "'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc',", "'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc',", "# This is needed to trigger the dll copy step", "{ 'target_name': 'get_server_time', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl',", "{ 'target_name': 'net_unittests_apk', 'type': 'none', 'dependencies': [ 'net_java', 'net_javatests', 'net_unittests',", "'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc',", "}, ], [ 'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gdk',", "issue with llvm_gcda_increment_indirect_counter: # http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc',", "strategy. ['OS == \"android\" and gtest_target_type == \"shared_library\"', { 'targets':", "'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', # TODO(tc): gnome-vfs? xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc',", "['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'],", "'../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h',", "!= \"android\"', { 'targets': [ { 'target_name': 'flip_balsa_and_epoll_library', 'type': 'static_library',", "'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ], }, ], [ 'enable_websockets != 1',", "and OS != \"ios\"', { 'conditions': [ ['use_openssl==1', { 'dependencies':", "'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "}, }, ], ['OS==\"android\" and _toolset==\"target\" and android_webview_build == 0',", "'ssl/client_cert_store_impl_unittest.cc', ], }, { # else !use_openssl: remove the unneeded", "'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc',", "}, { # else 'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }], ['disable_ftp_support==1',", "'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc',", "mac 'sources!': [ 'cert/nss_cert_database_unittest.cc', ], }, ], [ 'toolkit_uses_gtk ==", "wrap a gtest_target_type==shared_library # net_unittests into an android apk for", "on iOS. 'enable_websockets%': 0, # iOS does not use V8.", "'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ], }], ['enable_built_in_dns==1', { 'defines': [ 'ENABLE_BUILT_IN_DNS',", "[ # These sources can't be built with coverage due", "'use_v8_in_net%': 0, 'enable_built_in_dns%': 0, }, { 'enable_websockets%': 1, 'use_v8_in_net%': 1,", "'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc',", "'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc',", "'target_name': 'dns_fuzz_stub', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources':", "'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'certificate_mime_types_java', 'type': 'none',", "'sources!': [ 'ssl/client_cert_store_impl_nss.cc', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ],", "'msvs_disabled_warnings': [4267, ], }, ], 'conditions': [ ['use_v8_in_net == 1',", "'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc',", "'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi'", "'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc',", "'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h',", "'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ],", "}], [ 'OS == \"android\"', { 'sources!': [ # No", "'../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/get_server_time/get_server_time.cc', ], # TODO(jschuh): crbug.com/167187", "we cannot be so sure about the # variety of", "{ 'target_name': 'net_java', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/java', },", "'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h',", "== \"android\" and gtest_target_type == \"shared_library\"', { 'targets': [ {", "], 'sources': [ 'tools/quic/quic_client_bin.cc', ], }, { 'target_name': 'quic_server', 'type':", "[ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'certificate_mime_types_java', 'type': 'none', 'sources':", "'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc',", "When building for OpenSSL, we need to exclude NSS specific", "{ 'target_name': 'gdig', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ],", "], [ 'OS == \"mac\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss',", "'-Wno-deprecated', ], 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources':", "'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc',", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_watcher', 'type': 'executable',", "'net_unittests.isolate', ], 'actions': [ { 'action_name': 'isolate', 'inputs': [ 'net_unittests.isolate',", "'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc',", "'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp',", "}, 'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_javatests', 'type':", "'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc',", "'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ], # TODO(jschuh): crbug.com/167187 fix size_t", "], 'conditions': [ [ 'use_glib == 1', { 'dependencies': [", "], }], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], },", "'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h',", "[ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc',", "{ 'conditions': [ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], },", "{ 'target_name': 'fetch_server', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1, },", "# else: OS is not in the above list 'sources!':", "an OpenSSL-internal header. 'include_dirs': [ '../third_party/openssl', ], }, { #", "now. 'posix_avoid_mmap%': 1, }, { 'posix_avoid_mmap%': 0, }], ['OS==\"ios\"', {", "'net_unittests', ], 'includes': [ 'net_unittests.isolate', ], 'actions': [ { 'action_name':", "'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc',", "'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc',", "'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc',", "'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc',", "'../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/get_server_time/get_server_time.cc', ], #", "'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc',", "}, { # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_perftest.cc', ], },", "'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h',", "}, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'certificate_mime_types_java', 'type':", "'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h',", "'tools/quic/quic_client_bin.cc', ], }, { 'target_name': 'quic_server', 'type': 'executable', 'dependencies': [", "'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h',", "'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc',", "'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h',", "'http/http_auth_gssapi_posix_unittest.cc', ], # This is needed to trigger the dll", "'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings':", "'quic_library', ], 'sources': [ 'tools/quic/quic_server_bin.cc', ], }, { 'target_name': 'quic_unittests',", "'../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], }, ], [ 'OS == \"ios\"', {", "'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc',", "== \"shared_library\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ] }], [ 'OS", "'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h',", "'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc',", "], }, { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ], }],", "'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h',", "'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ], }, ], [ 'enable_websockets != 1', {", "'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h',", "[ 'NET_IMPLEMENTATION', ], 'export_dependent_settings': [ '../base/base.gyp:base', ], 'conditions': [ ['chromeos==1',", "fix size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, {", "'spdy/spdy_session_spdy3_unittest.cc', # These tests crash when run with coverage turned", "'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h',", "'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h',", "'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc',", "'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h',", "'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h',", "'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc',", "[ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ], }, }, ],", "1', { 'dependencies': [ '../build/linux/system.gyp:gdk', ], }], [ 'use_nss !=", "}, { 'target_name': 'certificate_mime_types_java', 'type': 'none', 'sources': [ 'android/java/CertificateMimeType.template', ],", "# TODO(mark): Specifying this here shouldn't be necessary. [ 'OS", "'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h',", "[ '../base/base.gyp:base', 'net', 'net_with_v8', ], 'conditions': [ [ 'use_glib ==", "'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h',", "], 'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings': { 'include_dirs': [", "{ 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions': [ { 'action_name': 'net_resources', 'variables':", "'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net' ],", "# The way the cache uses mmap() is inefficient on", "!= \"ios\"', { 'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto', ], }], ['os_posix ==", "[ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ], }], [ 'enable_websockets != 1',", "'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc',", "{ 'defines': [ 'POSIX_AVOID_MMAP', ], }, 'sources!': [ 'disk_cache/mapped_file_posix.cc', ],", "'<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions': [ { 'action_name': 'net_resources', 'variables': { 'grit_grd_file':", "'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc',", "header. 'include_dirs': [ '../third_party/openssl', ], }, { # else OS", "'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h',", "], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'], }, 'includes': [", "'base/filter.cc', 'base/filter.h', 'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h',", "'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc',", "'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ],", "'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc',", "'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc',", "'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc',", "# implementation is missing or incomplete. # KeygenHandler::GenKeyAndSignChallenge() is not", "\"android\" and OS != \"ios\"', { 'conditions': [ ['linux_use_tcmalloc==1', {", "'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h',", "'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, ], [ 'toolkit_uses_gtk", "'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc',", "'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc',", "'^socket_stream/'], ['exclude', '^websockets/'], ], 'sources!': [ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ], }],", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_client', 'type': 'executable', 'variables':", "'sources': [ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h',", "'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc',", "'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc',", "'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings':", "], 'sources': [ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h',", "'net', 'net_test_support', ], 'sources': [ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h',", "[ { 'target_name': 'net', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1,", "'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h',", "'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc',", "iOS. # OS is not \"linux\" or \"freebsd\" or \"openbsd\".", "'none', 'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables':", "'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ], #", "'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc',", "'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp',", "'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc',", "'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h',", "}], ], }, { 'target_name': 'net_perftests', 'type': 'executable', 'dependencies': [", "'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, ], [ 'toolkit_uses_gtk == 1',", "'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc',", "[ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables': { 'jni_gen_package':", "[ '../build/linux/system.gyp:ssl', ], }], ['os_bsd==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc',", "'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc',", "'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h',", "'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [", "'none', 'dependencies': [ 'net_unittests', ], 'includes': [ 'net_unittests.isolate', ], 'actions':", "{ 'posix_avoid_mmap%': 0, }], ['OS==\"ios\"', { # Websockets and socket", "'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc',", "}, 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_with_v8', ],", "], }, { 'target_name': 'net_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:base',", "'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc',", "needs configuration (krb5.conf and so on). 'use_kerberos%': 0, }, {", "'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc',", "{ # use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h',", "[ 'net_with_v8', ], }, { # else: !use_v8_in_net 'sources!': [", "'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc',", "'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc',", "'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h',", "'executable', 'cflags': [ '-Wno-deprecated', ], 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library',", "hackily avoid using mmap() in the disk cache. # We", "[ { 'target_name': 'net_unittests_run', 'type': 'none', 'dependencies': [ 'net_unittests', ],", "'--variable', 'OS', '<(OS)', '--result', '<@(_outputs)', '--isolate', 'net_unittests.isolate', ], }, ],", "'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { # else use_openssl==0, use", "we hackily avoid using mmap() in the disk cache. #", "'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc',", "'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc',", "'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc',", "files 'sources!': [ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc',", "'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc',", "], [ 'os_posix == 1 and OS != \"mac\" and", "'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc',", "'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc',", "'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies': [ 'net_javatests', 'net_test_jni_headers', ], }], [ 'use_glib", "[ ['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'], # The iOS", "Specifying this here shouldn't be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr',", "cases on other platforms. Re-including them can # only be", "and OS != \"mac\" and OS != \"ios\" and OS", "[ # TODO(droger): The following tests are disabled because the", "], }, 'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_java',", "{ 'jni_gen_package': 'net', }, 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net', ],", "'java_in_dir': '../net/android/javatests', }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java', ], 'includes':", "}, 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net', ], }, 'includes': [", "}, }], ], }, { # else: OS is not", "}, ], }], ['test_isolation_mode != \"noop\"', { 'targets': [ {", "], 'defines': [ 'NET_IMPLEMENTATION', ], 'sources': [ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc',", "'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h',", "# No res_ninit() et al on Android, so this doesn't", "}, { 'target_name': 'crl_set_dump', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net',", "'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h',", "'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h',", "'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h',", "['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'], ], }], ], },", "'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', 'net', ],", "'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h',", "'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h',", "'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h',", "'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h',", "[ 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ], }, ],", "'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc',", "'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc',", "'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h',", "], 'sources': [ 'tools/crash_cache/crash_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h',", "'base/keygen_handler_unittest.cc', # Need to read input data files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc',", "'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h',", "[ 'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable',", "'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc', ], }, { 'target_name':", "'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc',", "[ 'tools/quic/quic_server_bin.cc', ], }, { 'target_name': 'quic_unittests', 'type': '<(gtest_target_type)', 'dependencies':", "'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h',", "[ 'tools/fetch/fetch_client.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc',", "'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc',", "'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc',", "'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h', 'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc',", "'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/crl_set_dump/crl_set_dump.cc', ], #", "'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h',", "'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc',", "[ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }],", "1', { 'targets': [ { 'target_name': 'net_with_v8', 'type': '<(component)', 'variables':", "'net_test_support', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net',", "so this doesn't make a lot of # sense. 'dns/dns_config_service_posix_unittest.cc',", "'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ],", "}, { 'target_name': 'quic_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h',", "building for OpenSSL, we need to exclude NSS specific tests.", "OS != \"win\" 'sources!': [ 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc',", "'sources': [ 'android/java/NetError.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/net_error_list.h'],", "'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc',", "[ '../build/grit_target.gypi' ], }, { 'target_name': 'http_server', 'type': 'static_library', 'variables':", "'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc',", "'direct_dependent_settings': { 'defines': [ 'POSIX_AVOID_MMAP', ], }, 'sources!': [ 'disk_cache/mapped_file_posix.cc',", "], # This is needed to trigger the dll copy", "'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h',", "[ '<!@(krb5-config --libs gssapi)', ], }, }, { # linux_link_kerberos==0", "'net_perftests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest',", "[4267, ], }, { # else: OS != \"win\" 'sources!':", "'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc',", "{ 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources':", "'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h',", "'target_name': 'net_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java',", "'../build/linux/system.gyp:ssl', ], }], ['os_bsd==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc',", "'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc',", "'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h',", "'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc',", "{ 'target_name': 'net_errors_java', 'type': 'none', 'sources': [ 'android/java/NetError.template', ], 'variables':", "'chromium_code': 1, 'linux_link_kerberos%': 0, 'conditions': [ ['chromeos==1 or OS==\"android\" or", "== \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': {", "way the cache uses mmap() is inefficient on some Android", "'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc',", "'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc',", "'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ], 'conditions':", "'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', # Needs GetAppOutput(). 'test/python_utils_unittest.cc', #", "this strategy. ['OS == \"android\" and gtest_target_type == \"shared_library\"', {", "'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc',", "'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc',", "'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc',", "'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h',", "unneeded files 'sources!': [ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc',", "'target_name': 'net_unittests_apk', 'type': 'none', 'dependencies': [ 'net_java', 'net_javatests', 'net_unittests', ],", "['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name': 'net_unittests_run', 'type':", "], }, { # else use_glib == 0: !posix ||", "{ # Websockets and socket stream are not used on", "'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, { # else", "[ 'POSIX_AVOID_MMAP', ], }, 'sources!': [ 'disk_cache/mapped_file_posix.cc', ], }, {", "use_glib == 0: !posix || mac 'sources!': [ 'cert/nss_cert_database_unittest.cc', ],", "'tools/fetch/fetch_client.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "{ # use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc',", "'sources': [ 'tools/net_watcher/net_watcher.cc', ], }, { 'target_name': 'run_testserver', 'type': 'executable',", "'sources': [ 'disk_cache/stress_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "run with coverage turned on due to an # issue", "'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc',", "# else !use_openssl: remove the unneeded files 'sources!': [ 'cert/x509_util_openssl_unittest.cc',", "}, ], [ 'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gtk',", "'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc',", "'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc',", "'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc',", "], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ]", "\"ios\"', { 'targets': [ # iOS doesn't have the concept", "[ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ], }], [ 'OS == \"android\"', {", "'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ], },", "disk cache. # We are pretty confident that mmap-ing the", "'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc',", "'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h',", "'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc',", "'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc',", "'template_deps': ['android/cert_verify_result_android_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name':", "'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc',", "!= \"win\" and OS != \"mac\"', { 'sources!': [ 'cert/x509_cert_types_unittest.cc',", "and target_arch != \"ia32\"', { # The way the cache", "0, }, { # chromeos == 0 'use_kerberos%': 1, }],", "'../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', ], 'export_dependent_settings': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base',", "], 'sources': [ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc',", "'android/network_library.h', 'base/address_family.h', 'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h',", "'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ], }, { 'target_name': 'quic_library', 'type':", "'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h',", "'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc',", "'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc',", "'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ],", "'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc',", "'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h',", "for OpenSSL, we need to exclude NSS specific tests. #", "# access an OpenSSL-internal header. 'include_dirs': [ '../third_party/openssl', ], },", "[ 'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h', ],", "android devices, but we cannot be so sure about the", "'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h',", "'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc',", "'../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h',", "], ], }, { 'target_name': 'net_test_support', 'type': 'static_library', 'dependencies': [", "], }], ], }], ['os_posix == 1 and OS !=", "'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources':", "], 'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc',", "'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h',", "'disk_cache/mapped_file_posix.cc', ], }, { # else 'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ],", "is governed by a BSD-style license that can be #", "'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ], }], [ 'OS == \"android\"', { 'sources!':", "'../testing/gtest.gyp:gtest', 'net', ], 'export_dependent_settings': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ], 'sources':", "'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc',", "iOS. 'base/keygen_handler_unittest.cc', # Need to read input data files. 'base/gzip_filter_unittest.cc',", "'action_name': 'net_resources', 'variables': { 'grit_grd_file': 'base/net_resources.grd', }, 'includes': [ '../build/grit_action.gypi'", "'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h',", "OS != \"mac\"', { 'sources!': [ 'cert/x509_cert_types_unittest.cc', ], }], ],", "'run_testserver', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support', ],", "not in the above list 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc',", "'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable', 'OS', '<(OS)', '--result', '<@(_outputs)', '--isolate', 'net_unittests.isolate', ],", "'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc',", "'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc',", "KeygenHandler::GenKeyAndSignChallenge() is not ported to iOS. 'base/keygen_handler_unittest.cc', # Need to", "}, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n',", "[ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ], }], [ 'OS == \"win\"', {", "'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h',", "'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc',", "'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc',", "'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc',", "], }, { 'target_name': 'net_errors_java', 'type': 'none', 'sources': [ 'android/java/NetError.template',", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dns_fuzz_stub', 'type': 'executable', 'dependencies':", "'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ], }, { 'target_name':", "'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc', 'http/md4.h',", "'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings': { 'include_dirs':", "'tools/crash_cache/crash_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { # else:", "'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc',", "'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc',", "'sources!': [ # These sources can't be built with coverage", "{ 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ], }], ['os_posix ==", "{ 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { # else use_openssl==0,", "'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc', 'http/des.h',", "{ 'target_name': 'run_testserver', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest',", "{ 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], 'actions': [ { 'action_name': 'copy_test_data',", "mmap() in the disk cache. # We are pretty confident", "'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc',", "'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc',", "], }], [ 'OS == \"win\"', { 'sources!': [ 'http/http_auth_handler_ntlm_portable.cc',", "!= \"ios\"', { 'conditions': [ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl',", "[ { 'target_name': 'net_with_v8', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1,", "about this strategy. ['OS == \"android\" and gtest_target_type == \"shared_library\"',", "'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h',", "else: OS != \"win\" 'sources!': [ 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h',", "{ 'test_suite_name': 'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [ '../build/apk_test.gypi' ],", "target_conditions as it is evaluated after the # platform rules.", "== 1', { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }, { #", "'POSIX_AVOID_MMAP', ], 'direct_dependent_settings': { 'defines': [ 'POSIX_AVOID_MMAP', ], }, 'sources!':", "'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', # These tests crash", "only for now. 'posix_avoid_mmap%': 1, }, { 'posix_avoid_mmap%': 0, }],", "[ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',", "source file needs to # access an OpenSSL-internal header. 'include_dirs':", "'includes': [ '../build/apk_test.gypi' ], }, ], }], ['test_isolation_mode != \"noop\"',", "'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h',", "'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc',", "'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc',", "['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ], }], [ 'OS", "'net_test_support', ], 'sources': [ 'tools/testserver/run_testserver.cc', ], }, { 'target_name': 'stress_cache',", "[ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h',", "], }, { 'target_name': 'quic_server', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ], # The net/android/keystore_openssl.cc source file needs", "], }, { 'target_name': 'gdig', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "], }, ], }], ['test_isolation_mode != \"noop\"', { 'targets': [", "'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc',", "'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc',", "'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc',", "'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h',", "'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc',", "'sources!': [ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc', ], }], ['use_openssl==1', { 'sources!':", "Use of this source code is governed by a BSD-style", "'../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'private_key_types_java', 'type': 'none', 'sources': [", "'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_test_support',", "'tld_cleanup', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', #", "[ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }], ['disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'],", "'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc',", "'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h',", "], 'sources': [ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h',", "target_arch != \"ia32\"', { # The way the cache uses", "'sources': [ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc',", "used on iOS. 'enable_websockets%': 0, # iOS does not use", "[ 'use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], }, { #", "], 'sources': [ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc',", "'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h',", "'target_name': 'dump_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ],", "'target_name': 'net_java', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/java', }, 'dependencies':", "'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc',", "!= 0', { 'sources!': [ # These sources can't be", "and OS != \"ios\"', { 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies':", "'net', ], 'sources': [ 'tools/get_server_time/get_server_time.cc', ], # TODO(jschuh): crbug.com/167187 fix", "'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ], }], ['enable_built_in_dns==1', { 'defines': [ 'ENABLE_BUILT_IN_DNS', ]", "'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc',", "'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h',", "'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc',", "'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc',", "'^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'], ], }], ], }, { 'target_name': 'net_unittests',", "'../net/android/java', }, 'dependencies': [ '../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java', ],", "'../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_with_v8', ], 'sources': [ 'tools/fetch/fetch_client.cc', ], #", "'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h',", "'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc',", "'enable_built_in_dns%': 1, }], ], }, 'includes': [ '../build/win_precompile.gypi', ], 'targets':", "], }, ], # This is needed to trigger the", "'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc',", "], }, ], [ 'toolkit_uses_gtk == 1', { 'dependencies': [", "'net_test_support', ], 'sources': [ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc',", "== \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ], }, ],", "are the features Android doesn't support. 'ENABLE_MEDIA_CODEC_THEORA', ], }, ],", "{ 'grit_grd_file': 'base/net_resources.grd', }, 'includes': [ '../build/grit_action.gypi' ], }, ],", "'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h',", "], 'sources': [ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ], }, { 'target_name': 'get_server_time',", "'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc',", "coverage due to a # toolchain bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', #", "'../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_with_v8', ], 'sources': [ 'tools/fetch/fetch_client.cc', ],", "'server/web_socket.cc', 'server/web_socket.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "], }], ['use_openssl==1', { 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h',", "'../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'disk_cache/stress_cache.cc', ], # TODO(jschuh):", "|USE_NSS| preprocessor # definition is not used. The following files", "'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h',", "'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { 'dependencies': [ '../build/linux/system.gyp:ssl', ],", "'url_request/url_request_test_util.h', ], 'conditions': [ ['inside_chromium_build==1 and OS != \"ios\"', {", "'none', 'variables': { 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions': [ { 'action_name':", "'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, {", "# Need to read input data files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc',", "'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc',", "size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], ],", "'net', 'net_test_support', ], 'sources': [ 'tools/crash_cache/crash_cache.cc', ], # TODO(jschuh): crbug.com/167187", "'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc',", "'sources!': [ 'disk_cache/mapped_file_posix.cc', ], }, { # else 'sources!': [", "shouldn't be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ],", "'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ], }, { 'target_name': 'quic_client',", "'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java', ], 'includes': [ '../build/java.gypi' ], },", "[ ['include', '^base/platform_mime_util_linux\\\\.cc$'], ], }], ['OS == \"ios\"', { 'sources/':", "], }], [ 'disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ],", "'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h',", "rights reserved. # Use of this source code is governed", "size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], }],", "], 'sources!': [ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ], }], ['enable_built_in_dns==1',", "'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc',", "'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc',", "'../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc',", "'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc',", "], 'sources': [ 'tools/quic/quic_server_bin.cc', ], }, { 'target_name': 'quic_unittests', 'type':", "!= \"mac\" and OS != \"ios\" and OS != \"android\"',", "'targets': [ { 'target_name': 'net_unittests_run', 'type': 'none', 'dependencies': [ 'net_unittests',", "'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h',", "!use_openssl: remove the unneeded files 'sources!': [ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h',", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'tld_cleanup', 'type': 'executable', 'dependencies':", "'use_kerberos%': 1, }], ['OS==\"android\" and target_arch != \"ia32\"', { #", "== 1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], }, ],", "}, 'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_test_jni_headers', 'type':", "'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc',", "'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc',", "[ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'cert_verify_result_android_java', 'type': 'none', 'sources':", "'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [", "{ 'target_name': 'net_resources', 'type': 'none', 'variables': { 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', },", "'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "[ ['inside_chromium_build==1 and OS != \"ios\"', { 'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto',", "'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc',", "'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc',", "'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc',", "# Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', # Needs", "'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_client_bin.cc', ], }, { 'target_name':", "== 0', { 'dependencies': [ 'net_java', ], }], [ 'OS", "['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ], 'sources!': [ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ],", "'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc',", "'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h',", "{ 'defines': [ 'USE_KERBEROS', ], 'conditions': [ ['OS==\"openbsd\"', { 'include_dirs':", "Re-including them can # only be done in target_conditions as", "'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h',", "'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ],", "'net' ], 'defines': [ 'NET_IMPLEMENTATION', ], 'sources': [ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h',", "'../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support', ], 'sources': [ 'android/keystore_unittest.cc',", "'sources!': [ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h',", "'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h',", "'target_name': 'net_with_v8', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies':", "{ 'package_name': 'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ],", "android apk for execution. # See base.gyp for TODO(jrg)s about", "}, ], # This is needed to trigger the dll", "'../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ], }, ], ], 'target_conditions': [ # These", "'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc',", "the LICENSE file. { 'variables': { 'chromium_code': 1, 'linux_link_kerberos%': 0,", "'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc',", "], [ 'enable_websockets != 1', { 'sources/': [ ['exclude', '^socket_stream/'],", "'variables': { 'java_in_dir': '../net/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], },", "'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc',", "}, { # else use_glib == 0: !posix || mac", "'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h',", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'crl_set_dump', 'type': 'executable', 'dependencies':", "'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc', 'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h',", "'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc',", "# else use_openssl==0, use NSS 'dependencies': [ '../build/linux/system.gyp:ssl', ], }],", "'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], ['OS != \"android\"',", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dns_fuzz_stub', 'type': 'executable',", "'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc',", "'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h',", "'target_name': 'net', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies':", "'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc',", "'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h',", "'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h',", "'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc', ], }, { 'target_name': 'flip_in_mem_edsm_server',", "'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h',", "'dependencies': [ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], # TODO(jschuh): crbug.com/167187", "'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc', ], },", "'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h',", "'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ], }, {", "== \"shared_library\"', { 'targets': [ { 'target_name': 'net_unittests_apk', 'type': 'none',", "'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h',", "'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc', ],", "'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc',", "[ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ], }], [ 'use_openssl==1', {", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_watcher', 'type':", "'executable', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "'^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'], # The iOS implementation only partially uses", "'../base/base.gyp:base', 'net', ], 'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], # TODO(jschuh): crbug.com/167187", "'../base/base.gyp:base_java_test_support', 'net_java', ], 'includes': [ '../build/java.gypi' ], }, { 'target_name':", "}], [ 'use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], }, {", "'test/spawner_communicator.h', ], }], ['OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss',", "'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h',", "'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h',", "'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h',", "], 'sources': [ 'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc',", "'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h',", "'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc',", "apk for execution. # See base.gyp for TODO(jrg)s about this", "'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc',", "built with coverage due to a # toolchain bug: http://openradar.appspot.com/radar?id=1499403", "'type': 'none', 'dependencies': [ 'net_unittests', ], 'includes': [ 'net_unittests.isolate', ],", "'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h',", "'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h',", "'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], 'sources!': [", "{ 'target_name': 'net_test_support', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl',", "], }, { # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc',", "'net_javatests', 'net_test_jni_headers', ], }], [ 'use_glib == 1', { 'dependencies':", "is missing or incomplete. # KeygenHandler::GenKeyAndSignChallenge() is not ported to", "'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h',", "'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc',", "'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h',", "[ '../base/allocator/allocator.gyp:allocator', ], }], ], }], [ 'use_kerberos==1', { 'defines':", "}, { 'target_name': 'gdig', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net',", "'../testing/gtest.gyp:gtest', 'net_test_support', ], 'sources': [ 'tools/testserver/run_testserver.cc', ], }, { 'target_name':", "'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h',", "license that can be # found in the LICENSE file.", "'action_name': 'isolate', 'inputs': [ 'net_unittests.isolate', '<@(isolate_dependency_tracked)', ], 'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated',", "'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc',", "'test/python_utils_unittest.cc', # The following tests are disabled because they don't", "'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h',", "'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc',", "'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h',", "access an OpenSSL-internal header. 'include_dirs': [ '../third_party/openssl', ], }, {", "'sources!': [ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ], }, ], [ 'enable_websockets", "'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc',", "'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc',", "'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc',", "'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc',", "'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc',", "'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h',", "'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc',", "'../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', ], 'export_dependent_settings': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest',", "'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc',", "'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc',", "['use_openssl==1', { 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc',", "not used. The following files are needed though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'],", "# Use of this source code is governed by a", "'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc',", "'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc',", "['disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/ftp_protocol_handler.cc',", "'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h',", "'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h',", "{ 'action_name': 'isolate', 'inputs': [ 'net_unittests.isolate', '<@(isolate_dependency_tracked)', ], 'outputs': [", "on windows. # TODO(mark): Specifying this here shouldn't be necessary.", "'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h',", "'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h',", "[4267, ], }, { 'target_name': 'tld_cleanup', 'type': 'executable', 'dependencies': [", "'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h',", "'msvs_disabled_warnings': [4267, ], }, ], [ 'OS == \"mac\"', {", "'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h',", "'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc',", "uses NSS and thus does not # defines |use_nss|. In", "'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc',", "OS != \"mac\" and OS != \"ios\" and OS !=", "'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc',", "'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc',", "'sources': [ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ], }, { 'target_name': 'get_server_time', 'type':", "'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, ],", "'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h',", "}, ], [ 'OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss',", "'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h',", "['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], [", "# The following tests are disabled because they don't apply", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib',", "'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ], 'conditions': [", "'net_with_v8', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [", "], }, { 'target_name': 'get_server_time', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc',", "'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], }, ], [ 'OS", "'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h',", "'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc',", "'net', }, 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net', ], }, 'includes':", "[ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ],", "'sources!': [ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ], }, ], [ 'use_v8_in_net==1', {", "'executable', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl',", "'../build/linux/system.gyp:gtk', ], }, ], [ 'os_posix == 1 and OS", "'ldflags': [ '<!@(krb5-config --libs gssapi)', ], }, }, { #", "'$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ], }, }, ], ['OS==\"android\"", "input data files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', # Need TestServer.", "'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h',", "truncations. 'msvs_disabled_warnings': [4267, ], }, ], }], ['OS != \"ios\"',", "'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp',", "}, 'includes': [ '../build/apk_test.gypi' ], }, ], }], ['test_isolation_mode !=", "'../third_party/openssl', ], }, { # else OS != \"android\" 'defines':", "a BSD-style license that can be # found in the", "'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc',", "'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc',", "'sources': [ 'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h',", "Special target to wrap a gtest_target_type==shared_library # net_unittests into an", "'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc',", "'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h',", "'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], }, { # else !use_openssl: remove the", "'^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include',", "'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc',", "not use V8. 'use_v8_in_net%': 0, 'enable_built_in_dns%': 0, }, { 'enable_websockets%':", "to # iOS. # OS is not \"linux\" or \"freebsd\"", "because they don't apply to # iOS. # OS is", "'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc',", "'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h',", "'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h',", "'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc',", "'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ], } ]", "'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc',", "'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [ '../build/apk_test.gypi' ], }, ],", "], }, { 'target_name': 'fetch_client', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors':", "'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h',", "'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc',", "'sources/': [ ['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'], # The", "'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc',", "or OS==\"android\" or OS==\"ios\"', { # Disable Kerberos on ChromeOS,", "'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h',", "}, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], 'sources!': [ #", "'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', ],", "'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc',", "{ # else !use_openssl: remove the unneeded files 'sources!': [", "else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ], }, ], [", "[ '../third_party/openssl/openssl.gyp:openssl', ], 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', ], }, ], ['OS", "'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss',", "OS != \"android\" and OS != \"ios\"', { 'conditions': [", "'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h',", "'^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'], ], }], ],", "'dns/dns_client.cc', ], }], ['use_openssl==1', { 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c',", "['chromeos==1 or OS==\"android\" or OS==\"ios\"', { # Disable Kerberos on", "'^base/platform_mime_util_mac\\\\.mm$'], # The iOS implementation only partially uses NSS and", "'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc',", "'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi'", "'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc',", "'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc',", "'--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable', 'OS', '<(OS)', '--result', '<@(_outputs)', '--isolate', 'net_unittests.isolate',", "'tools/flip_server/string_piece_utils.h', ], }, { 'target_name': 'quic_library', 'type': 'static_library', 'dependencies': [", "== \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], 'sources!': [ 'dns/dns_config_service_posix_unittest.cc',", "'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc',", "'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc',", "'../third_party/openssl/openssl.gyp:openssl', ], 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', ], }, ], ['OS ==", "'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc',", "'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc',", "'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc',", "some Android devices. # If this flag is set, we", "The following files are needed though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'],", "], ['OS==\"android\" and _toolset==\"target\" and android_webview_build == 0', { 'dependencies':", "'http/mock_gssapi_library_posix.h', ], }], [ 'use_openssl==1', { # When building for", "'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], #", "'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h',", "[ 'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ],", "are disabled because the # implementation is missing or incomplete.", "'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h',", "or incomplete. # KeygenHandler::GenKeyAndSignChallenge() is not ported to iOS. 'base/keygen_handler_unittest.cc',", "'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ], 'conditions': [ ['inside_chromium_build==1 and", "[ '../base/allocator/allocator.gyp:allocator', ], }], ], }], ['OS != \"android\"', {", "[ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ], # TODO(jschuh):", "'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h',", "'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc',", "'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc',", "'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc',", "!posix || mac 'sources!': [ 'cert/nss_cert_database_unittest.cc', ], }, ], [", "'type': 'executable', 'cflags': [ '-Wno-deprecated', ], 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl',", "'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc',", "TODO(tc): gnome-vfs? xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h',", "'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h',", "[ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ], 'sources!': [ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc',", "'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h',", "'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ], # The net/android/keystore_openssl.cc source file needs to", "# Copyright 2013 The Chromium Authors. All rights reserved. #", "'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ], 'conditions': [ ['inside_chromium_build==1 and OS !=", "}, { 'target_name': 'get_server_time', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n',", "'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', # TODO(tc):", "'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_server_bin.cc', ], }, { 'target_name':", "'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h',", "'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc',", "'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc',", "'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc',", "'variables': { 'test_data_files': [ 'data/ssl/certificates/', 'data/url_request_unittest/', ], 'test_data_prefix': 'net', },", "of simple executables, these targets # can't be compiled on", "'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc',", "'target_name': 'quic_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net',", "[4267, ], }, ], }], ['os_posix == 1 and OS", "'java_in_dir': '../net/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, { 'target_name':", "'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc',", "}], ], }, { # else: OS is not in", "'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc',", "}, ], [ 'os_posix == 1 and OS != \"mac\"", "'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc',", "'quic_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library',", "'targets': [ { 'target_name': 'flip_balsa_and_epoll_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base',", "# net_unittests into an android apk for execution. # See", "'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc',", "'OS != \"win\" and OS != \"mac\"', { 'sources!': [", "{ 'target_name': 'certificate_mime_types_java', 'type': 'none', 'sources': [ 'android/java/CertificateMimeType.template', ], 'variables':", "'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h',", "'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc',", "'proxy/proxy_config_service_linux.h', ], }], ['use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], 'conditions':", "}, { # use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h',", "'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h',", "}, ], 'includes': [ '../build/grit_target.gypi' ], }, { 'target_name': 'http_server',", "'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h',", "coverage turned on: # http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ], }], ], }],", "'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc',", "], 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', ], }, ], ['OS == \"android\"", "'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc',", "'../build/jni_generator.gypi' ], }, { 'target_name': 'net_test_jni_headers', 'type': 'none', 'sources': [", "'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h',", "# iOS doesn't have the concept of simple executables, these", "'<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable', 'OS', '<(OS)', '--result', '<@(_outputs)', '--isolate',", "'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc',", "'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc',", "'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h',", "'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc',", "'dependencies': [ '../build/linux/system.gyp:gdk', ], }], [ 'use_nss != 1', {", "'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc',", "}, { # use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc',", "to iOS. 'base/keygen_handler_unittest.cc', # Need to read input data files.", "'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc',", "[ 'tools/get_server_time/get_server_time.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable', 'OS', '<(OS)',", "'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc',", "'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc',", "], }, ], ], 'sources': [ 'tools/net_watcher/net_watcher.cc', ], }, {", "'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc',", "'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h',", "'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h',", "'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h',", "implementation is missing or incomplete. # KeygenHandler::GenKeyAndSignChallenge() is not ported", "'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h',", "'tools/dump_cache/url_utilities.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "for now. 'posix_avoid_mmap%': 1, }, { 'posix_avoid_mmap%': 0, }], ['OS==\"ios\"',", "'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc',", "variety of ARM devices. So enable it for x86 only", "[ 'cert/x509_cert_types_unittest.cc', ], }], ], }, { 'target_name': 'net_perftests', 'type':", "'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "to # access an OpenSSL-internal header. 'include_dirs': [ '../third_party/openssl', ],", "and _toolset==\"target\" and android_webview_build == 0', { 'dependencies': [ 'net_java',", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'gdig', 'type': 'executable',", "'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h',", "}, }, { # linux_link_kerberos==0 'defines': [ 'DLOPEN_KERBEROS', ], }],", "'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h',", "[ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'private_key_types_java', 'type': 'none', 'sources':", "'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc',", "truncations. 'msvs_disabled_warnings': [4267, ], }, { # else: OS !=", "'type': 'none', 'variables': { 'java_in_dir': '../net/android/javatests', }, 'dependencies': [ '../base/base.gyp:base',", "'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h',", "'<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [ '../build/apk_test.gypi' ], }, ], }], ['test_isolation_mode", "'target_name': 'net_perftests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl',", "'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net', ], }, 'includes': [ '../build/jni_generator.gypi'", "'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc',", "on other platforms. Re-including them can # only be done", "1, }, 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_with_v8',", "'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h',", "'targets': [ { 'target_name': 'net', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors':", "'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h',", "source code is governed by a BSD-style license that can", "'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc',", "'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h',", "'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h',", "'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc',", "'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h',", "}], ], }], [ 'use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ],", "'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc',", "[4267, ], }, { 'target_name': 'crl_set_dump', 'type': 'executable', 'dependencies': [", "'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h',", "'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc',", "'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc',", "# These source files are excluded by default platform rules,", "'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h',", "}, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'private_key_types_java', 'type':", "], }, { 'target_name': 'net_resources', 'type': 'none', 'variables': { 'grit_out_dir':", "'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc',", "], }], ['os_posix == 1 and OS != \"mac\" and", "'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc',", "'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc',", "== \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], }], [ 'use_v8_in_net==1',", "'conditions': [ ['use_v8_in_net == 1', { 'targets': [ { 'target_name':", "], }], ['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name':", "'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h',", "'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h',", "'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc',", "by default platform rules, but they # are needed in", "'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc',", "set, we hackily avoid using mmap() in the disk cache.", "'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib',", "'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc',", "'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc',", "'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc',", "'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h',", "}, { # linux_link_kerberos==0 'defines': [ 'DLOPEN_KERBEROS', ], }], ],", "], }, ], }], ['OS != \"ios\"', { 'targets': [", "'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc',", "'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h',", "'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc', 'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc',", "], 'export_dependent_settings': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'base/capturing_net_log.cc',", "'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc',", "'../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support', ], 'sources': [ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc',", "'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc',", "'test_data_files': [ 'data/ssl/certificates/', 'data/url_request_unittest/', ], 'test_data_prefix': 'net', }, 'includes': [", "}, { 'target_name': 'net_resources', 'type': 'none', 'variables': { 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net',", "], }], ], }, { 'target_name': 'net_perftests', 'type': 'executable', 'dependencies':", "], }, { 'target_name': 'dns_fuzz_stub', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "a gtest_target_type==shared_library # net_unittests into an android apk for execution.", "'<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl',", "'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc',", "'dependencies': [ 'net_unittests', ], 'includes': [ 'net_unittests.isolate', ], 'actions': [", "'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc',", "'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc',", "'../dbus/dbus.gyp:dbus', ], }, ], ], 'target_conditions': [ # These source", "'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc',", "[ '../build/java.gypi' ], }, { 'target_name': 'net_java_test_support', 'type': 'none', 'variables':", "'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h',", "'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h',", "'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h',", "'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h',", "'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc',", "'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc',", "'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h',", "following tests are disabled because the # implementation is missing", "mmap() is inefficient on some Android devices. # If this", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java', ], 'includes': [ '../build/java.gypi' ],", "'../net/android/javatests', }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java', ], 'includes': [", "['inside_chromium_build==1 and OS != \"ios\"', { 'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto', ],", "'quic_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net', 'quic_library',", "tests crash when run with coverage turned on due to", "'http_server', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [", "'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl',", "'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h',", "'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc',", "], }, ], }], # Special target to wrap a", "'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h',", "'variables': { 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions': [ { 'action_name': 'net_resources',", "'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h',", "'sources': [ 'tools/fetch/fetch_client.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc',", "'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc',", "http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc',", "truncations. 'msvs_disabled_warnings': [4267, ], }, ], 'conditions': [ ['use_v8_in_net ==", "'../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/crash_cache/crash_cache.cc', ], # TODO(jschuh):", "'../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources', ], 'sources': [ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h',", "# When building for OpenSSL, we need to exclude NSS", "'link_settings': { 'ldflags': [ '<!@(krb5-config --libs gssapi)', ], }, },", "'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ], }], [ 'use_openssl==1',", "], }], [ 'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus',", "}, { 'target_name': 'tld_cleanup', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n',", "'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h',", "'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc',", "'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc',", "[ 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', ], }], ['OS == \"ios\"',", "[ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc',", "'<(SHARED_INTERMEDIATE_DIR)/net', ], }, 'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name':", "'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc',", "'target_name': 'net_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl',", "The following tests are disabled because the # implementation is", "'dependencies': [ '../build/linux/system.gyp:libresolv', ], }], ['OS==\"solaris\"', { 'link_settings': { 'ldflags':", "'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h',", "'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc',", "{ 'java_in_dir': '../net/android/java', }, 'dependencies': [ '../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java',", "'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h',", "Copyright 2013 The Chromium Authors. All rights reserved. # Use", "'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc',", "'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h',", "}, { 'target_name': 'net_java_test_support', 'type': 'none', 'variables': { 'java_in_dir': '../net/test/android/javatests',", "'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h',", "'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc',", "'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc',", "TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', # Needs GetAppOutput(). 'test/python_utils_unittest.cc',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'crl_set_dump', 'type':", "'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc',", "'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc',", "'target_name': 'net_test_support', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest',", "[ '/usr/include/kerberosV' ], }], ['linux_link_kerberos==1', { 'link_settings': { 'ldflags': [", "'http/md4.cc', 'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc',", "], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib',", "'sources': [ 'android/java/PrivateKeyType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'],", "'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc',", "'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h',", "\"android\"', { 'sources/': [ ['include', '^base/platform_mime_util_linux\\\\.cc$'], ], }], ['OS ==", "'$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ], }, }, ], ['OS==\"android\" and _toolset==\"target\"", "'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc',", "use_openssl==0, use NSS 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ['os_bsd==1', {", "], }], ['linux_link_kerberos==1', { 'link_settings': { 'ldflags': [ '<!@(krb5-config --libs", "\"android\"', { 'sources!': [ 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', ], }],", "'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h',", "'url_request/url_request_throttler_manager.cc', 'url_request/url_request_throttler_manager.h', 'url_request/view_cache_helper.cc', 'url_request/view_cache_helper.h', 'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h',", "'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h',", "'android/java/CertificateMimeType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'], }, 'includes':", "'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc',", "'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h',", "read input data files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', # Need", "'sources': [ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ], 'conditions': [ [ 'use_v8_in_net==1',", "], }, { 'target_name': 'private_key_types_java', 'type': 'none', 'sources': [ 'android/java/PrivateKeyType.template',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], ], },", "'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/crash_cache/crash_cache.cc', ],", "'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc',", "'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h',", "{ 'target_name': 'net_javatests', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/javatests', },", "'android/java/CertVerifyResultAndroid.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'], }, 'includes':", "'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h',", "'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc',", "], }], ], }, { # use_kerberos == 0 'sources!':", "'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h',", "'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc',", "be compiled on the platform. { 'target_name': 'crash_cache', 'type': 'executable',", "'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc',", "'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h',", "'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc',", "], }], ['use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], 'conditions': [", "}], ['linux_link_kerberos==1', { 'link_settings': { 'ldflags': [ '<!@(krb5-config --libs gssapi)',", "'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h',", "'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h',", "'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ], # TODO(jschuh): crbug.com/167187 fix", "'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h',", "in the above list 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc',", "'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h',", "1', { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }, { # else", "copy step on windows. # TODO(mark): Specifying this here shouldn't", "'sources': [ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ], #", "'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc',", "== 0 'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ], }],", "'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc',", "'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc',", "# See base.gyp for TODO(jrg)s about this strategy. ['OS ==", "'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc',", "tests. # TODO(bulach): Add equivalent tests when the underlying #", "is ported to OpenSSL. 'sources!': [ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ],", "is set, we hackily avoid using mmap() in the disk", "use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ],", "'net', ], 'sources': [ 'tools/crl_set_dump/crl_set_dump.cc', ], # TODO(jschuh): crbug.com/167187 fix", "[ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ], }, ], [ 'OS == \"android\"',", "the disk cache. # We are pretty confident that mmap-ing", "'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8',", "'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h',", "windows. # TODO(mark): Specifying this here shouldn't be necessary. 'dependencies':", "[ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], }, ], [ 'OS ==", "'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings': { 'include_dirs':", "['os_posix == 1 and OS != \"mac\" and OS !=", "'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h',", "{ 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ], 'sources!': [ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc',", "], }, { # use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix.cc',", "'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc',", "'none', 'sources': [ 'android/java/NetError.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps':", "'$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ] }, }, ], [ 'OS == \"ios\"',", "'target_name': 'run_testserver', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support',", "'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h',", "'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h',", "!use_openssl: remove the unneeded files 'sources!': [ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc',", "'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc',", "'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h',", "'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc',", "}, ], }], ['OS != \"ios\"', { 'targets': [ #", "'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h',", "# can't be compiled on the platform. { 'target_name': 'crash_cache',", "'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h',", "'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h',", "}, { # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ],", "'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc',", "'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable', 'OS',", "{ 'target_name': 'crash_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support',", "are pretty confident that mmap-ing the index would not hurt", "'target_name': 'private_key_types_java', 'type': 'none', 'sources': [ 'android/java/PrivateKeyType.template', ], 'variables': {", "'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c',", "ported to iOS. 'base/keygen_handler_unittest.cc', # Need to read input data", "}], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], }, ],", "int truncations. 'msvs_disabled_warnings': [4267, ], }, ], }], ['os_posix ==", "'net', ], 'sources': [ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc',", "'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc',", "'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h', 'base/address_family.h',", "'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h',", "== \"android\"', { 'sources/': [ ['include', '^base/platform_mime_util_linux\\\\.cc$'], ], }], ['OS", "'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], }, { # else !use_openssl: remove", "'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h',", "'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc',", "'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h',", "else 'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }], ['disable_ftp_support==1', { 'sources/': [", "'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc',", "'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc',", "!= 1', { 'sources!': [ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ], }],", "{ 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h',", "coverage turned on due to an # issue with llvm_gcda_increment_indirect_counter:", "tests crash when run with coverage turned on: # http://crbug.com/177203", "'target_name': 'flip_in_mem_edsm_server', 'type': 'executable', 'cflags': [ '-Wno-deprecated', ], 'dependencies': [", "'../base/base.gyp:base', ], 'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h',", "here shouldn't be necessary. [ 'OS == \"win\"', { 'dependencies':", "[ 'net_javatests', 'net_test_jni_headers', ], }], [ 'use_glib == 1', {", "'<(PRODUCT_DIR)/net_unittests.isolated', ], 'action': [ 'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)', '--variable',", "[ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h',", "'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc',", "'../base/allocator/allocator.gyp:allocator', ], }], ], }], [ 'use_kerberos==1', { 'defines': [", "'target_name': 'stress_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ],", "}], ['OS != \"ios\"', { 'targets': [ # iOS doesn't", "], 'defines': [ 'NET_IMPLEMENTATION', ], 'export_dependent_settings': [ '../base/base.gyp:base', ], 'conditions':", "'dependencies': [ '../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java', ], 'includes': [", "'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h',", "'includes': [ 'net_unittests.isolate', ], 'actions': [ { 'action_name': 'isolate', 'inputs':", "[ '../build/android/java_cpp_template.gypi' ], }, ], }], # Special target to", "'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc',", "'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources':", "on some Android devices. # If this flag is set,", "'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ], 'conditions': [", "'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h',", "'defines': [ 'NET_IMPLEMENTATION', ], 'sources': [ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h',", "], }, 'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_test_jni_headers',", "'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ], }, ], [", "'http/http_version.h', 'http/md4.cc', 'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h',", "'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h',", "[ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/crl_set_dump/crl_set_dump.cc', ], # TODO(jschuh):", "'net', 'net_with_v8', ], 'sources': [ 'tools/fetch/fetch_client.cc', ], # TODO(jschuh): crbug.com/167187", "'net', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [", "'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc',", "['OS==\"android\"', { 'targets': [ { 'target_name': 'net_jni_headers', 'type': 'none', 'sources':", "0, 'conditions': [ ['chromeos==1 or OS==\"android\" or OS==\"ios\"', { #", "'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc',", "'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc',", "{ 'sources!': [ # No res_ninit() et al on Android,", "], }], ['OS == \"ios\"', { 'sources/': [ ['include', '^base/network_change_notifier_mac\\\\.cc$'],", "'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h',", "'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ], }, ], [ 'OS == \"win\"', {", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/crl_set_dump/crl_set_dump.cc',", "'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings': {", "0, # iOS does not use V8. 'use_v8_in_net%': 0, 'enable_built_in_dns%':", "'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc',", "[ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib',", "'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc',", "'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc',", "with coverage turned on: # http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ], }], ],", "'tools/flip_server/split.cc', ], }, { 'target_name': 'flip_in_mem_edsm_server', 'type': 'executable', 'cflags': [", "[ 'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ], },", "'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp',", "'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [", "[ 'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ],", "[ 'android/java/NetError.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/net_error_list.h'], },", "'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ], }], [ 'enable_websockets != 1', { 'sources/':", "'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h',", "'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc',", "'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net', ], }, 'includes': [ '../build/jni_generator.gypi' ], },", "'package_name': 'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], },", "after the # platform rules. ['OS == \"android\"', { 'sources/':", "'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h',", "'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ['os_bsd==1', { 'sources!': [ 'base/network_change_notifier_linux.cc',", "'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h',", "'../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], 'conditions': [ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl',", "platform rules, but they # are needed in specific cases", "The Chromium Authors. All rights reserved. # Use of this", "'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc',", "\"ios\"', { 'conditions': [ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ],", "'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h', 'base/address_family.h', 'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc',", "[ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], # TODO(jschuh):", "'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h',", "{ 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }],", "'type': 'none', 'sources': [ 'android/java/PrivateKeyType.template', ], 'variables': { 'package_name': 'org/chromium/net',", "[ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'disk_cache/stress_cache.cc', ], #", "# use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc',", "'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc',", "'cflags': [ '-Wno-deprecated', ], 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net',", "], }, { # else !use_openssl: remove the unneeded files", "# TODO(tc): gnome-vfs? xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h',", "# definition is not used. The following files are needed", "'^ocsp/nss_ocsp\\\\.h$'], ], }], ], }, { 'target_name': 'net_unittests', 'type': '<(gtest_target_type)',", "does not use V8. 'use_v8_in_net%': 0, 'enable_built_in_dns%': 0, }, {", "{ 'dependencies': [ 'net_with_v8', ], }, ], ], # TODO(jschuh):", "{ 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], }, ], ], 'sources':", "'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc',", "], }, { 'target_name': 'stress_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h',", "'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h',", "'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h',", "], 'conditions': [ ['coverage != 0', { 'sources!': [ #", "'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc',", "1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ], }, ], [ 'os_posix", "socket stream are not used on iOS. 'enable_websockets%': 0, #", "'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h',", "'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc',", "}, 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'server/http_connection.cc', 'server/http_connection.h',", "'sources!': [ 'cert/x509_cert_types_unittest.cc', ], }], ], }, { 'target_name': 'net_perftests',", "], 'sources': [ 'disk_cache/stress_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'type': 'none', 'dependencies': [ 'net_java', 'net_javatests', 'net_unittests', ], 'variables': {", "'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc',", "be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], #", "'OS == \"win\"', { 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], # TODO(jschuh):", "OS != \"android\" 'defines': [ # These are the features", "the # platform rules. ['OS == \"android\"', { 'sources/': [", "], 'test_data_prefix': 'net', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ],", "'../v8/tools/gyp/v8.gyp:v8', 'net' ], 'defines': [ 'NET_IMPLEMENTATION', ], 'sources': [ 'proxy/proxy_resolver_v8.cc',", "'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc',", "'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h',", "}], ['OS==\"android\"', { 'targets': [ { 'target_name': 'net_jni_headers', 'type': 'none',", "], }, { # use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc',", "'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc',", "'../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc',", "platforms. Re-including them can # only be done in target_conditions", "'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc',", "the unneeded files 'sources!': [ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ], },", "'include_dirs': [ '/usr/include/kerberosV' ], }], ['linux_link_kerberos==1', { 'link_settings': { 'ldflags':", "[ 'dns/dns_config_service_posix_unittest.cc', ], }, ], ['OS == \"android\" and gtest_target_type", "1, 'enable_built_in_dns%': 1, }], ], }, 'includes': [ '../build/win_precompile.gypi', ],", "{ # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_perftest.cc', ], }, ],", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc',", "['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'],", "tests are disabled because the # implementation is missing or", "}, { 'target_name': 'dump_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net',", "[ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net', 'quic_library', ], 'sources': [ 'quic/test_tools/quic_session_peer.cc',", "'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h',", "not ported to iOS. 'base/keygen_handler_unittest.cc', # Need to read input", "}], ['posix_avoid_mmap==1', { 'defines': [ 'POSIX_AVOID_MMAP', ], 'direct_dependent_settings': { 'defines':", "'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h',", "], }, { 'target_name': 'tld_cleanup', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'socket/ssl_server_socket_unittest.cc', # Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', #", "'conditions': [ [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], },", "{ 'target_name': 'fetch_client', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1, },", "'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h',", "'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h',", "# Needs GetAppOutput(). 'test/python_utils_unittest.cc', # The following tests are disabled", "'includes': [ '../build/grit_action.gypi' ], }, ], 'includes': [ '../build/grit_target.gypi' ],", "'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc',", "'net', ], 'sources': [ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc',", "'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables': {", "'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h',", "'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc',", "'<@(_outputs)', '--isolate', 'net_unittests.isolate', ], }, ], }, ], }], ],", "and so on). 'use_kerberos%': 0, }, { # chromeos ==", "In particular the |USE_NSS| preprocessor # definition is not used.", "'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ], } ] }], ['OS==\"android\"',", "'<@(isolate_dependency_tracked)', ], 'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated', ], 'action': [ 'python', '../tools/swarm_client/isolate.py',", "'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc',", "'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h',", "[ '-R/usr/lib/mps', ], }, }], ], }, { # else:", "'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ], # TODO(jschuh): crbug.com/167187", "], ], 'target_conditions': [ # These source files are excluded", "'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ], 'conditions': [ [ 'use_v8_in_net==1', { 'dependencies':", "the # variety of ARM devices. So enable it for", "'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc',", "'proxy/proxy_resolver_perftest.cc', ], }, ], # This is needed to trigger", "'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ], 'conditions': [ [ 'use_v8_in_net==1', { 'dependencies': [", "'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc',", "], 'includes': [ 'net_unittests.isolate', ], 'actions': [ { 'action_name': 'isolate',", "'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc',", "'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc',", "], }, ], [ 'use_glib == 1', { 'dependencies': [", "'target_name': 'crash_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ],", "'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc',", "only be done in target_conditions as it is evaluated after", "'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc',", "'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h',", "'../build/copy_test_data_ios.gypi' ], }, ], 'sources!': [ # TODO(droger): The following", "{ 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', ], },", "'include_dirs': [ '../third_party/openssl', ], }, { # else OS !=", "] }], [ 'OS != \"win\" and OS != \"mac\"',", "{ # chromeos == 0 'use_kerberos%': 1, }], ['OS==\"android\" and", "'../base/base.gyp:base', 'net', ], 'sources': [ 'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc',", "'../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_client_bin.cc', ], },", "'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc',", "'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h',", "'../third_party/openssl/openssl.gyp:openssl', ], }, { # else use_openssl==0, use NSS 'dependencies':", "a lot of # sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies': [", "'http/des.cc', 'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc',", "'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc',", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_watcher', 'type': 'executable', 'dependencies':", "'--outdir', '<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable', 'OS', '<(OS)', '--result', '<@(_outputs)',", "'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc',", "'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc',", "'../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support', ], 'sources': [ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc',", "{ 'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ],", "gtest_target_type == \"shared_library\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ] }], [", "is inefficient on some Android devices. # If this flag", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_client', 'type':", "[ '../build/java.gypi' ], }, { 'target_name': 'net_errors_java', 'type': 'none', 'sources':", "{ 'targets': [ { 'target_name': 'flip_balsa_and_epoll_library', 'type': 'static_library', 'dependencies': [", "# else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_perftest.cc', ], }, ], #", "'ssl/client_cert_store_impl_nss.cc', ], }], [ 'enable_websockets != 1', { 'sources/': [", "step on windows. # TODO(mark): Specifying this here shouldn't be", "{ 'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto', ], }], ['os_posix == 1 and", "'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc',", "'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h',", "truncations. 'msvs_disabled_warnings': [4267, ], }, ], [ 'OS == \"mac\"',", "'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h',", "['exclude', '^websockets/'], ], 'sources!': [ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ], }], [", "'../build/grit_target.gypi' ], }, { 'target_name': 'http_server', 'type': 'static_library', 'variables': {", "'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc',", "OS==\"ios\"', { # Disable Kerberos on ChromeOS, Android and iOS,", "'targets': [ { 'target_name': 'net_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java',", "'quic_server', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ],", "'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h',", "'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc',", "], }], ], }], [ 'OS == \"linux\"', { 'dependencies':", "'static_library', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', 'net',", "{ 'target_name': 'net_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc',", "[4267, ], }, { 'target_name': 'fetch_client', 'type': 'executable', 'variables': {", "'../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h',", "files are excluded by default platform rules, but they #", "'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc',", "# toolchain bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', # These tests crash when", "'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h',", "list 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc',", "[ 'USE_KERBEROS', ], }, { # use_kerberos == 0 'sources!':", "'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h',", "'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h',", "'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h',", "'target_name': 'gdig', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources':", "}, ], ], }, { 'target_name': 'net_test_support', 'type': 'static_library', 'dependencies':", "'target_name': 'fetch_client', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies':", "'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc',", "These are the features Android doesn't support. 'ENABLE_MEDIA_CODEC_THEORA', ], },", "], [ 'OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl',", "], }, ], [ 'OS == \"android\"', { 'dependencies': [", "'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ], # TODO(jschuh): crbug.com/167187 fix", "'target_name': 'certificate_mime_types_java', 'type': 'none', 'sources': [ 'android/java/CertificateMimeType.template', ], 'variables': {", "'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h',", "'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h',", "'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ], 'sources!':", "'../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources': [ 'tools/tld_cleanup/tld_cleanup.cc', ], # TODO(jschuh): crbug.com/167187 fix", "}], [ 'OS == \"win\"', { 'sources!': [ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc',", "'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc',", "{ 'sources!': [ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ], }], [ 'OS ==", "'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h',", "'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc',", "'^ftp/'], ], 'sources!': [ 'url_request/url_request_ftp_job_unittest.cc', ], }, ], [ 'enable_built_in_dns!=1',", "'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc',", "[ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h',", "'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc',", "}, { 'target_name': 'quic_client', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl',", "'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc',", "'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h',", "'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', # Needs GetAppOutput(). 'test/python_utils_unittest.cc', # The", "'net_java_test_support', 'type': 'none', 'variables': { 'java_in_dir': '../net/test/android/javatests', }, 'includes': [", "], }], [ 'use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], },", "does not # defines |use_nss|. In particular the |USE_NSS| preprocessor", "'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h',", "'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc',", "}, { 'target_name': 'quic_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock',", "['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }], [ 'disable_ftp_support==1',", "== \"win\"', { 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ], # This", "}, 'sources!': [ 'disk_cache/mapped_file_posix.cc', ], }, { # else 'sources!':", "'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc',", "'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc',", "'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', # TODO(tc): gnome-vfs?", "'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc',", "'../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net' ], 'defines': [ 'NET_IMPLEMENTATION', ], 'sources':", "'includes': [ '../build/win_precompile.gypi', ], 'targets': [ { 'target_name': 'net', 'type':", "\"mac\" and OS != \"ios\" and OS != \"android\"', {", "], }, { 'target_name': 'net_javatests', 'type': 'none', 'variables': { 'java_in_dir':", "'../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support', ],", "'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h',", "], }, { 'target_name': 'net_test_support', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base',", "'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc',", "'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc',", "'variables': { 'chromium_code': 1, 'linux_link_kerberos%': 0, 'conditions': [ ['chromeos==1 or", "# KeygenHandler::GenKeyAndSignChallenge() is not ported to iOS. 'base/keygen_handler_unittest.cc', # Need", "], }, ], 'conditions': [ ['use_v8_in_net == 1', { 'targets':", "'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc',", "unneeded files 'sources!': [ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ], }, ],", "'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc',", "{ 'target_name': 'private_key_types_java', 'type': 'none', 'sources': [ 'android/java/PrivateKeyType.template', ], 'variables':", "['use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], 'conditions': [ ['OS==\"openbsd\"', {", "as it is evaluated after the # platform rules. ['OS", "{ # linux_link_kerberos==0 'defines': [ 'DLOPEN_KERBEROS', ], }], ], },", "'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h',", "'net', ], 'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], # TODO(jschuh): crbug.com/167187 fix", "'../build/win_precompile.gypi', ], 'targets': [ { 'target_name': 'net', 'type': '<(component)', 'variables':", "'sources': [ 'android/java/CertificateMimeType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'],", "'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h',", "'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc',", "'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h',", "}, { 'target_name': 'net_test_jni_headers', 'type': 'none', 'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ],", "], }, { # else 'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }],", "], }], [ 'use_nss != 1', { 'sources!': [ 'cert/cert_verify_proc_nss.cc',", "1, }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch',", "iOS. 'enable_websockets%': 0, # iOS does not use V8. 'use_v8_in_net%':", "], 'sources!': [ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ], # The", "}, ], }], # Special target to wrap a gtest_target_type==shared_library", "{ 'enable_websockets%': 1, 'use_v8_in_net%': 1, 'enable_built_in_dns%': 1, }], ], },", "'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], }, { # else:", "'../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "{ 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], }, ], [", "'net_java', ], 'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_errors_java',", "'conditions': [ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, {", "'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h',", "'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc',", "'type': 'none', 'sources': [ 'android/java/CertificateMimeType.template', ], 'variables': { 'package_name': 'org/chromium/net',", "'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h',", "], 'conditions': [ ['use_v8_in_net == 1', { 'targets': [ {", "'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc',", "al on Android, so this doesn't make a lot of", "'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h',", "{ 'link_settings': { 'ldflags': [ '-R/usr/lib/mps', ], }, }], ],", "'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc',", "['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'], # The iOS implementation only partially", "'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h',", "'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc',", "}, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, ], }], # Special", "'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ], 'dependencies': [", "'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h',", "[4267, ], }, ], ], }, { 'target_name': 'net_test_support', 'type':", "be so sure about the # variety of ARM devices.", "cannot be so sure about the # variety of ARM", "], }, { 'target_name': 'fetch_server', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors':", "tests are disabled because they don't apply to # iOS.", "{ 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], [ 'use_kerberos==1',", "], }], ['OS != \"ios\"', { 'targets': [ # iOS", "['OS==\"ios\"', { # Websockets and socket stream are not used", "devices. # If this flag is set, we hackily avoid", "'variables': { 'java_in_dir': '../net/android/javatests', }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java',", "'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc',", "'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc',", "{ 'target_name': 'stress_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support',", "# TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [4267,", "'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc',", "{ 'target_name': 'quic_client', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net',", "[ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'gdig', 'type':", "}, { # chromeos == 0 'use_kerberos%': 1, }], ['OS==\"android\"", "the index would not hurt any # existing x86 android", "'ftp/ftp_response_info.h', 'ftp/ftp_server_type_histograms.cc', 'ftp/ftp_server_type_histograms.h', 'ftp/ftp_transaction.h', 'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc', 'http/des.h', 'http/http_atom_list.h',", "'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h',", "'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc',", "[ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], }, { #", "with llvm_gcda_increment_indirect_counter: # http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc',", "'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc',", "'net', ], 'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc',", "'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc',", "'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc',", "truncations. 'msvs_disabled_warnings': [4267, ], }, ], }], ['os_posix == 1", "'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h',", "'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc',", "], } ] }], ['OS==\"android\"', { 'targets': [ { 'target_name':", "}, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java', ], 'includes': [ '../build/java.gypi'", "'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h',", "['enable_built_in_dns==1', { 'defines': [ 'ENABLE_BUILT_IN_DNS', ] }, { # else", "'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h',", "'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, ], [", "platform rules. ['OS == \"android\"', { 'sources/': [ ['include', '^base/platform_mime_util_linux\\\\.cc$'],", "== 1 and OS != \"mac\" and OS != \"ios\"", "'tools/get_server_time/get_server_time.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc',", "functionality is ported to OpenSSL. 'sources!': [ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc',", "'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h',", "No res_ninit() et al on Android, so this doesn't make", "}, { 'target_name': 'fetch_client', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1,", "'org/chromium/net', 'template_deps': ['base/net_error_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, {", "], }, { 'target_name': 'certificate_mime_types_java', 'type': 'none', 'sources': [ 'android/java/CertificateMimeType.template',", "'package_name': 'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], },", "'--isolate', 'net_unittests.isolate', ], }, ], }, ], }], ], }", "], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], }, {", "governed by a BSD-style license that can be # found", "so on). 'use_kerberos%': 0, }, { # chromeos == 0", "'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc',", "'quic_client', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ],", "'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, { # else !use_openssl: remove the unneeded", "to OpenSSL. 'sources!': [ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], }, {", "'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc',", "for now. # It needs configuration (krb5.conf and so on).", "'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ], }],", "net_unittests into an android apk for execution. # See base.gyp", "'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ], },", "'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ], }, { 'target_name': 'quic_client', 'type': 'executable',", "TODO(jrg)s about this strategy. ['OS == \"android\" and gtest_target_type ==", "'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc',", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net',", "'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc',", "{ 'target_name': 'net_watcher', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_with_v8',", "], }, ], }], ['os_posix == 1 and OS !=", "'dependencies': [ '../third_party/nss/nss.gyp:nss', ], 'actions': [ { 'action_name': 'copy_test_data', 'variables':", "'dns/address_sorter_unittest.cc', ], }, ], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8',", "}], [ 'OS != \"win\" and OS != \"mac\"', {", "'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc',", "'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc',", "'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h',", "'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', # These tests", "}, ], ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'defines': [ 'NET_IMPLEMENTATION', ], 'export_dependent_settings': [ '../base/base.gyp:base', ], 'conditions': [", "be built with coverage due to a # toolchain bug:", "'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc',", "not \"linux\" or \"freebsd\" or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions': [", "'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc',", "'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc', 'base/escape.h',", "'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc',", "'variables': { 'grit_grd_file': 'base/net_resources.grd', }, 'includes': [ '../build/grit_action.gypi' ], },", "'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_test_jni_headers', 'type': 'none',", "'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc',", "sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies': [ 'net_javatests', 'net_test_jni_headers', ], }],", "'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h',", "'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base',", "Android, so this doesn't make a lot of # sense.", "'template_deps': ['android/private_key_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, ], }],", "'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h', 'base/address_family.h', 'base/address_list.cc',", "], 'sources!': [ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ], }], [ 'OS ==", "'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc',", "ported to OpenSSL. 'sources!': [ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], },", "'../testing/gtest.gyp:gtest', ], 'sources': [ 'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h',", "'use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], }, { # use_kerberos", "'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ], # TODO(jschuh):", "'flip_balsa_and_epoll_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [", "x86 android devices, but we cannot be so sure about", "target to wrap a gtest_target_type==shared_library # net_unittests into an android", "\"android\"', { 'targets': [ { 'target_name': 'flip_balsa_and_epoll_library', 'type': 'static_library', 'dependencies':", "size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], [", "'../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework',", "'<!@(krb5-config --libs gssapi)', ], }, }, { # linux_link_kerberos==0 'defines':", "{ 'defines': [ 'POSIX_AVOID_MMAP', ], 'direct_dependent_settings': { 'defines': [ 'POSIX_AVOID_MMAP',", "'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "'OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings':", "'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc',", "'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc', 'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc',", "'tools/gdig/gdig.cc', ], }, { 'target_name': 'get_server_time', 'type': 'executable', 'dependencies': [", "be # found in the LICENSE file. { 'variables': {", "'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h',", "'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h',", "'tools/quic/test_tools/run_all_unittests.cc', ], } ] }], ['OS==\"android\"', { 'targets': [ {", "'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h',", "0 'sources!': [ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ], }], ['posix_avoid_mmap==1',", "'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_with_v8', ], 'conditions': [ [", "'../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'cert_verify_result_android_java', 'type': 'none', 'sources': [", "OS != \"mac\" and OS != \"android\" and OS !=", "'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h',", "['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'], ], }],", "[ '../third_party/openssl/openssl.gyp:openssl', ], }, { # else use_openssl==0, use NSS", "'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc',", "[ '../base/base.gyp:base', ], 'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux.cc',", "'conditions': [ ['coverage != 0', { 'sources!': [ # These", "'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h',", "[ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc',", "'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc',", "'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc', 'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h',", "'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc',", "'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc',", "'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc',", "'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h',", "'DLOPEN_KERBEROS', ], }], ], }, { # use_kerberos == 0", "'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc', 'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h',", "'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc',", "not # defines |use_nss|. In particular the |USE_NSS| preprocessor #", "{ 'targets': [ { 'target_name': 'net_with_v8', 'type': '<(component)', 'variables': {", "'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc', 'base/static_cookie_policy_unittest.cc', 'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc',", "'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ], }], ['enable_built_in_dns==1', { 'defines': [", "'../build/linux/system.gyp:ssl', ], }, { # else use_glib == 0: !posix", "'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h', 'test/base_test_server.cc', 'test/base_test_server.h', 'test/cert_test_util.cc', 'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc',", "'net_resources', 'variables': { 'grit_grd_file': 'base/net_resources.grd', }, 'includes': [ '../build/grit_action.gypi' ],", "toolchain bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', # These tests crash when run", "'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h',", "the features Android doesn't support. 'ENABLE_MEDIA_CODEC_THEORA', ], }, ], [", "{ 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ], }, ], [ 'OS", "'dns_fuzz_stub', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [", "'target_name': 'net_errors_java', 'type': 'none', 'sources': [ 'android/java/NetError.template', ], 'variables': {", "{ 'target_name': 'net', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, },", "are not used on iOS. 'enable_websockets%': 0, # iOS does", "1, }], ], }, 'includes': [ '../build/win_precompile.gypi', ], 'targets': [", "'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h',", "'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h',", "# use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h',", "'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h',", "}, { 'target_name': 'net_errors_java', 'type': 'none', 'sources': [ 'android/java/NetError.template', ],", "'inputs': [ 'net_unittests.isolate', '<@(isolate_dependency_tracked)', ], 'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated', ], 'action':", "'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc',", "'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ], }], ['use_kerberos==1', { 'defines':", "'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h',", "{ 'dependencies': [ '../build/linux/system.gyp:gtk', ], }, ], [ 'os_posix ==", "}, ], [ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:gconf',", "following files are needed though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include',", "'android/java/PrivateKeyType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'], }, 'includes':", "[ 'net_java', ], }], [ 'OS == \"android\"', { 'dependencies':", "'grit_grd_file': 'base/net_resources.grd', }, 'includes': [ '../build/grit_action.gypi' ], }, ], 'includes':", "!= \"ios\"', { 'targets': [ # iOS doesn't have the", "'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_client_bin.cc',", "Need to read input data files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc',", "'get_server_time', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ],", "'../build/linux/system.gyp:gdk', ], }], [ 'use_nss != 1', { 'sources!': [", "'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java', ], 'includes': [ '../build/java.gypi' ], }, {", "'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc',", "to a # toolchain bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', # These tests", "[ # These source files are excluded by default platform", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_server', 'type': 'executable',", "'target_name': 'cert_verify_result_android_java', 'type': 'none', 'sources': [ 'android/java/CertVerifyResultAndroid.template', ], 'variables': {", "}], ], }], [ 'OS == \"linux\"', { 'dependencies': [", "'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h',", "'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc',", "[ '../build/linux/system.gyp:libresolv', ], }], ['OS==\"solaris\"', { 'link_settings': { 'ldflags': [", "'sources!': [ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ], }], ['posix_avoid_mmap==1', {", "['include', '^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'],", "['OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], }], [", "'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc',", "and OS != \"ios\"', { 'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto', ], }],", "'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc',", "'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, {", "'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h',", "'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h',", "stream are not used on iOS. 'enable_websockets%': 0, # iOS", "\"mac\" and OS != \"android\" and OS != \"ios\"', {", "{ # else use_glib == 0: !posix || mac 'sources!':", "'none', 'sources': [ 'android/java/CertificateMimeType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps':", "'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, {", "'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc',", "[ '../build/copy_test_data_ios.gypi' ], }, ], 'sources!': [ # TODO(droger): The", "{ 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ],", "OS != \"ios\" and OS != \"android\"', { 'targets': [", "[ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ], },", "[ 'data/ssl/certificates/', 'data/url_request_unittest/', ], 'test_data_prefix': 'net', }, 'includes': [ '../build/copy_test_data_ios.gypi'", "}, ], ], 'target_conditions': [ # These source files are", "'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h',", "'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc',", "[ '<(SHARED_INTERMEDIATE_DIR)/net', ], }, 'includes': [ '../build/jni_generator.gypi' ], }, {", "[4267, ], }, ], [ 'OS == \"mac\"', { 'dependencies':", "}], ['OS==\"android\" and target_arch != \"ia32\"', { # The way", "[ '../third_party/openssl', ], }, { # else OS != \"android\"", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], }], ['os_posix", "'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h',", "'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc',", "'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_javatests', 'type': 'none',", "'../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support', ], 'sources': [ 'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc',", "'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ], }, ], ], 'target_conditions': [", "'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net',", "'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h',", "== \"android\" and gtest_target_type == \"shared_library\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code',", "'dns/dns_response.h', 'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc',", "'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h',", "[ 'use_nss != 1', { 'sources!': [ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc',", "'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ], # TODO(jschuh): crbug.com/167187", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dump_cache',", "0', { 'dependencies': [ 'net_java', ], }], [ 'OS ==", "'sources!': [ 'url_request/url_request_ftp_job_unittest.cc', ], }, ], [ 'enable_built_in_dns!=1', { 'sources!':", "'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc',", "# TODO(bulach): Add equivalent tests when the underlying # functionality", "['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], ['OS", "platform. { 'target_name': 'crash_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net',", "this doesn't make a lot of # sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc',", "[ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ], }], ['use_kerberos==1',", "to read input data files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', #", "{ 'targets': [ { 'target_name': 'net_unittests_run', 'type': 'none', 'dependencies': [", "'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc',", "'../third_party/nss/nss.gyp:nss', ], 'actions': [ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files':", "needs to # access an OpenSSL-internal header. 'include_dirs': [ '../third_party/openssl',", "'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h',", "'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc',", "'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc',", "'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc',", "underlying # functionality is ported to OpenSSL. 'sources!': [ 'cert/nss_cert_database_unittest.cc',", "and OS != \"ios\" and OS != \"android\"', { 'targets':", "android_webview_build == 0', { 'dependencies': [ 'net_java', ], }], [", "[ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [", "{ 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ], },{ 'dependencies': [", "[ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ], }, ], [ 'enable_websockets !=", "windows. # TODO(mark): Specifying this here shouldn't be necessary. [", "}], [ 'enable_websockets != 1', { 'sources/': [ ['exclude', '^socket_stream/'],", "'sources!': [ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], }, { # else", "[ 'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc',", "{ 'target_name': 'cert_verify_result_android_java', 'type': 'none', 'sources': [ 'android/java/CertVerifyResultAndroid.template', ], 'variables':", "or \"freebsd\" or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions': [ ['coverage !=", "'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h',", "'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', ], }, ],", "size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], 'conditions':", "'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h',", "}], ], }, { 'target_name': 'net_unittests', 'type': '<(gtest_target_type)', 'dependencies': [", "'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ], }], ['use_kerberos==1', { 'defines': [ 'USE_KERBEROS',", "'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', 'udp/udp_socket_win.cc', 'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc',", "[ 'USE_KERBEROS', ], 'conditions': [ ['OS==\"openbsd\"', { 'include_dirs': [ '/usr/include/kerberosV'", "'websockets/websocket_throttle_unittest.cc', ], 'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc',", "'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_with_v8', ], 'sources':", "[ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources': [ 'tools/tld_cleanup/tld_cleanup.cc', ], #", "], }], ['OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ],", "], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/net_error_list.h'], }, 'includes': [", "['android/cert_verify_result_android_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'private_key_types_java',", "'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc',", "OS is not in the above list 'sources!': [ 'base/crypto_module_nss.cc',", "{ 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ], }, ], ], 'target_conditions':", "'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc',", "'spdy/spdy_test_util_spdy2.h', 'spdy/spdy_test_utils.cc', 'spdy/spdy_test_utils.h', 'spdy/spdy_websocket_stream_spdy2_unittest.cc', 'spdy/spdy_websocket_stream_spdy3_unittest.cc', 'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc',", "'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc',", "], [ 'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus',", "'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc',", "'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc',", "'net_test_support', ], 'sources': [ 'tools/crash_cache/crash_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix", "}], ['OS==\"ios\"', { # Websockets and socket stream are not", "[ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ], }, { 'target_name': 'get_server_time', 'type': 'executable',", "'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc',", "'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ], },", "iOS implementation only partially uses NSS and thus does not", "'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h',", "devices. So enable it for x86 only for now. 'posix_avoid_mmap%':", "'android/network_library.cc', 'android/network_library.h', 'base/address_family.h', 'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc',", "'quic/quic_stats.h', 'quic/quic_stream_factory.cc', 'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc',", "'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h',", "'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp',", "'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc',", "'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h',", "'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc',", "'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc',", "'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc',", "], 'sources': [ 'tools/net_watcher/net_watcher.cc', ], }, { 'target_name': 'run_testserver', 'type':", "'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc',", "'ssl/client_cert_store_impl_nss.cc', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': {", "'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc',", "'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', ], }], ['OS == \"ios\"', {", "'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h',", "'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h',", "'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h', 'server/web_socket.cc', 'server/web_socket.h', ], #", "[ 'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ],", "'../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h',", "'crash_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources':", "doesn't have the concept of simple executables, these targets #", "'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h',", "'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc',", "devices, but we cannot be so sure about the #", "'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc',", "}, ], [ 'OS == \"mac\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nspr',", "'NET_IMPLEMENTATION', ], 'sources': [ 'proxy/proxy_resolver_v8.cc', 'proxy/proxy_resolver_v8.h', 'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h',", "'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc',", "'type': 'none', 'sources': [ 'android/java/CertVerifyResultAndroid.template', ], 'variables': { 'package_name': 'org/chromium/net',", "] }, { # else 'sources!': [ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc',", "'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h', 'cookies/cookie_util.cc', 'cookies/cookie_util.h', 'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h',", "If this flag is set, we hackily avoid using mmap()", "'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ], }, { 'target_name': 'quic_client', 'type':", "'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc',", "'data/url_request_unittest/', ], 'test_data_prefix': 'net', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], },", "'sources': [ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h',", "'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc',", "[ [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], }, {", "'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h', 'quic/quic_stream_factory.cc',", "'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h',", "[ 'net_with_v8', ], }, ], ], # TODO(jschuh): crbug.com/167187 fix", "'http/http_auth_handler_negotiate.cc', ], }], ['posix_avoid_mmap==1', { 'defines': [ 'POSIX_AVOID_MMAP', ], 'direct_dependent_settings':", "'target_name': 'net_javatests', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/javatests', }, 'dependencies':", "[ 'enable_websockets != 1', { 'sources/': [ ['exclude', '^socket_stream/'], ['exclude',", "LICENSE file. { 'variables': { 'chromium_code': 1, 'linux_link_kerberos%': 0, 'conditions':", "simple executables, these targets # can't be compiled on the", "'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net',", "'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h',", "'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h',", "[ 'POSIX_AVOID_MMAP', ], 'direct_dependent_settings': { 'defines': [ 'POSIX_AVOID_MMAP', ], },", "{ 'target_name': 'net_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java',", "'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc',", "[ 'use_openssl==1', { # When building for OpenSSL, we need", "== 1', { 'targets': [ { 'target_name': 'net_with_v8', 'type': '<(component)',", "{ 'package_name': 'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ],", "on). 'use_kerberos%': 0, }, { # chromeos == 0 'use_kerberos%':", "'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc',", "'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ], }], ['os_posix == 1", "'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc',", "'sources': [ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc',", "# If this flag is set, we hackily avoid using", "'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc',", "{ # else: OS is not in the above list", "[ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], 'conditions': [ ['use_openssl==1', { 'dependencies': [", "'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/url_request_ftp_job_unittest.cc', ], },", "when run with coverage turned on due to an #", "}], [ 'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support',", "'../build/java.gypi' ], }, { 'target_name': 'net_javatests', 'type': 'none', 'variables': {", "{ 'package_name': 'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ],", "'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ], 'defines': [ 'NET_IMPLEMENTATION', ],", "'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h',", "'target_conditions': [ # These source files are excluded by default", "'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h',", "'tools/fetch/http_session.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h', 'cert/multi_threaded_cert_verifier.cc', 'cert/multi_threaded_cert_verifier.h', 'cert/nss_cert_database.cc',", "'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc', 'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h',", "'../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources': [ 'tools/tld_cleanup/tld_cleanup.cc',", "'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc', ], }, {", "\"freebsd\" or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions': [ ['coverage != 0',", "'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc',", "'fetch_client', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [", "'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h',", "'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h',", "'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h',", "'net_with_v8', ], }, { # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_perftest.cc',", "See base.gyp for TODO(jrg)s about this strategy. ['OS == \"android\"", "to wrap a gtest_target_type==shared_library # net_unittests into an android apk", "'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h', 'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h',", "'sources!': [ 'cert/nss_cert_database_unittest.cc', ], }, ], [ 'toolkit_uses_gtk == 1',", "'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc',", "'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', ], }], ['use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ],", "'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc',", "[ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ], # TODO(jschuh): crbug.com/167187 fix", "'net', ], 'sources': [ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ], }, { 'target_name':", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support', ], 'sources':", "here shouldn't be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl',", "'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc',", "'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc',", "], ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "], [ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio',", "], [ 'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gdk', ],", "1 and OS != \"mac\" and OS != \"android\" and", "the unneeded files 'sources!': [ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc',", "'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h',", "], 'conditions': [ ['inside_chromium_build==1 and OS != \"ios\"', { 'dependencies':", "'sources!': [ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h',", "{ 'sources!': [ 'ssl/client_cert_store_impl_nss.cc', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl',", "'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h',", "'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc',", "size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, { #", "'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h',", "], }, { 'target_name': 'dump_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h',", "implementation only partially uses NSS and thus does not #", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/gdig/file_net_log.cc',", "'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h',", "'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc',", "'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc',", "the platform. { 'target_name': 'crash_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc',", "'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support', ], 'sources': [", "# sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies': [ 'net_javatests', 'net_test_jni_headers', ],", "'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h',", "'cert/test_root_certs_openssl.cc', ], # The net/android/keystore_openssl.cc source file needs to #", "'use_v8_in_net%': 1, 'enable_built_in_dns%': 1, }], ], }, 'includes': [ '../build/win_precompile.gypi',", "'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'data/ssl/certificates/', 'data/url_request_unittest/', ], 'test_data_prefix':", "'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc',", "[ 'tools/crl_set_dump/crl_set_dump.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc',", "}, ], ['OS==\"android\" and _toolset==\"target\" and android_webview_build == 0', {", "'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc',", "'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h',", "'OS == \"win\"', { 'sources!': [ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc',", "['OS == \"android\" and gtest_target_type == \"shared_library\"', { 'dependencies': [", "'tools/quic/quic_server_bin.cc', ], }, { 'target_name': 'quic_unittests', 'type': '<(gtest_target_type)', 'dependencies': [", "Authors. All rights reserved. # Use of this source code", "'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc', 'base/prioritized_dispatcher.h', 'base/priority_queue.h', 'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h',", "'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc',", "'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ], }], [ 'use_openssl==1', { #", "'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc',", "], }, ], 'sources!': [ # TODO(droger): The following tests", "'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ], }, { 'target_name':", "'net_watcher', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_with_v8', ], 'conditions':", "'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h',", "[ 'OS == \"android\"', { 'sources!': [ # No res_ninit()", "'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h',", "[ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }], [", "[ 'android/java/CertVerifyResultAndroid.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'], },", "'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc',", "'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc',", "'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc',", "}], [ 'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers',", "'target_name': 'flip_balsa_and_epoll_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources':", "'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc',", "{ 'target_name': 'net_with_v8', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, },", "{ 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/net', ], }, 'includes': [ '../build/jni_generator.gypi' ],", "'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h',", "don't apply to # iOS. # OS is not \"linux\"", "[ 'net_unittests.isolate', '<@(isolate_dependency_tracked)', ], 'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated', ], 'action': [", "'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc',", "[ ['use_v8_in_net == 1', { 'targets': [ { 'target_name': 'net_with_v8',", "[ '../build/apk_test.gypi' ], }, ], }], ['test_isolation_mode != \"noop\"', {", "'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h',", "'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h',", "'^ftp/'], ], 'sources!': [ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', ], }],", "'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc',", "'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc',", "turned on due to an # issue with llvm_gcda_increment_indirect_counter: #", "# existing x86 android devices, but we cannot be so", "'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h',", "the cache uses mmap() is inefficient on some Android devices.", "'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc',", "], }, ], [ 'OS == \"ios\"', { 'dependencies': [", "'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h',", "'../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support',", "'sources!': [ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ], # The net/android/keystore_openssl.cc", "'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h',", "}], ], }], ['os_posix == 1 and OS != \"mac\"", "[ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java', ], 'includes': [ '../build/java.gypi' ], },", "'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc',", "'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h',", "1', { 'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'],", "'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc', 'base/net_util.h',", "'../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support', ], 'sources': [ 'tools/testserver/run_testserver.cc', ], },", "'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h',", "], }, ], ], # TODO(jschuh): crbug.com/167187 fix size_t to", "[4267, ], }, { 'target_name': 'dns_fuzz_stub', 'type': 'executable', 'dependencies': [", "'certificate_mime_types_java', 'type': 'none', 'sources': [ 'android/java/CertificateMimeType.template', ], 'variables': { 'package_name':", "at least for now. # It needs configuration (krb5.conf and", "['OS == \"android\"', { 'sources/': [ ['include', '^base/platform_mime_util_linux\\\\.cc$'], ], }],", "'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc',", "'net_with_v8', ], 'sources': [ 'tools/fetch/fetch_client.cc', ], # TODO(jschuh): crbug.com/167187 fix", "{ 'targets': [ { 'target_name': 'net_jni_headers', 'type': 'none', 'sources': [", "TODO(droger): The following tests are disabled because the # implementation", "'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc',", "cache uses mmap() is inefficient on some Android devices. #", "'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc',", "'^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include',", "'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc',", "'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc',", "'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc',", "'sources': [ 'tools/tld_cleanup/tld_cleanup.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables': { 'jni_gen_package': 'net', },", "'enable_built_in_dns%': 0, }, { 'enable_websockets%': 1, 'use_v8_in_net%': 1, 'enable_built_in_dns%': 1,", "any # existing x86 android devices, but we cannot be", "'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc',", "'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc',", "'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc',", "concept of simple executables, these targets # can't be compiled", "'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc',", "[ 'disk_cache/mapped_file_posix.cc', ], }, { # else 'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc',", "'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc',", "# are needed in specific cases on other platforms. Re-including", "'disk_cache/net_log_parameters.h', 'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h',", "'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc',", "'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base',", "== \"android\"', { 'sources!': [ # No res_ninit() et al", "'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ], 'conditions': [ ['inside_chromium_build==1", "'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ],", "'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc',", "'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'disk_cache/stress_cache.cc', ],", "'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc',", "\"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ], }, ], ],", "Android devices. # If this flag is set, we hackily", "'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h',", "'http/http_auth_handler_negotiate_unittest.cc', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', ], }], [ 'use_openssl==1', { # When", "'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc', 'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc',", "'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h', 'ftp/ftp_auth_cache.cc', 'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h',", "'tools/net_watcher/net_watcher.cc', ], }, { 'target_name': 'run_testserver', 'type': 'executable', 'dependencies': [", "NSS 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ['os_bsd==1', { 'sources!': [", "'base/net_resources.grd', }, 'includes': [ '../build/grit_action.gypi' ], }, ], 'includes': [", "'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc',", "'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h',", "'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc',", "when the underlying # functionality is ported to OpenSSL. 'sources!':", "'../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources', ], 'sources': [ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h',", "['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }], [ 'disable_ftp_support==1', { 'sources/': [ ['exclude',", "'dependencies': [ 'net_with_v8', ], }, ], ], # TODO(jschuh): crbug.com/167187", "OpenSSL. 'sources!': [ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], }, { #", "'net', ], 'sources': [ 'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h', 'server/http_server_request_info.cc', 'server/http_server_request_info.h',", "'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ], 'defines':", "'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h',", "'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc', 'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, ], }], ['OS !=", "'../build/apk_test.gypi' ], }, ], }], ['test_isolation_mode != \"noop\"', { 'targets':", "'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc',", "'tools/dns_fuzz_stub/dns_fuzz_stub.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h',", "'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h',", "!= \"win\" 'sources!': [ 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dns_fuzz_stub', 'type':", "'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc',", "}, { 'target_name': 'quic_server', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl',", "'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc',", "iOS doesn't have the concept of simple executables, these targets", "'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc',", "], }, { 'target_name': 'net_perftests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "{ 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { 'dependencies': [ '../build/linux/system.gyp:ssl',", "'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h',", "'udp/udp_socket_libevent.h', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ], #", "'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h', 'base/address_family.h', 'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h',", "'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc', 'tools/fetch/http_server_request_info.h', 'tools/fetch/http_server_response_info.cc', 'tools/fetch/http_server_response_info.h', 'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ],", "'../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc', 'tools/dump_cache/dump_files.cc',", "[ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', ], 'export_dependent_settings': [ '../base/base.gyp:base',", "'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h',", "'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc',", "== \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ], }, ],", "'proxy/proxy_service_unittest.cc', ], }], ], }], [ 'OS == \"linux\"', {", "base.gyp for TODO(jrg)s about this strategy. ['OS == \"android\" and", "'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc',", "['OS==\"solaris\"', { 'link_settings': { 'ldflags': [ '-R/usr/lib/mps', ], }, }],", "'sources!': [ 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ], },", "'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc',", "'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc',", "'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h',", "'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h', 'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc',", "}, { # else !use_openssl: remove the unneeded files 'sources!':", "'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework',", "'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_java_test_support', 'type': 'none',", "[ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h',", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/get_server_time/get_server_time.cc',", "{ 'dependencies': [ '../build/linux/system.gyp:gdk', ], }], [ 'use_nss != 1',", "due to a # toolchain bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc', # These", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources': [ 'tools/tld_cleanup/tld_cleanup.cc', ],", "'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h', 'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc',", "ARM devices. So enable it for x86 only for now.", "'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc',", "'dump_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources':", "!= \"android\" and OS != \"ios\"', { 'conditions': [ ['use_openssl==1',", "# These tests crash when run with coverage turned on:", "of ARM devices. So enable it for x86 only for", "\"ios\"', { 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ],", "], 'export_dependent_settings': [ '../base/base.gyp:base', ], 'conditions': [ ['chromeos==1', { 'sources!':", "'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc',", "'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc',", "'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h', 'tools/quic/quic_time_wait_list_manager.h', 'tools/quic/quic_time_wait_list_manager.cc', 'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ],", "'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h',", "'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_resources', 'type':", "'target_name': 'http_server', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies':", "], 'sources': [ 'tools/tld_cleanup/tld_cleanup.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'isolate', 'inputs': [ 'net_unittests.isolate', '<@(isolate_dependency_tracked)', ], 'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated', ],", "[ '../base/base.gyp:base', 'net', ], 'sources': [ 'server/http_connection.cc', 'server/http_connection.h', 'server/http_server.cc', 'server/http_server.h',", "'quic/test_tools/test_task_runner.cc', 'quic/test_tools/test_task_runner.h', 'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc',", "'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc',", "'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies': [ 'net_javatests', 'net_test_jni_headers', ], }], [", "'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h',", "'ftp/ftp_transaction_factory.h', 'ftp/ftp_util.cc', 'ftp/ftp_util.h', 'http/des.cc', 'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h',", "'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h',", "'net_java', 'net_javatests', 'net_unittests', ], 'variables': { 'test_suite_name': 'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)',", "{ 'sources!': [ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc',", "'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h',", "'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h',", "'target_name': 'net_resources', 'type': 'none', 'variables': { 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions':", "'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h',", "'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc',", "'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h',", "'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ], }, ], [ 'OS == \"mac\"',", "thus does not # defines |use_nss|. In particular the |USE_NSS|", "'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'tld_cleanup',", "'quic_library', ], 'sources': [ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h',", "'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc',", "'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc', 'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc',", "'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc',", "'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc',", "'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc',", "!= \"ia32\"', { # The way the cache uses mmap()", "'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc',", "], 'sources': [ 'tools/crl_set_dump/crl_set_dump.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h',", "'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h', 'base/file_stream.cc', 'base/file_stream.h', 'base/file_stream_context.cc', 'base/file_stream_context.h',", "'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc',", "fix size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, ],", "'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc',", "[ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ], 'conditions': [ [ 'use_v8_in_net==1', {", "'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc',", "'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc',", "'proxy/proxy_resolver_winhttp.h', ], }, ], [ 'OS == \"mac\"', { 'sources!':", "'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h',", "'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc', 'socket/client_socket_pool_manager_impl.h', 'socket/next_proto.h',", "], }, ], 'includes': [ '../build/grit_target.gypi' ], }, { 'target_name':", "}, { 'target_name': 'private_key_types_java', 'type': 'none', 'sources': [ 'android/java/PrivateKeyType.template', ],", "'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc',", "in the LICENSE file. { 'variables': { 'chromium_code': 1, 'linux_link_kerberos%':", "'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h', 'http/http_stream_factory_impl.cc', 'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h',", "'test_suite_name': 'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [ '../build/apk_test.gypi' ], },", "that can be # found in the LICENSE file. {", "'http/transport_security_state_unittest.cc', # These tests crash when run with coverage turned", "need to exclude NSS specific tests. # TODO(bulach): Add equivalent", "], }], ], }], [ 'use_kerberos==1', { 'defines': [ 'USE_KERBEROS',", "'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ], 'conditions':", "'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h',", "'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc',", "], }], [ 'OS == \"android\"', { 'sources!': [ #", "'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ], },", "[ 'net_java', 'net_javatests', 'net_unittests', ], 'variables': { 'test_suite_name': 'net_unittests', 'input_shlib_path':", "'^cert/x509_util_nss\\\\.h$'], ['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include',", "disabled because they don't apply to # iOS. # OS", "'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h', 'url_request/url_request_throttler_manager.cc',", "'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h', 'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h',", "'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi'", "disabled because the # implementation is missing or incomplete. #", "else !use_openssl: remove the unneeded files 'sources!': [ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc',", "'defines': [ 'DLOPEN_KERBEROS', ], }], ], }, { # use_kerberos", "{ 'defines': [ 'USE_KERBEROS', ], }, { # use_kerberos ==", "'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h',", "'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc', 'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h',", "'ftp/ftp_util.h', 'http/des.cc', 'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h',", "['use_v8_in_net == 1', { 'targets': [ { 'target_name': 'net_with_v8', 'type':", "x86 only for now. 'posix_avoid_mmap%': 1, }, { 'posix_avoid_mmap%': 0,", "'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h',", "'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ], 'conditions': [ ['inside_chromium_build==1 and OS", "{ 'sources!': [ 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', ], }], ['OS", "are excluded by default platform rules, but they # are", "'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc',", "'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h',", "'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h',", "'tools/flip_server/http_message_constants.cc', 'tools/flip_server/http_message_constants.h', 'tools/flip_server/split.h', 'tools/flip_server/split.cc', ], }, { 'target_name': 'flip_in_mem_edsm_server', 'type':", "0, 'enable_built_in_dns%': 0, }, { 'enable_websockets%': 1, 'use_v8_in_net%': 1, 'enable_built_in_dns%':", "'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc',", "'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc',", "[ { 'target_name': 'net_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java',", "'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc',", "'base/address_family.h', 'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h', 'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc',", "{ 'sources/': [ ['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'], #", "], [ 'OS == \"mac\"', { 'sources!': [ 'ssl/client_cert_store_impl_nss.cc', ],", "to trigger the dll copy step on windows. # TODO(mark):", "NSS and thus does not # defines |use_nss|. In particular", "'proxy/proxy_config_service_linux.cc', ], },{ 'dependencies': [ '../build/linux/system.gyp:libresolv', ], }], ['OS==\"solaris\"', {", "'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h',", "'$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ] }, }, ], [ 'OS ==", "], 'dependencies': [ 'net_javatests', 'net_test_jni_headers', ], }], [ 'use_glib ==", "'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h',", "'tools/flip_server/split.h', 'tools/flip_server/split.cc', ], }, { 'target_name': 'flip_in_mem_edsm_server', 'type': 'executable', 'cflags':", "'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc',", "[ { 'target_name': 'flip_balsa_and_epoll_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', 'net',", "'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc',", "though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'], ['include',", "['base/net_error_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'certificate_mime_types_java',", "'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc', 'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc',", "'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h',", "'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ], } ] }],", "to exclude NSS specific tests. # TODO(bulach): Add equivalent tests", "'dependencies': [ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework',", "!use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_perftest.cc', ], }, ], # This is", "[ 'OS == \"win\"', { 'sources!': [ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h',", "by a BSD-style license that can be # found in", "'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h', 'dns/dns_response.cc', 'dns/dns_response.h',", "'^base/platform_mime_util_linux\\\\.cc$'], ], }], ['OS == \"ios\"', { 'sources/': [ ['include',", "\"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], 'actions': [ { 'action_name':", "'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc',", "[ 'os_posix == 1 and OS != \"mac\" and OS", "'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc', 'test/python_utils_unittest.cc', 'test/run_all_unittests.cc', 'test/test_certificate_data.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_to_filename_encoder_unittest.cc',", "{ 'ldflags': [ '<!@(krb5-config --libs gssapi)', ], }, }, {", "'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ], }], ['posix_avoid_mmap==1', { 'defines': [", "[ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:ssl', ], },", "TODO(mark): Specifying this here shouldn't be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata',", "'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h',", "'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ], }, { 'target_name': 'quic_library', 'type': 'static_library',", "{ 'variables': { 'chromium_code': 1, 'linux_link_kerberos%': 0, 'conditions': [ ['chromeos==1", "'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h',", "'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h',", "'flip_in_mem_edsm_server', 'type': 'executable', 'cflags': [ '-Wno-deprecated', ], 'dependencies': [ '../base/base.gyp:base',", "'tools/fetch/http_session.cc', 'tools/fetch/http_session.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'/usr/include/kerberosV' ], }], ['linux_link_kerberos==1', { 'link_settings': { 'ldflags': [ '<!@(krb5-config", "'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h', 'base/address_family.h', 'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc', 'base/address_tracker_linux.h',", "'template_deps': ['base/mime_util_certificate_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name':", "\"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions': [ ['coverage != 0', { 'sources!':", "'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h',", "{ 'target_name': 'net_perftests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf',", "\"win\"', { 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ], # This is", "}], [ 'use_openssl==1', { # When building for OpenSSL, we", "[ 'tools/quic/quic_client_bin.cc', ], }, { 'target_name': 'quic_server', 'type': 'executable', 'dependencies':", "[ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_test_jni_headers', 'type': 'none', 'sources':", "so sure about the # variety of ARM devices. So", "'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc',", "'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h', 'ssl/server_bound_cert_store.cc', 'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h',", "}, { 'target_name': 'net_perftests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n',", "'url_request/url_request_ftp_job.h', ], }], ['enable_built_in_dns==1', { 'defines': [ 'ENABLE_BUILT_IN_DNS', ] },", "'-R/usr/lib/mps', ], }, }], ], }, { # else: OS", "['exclude', '^ftp/'], ], 'sources!': [ 'url_request/url_request_ftp_job_unittest.cc', ], }, ], [", "], }], ['OS != \"android\"', { 'sources!': [ 'test/remote_test_server.cc', 'test/remote_test_server.h',", "'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc',", "'$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ], }, }, ], ['OS==\"android\" and _toolset==\"target\" and", "inefficient on some Android devices. # If this flag is", "'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc', 'base/connection_type_histograms.h', 'base/crypto_module.h', 'base/crypto_module_nss.cc',", "'../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources', ],", "'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h', 'base/address_family.h', 'base/address_list.cc', 'base/address_list.h', 'base/address_tracker_linux.cc',", "'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc',", "'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto',", "'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h',", "'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc', 'http/mock_http_cache.h', 'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h',", "'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ], }, ], ], #", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], 'conditions': [", "and android_webview_build == 0', { 'dependencies': [ 'net_java', ], }],", "'ssl/client_cert_store_impl_nss.cc', 'udp/udp_socket_libevent.cc', 'udp/udp_socket_libevent.h', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup',", "'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc',", "[ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc', ], }], ['use_openssl==1', { 'sources!': [", "'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h',", "in target_conditions as it is evaluated after the # platform", "'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc', ],", "'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc',", "'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h',", "'socket/ssl_error_params.cc', 'socket/ssl_error_params.h', 'socket/ssl_server_socket.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc',", "'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc',", "'link_settings': { 'ldflags': [ '-R/usr/lib/mps', ], }, }], ], },", "Disable Kerberos on ChromeOS, Android and iOS, at least for", "'../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net', 'quic_library', ], 'sources': [ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc',", "'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h',", "'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc',", "'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc',", "'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h',", "'base/net_module.h', 'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h',", "'net', ], 'export_dependent_settings': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [", "'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc', 'base/zap.h',", "[ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ],", "'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc',", "'proxy/proxy_resolver_v8_tracing_unittest.cc', ], }, ], [ 'OS == \"win\"', { 'sources!':", "'../testing/gtest.gyp:gtest', 'net', 'net_with_v8', ], 'sources': [ 'tools/fetch/fetch_client.cc', ], # TODO(jschuh):", "'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc',", "All rights reserved. # Use of this source code is", "crash when run with coverage turned on: # http://crbug.com/177203 'proxy/proxy_service_unittest.cc',", "'<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)', '--variable', 'PRODUCT_DIR', '<(PRODUCT_DIR)', '--variable', 'OS', '<(OS)', '--result',", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources':", "'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h',", "'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/flip_server/balsa_enums.h',", "1, 'use_v8_in_net%': 1, 'enable_built_in_dns%': 1, }], ], }, 'includes': [", "'crl_set_dump', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [", "'websockets/websocket_errors.cc', 'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h',", "\"mac\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], }, ],", "'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions': [ ['coverage != 0', { 'sources!': [", "'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h',", "!= \"android\" 'defines': [ # These are the features Android", "an # issue with llvm_gcda_increment_indirect_counter: # http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc',", "'../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc',", "'net', ], 'sources': [ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h', 'tools/fetch/http_server_request_info.cc',", "[ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], }, ], ], 'sources': [ 'tools/net_watcher/net_watcher.cc',", "'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc',", "[4267, ], }, ], 'conditions': [ ['use_v8_in_net == 1', {", "'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h',", "'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h', 'disk_cache/flash/internal_entry.cc', 'disk_cache/flash/internal_entry.h', 'disk_cache/flash/log_store.cc', 'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc',", "remove the unneeded files 'sources!': [ 'base/crypto_module_openssl.cc', 'base/keygen_handler_openssl.cc', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc',", "# TODO(droger): The following tests are disabled because the #", "'dependencies': [ '../build/linux/system.gyp:ssl', ], }, { # else use_glib ==", "'targets': [ { 'target_name': 'net_with_v8', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors':", "'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [ '../build/apk_test.gypi' ], }, ], }],", "'test_data_prefix': 'net', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], 'sources!':", "'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h',", "'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ], }, },", "'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc',", "'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc',", "et al on Android, so this doesn't make a lot", "[ 'OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ],", "'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h',", "[4267, ], }, { 'target_name': 'fetch_server', 'type': 'executable', 'variables': {", "'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc',", "'tools/quic/spdy_utils.cc', 'tools/quic/spdy_utils.h', ], }, { 'target_name': 'quic_client', 'type': 'executable', 'dependencies':", "for TODO(jrg)s about this strategy. ['OS == \"android\" and gtest_target_type", "'base/auth.cc', 'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h',", "'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h',", "'dns/address_sorter_posix.h', 'dns/dns_client.cc', ], }], ['use_openssl==1', { 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc',", "], [ 'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ],", "{ 'dependencies': [ '../build/linux/system.gyp:ssl', ], }, { # else use_glib", "'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc',", "the |USE_NSS| preprocessor # definition is not used. The following", "this here shouldn't be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss',", "necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], # TODO(jschuh):", "'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dns_fuzz_stub',", "'http/http_pipelined_host_impl.h', 'http/http_pipelined_host_pool.cc', 'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc',", "'base/rand_callback.h', 'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h',", "res_ninit() et al on Android, so this doesn't make a", "'../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework', '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework',", "'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc', 'tools/flip_server/flip_config.h', 'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h',", "'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h',", "'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc',", "'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc',", "'use_nss != 1', { 'sources!': [ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ],", "'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc', 'android/network_library.h',", "'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc', 'tools/quic/quic_spdy_server_stream.h',", "# iOS does not use V8. 'use_v8_in_net%': 0, 'enable_built_in_dns%': 0,", "'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h',", "'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h',", "'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc',", "Chromium Authors. All rights reserved. # Use of this source", "'actions': [ { 'action_name': 'isolate', 'inputs': [ 'net_unittests.isolate', '<@(isolate_dependency_tracked)', ],", "}], [ 'disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ], 'sources!':", "'base/auth.h', 'base/backoff_entry.cc', 'base/backoff_entry.h', 'base/bandwidth_metrics.cc', 'base/bandwidth_metrics.h', 'base/big_endian.cc', 'base/big_endian.h', 'base/cache_type.h', 'base/completion_callback.h', 'base/connection_type_histograms.cc',", "and gtest_target_type == \"shared_library\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ] }],", "'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h',", "'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc',", "\"ios\" and OS != \"android\"', { 'targets': [ { 'target_name':", "'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc',", "}], ], }, 'includes': [ '../build/win_precompile.gypi', ], 'targets': [ {", "}, ], 'sources!': [ # TODO(droger): The following tests are", "'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc',", "'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', # TODO(tc): gnome-vfs? xdgmime? /etc/mime.types?", "'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h', 'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc',", "# TODO(mark): Specifying this here shouldn't be necessary. 'dependencies': [", "'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h',", "'target_name': 'tld_cleanup', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ],", "'use_kerberos%': 0, }, { # chromeos == 0 'use_kerberos%': 1,", "'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h',", "'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h',", "'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h',", "'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc', 'http/http_auth_handler_basic.h', 'http/http_auth_handler_digest.cc', 'http/http_auth_handler_digest.h', 'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc',", "'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h',", "'../dbus/dbus.gyp:dbus_test_support', ], }, ], [ 'OS == \"android\"', { 'dependencies':", "], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ], # TODO(jschuh):", "], [ 'OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ],", "Specifying this here shouldn't be necessary. [ 'OS == \"win\"',", "'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc', 'tools/quic/quic_socket_utils.h', 'tools/quic/quic_spdy_client_stream.cc', 'tools/quic/quic_spdy_client_stream.h', 'tools/quic/quic_spdy_server_stream.cc',", "'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc',", "about the # variety of ARM devices. So enable it", "'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc',", "'type': 'none', 'sources': [ 'android/java/NetError.template', ], 'variables': { 'package_name': 'org/chromium/net',", "\"win\" 'sources!': [ 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ],", "are needed in specific cases on other platforms. Re-including them", "\"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', ],", "[4267, ], }, { 'target_name': 'net_watcher', 'type': 'executable', 'dependencies': [", "'net_test_support', ], 'sources': [ 'disk_cache/stress_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix", "'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h',", "}, ], [ 'enable_built_in_dns!=1', { 'sources!': [ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ],", "truncations. 'msvs_disabled_warnings': [4267, ], }, ], ], }, { 'target_name':", "rules. ['OS == \"android\"', { 'sources/': [ ['include', '^base/platform_mime_util_linux\\\\.cc$'], ],", "[ 'OS == \"win\"', { 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ],", "'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc', 'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h',", "'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc',", "gtest_target_type==shared_library # net_unittests into an android apk for execution. #", "], 'sources!': [ 'url_request/url_request_ftp_job_unittest.cc', ], }, ], [ 'enable_built_in_dns!=1', {", "'sources!': [ 'dns/dns_config_service_posix_unittest.cc', ], }, ], ['OS == \"android\" and", "'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h',", "'$(SDKROOT)/usr/lib/libresolv.dylib', ] }, }, ], [ 'OS == \"ios\"', {", "'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h',", "compiled on the platform. { 'target_name': 'crash_cache', 'type': 'executable', 'dependencies':", "'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], 'conditions':", "excluded by default platform rules, but they # are needed", "'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc', 'cookies/cookie_store.h',", "== 0 'sources!': [ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ], }],", "but they # are needed in specific cases on other", "'tools/dump_cache/url_utilities_unittest.cc', 'udp/udp_socket_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc',", "'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }, {", "'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', # Needs GetAppOutput(). 'test/python_utils_unittest.cc', # The following tests", "'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], }, ], ], 'sources': [", "'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h',", "'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc',", "], }], [ 'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl',", "'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h',", "], }], ['enable_built_in_dns==1', { 'defines': [ 'ENABLE_BUILT_IN_DNS', ] }, {", "'$(SDKROOT)/usr/lib/libresolv.dylib', ], }, }, ], ['OS==\"android\" and _toolset==\"target\" and android_webview_build", "'cookies/parsed_cookie.cc', 'cookies/parsed_cookie.h', 'disk_cache/addr.cc', 'disk_cache/addr.h', 'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h',", "'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h',", "'net_with_v8', ], }, { # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc',", "'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h',", "due to an # issue with llvm_gcda_increment_indirect_counter: # http://crbug.com/156058 'cookies/cookie_monster_unittest.cc',", "size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name':", "'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h',", "'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h',", "'../build/java.gypi' ], }, { 'target_name': 'net_errors_java', 'type': 'none', 'sources': [", "'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h',", "'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/flip_server/sm_connection.cc', 'tools/flip_server/sm_connection.h', 'tools/flip_server/sm_interface.h', 'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h',", "'websockets/websocket_errors.h', 'websockets/websocket_frame.cc', 'websockets/websocket_frame.h', 'websockets/websocket_frame_parser.cc', 'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc',", "are needed though: ['include', '^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include',", "[ 'OS != \"win\" and OS != \"mac\"', { 'sources!':", "is evaluated after the # platform rules. ['OS == \"android\"',", "use NSS 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ['os_bsd==1', { 'sources!':", "# variety of ARM devices. So enable it for x86", "'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc', 'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h',", "'sources!': [ 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', ], }], ['OS ==", "'../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/fetch/fetch_server.cc', 'tools/fetch/http_listen_socket.cc', 'tools/fetch/http_listen_socket.h', 'tools/fetch/http_server.cc', 'tools/fetch/http_server.h',", "], 'direct_dependent_settings': { 'defines': [ 'POSIX_AVOID_MMAP', ], }, 'sources!': [", "\"shared_library\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ] }], [ 'OS !=", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_server', 'type':", "'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h', 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/quic_test_utils.cc', 'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'quic/test_tools/simple_quic_framer.cc',", "[ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/crash_cache/crash_cache.cc', ], #", "'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h',", "'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc',", "'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc', 'cert/cert_verify_proc_win.h', 'cert/cert_verify_result.cc', 'cert/cert_verify_result.h', 'cert/crl_set.cc', 'cert/crl_set.h', 'cert/ev_root_ca_metadata.cc', 'cert/ev_root_ca_metadata.h',", "'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc',", "'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc',", "'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp',", "[ '../build/java.gypi' ], }, { 'target_name': 'net_javatests', 'type': 'none', 'variables':", "'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc',", "'disk_cache/backend_impl.cc', 'disk_cache/backend_impl.h', 'disk_cache/bitmap.cc', 'disk_cache/bitmap.h', 'disk_cache/block_files.cc', 'disk_cache/block_files.h', 'disk_cache/cache_creator.cc', 'disk_cache/cache_util.h', 'disk_cache/cache_util.cc', 'disk_cache/cache_util_posix.cc',", "[ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../testing/gtest.gyp:gtest', 'net_test_support', ], 'sources': [ 'tools/testserver/run_testserver.cc', ],", "'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc', 'ftp/ftp_directory_listing_parser_vms.h', 'ftp/ftp_directory_listing_parser_windows.cc', 'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc',", "'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc', 'dns/host_cache_unittest.cc', 'dns/host_resolver_impl_unittest.cc',", "},{ 'dependencies': [ '../build/linux/system.gyp:libresolv', ], }], ['OS==\"solaris\"', { 'link_settings': {", "'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc',", "'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', # These tests crash when", "], 'sources': [ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h',", "[ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { 'dependencies':", "'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc',", "'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc',", "'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h',", "'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, ],", "'disk_cache/rankings.cc', 'disk_cache/rankings.h', 'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h',", "'url_request/url_request_test_util.cc', 'url_request/url_request_test_util.h', ], 'conditions': [ ['inside_chromium_build==1 and OS != \"ios\"',", "'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc', 'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc',", "'../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources': [ 'tools/tld_cleanup/tld_cleanup.cc', ], # TODO(jschuh): crbug.com/167187", "[ '<(PRODUCT_DIR)/net_unittests.isolated', ], 'action': [ 'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir', '<(test_isolation_outdir)',", "}, { 'posix_avoid_mmap%': 0, }], ['OS==\"ios\"', { # Websockets and", "'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc',", "], }, { # else: OS is not in the", "{ 'target_name': 'http_server', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, },", "'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc', 'disk_cache/flash/storage_unittest.cc', 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc',", "}, { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ], }], ['os_posix", "'net_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto',", "{ # else OS != \"android\" 'defines': [ # These", "'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h',", "'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h',", "['include', '^base/platform_mime_util_linux\\\\.cc$'], ], }], ['OS == \"ios\"', { 'sources/': [", "'net_with_v8', ], 'conditions': [ [ 'use_glib == 1', { 'dependencies':", "'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h',", "least for now. # It needs configuration (krb5.conf and so", "'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h',", "[ 'url_request/url_request_ftp_job_unittest.cc', ], }, ], [ 'enable_built_in_dns!=1', { 'sources!': [", "'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h',", "{ 'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ], 'sources!': [", "}], ['use_kerberos==1', { 'defines': [ 'USE_KERBEROS', ], 'conditions': [ ['OS==\"openbsd\"',", "run with coverage turned on: # http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ], }],", "!= \"ios\"', { 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator',", "[ { 'target_name': 'net_unittests_apk', 'type': 'none', 'dependencies': [ 'net_java', 'net_javatests',", "'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ], }, ],", "'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc',", "'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc',", "'net_resources', 'type': 'none', 'variables': { 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions': [", "# else OS != \"android\" 'defines': [ # These are", "], }, { 'target_name': 'quic_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base',", "'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc', 'ssl/ssl_config_service_unittest.cc',", "'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc',", "'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc',", "code is governed by a BSD-style license that can be", "'../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net', 'net_test_support', ], 'sources': [", "tests when the underlying # functionality is ported to OpenSSL.", "'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc', 'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc',", "}, { 'target_name': 'stress_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net',", "'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_resources',", "{ # The way the cache uses mmap() is inefficient", "'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ], 'conditions': [ ['chromeos==1', { 'sources!': [", "], 'sources': [ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc',", "enable it for x86 only for now. 'posix_avoid_mmap%': 1, },", "1', { 'sources!': [ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ], }], [", "doesn't support. 'ENABLE_MEDIA_CODEC_THEORA', ], }, ], [ 'OS == \"linux\"',", "on: # http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ], }], ], }], [ 'OS", "'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', # TODO(tc): gnome-vfs? xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc',", "because the # implementation is missing or incomplete. # KeygenHandler::GenKeyAndSignChallenge()", "'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h',", "'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc',", "'proxy/proxy_service_v8.h', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "1, 'linux_link_kerberos%': 0, 'conditions': [ ['chromeos==1 or OS==\"android\" or OS==\"ios\"',", "'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc',", "'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h',", "{ # else use_openssl==0, use NSS 'dependencies': [ '../build/linux/system.gyp:ssl', ],", "], }, ], [ 'OS == \"mac\"', { 'sources!': [", "'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h',", "'websockets/websocket_throttle.h', ], 'defines': [ 'NET_IMPLEMENTATION', ], 'export_dependent_settings': [ '../base/base.gyp:base', ],", "'none', 'sources': [ 'android/java/CertVerifyResultAndroid.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps':", "'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h',", "{ 'defines': [ 'ENABLE_BUILT_IN_DNS', ] }, { # else 'sources!':", "], }, { 'target_name': 'net_java', 'type': 'none', 'variables': { 'java_in_dir':", "\"shared_library\"', { 'targets': [ { 'target_name': 'net_unittests_apk', 'type': 'none', 'dependencies':", "linux_link_kerberos==0 'defines': [ 'DLOPEN_KERBEROS', ], }], ], }, { #", "'third_party/nss/ssl.gyp:libssl', ], }, ], [ 'OS == \"ios\"', { 'dependencies':", "'url_request/url_request_data_job.h', 'url_request/url_request_error_job.cc', 'url_request/url_request_error_job.h', 'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc',", "'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, ], [ 'toolkit_uses_gtk == 1', { 'dependencies':", "'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h', ], 'defines': [", "can't be built with coverage due to a # toolchain", "[ 'tools/crash_cache/crash_cache.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "but we cannot be so sure about the # variety", "'net_unittests_run', 'type': 'none', 'dependencies': [ 'net_unittests', ], 'includes': [ 'net_unittests.isolate',", "'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc',", "!= 1', { 'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ['exclude',", "}, 'includes': [ '../build/grit_action.gypi' ], }, ], 'includes': [ '../build/grit_target.gypi'", "'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h',", "'target_name': 'quic_server', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library',", "'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ], },{ 'dependencies': [ '../build/linux/system.gyp:libresolv', ], }], ['OS==\"solaris\"',", "== \"win\"', { 'sources!': [ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h',", "not used on iOS. 'enable_websockets%': 0, # iOS does not", "'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ], }, ],", "'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h',", "# else: OS != \"win\" 'sources!': [ 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc',", "'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/crl_set_dump/crl_set_dump.cc', ],", "{ 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], 'conditions': [ ['use_openssl==1', {", "'actions': [ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'data/ssl/certificates/',", "'net_with_v8', ], }, ], ], # TODO(jschuh): crbug.com/167187 fix size_t", "TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [4267, ],", "'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc',", "'enable_websockets%': 1, 'use_v8_in_net%': 1, 'enable_built_in_dns%': 1, }], ], }, 'includes':", "'../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net' ], 'defines': [ 'NET_IMPLEMENTATION', ], 'sources': [", "'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, ], [ 'OS ==", "'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ], } ] }], ['OS==\"android\"', {", "now. # It needs configuration (krb5.conf and so on). 'use_kerberos%':", "# The net/android/keystore_openssl.cc source file needs to # access an", "else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_perftest.cc', ], }, ], # This", "'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc',", "}, ], [ 'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus',", "'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc', 'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc',", "\"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], }], [ 'use_v8_in_net==1', {", "}, 'includes': [ '../build/win_precompile.gypi', ], 'targets': [ { 'target_name': 'net',", "# issue with llvm_gcda_increment_indirect_counter: # http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc',", "'proxy/proxy_config_service_linux_unittest.cc', ], }], [ 'OS == \"android\"', { 'sources!': [", "# Disable Kerberos on ChromeOS, Android and iOS, at least", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_client',", "'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc',", "'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h',", "specific tests. # TODO(bulach): Add equivalent tests when the underlying", "'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc',", "'net_errors_java', 'private_key_types_java', ], 'includes': [ '../build/java.gypi' ], }, { 'target_name':", "OS is not \"linux\" or \"freebsd\" or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ],", "'http/http_pipelined_host_pool.h', 'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc',", "preprocessor # definition is not used. The following files are", "'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net',", "'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'base/nss_memio.c', 'base/nss_memio.h', 'cert/cert_database_nss.cc', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc',", "'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc',", "!= \"android\" and OS != \"ios\"', { 'conditions': [ ['linux_use_tcmalloc==1',", "'net_resources', ], 'sources': [ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h',", "# The iOS implementation only partially uses NSS and thus", "'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc',", "'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc', ],", "'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc', 'quic/crypto/p256_key_exchange_nss.cc', 'socket/nss_ssl_util.cc',", "'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ], }], ['posix_avoid_mmap==1', { 'defines': [ 'POSIX_AVOID_MMAP',", "[ 'OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], 'actions':", "'net_javatests', 'net_unittests', ], 'variables': { 'test_suite_name': 'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', },", "'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h',", "'dependencies': [ 'net_javatests', 'net_test_jni_headers', ], }], [ 'use_glib == 1',", "], 'target_conditions': [ # These source files are excluded by", "gtest_target_type == \"shared_library\"', { 'targets': [ { 'target_name': 'net_unittests_apk', 'type':", "'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, { #", "== \"mac\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], },", "'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/crash_cache/crash_cache.cc',", "'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc',", "'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h',", "[ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ], 'sources!': [ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h',", "'net_javatests', 'type': 'none', 'variables': { 'java_in_dir': '../net/android/javatests', }, 'dependencies': [", "1, }, { 'posix_avoid_mmap%': 0, }], ['OS==\"ios\"', { # Websockets", "'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h',", "'defines': [ # These are the features Android doesn't support.", "'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h',", "'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc',", "'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h', 'base/escape.cc', 'base/escape.h', 'base/expiring_cache.h',", "'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc',", "'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc',", "'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc',", "'target_name': 'fetch_server', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies':", "'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', ], #", "'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc',", "'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h',", "'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc',", "'base/crypto_module_nss.cc', 'base/crypto_module_openssl.cc', 'base/data_url.cc', 'base/data_url.h', 'base/directory_lister.cc', 'base/directory_lister.h', 'base/dns_reloader.cc', 'base/dns_reloader.h', 'base/dns_util.cc', 'base/dns_util.h',", "], 'actions': [ { 'action_name': 'isolate', 'inputs': [ 'net_unittests.isolate', '<@(isolate_dependency_tracked)',", "can be # found in the LICENSE file. { 'variables':", "== 1', { 'dependencies': [ '../build/linux/system.gyp:gdk', ], }], [ 'use_nss", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'fetch_server', 'type': 'executable', 'variables':", "'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/quic_connection_peer.cc', 'quic/test_tools/quic_connection_peer.h', 'quic/test_tools/quic_framer_peer.cc', 'quic/test_tools/quic_framer_peer.h', 'quic/test_tools/quic_packet_creator_peer.cc', 'quic/test_tools/quic_packet_creator_peer.h',", "'base/registry_controlled_domains/registry_controlled_domain.cc', 'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h',", "[ '../third_party/nss/nss.gyp:nss', ], }], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8',", "'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc',", "['posix_avoid_mmap==1', { 'defines': [ 'POSIX_AVOID_MMAP', ], 'direct_dependent_settings': { 'defines': [", "'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h',", "'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h', 'quic/congestion_control/inter_arrival_state_machine.cc', 'quic/congestion_control/inter_arrival_state_machine.h', 'quic/congestion_control/leaky_bucket.cc', 'quic/congestion_control/leaky_bucket.h', 'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h',", "the underlying # functionality is ported to OpenSSL. 'sources!': [", "source files are excluded by default platform rules, but they", "'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h',", "'tools/tld_cleanup/tld_cleanup.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc',", "'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc',", "'net_unittests_apk', 'type': 'none', 'dependencies': [ 'net_java', 'net_javatests', 'net_unittests', ], 'variables':", "[ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h',", "'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h', 'quic/quic_protocol.cc', 'quic/quic_protocol.h', 'quic/quic_reliable_client_stream.cc', 'quic/quic_reliable_client_stream.h', 'quic/quic_session.cc', 'quic/quic_session.h', 'quic/quic_stats.cc', 'quic/quic_stats.h',", "it is evaluated after the # platform rules. ['OS ==", "], }, ], [ 'os_posix == 1 and OS !=", "[ 'OS == \"mac\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl',", "'OS == \"android\"', { 'sources!': [ # No res_ninit() et", "], 'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_java_test_support', 'type':", "'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc',", "'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc',", "}], ['OS != \"android\"', { 'sources!': [ 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc',", "], }], ], }, { 'target_name': 'net_unittests', 'type': '<(gtest_target_type)', 'dependencies':", "['linux_link_kerberos==1', { 'link_settings': { 'ldflags': [ '<!@(krb5-config --libs gssapi)', ],", "}, ], [ 'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl',", "'../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_server_bin.cc', ], },", "], [ 'OS == \"win\"', { 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc',", "'spdy/buffered_spdy_framer_spdy3_unittest.cc', 'spdy/buffered_spdy_framer_spdy2_unittest.cc', 'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc',", "'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h', 'tools/flip_server/flip_config.cc',", "'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc', 'quic/quic_stream_factory_test.cc', 'quic/quic_stream_sequencer_test.cc', 'quic/quic_time_test.cc', 'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc',", "[ # No res_ninit() et al on Android, so this", "'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc',", "['OS==\"android\" and target_arch != \"ia32\"', { # The way the", "'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h',", "'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h',", "[ 'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gdk', ], }],", "== 1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ], }, ], [", "}, { 'target_name': 'fetch_server', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1,", "'includes': [ '../build/grit_target.gypi' ], }, { 'target_name': 'http_server', 'type': 'static_library',", "'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ], },{ 'dependencies': [ '../build/linux/system.gyp:libresolv',", "'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net', 'quic_library', ], 'sources': [", "'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated', ], 'action': [ 'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)', '--outdir',", "'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_http_cache.cc',", "'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h', 'quic/crypto/null_decrypter.cc', 'quic/crypto/null_decrypter.h', 'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h',", "'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h',", "Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc', 'url_request/url_request_context_builder_unittest.cc', # Needs GetAppOutput().", "'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], [ 'use_kerberos==1', {", "iOS, at least for now. # It needs configuration (krb5.conf", "'quic/crypto/crypto_framer.cc', 'quic/crypto/crypto_framer.h', 'quic/crypto/crypto_handshake.cc', 'quic/crypto/crypto_handshake.h', 'quic/crypto/crypto_protocol.h', 'quic/crypto/crypto_utils.cc', 'quic/crypto/crypto_utils.h', 'quic/crypto/curve25519_key_exchange.cc', 'quic/crypto/curve25519_key_exchange.h', 'quic/crypto/key_exchange.h',", "net/android/keystore_openssl.cc source file needs to # access an OpenSSL-internal header.", "'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc',", "!= \"noop\"', { 'targets': [ { 'target_name': 'net_unittests_run', 'type': 'none',", "'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/net_error_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi'", "'base/file_stream_context.h', 'base/file_stream_context_posix.cc', 'base/file_stream_context_win.cc', 'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h',", "}, { # else use_openssl==0, use NSS 'dependencies': [ '../build/linux/system.gyp:ssl',", "for execution. # See base.gyp for TODO(jrg)s about this strategy.", "'linux_link_kerberos%': 0, 'conditions': [ ['chromeos==1 or OS==\"android\" or OS==\"ios\"', {", "'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc', 'quic/quic_packet_generator.h',", "BSD-style license that can be # found in the LICENSE", "], }, { 'target_name': 'net_java_test_support', 'type': 'none', 'variables': { 'java_in_dir':", "'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc',", "'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], },", "[4267, ], }, { 'target_name': 'gdig', 'type': 'executable', 'dependencies': [", "{ 'sources!': [ # These sources can't be built with", "'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc',", "'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc',", "'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc', 'spdy/spdy_frame_builder.h', 'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h',", "with coverage turned on due to an # issue with", "'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net',", "'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h', 'base/keygen_handler_mac.cc', 'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h',", "[ 'proxy/proxy_resolver_perftest.cc', ], }, ], # This is needed to", "# chromeos == 0 'use_kerberos%': 1, }], ['OS==\"android\" and target_arch", "'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc', 'base/net_util_win.cc',", "'quic/quic_utils_test.cc', 'quic/reliable_quic_stream_test.cc', 'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, ], ], }, {", "'NET_IMPLEMENTATION', ], 'export_dependent_settings': [ '../base/base.gyp:base', ], 'conditions': [ ['chromeos==1', {", "'disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/url_request_ftp_job_unittest.cc',", "'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h',", "This is needed to trigger the dll copy step on", "'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', ], 'export_dependent_settings':", "[ 'disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [", "'fetch_server', 'type': 'executable', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [", "'tools/dump_cache/dump_files.cc', 'tools/dump_cache/dump_files.h', 'tools/dump_cache/simple_cache_dumper.cc', 'tools/dump_cache/simple_cache_dumper.h', 'tools/dump_cache/upgrade_win.cc', 'tools/dump_cache/upgrade_win.h', 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc',", "}], ['disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [", "'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc', 'websockets/websocket_throttle_unittest.cc',", "them can # only be done in target_conditions as it", "'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], [ 'OS", "'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc',", "'base/test_completion_callback_unittest.cc', 'base/upload_bytes_element_reader_unittest.cc', 'base/upload_data_stream_unittest.cc', 'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc',", "'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc',", "'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc',", "'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h', 'http/http_pipelined_host_forced.cc', 'http/http_pipelined_host_forced.h', 'http/http_pipelined_host_impl.cc',", "'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc', 'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc',", "'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_test_support', ],", "'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h', 'quic/quic_data_writer.cc', 'quic/quic_data_writer.h', 'quic/quic_fec_group.cc',", "'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc',", "'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h',", "'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h',", "['exclude', '^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }], [ 'disable_ftp_support==1', { 'sources/':", "'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', # These tests crash when run with coverage", "'net_test_support', ], 'sources': [ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ], 'conditions': [", "'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], },", "'websockets/websocket_frame_parser.h', 'websockets/websocket_handshake_handler.cc', 'websockets/websocket_handshake_handler.h', 'websockets/websocket_job.cc', 'websockets/websocket_job.h', 'websockets/websocket_net_log_params.cc', 'websockets/websocket_net_log_params.h', 'websockets/websocket_stream.h', 'websockets/websocket_throttle.cc', 'websockets/websocket_throttle.h',", "'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ], }], ['posix_avoid_mmap==1', { 'defines': [ 'POSIX_AVOID_MMAP', ],", "], }, { 'target_name': 'quic_client', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net', 'quic_library', ], 'sources': [ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h',", "'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h',", "['include', '^ocsp/nss_ocsp\\\\.h$'], ], }], ], }, { 'target_name': 'net_unittests', 'type':", "are disabled because they don't apply to # iOS. #", "ChromeOS, Android and iOS, at least for now. # It", "[ '../third_party/nss/nss.gyp:nss', ], 'actions': [ { 'action_name': 'copy_test_data', 'variables': {", "[ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_with_v8', ], 'sources': [", "'net', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], 'sources!': [", "'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h',", "[4267, ], }, { 'target_name': 'dump_cache', 'type': 'executable', 'dependencies': [", "'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h',", "{ 'sources!': [ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ], }, ], [ 'use_v8_in_net==1',", "'<(OS)', '--result', '<@(_outputs)', '--isolate', 'net_unittests.isolate', ], }, ], }, ],", "[ [ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio',", "], }, ], [ 'OS == \"mac\"', { 'dependencies': [", "# These sources can't be built with coverage due to", "'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/pem_tokenizer.cc', 'cert/pem_tokenizer.h', 'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc',", "'^cert/cert_verify_proc_nss\\\\.cc$'], ['include', '^cert/cert_verify_proc_nss\\\\.h$'], ['include', '^cert/test_root_certs_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.cc$'], ['include', '^cert/x509_util_nss\\\\.h$'], ['include',", "'tools/flip_server/spdy_ssl.cc', 'tools/flip_server/spdy_ssl.h', 'tools/flip_server/spdy_interface.cc', 'tools/flip_server/spdy_interface.h', 'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ],", "{ 'java_in_dir': '../net/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, {", "'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc',", "'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h',", "an android apk for execution. # See base.gyp for TODO(jrg)s", "'quic/test_tools/quic_test_utils.h', 'quic/test_tools/reliable_quic_stream_peer.cc', 'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc',", "'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h', 'base/mime_util.cc', 'base/mime_util.h', 'base/net_error_list.h', 'base/net_errors.cc', 'base/net_errors.h', 'base/net_errors_posix.cc', 'base/net_errors_win.cc',", "['OS==\"android\" and _toolset==\"target\" and android_webview_build == 0', { 'dependencies': [", "], 'sources!': [ # TODO(droger): The following tests are disabled", "the concept of simple executables, these targets # can't be", "'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc', 'cert/cert_verify_proc_mac.h', 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/cert_verify_proc_win.cc',", "'test/spawner_communicator.cc', 'test/spawner_communicator.h', ], }], ['OS == \"ios\"', { 'dependencies': [", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [", "}], ['enable_built_in_dns==1', { 'defines': [ 'ENABLE_BUILT_IN_DNS', ] }, { #", "], }, }, ], ['OS==\"android\" and _toolset==\"target\" and android_webview_build ==", "'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', 'test/test_server.h', 'url_request/test_url_fetcher_factory.cc', 'url_request/test_url_fetcher_factory.h', 'url_request/url_request_test_util.cc',", "}], ['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name': 'net_unittests_run',", "{ 'target_name': 'flip_in_mem_edsm_server', 'type': 'executable', 'cflags': [ '-Wno-deprecated', ], 'dependencies':", "'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', # Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc',", "[ '../testing/android/native_test.gyp:native_test_native_code', ] }], [ 'OS != \"win\" and OS", "\"ios\"', { 'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto', ], }], ['os_posix == 1", "}, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net' ], 'defines': [", "'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', # TODO(tc): gnome-vfs? xdgmime?", "}, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/fetch/fetch_server.cc',", "'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h', 'http/http_util.cc', 'http/http_util.h', 'http/http_util_icu.cc', 'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc',", "'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h',", "\"noop\"', { 'targets': [ { 'target_name': 'net_unittests_run', 'type': 'none', 'dependencies':", "}, ], ['OS == \"android\" and gtest_target_type == \"shared_library\"', {", "{ 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest',", "'cert_verify_result_android_java', 'type': 'none', 'sources': [ 'android/java/CertVerifyResultAndroid.template', ], 'variables': { 'package_name':", "'url_request/url_request_context_builder_unittest.cc', # Needs GetAppOutput(). 'test/python_utils_unittest.cc', # The following tests are", "'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc', 'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc',", "# Special target to wrap a gtest_target_type==shared_library # net_unittests into", "# We are pretty confident that mmap-ing the index would", "'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc', 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h',", "'../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], }, ], ], 'sources': [ 'tools/net_watcher/net_watcher.cc', ],", "'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ], }, ], [", "'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h', 'disk_cache/flash/format.h',", "{ 'target_name': 'quic_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl',", "[ 'quic/test_tools/quic_session_peer.cc', 'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc',", "[ { 'action_name': 'isolate', 'inputs': [ 'net_unittests.isolate', '<@(isolate_dependency_tracked)', ], 'outputs':", "'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ], 'sources!': [ 'spdy/spdy_websocket_stream.cc',", "'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ], } ] }], ['OS==\"android\"', { 'targets':", "{ 'dependencies': [ 'net_with_v8', ], }, { # else: !use_v8_in_net", "data files. 'base/gzip_filter_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', # Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc',", "'../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources', ], 'sources': [ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc',", "'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h', 'proxy/proxy_config_service_android.cc',", "'base/net_util_posix.cc', 'base/net_util_win.cc', 'base/network_change_notifier.cc', 'base/network_change_notifier.h', 'base/network_change_notifier_factory.h', 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_mac.cc', 'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc',", "[ '../third_party/protobuf/protobuf.gyp:py_proto', ], }], ['os_posix == 1 and OS !=", "http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ], }], ], }], [ 'OS == \"linux\"',", "'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc',", "], 'sources': [ 'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc',", "'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java', ], 'variables': { 'jni_gen_package': 'net',", "'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, { # else !use_openssl:", "1, }, 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'server/http_connection.cc',", "'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ] }, }, ],", "'java_in_dir': '../net/android/java', }, 'dependencies': [ '../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java',", "'socket/buffered_write_stream_socket_unittest.cc', 'socket/client_socket_pool_base_unittest.cc', 'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc',", "['android/private_key_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, ], }], #", "'../build/android/java_cpp_template.gypi' ], }, ], }], # Special target to wrap", "[ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus', ], }, ], ], 'target_conditions': [ #", "'ftp/ftp_auth_cache.h', 'ftp/ftp_ctrl_response_buffer.cc', 'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc',", "{ 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], # TODO(jschuh): crbug.com/167187 fix size_t", "1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net' ], 'defines':", "'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc', 'base/prioritized_dispatcher_unittest.cc', 'base/priority_queue_unittest.cc', 'base/registry_controlled_domains/registry_controlled_domain_unittest.cc', 'base/sdch_filter_unittest.cc',", "], }, ], ], 'target_conditions': [ # These source files", "'base/ip_endpoint_unittest.cc', 'base/keygen_handler_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', 'base/mock_filter_context.cc', 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', 'base/net_util_unittest.cc', 'base/network_change_notifier_win_unittest.cc',", "'none', 'dependencies': [ 'net_java', 'net_javatests', 'net_unittests', ], 'variables': { 'test_suite_name':", "'quic/congestion_control/inter_arrival_overuse_detector_test.cc', 'quic/congestion_control/inter_arrival_probe_test.cc', 'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc',", "'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h', 'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc',", "[ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', 'net',", "else 'sources!': [ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc', ], }], ['use_openssl==1', {", "], }], ['posix_avoid_mmap==1', { 'defines': [ 'POSIX_AVOID_MMAP', ], 'direct_dependent_settings': {", "'^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'], ], }], ], }, {", "'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc',", "'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc',", "'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ], # This is needed to trigger the", "on Android, so this doesn't make a lot of #", "'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc',", "'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h', 'base/mime_sniffer.cc', 'base/mime_sniffer.h',", "'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc',", "'android/keystore_openssl.cc', 'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h',", "'actions': [ { 'action_name': 'net_resources', 'variables': { 'grit_grd_file': 'base/net_resources.grd', },", "'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc', 'cert/cert_database_nss.cc', 'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc',", "], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'], }, 'includes': [", "and OS != \"mac\"', { 'sources!': [ 'cert/x509_cert_types_unittest.cc', ], }],", "'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h', 'socket/ssl_client_socket_pool.cc', 'socket/ssl_client_socket_pool.h', 'socket/ssl_error_params.cc', 'socket/ssl_error_params.h',", "'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc',", "'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc',", "'../build/linux/system.gyp:gio', ], }, ], ], 'sources': [ 'tools/net_watcher/net_watcher.cc', ], },", "avoid using mmap() in the disk cache. # We are", "'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', # These tests crash when run", "be necessary. [ 'OS == \"win\"', { 'dependencies': [ '../third_party/icu/icu.gyp:icudata',", "'msvs_disabled_warnings': [4267, ], }, ], }], ['os_posix == 1 and", "{ 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ] }], [ 'OS != \"win\"", "'enable_websockets != 1', { 'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'],", "'tools/testserver/run_testserver.cc', ], }, { 'target_name': 'stress_cache', 'type': 'executable', 'dependencies': [", "not hurt any # existing x86 android devices, but we", "'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h', 'disk_cache/flash/flash_cache_test_base.h', 'disk_cache/flash/flash_cache_test_base.cc', 'dns/dns_test_util.cc', 'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h',", "'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'disk_cache/stress_cache.cc',", "'conditions': [ ['OS==\"openbsd\"', { 'include_dirs': [ '/usr/include/kerberosV' ], }], ['linux_link_kerberos==1',", "necessary. [ 'OS == \"win\"', { 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ],", "[ 'OS == \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], 'sources!':", "'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc',", "], 'sources': [ 'tools/get_server_time/get_server_time.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "OS != \"ios\"', { 'conditions': [ ['use_openssl==1', { 'dependencies': [", "'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ], # The net/android/keystore_openssl.cc source file", "], 'sources': [ 'tools/testserver/run_testserver.cc', ], }, { 'target_name': 'stress_cache', 'type':", "'tools/flip_server/spdy_util.cc', 'tools/flip_server/spdy_util.h', 'tools/flip_server/streamer_interface.cc', 'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ], }, { 'target_name': 'quic_library',", "'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc', 'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc',", "[ '../build/grit_action.gypi' ], }, ], 'includes': [ '../build/grit_target.gypi' ], },", "'proxy/proxy_config_service_android.cc', 'proxy/proxy_config_service_android.h', 'proxy/proxy_config_service_fixed.cc', 'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h',", "# else 'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }], ['disable_ftp_support==1', { 'sources/':", "'http/http_pipelined_stream.cc', 'http/http_pipelined_stream.h', 'http/http_proxy_client_socket.cc', 'http/http_proxy_client_socket.h', 'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, ], 'conditions': [ ['use_v8_in_net", "'tools/quic/spdy_utils.h', ], }, { 'target_name': 'quic_client', 'type': 'executable', 'dependencies': [", "'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h',", "'../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources': [ 'tools/tld_cleanup/tld_cleanup.cc', ], # TODO(jschuh):", "'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_client_socket_openssl.cc', 'socket/ssl_client_socket_openssl.h',", "], }, }, { # linux_link_kerberos==0 'defines': [ 'DLOPEN_KERBEROS', ],", "'base/file_stream_metrics.cc', 'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h', 'base/int128.cc',", "'sources/': [ ['include', '^base/platform_mime_util_linux\\\\.cc$'], ], }], ['OS == \"ios\"', {", "'sources': [ 'tools/testserver/run_testserver.cc', ], }, { 'target_name': 'stress_cache', 'type': 'executable',", "'../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework',", "'base/upload_progress.h', 'base/url_util.cc', 'base/url_util.h', 'base/winsock_init.cc', 'base/winsock_init.h', 'base/winsock_util.cc', 'base/winsock_util.h', 'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc',", "'quic/quic_stream_factory.h', 'quic/quic_stream_sequencer.cc', 'quic/quic_stream_sequencer.h', 'quic/quic_time.cc', 'quic/quic_time.h', 'quic/quic_utils.cc', 'quic/quic_utils.h', 'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc',", "'net_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/net/AndroidKeyStore.java', 'android/java/src/org/chromium/net/AndroidNetworkLibrary.java', 'android/java/src/org/chromium/net/GURLUtils.java', 'android/java/src/org/chromium/net/NetworkChangeNotifier.java', 'android/java/src/org/chromium/net/ProxyChangeListener.java',", "'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h',", "Needs GetAppOutput(). 'test/python_utils_unittest.cc', # The following tests are disabled because", "'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h',", "'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', ], }, ], [ 'OS == \"mac\"', {", "], 'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h',", "'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc',", "[ 'OS == \"win\"', { 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], #", "'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc', 'cert/x509_cert_types_win.cc', 'cert/x509_certificate.cc', 'cert/x509_certificate.h', 'cert/x509_certificate_ios.cc',", "{ 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], ['OS !=", "'../third_party/openssl/openssl.gyp:openssl', ], }, { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }], ],", "[ 'android/java/PrivateKeyType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/private_key_type_list.h'], },", "they don't apply to # iOS. # OS is not", "[ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_test_support', ], 'sources':", "], 'outputs': [ '<(PRODUCT_DIR)/net_unittests.isolated', ], 'action': [ 'python', '../tools/swarm_client/isolate.py', '<(test_isolation_mode)',", "'tools/flip_server/streamer_interface.h', 'tools/flip_server/string_piece_utils.h', ], }, { 'target_name': 'quic_library', 'type': 'static_library', 'dependencies':", "'socket/ssl_server_socket_openssl.cc', 'socket/ssl_socket.h', 'socket/stream_listen_socket.cc', 'socket/stream_listen_socket.h', 'socket/stream_socket.cc', 'socket/stream_socket.h', 'socket/tcp_client_socket.cc', 'socket/tcp_client_socket.h', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h',", "], }, 'includes': [ '../build/win_precompile.gypi', ], 'targets': [ { 'target_name':", "or \"openbsd\". 'socket/unix_domain_socket_posix_unittest.cc', ], 'conditions': [ ['coverage != 0', {", "'stress_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources':", "'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc', 'socket/socks_client_socket.h', 'socket/socks_client_socket_pool.cc', 'socket/socks_client_socket_pool.h', 'socket/ssl_client_socket.cc', 'socket/ssl_client_socket.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h',", "}, 'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_java', 'type':", "# These tests crash when run with coverage turned on", "== \"mac\"', { 'sources!': [ 'ssl/client_cert_store_impl_nss.cc', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr',", "incomplete. # KeygenHandler::GenKeyAndSignChallenge() is not ported to iOS. 'base/keygen_handler_unittest.cc', #", "'data/ssl/certificates/', 'data/url_request_unittest/', ], 'test_data_prefix': 'net', }, 'includes': [ '../build/copy_test_data_ios.gypi' ],", "[4267, ], }, { 'target_name': 'net_resources', 'type': 'none', 'variables': {", "'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc',", "'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc',", "features Android doesn't support. 'ENABLE_MEDIA_CODEC_THEORA', ], }, ], [ 'OS", "'../base/base.gyp:base_i18n', '../base/base.gyp:test_support_perf', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_test_support', ], 'sources': [ 'cookies/cookie_monster_perftest.cc',", "'cert/cert_database_nss.cc', 'cert/cert_database_openssl.cc', 'cert/cert_database_win.cc', 'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h',", "[ 'tools/dump_cache/url_to_filename_encoder.cc', 'tools/dump_cache/url_to_filename_encoder.h', 'tools/dump_cache/url_utilities.h', 'tools/dump_cache/url_utilities.cc', 'tools/flip_server/acceptor_thread.h', 'tools/flip_server/acceptor_thread.cc', 'tools/flip_server/buffer_interface.h', 'tools/flip_server/create_listener.cc', 'tools/flip_server/create_listener.h',", "'cert/nss_cert_database_unittest.cc', ], }, ], [ 'toolkit_uses_gtk == 1', { 'dependencies':", "1', { 'dependencies': [ '../build/linux/system.gyp:gconf', '../build/linux/system.gyp:gio', ], 'conditions': [ ['use_openssl==1',", "1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [", "'defines': [ 'USE_KERBEROS', ], 'conditions': [ ['OS==\"openbsd\"', { 'include_dirs': [", "'POSIX_AVOID_MMAP', ], }, 'sources!': [ 'disk_cache/mapped_file_posix.cc', ], }, { #", "'http/http_proxy_client_socket_pool.cc', 'http/http_proxy_client_socket_pool.h', 'http/http_request_headers.cc', 'http/http_request_headers.h', 'http/http_request_info.cc', 'http/http_request_info.h', 'http/http_response_body_drainer.cc', 'http/http_response_body_drainer.h', 'http/http_response_headers.cc', 'http/http_response_headers.h',", "{ 'sources/': [ ['exclude', '^ftp/'], ], 'sources!': [ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h',", "'base/test_data_stream.h', 'base/upload_bytes_element_reader.cc', 'base/upload_bytes_element_reader.h', 'base/upload_data.cc', 'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc',", "'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc', 'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc',", "'type': 'none', 'variables': { 'java_in_dir': '../net/test/android/javatests', }, 'includes': [ '../build/java.gypi'", "[ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_client_bin.cc', ],", "'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc',", "'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h',", "'http/http_cache_unittest.cc', 'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc',", "'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ], }],", "'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h', 'quic/congestion_control/inter_arrival_probe.cc', 'quic/congestion_control/inter_arrival_probe.h', 'quic/congestion_control/inter_arrival_receiver.cc', 'quic/congestion_control/inter_arrival_receiver.h', 'quic/congestion_control/inter_arrival_sender.cc', 'quic/congestion_control/inter_arrival_sender.h',", "# http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc',", "These tests crash when run with coverage turned on due", "{ 'targets': [ { 'target_name': 'net_unittests_apk', 'type': 'none', 'dependencies': [", "'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h',", "'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_receiver.cc', 'quic/congestion_control/tcp_receiver.h', 'quic/crypto/aes_128_gcm_decrypter.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter.h', 'quic/crypto/aes_128_gcm_encrypter_nss.cc',", "'android/keystore_openssl.h', 'android/net_jni_registrar.cc', 'android/net_jni_registrar.h', 'android/network_change_notifier_android.cc', 'android/network_change_notifier_android.h', 'android/network_change_notifier_delegate_android.cc', 'android/network_change_notifier_delegate_android.h', 'android/network_change_notifier_factory_android.cc', 'android/network_change_notifier_factory_android.h', 'android/network_library.cc',", "'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h', 'http/http_auth_filter_win.h', 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler.cc', 'http/http_auth_handler.h', 'http/http_auth_handler_basic.cc',", "'spdy/spdy_credential_builder_unittest.cc', 'spdy/spdy_credential_state_unittest.cc', 'spdy/spdy_frame_builder_test.cc', 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc',", "'net', 'net_with_v8', ], 'conditions': [ [ 'use_glib == 1', {", "\"win\"', { 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], # TODO(jschuh): crbug.com/167187 fix", "'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', 'tld_cleanup', ], # TODO(jschuh): crbug.com/167187", "'socket/ssl_client_socket_openssl.h', 'socket/ssl_server_socket_openssl.cc', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ], }, ], [ 'use_glib ==", "\"ios\"', { 'sources/': [ ['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'],", "== 1 and OS != \"mac\" and OS != \"android\"", "'base/network_change_notifier_mac.h', 'base/network_change_notifier_win.cc', 'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h',", "'USE_KERBEROS', ], }, { # use_kerberos == 0 'sources!': [", "remove the unneeded files 'sources!': [ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ],", "following tests are disabled because they don't apply to #", "'defines': [ 'POSIX_AVOID_MMAP', ], 'direct_dependent_settings': { 'defines': [ 'POSIX_AVOID_MMAP', ],", "\"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ], 'sources!': [ 'base/openssl_private_key_store_memory.cc',", "'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/gdig/file_net_log.cc', 'tools/gdig/gdig.cc',", "], ], 'sources': [ 'tools/net_watcher/net_watcher.cc', ], }, { 'target_name': 'run_testserver',", "{ 'target_name': 'net_test_jni_headers', 'type': 'none', 'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables':", "files 'sources!': [ 'cert/x509_util_openssl_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', ], }, ], [", "needed to trigger the dll copy step on windows. #", "sure about the # variety of ARM devices. So enable", "'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h', 'http/http_pipelined_host_capability.h',", "], }, { # else use_openssl==0, use NSS 'dependencies': [", "[ '../build/linux/system.gyp:gdk', ], }], [ 'use_nss != 1', { 'sources!':", "], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings':", "\"android\" and gtest_target_type == \"shared_library\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ]", "[ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/dump_cache/cache_dumper.cc', 'tools/dump_cache/cache_dumper.h', 'tools/dump_cache/dump_cache.cc',", "else use_glib == 0: !posix || mac 'sources!': [ 'cert/nss_cert_database_unittest.cc',", "'base/platform_mime_util.h', # TODO(tc): gnome-vfs? xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm', 'base/platform_mime_util_win.cc', 'base/prioritized_dispatcher.cc',", "[ 'DLOPEN_KERBEROS', ], }], ], }, { # use_kerberos ==", "'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h',", "'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc',", "'base/net_export.h', 'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc', 'base/net_util.h', 'base/net_util_posix.cc',", "'sources': [ 'tools/quic/quic_server_bin.cc', ], }, { 'target_name': 'quic_unittests', 'type': '<(gtest_target_type)',", "'none', 'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables': { 'jni_gen_package': 'net', },", "'cert/x509_util_unittest.cc', 'cert/x509_util_nss_unittest.cc', 'cert/x509_util_openssl_unittest.cc', 'cookies/canonical_cookie_unittest.cc', 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc',", "'sources!': [ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ], # This is needed to", "'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc',", "'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h',", "'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h', 'socket/client_socket_pool_base.cc', 'socket/client_socket_pool_base.h', 'socket/client_socket_pool_histograms.cc', 'socket/client_socket_pool_histograms.h', 'socket/client_socket_pool_manager.cc', 'socket/client_socket_pool_manager.h', 'socket/client_socket_pool_manager_impl.cc',", "}, }, ], [ 'OS == \"ios\"', { 'dependencies': [", "'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h',", "'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', 'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc',", "'sources': [ 'android/cert_verify_result_android.h', 'android/cert_verify_result_android_list.h', 'android/gurl_utils.cc', 'android/gurl_utils.h', 'android/keystore.cc', 'android/keystore.h', 'android/keystore_openssl.cc', 'android/keystore_openssl.h',", "'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc', 'dns/single_request_host_resolver.h',", "[ '../third_party/icu/icu.gyp:icudata', '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], # TODO(jschuh): crbug.com/167187 fix", "'sources!': [ 'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }], ['disable_ftp_support==1', { 'sources/': [ ['exclude',", "'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc', 'socket_stream/socket_stream_job.h', 'socket_stream/socket_stream_job_manager.cc', 'socket_stream/socket_stream_job_manager.h', 'socket_stream/socket_stream_metrics.cc',", "'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h', 'proxy/proxy_resolver_mac.cc', 'proxy/proxy_resolver_mac.h', 'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc',", "'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, ], [ 'toolkit_uses_gtk ==", "'base/winsock_util.h', 'base/zap.cc', 'base/zap.h', 'cert/asn1_util.cc', 'cert/asn1_util.h', 'cert/cert_database.cc', 'cert/cert_database.h', 'cert/cert_database_android.cc', 'cert/cert_database_ios.cc', 'cert/cert_database_mac.cc',", "'quic/congestion_control/paced_sender.cc', 'quic/congestion_control/paced_sender.h', 'quic/congestion_control/quic_congestion_manager.cc', 'quic/congestion_control/quic_congestion_manager.h', 'quic/congestion_control/quic_max_sized_map.h', 'quic/congestion_control/receive_algorithm_interface.cc', 'quic/congestion_control/receive_algorithm_interface.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', 'quic/congestion_control/tcp_cubic_sender.cc',", "'disk_cache/cache_util_posix.cc', 'disk_cache/cache_util_win.cc', 'disk_cache/disk_cache.h', 'disk_cache/disk_format.cc', 'disk_cache/disk_format.h', 'disk_cache/entry_impl.cc', 'disk_cache/entry_impl.h', 'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h',", "'../build/linux/system.gyp:gio', ], 'conditions': [ ['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ],", "'http/http_network_session.h', 'http/http_network_session_peer.cc', 'http/http_network_session_peer.h', 'http/http_network_transaction.cc', 'http/http_network_transaction.h', 'http/http_pipelined_connection.h', 'http/http_pipelined_connection_impl.cc', 'http/http_pipelined_connection_impl.h', 'http/http_pipelined_host.cc', 'http/http_pipelined_host.h',", "and OS != \"android\"', { 'targets': [ { 'target_name': 'flip_balsa_and_epoll_library',", "# It needs configuration (krb5.conf and so on). 'use_kerberos%': 0,", "'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc',", "'base/upload_file_element_reader_unittest.cc', 'base/url_util_unittest.cc', 'cert/cert_verify_proc_unittest.cc', 'cert/crl_set_unittest.cc', 'cert/ev_root_ca_metadata_unittest.cc', 'cert/multi_threaded_cert_verifier_unittest.cc', 'cert/nss_cert_database_unittest.cc', 'cert/pem_tokenizer_unittest.cc', 'cert/x509_certificate_unittest.cc', 'cert/x509_cert_types_unittest.cc',", "'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h',", "'target_name': 'net_unittests_run', 'type': 'none', 'dependencies': [ 'net_unittests', ], 'includes': [", "# else 'sources!': [ 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc', ], }], ['use_openssl==1',", "'disk_cache/flash/log_store.h', 'disk_cache/flash/log_store_entry.cc', 'disk_cache/flash/log_store_entry.h', 'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h',", "'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp',", "'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support', ], 'sources': [ 'tools/dump_cache/cache_dumper.cc',", "'base/capturing_net_log.cc', 'base/capturing_net_log.h', 'base/load_timing_info_test_util.cc', 'base/load_timing_info_test_util.h', 'base/mock_file_stream.cc', 'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h',", "'url_request/url_request_http_job.h', 'url_request/url_request_job.cc', 'url_request/url_request_job.h', 'url_request/url_request_job_factory.cc', 'url_request/url_request_job_factory.h', 'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc',", "_toolset==\"target\" and android_webview_build == 0', { 'dependencies': [ 'net_java', ],", "'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h', 'dns/single_request_host_resolver.cc',", "These tests crash when run with coverage turned on: #", "'../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../testing/gtest.gyp:gtest', 'net', 'net_with_v8', ], 'sources': [ 'tools/fetch/fetch_client.cc',", "'cert/x509_certificate_mac.cc', 'cert/x509_certificate_net_log_param.cc', 'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h',", "'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc',", "'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc', 'socket/socket_test_util.h',", "'proxy/proxy_config_service_android_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', 'proxy/proxy_config_service_win_unittest.cc', 'proxy/proxy_config_unittest.cc', 'proxy/proxy_info_unittest.cc', 'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc',", "it for x86 only for now. 'posix_avoid_mmap%': 1, }, {", "'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc',", "}, { 'target_name': 'net_test_support', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base',", "'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h',", "'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'private_key_types_java', 'type': 'none',", "'msvs_disabled_warnings': [4267, ], }, ], }], ['OS != \"ios\"', {", "] }, }, ], [ 'OS == \"ios\"', { 'dependencies':", "with coverage due to a # toolchain bug: http://openradar.appspot.com/radar?id=1499403 'http/transport_security_state_unittest.cc',", "'ssl/openssl_client_key_store.h', ], }, ], [ 'use_glib == 1', { 'dependencies':", "'../third_party/openssl/openssl.gyp:openssl', 'net', 'quic_library', ], 'sources': [ 'tools/quic/quic_client_bin.cc', ], }, {", "'quic/quic_bandwidth_test.cc', 'quic/quic_client_session_test.cc', 'quic/quic_clock_test.cc', 'quic/quic_connection_helper_test.cc', 'quic/quic_connection_test.cc', 'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc',", "'http/http_auth_handler_factory.cc', 'http/http_auth_handler_factory.h', 'http/http_auth_handler_negotiate.cc', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_ntlm.cc', 'http/http_auth_handler_ntlm.h', 'http/http_auth_handler_ntlm_portable.cc', 'http/http_auth_handler_ntlm_win.cc', 'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h',", "'target_name': 'net_test_jni_headers', 'type': 'none', 'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables': {", "{ 'include_dirs': [ '/usr/include/kerberosV' ], }], ['linux_link_kerberos==1', { 'link_settings': {", "{ 'dependencies': [ '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings': { 'libraries': [", "[ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_netlink_linux.cc', 'proxy/proxy_config_service_linux.cc', ], },{ 'dependencies': [ '../build/linux/system.gyp:libresolv', ],", "'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h',", "], 'sources': [ 'tools/fetch/fetch_client.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "[ '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework', '$(SDKROOT)/usr/lib/libresolv.dylib', ] }, }, ], [", "'base/mock_file_stream.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc',", "[ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net' ], 'defines': [ 'NET_IMPLEMENTATION', ],", "[ 'ssl/client_cert_store_impl_nss.cc', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], 'link_settings':", "'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc',", "'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/dump_cache/url_to_filename_encoder.cc',", "'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc',", "'test/cert_test_util.h', 'test/local_test_server_posix.cc', 'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc',", "'url_request/url_request_simple_job.h', 'url_request/url_request_status.h', 'url_request/url_request_test_job.cc', 'url_request/url_request_test_job.h', 'url_request/url_request_throttler_entry.cc', 'url_request/url_request_throttler_entry.h', 'url_request/url_request_throttler_entry_interface.h', 'url_request/url_request_throttler_header_adapter.cc', 'url_request/url_request_throttler_header_adapter.h', 'url_request/url_request_throttler_header_interface.h',", "'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/ssl_client_socket_nss.cc', 'socket/ssl_client_socket_nss.h', 'socket/ssl_server_socket_nss.cc', 'socket/ssl_server_socket_nss.h', 'ssl/client_cert_store_impl_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp',", "needed in specific cases on other platforms. Re-including them can", "# functionality is ported to OpenSSL. 'sources!': [ 'cert/nss_cert_database_unittest.cc', 'cert/x509_util_nss_unittest.cc',", "'udp/datagram_client_socket.h', 'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h',", "'cert/x509_certificate_net_log_param.h', 'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h',", "], }, ], ], }, { 'target_name': 'net_test_support', 'type': 'static_library',", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'dump_cache', 'type':", "'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc', 'disk_cache/flash/log_store_entry_unittest.cc', 'disk_cache/flash/log_store_unittest.cc', 'disk_cache/flash/segment_unittest.cc',", "'USE_KERBEROS', ], 'conditions': [ ['OS==\"openbsd\"', { 'include_dirs': [ '/usr/include/kerberosV' ],", "{ 'sources/': [ ['include', '^base/platform_mime_util_linux\\\\.cc$'], ], }], ['OS == \"ios\"',", "'sources!': [ # TODO(droger): The following tests are disabled because", "'^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'], # The iOS implementation only", "!= \"mac\" and OS != \"android\" and OS != \"ios\"',", "shouldn't be necessary. [ 'OS == \"win\"', { 'dependencies': [", "OS != \"ios\"', { 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [", "'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc', 'http/http_pipelined_host_test_util.h', 'http/http_pipelined_network_transaction_unittest.cc', 'http/http_proxy_client_socket_pool_spdy2_unittest.cc',", "[ '-Wno-deprecated', ], 'dependencies': [ '../base/base.gyp:base', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ],", "be done in target_conditions as it is evaluated after the", "'<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n',", "'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h',", "!= \"mac\"', { 'sources!': [ 'cert/x509_cert_types_unittest.cc', ], }], ], },", "[ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ], }], ['posix_avoid_mmap==1', { 'defines':", "'test/local_test_server_win.cc', 'test/local_test_server.cc', 'test/local_test_server.h', 'test/net_test_suite.cc', 'test/net_test_suite.h', 'test/python_utils.cc', 'test/python_utils.h', 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc',", "and iOS, at least for now. # It needs configuration", "'spdy/spdy_websocket_stream.h', ], }], [ 'OS == \"win\"', { 'sources!': [", "'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h',", "], }, { 'target_name': 'net_test_jni_headers', 'type': 'none', 'sources': [ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java',", "'ftp/ftp_ctrl_response_buffer.h', 'ftp/ftp_directory_listing_parser.cc', 'ftp/ftp_directory_listing_parser.h', 'ftp/ftp_directory_listing_parser_ls.cc', 'ftp/ftp_directory_listing_parser_ls.h', 'ftp/ftp_directory_listing_parser_netware.cc', 'ftp/ftp_directory_listing_parser_netware.h', 'ftp/ftp_directory_listing_parser_os2.cc', 'ftp/ftp_directory_listing_parser_os2.h', 'ftp/ftp_directory_listing_parser_vms.cc',", "'sources!': [ 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', ], }], [ 'OS == \"win\"',", "], }], [ 'use_openssl==1', { # When building for OpenSSL,", "'package_name': 'org/chromium/net', 'template_deps': ['base/net_error_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], },", "'net_unittests', ], 'variables': { 'test_suite_name': 'net_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)net_unittests<(SHARED_LIB_SUFFIX)', }, 'includes':", "'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'cookies/canonical_cookie.cc', 'cookies/canonical_cookie.h', 'cookies/cookie_monster.cc', 'cookies/cookie_monster.h', 'cookies/cookie_options.h', 'cookies/cookie_store.cc',", "'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc', 'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h',", "], }, ], ['OS == \"android\" and gtest_target_type == \"shared_library\"',", "confident that mmap-ing the index would not hurt any #", "'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc', 'quic/quic_bandwidth.h', 'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc',", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', ], 'sources': [ 'tools/dns_fuzz_stub/dns_fuzz_stub.cc',", "'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc', 'disk_cache/trace.h', 'disk_cache/simple/simple_backend_impl.cc', 'disk_cache/simple/simple_backend_impl.h',", "{ 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net'", "!= \"ios\" and OS != \"android\"', { 'targets': [ {", "'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc',", "'disk_cache/simple/simple_disk_format.cc', 'disk_cache/simple/simple_disk_format.h', 'disk_cache/simple/simple_entry_impl.cc', 'disk_cache/simple/simple_entry_impl.h', 'disk_cache/simple/simple_index.cc', 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_synchronous_entry.cc', 'disk_cache/simple/simple_synchronous_entry.h', 'disk_cache/flash/flash_entry_impl.cc', 'disk_cache/flash/flash_entry_impl.h',", "], }, ], [ 'use_v8_in_net==1', { 'dependencies': [ 'net_with_v8', ],", "'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', 'url_request/view_cache_helper_unittest.cc',", "], 'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_errors_java', 'type':", "'OS == \"mac\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ],", "'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc', 'base/io_buffer.h', 'base/ip_endpoint.cc', 'base/ip_endpoint.h', 'base/keygen_handler.cc', 'base/keygen_handler.h',", "# else use_glib == 0: !posix || mac 'sources!': [", "index would not hurt any # existing x86 android devices,", "], }, ], [ 'enable_built_in_dns!=1', { 'sources!': [ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc',", "'base/file_stream_metrics.h', 'base/file_stream_metrics_posix.cc', 'base/file_stream_metrics_win.cc', 'base/file_stream_net_log_parameters.cc', 'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h', 'base/int128.cc', 'base/int128.h',", "'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc', 'disk_cache/mem_backend_impl.cc', 'disk_cache/mem_backend_impl.h', 'disk_cache/mem_entry_impl.cc', 'disk_cache/mem_entry_impl.h', 'disk_cache/mem_rankings.cc', 'disk_cache/mem_rankings.h', 'disk_cache/net_log_parameters.cc', 'disk_cache/net_log_parameters.h',", "{ 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], }], [ 'use_v8_in_net==1', { 'dependencies':", "'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h', 'ssl/ssl_config_service_defaults.cc', 'ssl/ssl_config_service_defaults.h', 'ssl/ssl_info.cc', 'ssl/ssl_info.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp',", "'base/network_change_notifier_win.h', 'base/network_config_watcher_mac.cc', 'base/network_config_watcher_mac.h', 'base/network_delegate.cc', 'base/network_delegate.h', 'base/nss_memio.c', 'base/nss_memio.h', 'base/openssl_private_key_store.h', 'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc',", "'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../v8/tools/gyp/v8.gyp:v8', 'net' ], 'defines': [ 'NET_IMPLEMENTATION',", "can # only be done in target_conditions as it is", "'quic/congestion_control/inter_arrival_receiver_test.cc', 'quic/congestion_control/inter_arrival_state_machine_test.cc', 'quic/congestion_control/inter_arrival_sender_test.cc', 'quic/congestion_control/leaky_bucket_test.cc', 'quic/congestion_control/paced_sender_test.cc', 'quic/congestion_control/quic_congestion_control_test.cc', 'quic/congestion_control/quic_congestion_manager_test.cc', 'quic/congestion_control/quic_max_sized_map_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc',", "truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_resources', 'type': 'none',", "is not ported to iOS. 'base/keygen_handler_unittest.cc', # Need to read", "], }, { 'target_name': 'quic_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:test_support_base',", "['coverage != 0', { 'sources!': [ # These sources can't", "'cert/x509_cert_types_unittest.cc', ], }], ], }, { 'target_name': 'net_perftests', 'type': 'executable',", "'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h', 'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc',", "'proxy/proxy_resolver_v8_tracing.cc', 'proxy/proxy_resolver_v8_tracing.h', 'proxy/proxy_service_v8.cc', 'proxy/proxy_service_v8.h', ], # TODO(jschuh): crbug.com/167187 fix size_t", "[ ['chromeos==1 or OS==\"android\" or OS==\"ios\"', { # Disable Kerberos", "'socket/next_proto.h', 'socket/nss_ssl_util.cc', 'socket/nss_ssl_util.h', 'socket/server_socket.h', 'socket/socket_net_log_params.cc', 'socket/socket_net_log_params.h', 'socket/socket.h', 'socket/socks5_client_socket.cc', 'socket/socks5_client_socket.h', 'socket/socks_client_socket.cc',", "'../base/base.gyp:base', '../base/base.gyp:base_java_test_support', 'net_java', ], 'includes': [ '../build/java.gypi' ], }, {", "0 'use_kerberos%': 1, }], ['OS==\"android\" and target_arch != \"ia32\"', {", "'ssl/client_cert_store_impl.h', 'ssl/client_cert_store_impl_mac.cc', 'ssl/client_cert_store_impl_nss.cc', 'ssl/client_cert_store_impl_win.cc', 'ssl/default_server_bound_cert_store.cc', 'ssl/default_server_bound_cert_store.h', 'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', 'ssl/server_bound_cert_service.cc', 'ssl/server_bound_cert_service.h',", "[ '../base/base.gyp:base', 'cert_verify_result_android_java', 'certificate_mime_types_java', 'net_errors_java', 'private_key_types_java', ], 'includes': [ '../build/java.gypi'", "'url_request/url_request_about_job.h', 'url_request/url_request_context.cc', 'url_request/url_request_context.h', 'url_request/url_request_context_builder.cc', 'url_request/url_request_context_builder.h', 'url_request/url_request_context_getter.cc', 'url_request/url_request_context_getter.h', 'url_request/url_request_context_storage.cc', 'url_request/url_request_context_storage.h', 'url_request/url_request_data_job.cc',", "}, { # else: OS is not in the above", "['use_openssl==1', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, { 'dependencies': [", "'ssl/openssl_client_key_store.cc', 'ssl/openssl_client_key_store.h', ], }, ], [ 'use_glib == 1', {", "'none', 'variables': { 'java_in_dir': '../net/android/javatests', }, 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_java_test_support',", "'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc', 'spdy/spdy_session_pool.h', 'spdy/spdy_stream.cc', 'spdy/spdy_stream.h', 'spdy/spdy_websocket_stream.cc', 'spdy/spdy_websocket_stream.h', 'ssl/client_cert_store.h',", "'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, { # else !use_openssl: remove", "'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up.h', 'quic/congestion_control/inter_arrival_overuse_detector.cc', 'quic/congestion_control/inter_arrival_overuse_detector.h',", "'url_request/url_request_job_factory_impl.cc', 'url_request/url_request_job_factory_impl.h', 'url_request/url_request_job_manager.cc', 'url_request/url_request_job_manager.h', 'url_request/url_request_netlog_params.cc', 'url_request/url_request_netlog_params.h', 'url_request/url_request_redirect_job.cc', 'url_request/url_request_redirect_job.h', 'url_request/url_request_simple_job.cc', 'url_request/url_request_simple_job.h',", "'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc', 'tools/quic/quic_in_memory_cache.h', 'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h',", "'proxy/proxy_resolver_script.h', 'proxy/proxy_resolver_script_data.cc', 'proxy/proxy_resolver_script_data.h', 'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc',", "'udp/datagram_server_socket.h', 'udp/datagram_socket.h', 'udp/udp_client_socket.cc', 'udp/udp_client_socket.h', 'udp/udp_net_log_parameters.cc', 'udp/udp_net_log_parameters.h', 'udp/udp_server_socket.cc', 'udp/udp_server_socket.h', 'udp/udp_socket.h', 'udp/udp_socket_libevent.cc',", "'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h', 'http/http_status_code.h', 'http/http_stream.h', 'http/http_stream_base.h', 'http/http_stream_factory.cc', 'http/http_stream_factory.h',", "of # sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies': [ 'net_javatests', 'net_test_jni_headers',", "they # are needed in specific cases on other platforms.", "['include', '^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'],", "!use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ], }, ], [ 'OS", "'../testing/android/native_test.gyp:native_test_native_code', ] }], [ 'OS != \"win\" and OS !=", "'package_name': 'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], },", "'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ], } ] }], ['OS==\"android\"', { 'targets': [", "'http/des.h', 'http/http_atom_list.h', 'http/http_auth.cc', 'http/http_auth.h', 'http/http_auth_cache.cc', 'http/http_auth_cache.h', 'http/http_auth_controller.cc', 'http/http_auth_controller.h', 'http/http_auth_filter.cc', 'http/http_auth_filter.h',", "'base/openssl_private_key_store_android.cc', 'base/openssl_private_key_store_memory.cc', 'base/platform_mime_util.h', # TODO(tc): gnome-vfs? xdgmime? /etc/mime.types? 'base/platform_mime_util_linux.cc', 'base/platform_mime_util_mac.mm',", "'cert/single_request_cert_verifier.cc', 'cert/single_request_cert_verifier.h', 'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc',", "'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc', 'quic/quic_packet_generator_test.cc', 'quic/quic_protocol_test.cc', 'quic/quic_reliable_client_stream_test.cc', 'quic/quic_session_test.cc',", "'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h',", "use_kerberos == 0 'sources!': [ 'http/http_auth_gssapi_posix.cc', 'http/http_auth_gssapi_posix.h', 'http/http_auth_handler_negotiate.h', 'http/http_auth_handler_negotiate.cc', ],", "'net_jni_headers', ], 'sources!': [ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ], #", "'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', 'http/http_auth_handler_basic_unittest.cc', 'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h',", "'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', 'http/mock_allow_url_security_manager.cc', 'http/mock_allow_url_security_manager.h',", "# else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ], }, ],", "on ChromeOS, Android and iOS, at least for now. #", "'base/net_errors_posix.cc', 'base/net_errors_win.cc', 'base/net_export.h', 'base/net_log.cc', 'base/net_log.h', 'base/net_log_event_type_list.h', 'base/net_log_source_type_list.h', 'base/net_module.cc', 'base/net_module.h', 'base/net_util.cc',", "{ 'sources!': [ 'cert/x509_cert_types_unittest.cc', ], }], ], }, { 'target_name':", "executables, these targets # can't be compiled on the platform.", "'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc', 'base/expiring_cache_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', 'base/int128_unittest.cc', 'base/gzip_filter_unittest.cc', 'base/host_mapping_rules_unittest.cc', 'base/host_port_pair_unittest.cc',", "[ ['OS==\"openbsd\"', { 'include_dirs': [ '/usr/include/kerberosV' ], }], ['linux_link_kerberos==1', {", "'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', 'quic/congestion_control/fix_rate_receiver.cc', 'quic/congestion_control/fix_rate_receiver.h', 'quic/congestion_control/fix_rate_sender.cc', 'quic/congestion_control/fix_rate_sender.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h',", "'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', # These tests crash when run with", "Kerberos on ChromeOS, Android and iOS, at least for now.", "'copy_test_data', 'variables': { 'test_data_files': [ 'data/ssl/certificates/', 'data/url_request_unittest/', ], 'test_data_prefix': 'net',", "}, ], }], ['os_posix == 1 and OS != \"mac\"", "'cert/cert_verify_proc_openssl.h', 'cert/test_root_certs_openssl.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_util_openssl.cc', 'cert/x509_util_openssl.h', 'quic/crypto/aes_128_gcm_decrypter_openssl.cc', 'quic/crypto/aes_128_gcm_encrypter_openssl.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/scoped_evp_cipher_ctx.h', 'socket/ssl_client_socket_openssl.cc',", "'quic/quic_fec_group.h', 'quic/quic_framer.cc', 'quic/quic_framer.h', 'quic/quic_http_stream.cc', 'quic/quic_http_stream.h', 'quic/quic_packet_creator.cc', 'quic/quic_packet_creator.h', 'quic/quic_packet_entropy_manager.cc', 'quic/quic_packet_entropy_manager.h', 'quic/quic_packet_generator.cc',", "These sources can't be built with coverage due to a", "== \"android\"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', 'net_jni_headers', ], 'sources!': [", "'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h', 'proxy/proxy_bypass_rules.cc', 'proxy/proxy_bypass_rules.h', 'proxy/proxy_config.cc', 'proxy/proxy_config.h', 'proxy/proxy_config_service.h',", "uses mmap() is inefficient on some Android devices. # If", "'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h', 'url_request/url_fetcher_response_writer.cc', 'url_request/url_fetcher_response_writer.h', 'url_request/url_request.cc', 'url_request/url_request.h', 'url_request/url_request_about_job.cc', 'url_request/url_request_about_job.h', 'url_request/url_request_context.cc',", "\"mac\"', { 'sources!': [ 'ssl/client_cert_store_impl_nss.cc', ], 'dependencies': [ '../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss',", "into an android apk for execution. # See base.gyp for", "'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'base/test_data_directory.cc', 'base/test_data_directory.h', 'cert/mock_cert_verifier.cc', 'cert/mock_cert_verifier.h', 'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h',", "'tld_cleanup', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', ], 'sources':", "}], [ 'use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:ssl', ],", "turned on: # http://crbug.com/177203 'proxy/proxy_service_unittest.cc', ], }], ], }], [", "], }, 'sources!': [ 'disk_cache/mapped_file_posix.cc', ], }, { # else", "'posix_avoid_mmap%': 1, }, { 'posix_avoid_mmap%': 0, }], ['OS==\"ios\"', { #", "'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', 'dns/dns_config_service_posix_unittest.cc', 'dns/dns_config_service_unittest.cc', 'dns/dns_config_service_win_unittest.cc', 'dns/dns_hosts_unittest.cc', 'dns/dns_query_unittest.cc', 'dns/dns_response_unittest.cc', 'dns/dns_session_unittest.cc', 'dns/dns_transaction_unittest.cc',", "'../base/base.gyp:base', 'net', 'net_with_v8', ], 'conditions': [ [ 'use_glib == 1',", "], }, { 'target_name': 'flip_in_mem_edsm_server', 'type': 'executable', 'cflags': [ '-Wno-deprecated',", "'base/keygen_handler_nss.cc', 'base/keygen_handler_openssl.cc', 'base/keygen_handler_win.cc', 'base/linked_hash_map.h', 'base/load_flags.h', 'base/load_flags_list.h', 'base/load_states.h', 'base/load_states_list.h', 'base/load_timing_info.cc', 'base/load_timing_info.h',", "'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h', 'dns/dns_config_service.cc', 'dns/dns_config_service.h',", "'sources!': [ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h', 'ssl/client_cert_store_impl_nss.cc', ], }], [ 'enable_websockets !=", "'OS == \"linux\"', { 'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ], },", "'cookies/parsed_cookie_unittest.cc', 'disk_cache/addr_unittest.cc', 'disk_cache/backend_unittest.cc', 'disk_cache/bitmap_unittest.cc', 'disk_cache/block_files_unittest.cc', 'disk_cache/cache_util_unittest.cc', 'disk_cache/entry_unittest.cc', 'disk_cache/mapped_file_unittest.cc', 'disk_cache/storage_block_unittest.cc', 'disk_cache/flash/flash_entry_unittest.cc',", "'socket_stream/socket_stream_metrics.cc', 'socket_stream/socket_stream_metrics.h', 'spdy/buffered_spdy_framer.cc', 'spdy/buffered_spdy_framer.h', 'spdy/spdy_bitmasks.h', 'spdy/spdy_credential_builder.cc', 'spdy/spdy_credential_builder.h', 'spdy/spdy_credential_state.cc', 'spdy/spdy_credential_state.h', 'spdy/spdy_frame_builder.cc',", "'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc', 'spdy/spdy_stream_test_util.h', 'spdy/spdy_test_util_common.cc', 'spdy/spdy_test_util_common.h', 'spdy/spdy_test_util_spdy3.cc', 'spdy/spdy_test_util_spdy3.h', 'spdy/spdy_test_util_spdy2.cc',", "'net', 'net_test_support', ], 'sources': [ 'disk_cache/stress_cache.cc', ], # TODO(jschuh): crbug.com/167187", "'^socket_stream/'], ['exclude', '^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }], [ 'disable_ftp_support==1', {", "crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [4267, ], },", "'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h', 'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc',", "}, ], [ 'OS == \"mac\"', { 'sources!': [ 'ssl/client_cert_store_impl_nss.cc',", "'cert/x509_certificate_nss.cc', 'cert/x509_certificate_openssl.cc', 'cert/x509_certificate_win.cc', 'cert/x509_util.h', 'cert/x509_util.cc', 'cert/x509_util_ios.cc', 'cert/x509_util_ios.h', 'cert/x509_util_mac.cc', 'cert/x509_util_mac.h', 'cert/x509_util_nss.cc',", "}], [ 'use_nss != 1', { 'sources!': [ 'cert/cert_verify_proc_nss.cc', 'cert/cert_verify_proc_nss.h',", "[ '../build/jni_generator.gypi' ], }, { 'target_name': 'net_java', 'type': 'none', 'variables':", "'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h', 'quic/test_tools/mock_random.cc',", "'disk_cache/file_win.cc', 'disk_cache/histogram_macros.h', 'disk_cache/in_flight_backend_io.cc', 'disk_cache/in_flight_backend_io.h', 'disk_cache/in_flight_io.cc', 'disk_cache/in_flight_io.h', 'disk_cache/mapped_file.h', 'disk_cache/mapped_file_posix.cc', 'disk_cache/mapped_file_avoid_mmap_posix.cc', 'disk_cache/mapped_file_win.cc',", "1 and OS != \"mac\" and OS != \"ios\" and", "'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h', 'socket/transport_client_socket_pool.cc', 'socket/transport_client_socket_pool.h', 'socket/unix_domain_socket_posix.cc', 'socket/unix_domain_socket_posix.h', 'socket_stream/socket_stream.cc', 'socket_stream/socket_stream.h', 'socket_stream/socket_stream_job.cc',", "and thus does not # defines |use_nss|. In particular the", "'private_key_types_java', ], 'includes': [ '../build/java.gypi' ], }, { 'target_name': 'net_java_test_support',", "'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h', 'proxy/multi_threaded_proxy_resolver.cc', 'proxy/multi_threaded_proxy_resolver.h', 'proxy/network_delegate_error_observer.cc', 'proxy/network_delegate_error_observer.h', 'proxy/polling_proxy_config_service.cc', 'proxy/polling_proxy_config_service.h',", "'socket/tcp_client_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.cc', 'socket/tcp_listen_socket_unittest.h', 'socket/tcp_server_socket_unittest.cc', 'socket/transport_client_socket_pool_unittest.cc', 'socket/transport_client_socket_unittest.cc', 'socket/unix_domain_socket_posix_unittest.cc', 'socket_stream/socket_stream_metrics_unittest.cc', 'socket_stream/socket_stream_unittest.cc', 'spdy/buffered_spdy_framer_spdy3_unittest.cc',", "'quic/test_tools/reliable_quic_stream_peer.h', 'tools/flip_server/simple_buffer.cc', 'tools/flip_server/simple_buffer.h', 'tools/quic/end_to_end_test.cc', 'tools/quic/quic_client_session_test.cc', 'tools/quic/quic_dispatcher_test.cc', 'tools/quic/quic_epoll_clock_test.cc', 'tools/quic/quic_epoll_connection_helper_test.cc', 'tools/quic/quic_reliable_client_stream_test.cc', 'tools/quic/quic_reliable_server_stream_test.cc',", "'android/java/NetError.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/net_error_list.h'], }, 'includes':", "partially uses NSS and thus does not # defines |use_nss|.", "'sources': [ 'android/java/CertVerifyResultAndroid.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['android/cert_verify_result_android_list.h'],", "'toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gdk', ], }], [", "'^dns/notify_watcher_mac\\\\.cc$'], ['include', '^proxy/proxy_resolver_mac\\\\.cc$'], ['include', '^proxy/proxy_server_mac\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'], ],", "'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc', 'tools/quic/quic_client_session.h', 'tools/quic/quic_dispatcher.h', 'tools/quic/quic_dispatcher.cc', 'tools/quic/quic_epoll_clock.cc', 'tools/quic/quic_epoll_clock.h', 'tools/quic/quic_epoll_connection_helper.cc', 'tools/quic/quic_epoll_connection_helper.h', 'tools/quic/quic_in_memory_cache.cc',", "'http/http_proxy_client_socket_pool_spdy2_unittest.cc', 'http/http_proxy_client_socket_pool_spdy3_unittest.cc', 'http/http_request_headers_unittest.cc', 'http/http_response_body_drainer_unittest.cc', 'http/http_response_headers_unittest.cc', 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc',", "'dependencies': [ '../base/base.gyp:base', 'net', 'net_with_v8', ], 'conditions': [ [ 'use_glib", "'tools/quic/quic_packet_writer.h', 'tools/quic/quic_reliable_client_stream.cc', 'tools/quic/quic_reliable_client_stream.h', 'tools/quic/quic_reliable_server_stream.cc', 'tools/quic/quic_reliable_server_stream.h', 'tools/quic/quic_server.cc', 'tools/quic/quic_server.h', 'tools/quic/quic_server_session.cc', 'tools/quic/quic_server_session.h', 'tools/quic/quic_socket_utils.cc',", "It needs configuration (krb5.conf and so on). 'use_kerberos%': 0, },", "'quic/quic_clock.cc', 'quic/quic_clock.h', 'quic/quic_connection.cc', 'quic/quic_connection.h', 'quic/quic_connection_helper.cc', 'quic/quic_connection_helper.h', 'quic/quic_connection_logger.cc', 'quic/quic_connection_logger.h', 'quic/quic_data_reader.cc', 'quic/quic_data_reader.h',", "'dns/dns_config_service.h', 'dns/dns_config_service_posix.cc', 'dns/dns_config_service_posix.h', 'dns/dns_config_service_win.cc', 'dns/dns_config_service_win.h', 'dns/dns_hosts.cc', 'dns/dns_hosts.h', 'dns/dns_protocol.h', 'dns/dns_query.cc', 'dns/dns_query.h',", "['include', '^base/network_change_notifier_mac\\\\.cc$'], ['include', '^base/network_config_watcher_mac\\\\.cc$'], ['include', '^base/platform_mime_util_mac\\\\.mm$'], # The iOS implementation", "'http/proxy_client_socket.cc', 'http/transport_security_state.cc', 'http/transport_security_state.h', 'http/transport_security_state_static.h', 'http/url_security_manager.cc', 'http/url_security_manager.h', 'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h',", "'socket/tcp_client_socket_libevent.h', 'socket/tcp_client_socket_win.cc', 'socket/tcp_client_socket_win.h', 'socket/tcp_listen_socket.cc', 'socket/tcp_listen_socket.h', 'socket/tcp_server_socket.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'socket/tcp_server_socket_win.cc', 'socket/tcp_server_socket_win.h',", "'spdy/spdy_io_buffer.cc', 'spdy/spdy_io_buffer.h', 'spdy/spdy_priority_forest.h', 'spdy/spdy_protocol.cc', 'spdy/spdy_protocol.h', 'spdy/spdy_proxy_client_socket.cc', 'spdy/spdy_proxy_client_socket.h', 'spdy/spdy_session.cc', 'spdy/spdy_session.h', 'spdy/spdy_session_pool.cc',", "'http/mock_sspi_library_win.cc', 'http/mock_sspi_library_win.h', 'http/transport_security_state_unittest.cc', 'http/url_security_manager_unittest.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_factory_unittest.cc', 'proxy/dhcp_proxy_script_fetcher_win_unittest.cc', 'proxy/multi_threaded_proxy_resolver_unittest.cc', 'proxy/network_delegate_error_observer_unittest.cc', 'proxy/proxy_bypass_rules_unittest.cc',", "[ 'base/openssl_private_key_store_memory.cc', 'cert/cert_database_openssl.cc', 'cert/cert_verify_proc_openssl.cc', 'cert/test_root_certs_openssl.cc', ], # The net/android/keystore_openssl.cc source", "'tools/flip_server/flip_in_mem_edsm_server.cc', 'tools/flip_server/http_interface.cc', 'tools/flip_server/http_interface.h', 'tools/flip_server/loadtime_measurement.h', 'tools/flip_server/mem_cache.h', 'tools/flip_server/mem_cache.cc', 'tools/flip_server/output_ordering.cc', 'tools/flip_server/output_ordering.h', 'tools/flip_server/ring_buffer.cc', 'tools/flip_server/ring_buffer.h',", "'disk_cache/errors.h', 'disk_cache/eviction.cc', 'disk_cache/eviction.h', 'disk_cache/experiments.h', 'disk_cache/file.cc', 'disk_cache/file.h', 'disk_cache/file_block.h', 'disk_cache/file_lock.cc', 'disk_cache/file_lock.h', 'disk_cache/file_posix.cc',", "'http/url_security_manager_posix.cc', 'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h',", "'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h', 'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h',", "'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h', 'quic/quic_bandwidth.cc',", "!= 1', { 'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ],", "'url_request/url_request_context_builder_unittest.cc', 'url_request/url_request_filter_unittest.cc', 'url_request/url_request_ftp_job_unittest.cc', 'url_request/url_request_http_job_unittest.cc', 'url_request/url_request_job_factory_impl_unittest.cc', 'url_request/url_request_job_unittest.cc', 'url_request/url_request_throttler_simulation_unittest.cc', 'url_request/url_request_throttler_test_support.cc', 'url_request/url_request_throttler_test_support.h', 'url_request/url_request_throttler_unittest.cc',", "[ # iOS doesn't have the concept of simple executables,", "'http/http_response_headers.cc', 'http/http_response_headers.h', 'http/http_response_info.cc', 'http/http_response_info.h', 'http/http_security_headers.cc', 'http/http_security_headers.h', 'http/http_server_properties.cc', 'http/http_server_properties.h', 'http/http_server_properties_impl.cc', 'http/http_server_properties_impl.h',", "to int truncations. 'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_watcher',", "'OS == \"mac\"', { 'sources!': [ 'ssl/client_cert_store_impl_nss.cc', ], 'dependencies': [", "'../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', '../third_party/zlib/zlib.gyp:zlib', 'net_resources', ], 'sources': [", "'targets': [ # iOS doesn't have the concept of simple", "'net_errors_java', 'type': 'none', 'sources': [ 'android/java/NetError.template', ], 'variables': { 'package_name':", "'../testing/gtest.gyp:gtest', 'net', 'net_test_support', ], 'sources': [ 'cookies/cookie_monster_perftest.cc', 'disk_cache/disk_cache_perftest.cc', 'proxy/proxy_resolver_perftest.cc', ],", "[ 'android/java/CertificateMimeType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps': ['base/mime_util_certificate_type_list.h'], },", "{ # When building for OpenSSL, we need to exclude", "have the concept of simple executables, these targets # can't", "'target_name': 'quic_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl',", "'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc',", "'defines': [ 'USE_KERBEROS', ], }, { # use_kerberos == 0", "'http/http_auth_sspi_win.cc', 'http/http_auth_sspi_win.h', 'http/http_basic_stream.cc', 'http/http_basic_stream.h', 'http/http_byte_range.cc', 'http/http_byte_range.h', 'http/http_cache.cc', 'http/http_cache.h', 'http/http_cache_transaction.cc', 'http/http_cache_transaction.h',", "\"mac\"', { 'sources!': [ 'cert/x509_cert_types_unittest.cc', ], }], ], }, {", "'cert/test_root_certs.cc', 'cert/test_root_certs.h', 'cert/test_root_certs_mac.cc', 'cert/test_root_certs_nss.cc', 'cert/test_root_certs_openssl.cc', 'cert/test_root_certs_android.cc', 'cert/test_root_certs_win.cc', 'cert/x509_cert_types.cc', 'cert/x509_cert_types.h', 'cert/x509_cert_types_mac.cc',", "{ 'test_data_files': [ 'data/ssl/certificates/', 'data/url_request_unittest/', ], 'test_data_prefix': 'net', }, 'includes':", "'http/http_cache_transaction.h', 'http/http_content_disposition.cc', 'http/http_content_disposition.h', 'http/http_chunked_decoder.cc', 'http/http_chunked_decoder.h', 'http/http_network_layer.cc', 'http/http_network_layer.h', 'http/http_network_session.cc', 'http/http_network_session.h', 'http/http_network_session_peer.cc',", "}, { 'target_name': 'flip_in_mem_edsm_server', 'type': 'executable', 'cflags': [ '-Wno-deprecated', ],", "'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_errors_unittest.cc', 'websockets/websocket_frame_parser_unittest.cc', 'websockets/websocket_frame_unittest.cc', 'websockets/websocket_handshake_handler_unittest.cc', 'websockets/websocket_handshake_handler_spdy2_unittest.cc', 'websockets/websocket_handshake_handler_spdy3_unittest.cc', 'websockets/websocket_job_spdy2_unittest.cc', 'websockets/websocket_job_spdy3_unittest.cc', 'websockets/websocket_net_log_params_unittest.cc',", "configuration (krb5.conf and so on). 'use_kerberos%': 0, }, { #", "}, { 'target_name': 'run_testserver', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:test_support_base',", "], [ 'enable_built_in_dns!=1', { 'sources!': [ 'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ], },", "'quic/crypto/null_encrypter.cc', 'quic/crypto/null_encrypter.h', 'quic/crypto/p256_key_exchange.h', 'quic/crypto/p256_key_exchange_nss.cc', 'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc',", "'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto', ], }], ['os_posix == 1 and OS", "'ssl/server_bound_cert_store.h', 'ssl/ssl_cert_request_info.cc', 'ssl/ssl_cert_request_info.h', 'ssl/ssl_cipher_suite_names.cc', 'ssl/ssl_cipher_suite_names.h', 'ssl/ssl_client_auth_cache.cc', 'ssl/ssl_client_auth_cache.h', 'ssl/ssl_client_cert_type.h', 'ssl/ssl_config_service.cc', 'ssl/ssl_config_service.h',", "'disk_cache/mapped_file_avoid_mmap_posix.cc', ], }], ['disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'], ],", "'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], }, ], [ 'toolkit_uses_gtk == 1', {", "'disk_cache/backend_unittest.cc', 'disk_cache/block_files_unittest.cc', 'socket/ssl_server_socket_unittest.cc', # Need TestServer. 'proxy/proxy_script_fetcher_impl_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', 'url_request/url_fetcher_impl_unittest.cc',", "'OS', '<(OS)', '--result', '<@(_outputs)', '--isolate', 'net_unittests.isolate', ], }, ], },", "'enable_websockets%': 0, # iOS does not use V8. 'use_v8_in_net%': 0,", "'base/upload_data.h', 'base/upload_data_stream.cc', 'base/upload_data_stream.h', 'base/upload_element.cc', 'base/upload_element.h', 'base/upload_element_reader.cc', 'base/upload_element_reader.h', 'base/upload_file_element_reader.cc', 'base/upload_file_element_reader.h', 'base/upload_progress.h',", "\"ia32\"', { # The way the cache uses mmap() is", "'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_receiver_test.cc', 'quic/crypto/aes_128_gcm_decrypter_test.cc', 'quic/crypto/aes_128_gcm_encrypter_test.cc', 'quic/crypto/crypto_framer_test.cc', 'quic/crypto/crypto_handshake_test.cc', 'quic/crypto/curve25519_key_exchange_test.cc', 'quic/crypto/null_decrypter_test.cc', 'quic/crypto/null_encrypter_test.cc', 'quic/crypto/p256_key_exchange_test.cc',", "], }], ], }], ['OS != \"android\"', { 'sources!': [", "'../base/base.gyp:base', 'net', ], 'sources': [ 'tools/crl_set_dump/crl_set_dump.cc', ], # TODO(jschuh): crbug.com/167187", "} ] }], ['OS==\"android\"', { 'targets': [ { 'target_name': 'net_jni_headers',", "'proxy/proxy_resolver_winhttp.cc', 'proxy/proxy_resolver_winhttp.h', 'proxy/proxy_retry_info.h', 'proxy/proxy_script_decider.cc', 'proxy/proxy_script_decider.h', 'proxy/proxy_script_fetcher.h', 'proxy/proxy_script_fetcher_impl.cc', 'proxy/proxy_script_fetcher_impl.h', 'proxy/proxy_server.cc', 'proxy/proxy_server.h',", "'dns/address_sorter_posix_unittest.cc', 'dns/address_sorter_unittest.cc', ], }, ], [ 'use_v8_in_net==1', { 'dependencies': [", "{ 'target_name': 'flip_balsa_and_epoll_library', 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', 'net', ],", "int truncations. 'msvs_disabled_warnings': [4267, ], }, { # else: OS", "], 'targets': [ { 'target_name': 'net', 'type': '<(component)', 'variables': {", "'msvs_disabled_warnings': [4267, ], }, { 'target_name': 'net_resources', 'type': 'none', 'variables':", "'http/url_security_manager_win.cc', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc',", "can't be compiled on the platform. { 'target_name': 'crash_cache', 'type':", "'none', 'sources': [ 'android/java/PrivateKeyType.template', ], 'variables': { 'package_name': 'org/chromium/net', 'template_deps':", "{ # else: !use_v8_in_net 'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ], },", "'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc', 'proxy/proxy_config_source.h', 'proxy/proxy_info.cc', 'proxy/proxy_info.h', 'proxy/proxy_list.cc', 'proxy/proxy_list.h', 'proxy/proxy_resolver.h', 'proxy/proxy_resolver_error_observer.h',", "'socket/deterministic_socket_data_unittest.cc', 'socket/mock_client_socket_pool_manager.cc', 'socket/mock_client_socket_pool_manager.h', 'socket/socks5_client_socket_unittest.cc', 'socket/socks_client_socket_pool_unittest.cc', 'socket/socks_client_socket_unittest.cc', 'socket/ssl_client_socket_openssl_unittest.cc', 'socket/ssl_client_socket_pool_unittest.cc', 'socket/ssl_client_socket_unittest.cc', 'socket/ssl_server_socket_unittest.cc',", "], 'conditions': [ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ],", "'proxy/dhcp_proxy_script_adapter_fetcher_win.cc', 'proxy/dhcp_proxy_script_adapter_fetcher_win.h', 'proxy/dhcp_proxy_script_fetcher.cc', 'proxy/dhcp_proxy_script_fetcher.h', 'proxy/dhcp_proxy_script_fetcher_factory.cc', 'proxy/dhcp_proxy_script_fetcher_factory.h', 'proxy/dhcp_proxy_script_fetcher_win.cc', 'proxy/dhcp_proxy_script_fetcher_win.h', 'proxy/dhcpcsvc_init_win.cc', 'proxy/dhcpcsvc_init_win.h',", "'../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ], }, ], [ 'OS == \"android\"', {", "'../build/linux/system.gyp:ssl', ], }], ], }], ['os_posix == 1 and OS", "'none', 'variables': { 'java_in_dir': '../net/test/android/javatests', }, 'includes': [ '../build/java.gypi' ],", "'ldflags': [ '-R/usr/lib/mps', ], }, }], ], }, { #", "'spdy/spdy_websocket_test_util_spdy2.cc', 'spdy/spdy_websocket_test_util_spdy2.h', 'spdy/spdy_websocket_test_util_spdy3.cc', 'spdy/spdy_websocket_test_util_spdy3.h', 'ssl/client_cert_store_impl_unittest.cc', 'ssl/default_server_bound_cert_store_unittest.cc', 'ssl/openssl_client_key_store_unittest.cc', 'ssl/server_bound_cert_service_unittest.cc', 'ssl/ssl_cipher_suite_names_unittest.cc', 'ssl/ssl_client_auth_cache_unittest.cc',", "[ 'android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java', ], 'variables': { 'jni_gen_package': 'net', }, 'direct_dependent_settings': {", "in the disk cache. # We are pretty confident that", "'cookies/cookie_monster_store_test.cc', 'cookies/cookie_monster_store_test.h', 'cookies/cookie_store_test_callbacks.cc', 'cookies/cookie_store_test_callbacks.h', 'cookies/cookie_store_test_helpers.cc', 'cookies/cookie_store_test_helpers.h', 'disk_cache/disk_cache_test_base.cc', 'disk_cache/disk_cache_test_base.h', 'disk_cache/disk_cache_test_util.cc', 'disk_cache/disk_cache_test_util.h',", "'static_library', 'dependencies': [ '../base/base.gyp:base', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ],", "'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources':", "llvm_gcda_increment_indirect_counter: # http://crbug.com/156058 'cookies/cookie_monster_unittest.cc', 'cookies/cookie_store_unittest.h', 'http/http_auth_controller_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc',", "'<(gtest_target_type)', 'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', 'net', 'quic_library', ], 'sources':", "[ ['coverage != 0', { 'sources!': [ # These sources", "OS != \"ios\"', { 'dependencies': [ '../third_party/protobuf/protobuf.gyp:py_proto', ], }], ['os_posix", "'disk_cache/sparse_control.cc', 'disk_cache/sparse_control.h', 'disk_cache/stats.cc', 'disk_cache/stats.h', 'disk_cache/stats_histogram.cc', 'disk_cache/stats_histogram.h', 'disk_cache/storage_block-inl.h', 'disk_cache/storage_block.h', 'disk_cache/stress_support.h', 'disk_cache/trace.cc',", "'../third_party/nss/nss.gyp:nspr', '../third_party/nss/nss.gyp:nss', 'third_party/nss/ssl.gyp:libssl', ], }, ], [ 'OS == \"ios\"',", "'sources!': [ 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', ], }, ], [ 'OS ==", "particular the |USE_NSS| preprocessor # definition is not used. The", "# else !use_openssl: remove the unneeded files 'sources!': [ 'base/crypto_module_openssl.cc',", "'quic/quic_crypto_client_stream_test.cc', 'quic/quic_crypto_server_stream_test.cc', 'quic/quic_crypto_stream_test.cc', 'quic/quic_data_writer_test.cc', 'quic/quic_fec_group_test.cc', 'quic/quic_framer_test.cc', 'quic/quic_http_stream_test.cc', 'quic/quic_network_transaction_unittest.cc', 'quic/quic_packet_creator_test.cc', 'quic/quic_packet_entropy_manager_test.cc',", "'sources!': [ # No res_ninit() et al on Android, so", "'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/dns_client.cc', ], }], ['use_openssl==1', { 'sources!': [ 'base/crypto_module_nss.cc',", "'<(PRODUCT_DIR)', '--variable', 'OS', '<(OS)', '--result', '<@(_outputs)', '--isolate', 'net_unittests.isolate', ], },", "'base/file_stream_net_log_parameters.h', 'base/file_stream_whence.h', 'base/filter.cc', 'base/filter.h', 'base/int128.cc', 'base/int128.h', 'base/gzip_filter.cc', 'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h',", "'target_name': 'get_server_time', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net',", "V8. 'use_v8_in_net%': 0, 'enable_built_in_dns%': 0, }, { 'enable_websockets%': 1, 'use_v8_in_net%':", "'dns/mapped_host_resolver_unittest.cc', 'dns/serial_worker_unittest.cc', 'dns/single_request_host_resolver_unittest.cc', 'ftp/ftp_auth_cache_unittest.cc', 'ftp/ftp_ctrl_response_buffer_unittest.cc', 'ftp/ftp_directory_listing_parser_ls_unittest.cc', 'ftp/ftp_directory_listing_parser_netware_unittest.cc', 'ftp/ftp_directory_listing_parser_os2_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h',", "'http/http_stream_factory_impl.h', 'http/http_stream_factory_impl_job.cc', 'http/http_stream_factory_impl_job.h', 'http/http_stream_factory_impl_request.cc', 'http/http_stream_factory_impl_request.h', 'http/http_stream_parser.cc', 'http/http_stream_parser.h', 'http/http_transaction.h', 'http/http_transaction_delegate.h', 'http/http_transaction_factory.h',", "'tools/quic/test_tools/http_message_test_utils.cc', 'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ],", "'base/gzip_filter.h', 'base/gzip_header.cc', 'base/gzip_header.h', 'base/hash_value.cc', 'base/hash_value.h', 'base/host_mapping_rules.cc', 'base/host_mapping_rules.h', 'base/host_port_pair.cc', 'base/host_port_pair.h', 'base/io_buffer.cc',", "'proxy/proxy_list_unittest.cc', 'proxy/proxy_resolver_v8_tracing_unittest.cc', 'proxy/proxy_resolver_v8_unittest.cc', 'proxy/proxy_script_decider_unittest.cc', 'proxy/proxy_script_fetcher_impl_unittest.cc', 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc',", "'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc', 'spdy/spdy_proxy_client_socket_spdy3_unittest.cc', 'spdy/spdy_proxy_client_socket_spdy2_unittest.cc', 'spdy/spdy_session_spdy3_unittest.cc', 'spdy/spdy_session_spdy2_unittest.cc', 'spdy/spdy_stream_spdy3_unittest.cc', 'spdy/spdy_stream_spdy2_unittest.cc', 'spdy/spdy_stream_test_util.cc',", "], }], [ 'enable_websockets != 1', { 'sources/': [ ['exclude',", "'os_posix == 1 and OS != \"mac\" and OS !=", "\"android\"', { 'sources!': [ # No res_ninit() et al on", "}, ], [ 'enable_websockets != 1', { 'sources/': [ ['exclude',", "'http/http_auth_handler_digest_unittest.cc', 'http/http_auth_handler_factory_unittest.cc', 'http/http_auth_handler_mock.cc', 'http/http_auth_handler_mock.h', 'http/http_auth_handler_negotiate_unittest.cc', 'http/http_auth_handler_unittest.cc', 'http/http_auth_sspi_win_unittest.cc', 'http/http_auth_unittest.cc', 'http/http_byte_range_unittest.cc', 'http/http_cache_unittest.cc',", "sources can't be built with coverage due to a #", "'../base/base.gyp:base', 'net', ], 'sources': [ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h',", "], }, { 'target_name': 'run_testserver', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h', 'tools/flip_server/constants.h', 'tools/flip_server/epoll_server.cc', 'tools/flip_server/epoll_server.h', 'tools/flip_server/http_message_constants.cc',", "'OS == \"win\"', { 'sources!': [ 'dns/dns_config_service_posix_unittest.cc', 'http/http_auth_gssapi_posix_unittest.cc', ], #", "'url_request/url_request_file_dir_job.cc', 'url_request/url_request_file_dir_job.h', 'url_request/url_request_file_job.cc', 'url_request/url_request_file_job.h', 'url_request/url_request_filter.cc', 'url_request/url_request_filter.h', 'url_request/url_request_ftp_job.cc', 'url_request/url_request_ftp_job.h', 'url_request/url_request_http_job.cc', 'url_request/url_request_http_job.h',", "The way the cache uses mmap() is inefficient on some", "['OS != \"android\"', { 'sources!': [ 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h',", "{ 'target_name': 'dump_cache', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net', 'net_test_support',", "'quic/crypto/quic_random_test.cc', 'quic/crypto/strike_register_test.cc', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_crypto_client_stream.cc', 'quic/test_tools/mock_crypto_client_stream.h', 'quic/test_tools/mock_crypto_client_stream_factory.cc', 'quic/test_tools/mock_crypto_client_stream_factory.h',", "{ # Disable Kerberos on ChromeOS, Android and iOS, at", "'cert/cert_status_flags.cc', 'cert/cert_status_flags.h', 'cert/cert_trust_anchor_provider.h', 'cert/cert_verifier.cc', 'cert/cert_verifier.h', 'cert/cert_verify_proc.cc', 'cert/cert_verify_proc.h', 'cert/cert_verify_proc_android.cc', 'cert/cert_verify_proc_android.h', 'cert/cert_verify_proc_mac.cc',", "[ ['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux_unittest.cc', 'proxy/proxy_config_service_linux_unittest.cc', ], }], [", "'spdy/spdy_frame_reader.cc', 'spdy/spdy_frame_reader.h', 'spdy/spdy_framer.cc', 'spdy/spdy_framer.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', 'spdy/spdy_http_stream.cc', 'spdy/spdy_http_stream.h', 'spdy/spdy_http_utils.cc', 'spdy/spdy_http_utils.h',", "hurt any # existing x86 android devices, but we cannot", "'base/registry_controlled_domains/registry_controlled_domain.h', 'base/request_priority.h', 'base/sdch_filter.cc', 'base/sdch_filter.h', 'base/sdch_manager.cc', 'base/sdch_manager.h', 'base/static_cookie_policy.cc', 'base/static_cookie_policy.h', 'base/sys_addrinfo.h', 'base/test_data_stream.cc',", "trigger the dll copy step on windows. # TODO(mark): Specifying", "'dns/dns_test_util.h', 'dns/mock_host_resolver.cc', 'dns/mock_host_resolver.h', 'proxy/mock_proxy_resolver.cc', 'proxy/mock_proxy_resolver.h', 'proxy/mock_proxy_script_fetcher.cc', 'proxy/mock_proxy_script_fetcher.h', 'proxy/proxy_config_service_common_unittest.cc', 'proxy/proxy_config_service_common_unittest.h', 'socket/socket_test_util.cc',", "'udp/udp_socket_win.h', 'url_request/data_protocol_handler.cc', 'url_request/data_protocol_handler.h', 'url_request/file_protocol_handler.cc', 'url_request/file_protocol_handler.h', 'url_request/fraudulent_certificate_reporter.h', 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', 'url_request/protocol_intercept_job_factory.cc',", "'android/keystore_unittest.cc', 'android/network_change_notifier_android_unittest.cc', 'base/address_list_unittest.cc', 'base/address_tracker_linux_unittest.cc', 'base/backoff_entry_unittest.cc', 'base/big_endian_unittest.cc', 'base/data_url_unittest.cc', 'base/directory_lister_unittest.cc', 'base/dns_util_unittest.cc', 'base/escape_unittest.cc',", "'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "}], ], }], ['OS != \"android\"', { 'sources!': [ 'test/remote_test_server.cc',", "['include', '^ocsp/nss_ocsp\\\\.cc$'], ['include', '^ocsp/nss_ocsp\\\\.h$'], ], }], ], }, { 'target_name':", "'quic/test_tools/quic_session_peer.h', 'quic/test_tools/crypto_test_utils.cc', 'quic/test_tools/crypto_test_utils.h', 'quic/test_tools/mock_clock.cc', 'quic/test_tools/mock_clock.h', 'quic/test_tools/mock_random.cc', 'quic/test_tools/mock_random.h', 'quic/test_tools/simple_quic_framer.cc', 'quic/test_tools/simple_quic_framer.h', 'quic/test_tools/quic_connection_peer.cc',", "'quic/crypto/p256_key_exchange_openssl.cc', 'quic/crypto/quic_decrypter.cc', 'quic/crypto/quic_decrypter.h', 'quic/crypto/quic_encrypter.cc', 'quic/crypto/quic_encrypter.h', 'quic/crypto/quic_random.cc', 'quic/crypto/quic_random.h', 'quic/crypto/scoped_evp_cipher_ctx.h', 'quic/crypto/strike_register.cc', 'quic/crypto/strike_register.h',", "The following tests are disabled because they don't apply to", "}, { 'target_name': 'net_watcher', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', 'net',", "}], ['OS == \"ios\"', { 'dependencies': [ '../third_party/nss/nss.gyp:nss', ], }],", "chromeos == 0 'use_kerberos%': 1, }], ['OS==\"android\" and target_arch !=", "'proxy/proxy_service_unittest.cc', 'quic/blocked_list_test.cc', 'quic/congestion_control/available_channel_estimator_test.cc', 'quic/congestion_control/channel_estimator_test.cc', 'quic/congestion_control/cube_root_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/fix_rate_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/inter_arrival_bitrate_ramp_up_test.cc', 'quic/congestion_control/inter_arrival_overuse_detector_test.cc',", "# linux_link_kerberos==0 'defines': [ 'DLOPEN_KERBEROS', ], }], ], }, {", "'^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }], [ 'disable_ftp_support==1', { 'sources/': [ ['exclude', '^ftp/'],", "'proxy/proxy_config_service_fixed.h', 'proxy/proxy_config_service_ios.cc', 'proxy/proxy_config_service_ios.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h', 'proxy/proxy_config_service_mac.cc', 'proxy/proxy_config_service_mac.h', 'proxy/proxy_config_service_win.cc', 'proxy/proxy_config_service_win.h', 'proxy/proxy_config_source.cc',", "'http/http_chunked_decoder_unittest.cc', 'http/http_content_disposition_unittest.cc', 'http/http_network_layer_unittest.cc', 'http/http_network_transaction_spdy3_unittest.cc', 'http/http_network_transaction_spdy2_unittest.cc', 'http/http_pipelined_connection_impl_unittest.cc', 'http/http_pipelined_host_forced_unittest.cc', 'http/http_pipelined_host_impl_unittest.cc', 'http/http_pipelined_host_pool_unittest.cc', 'http/http_pipelined_host_test_util.cc',", "apply to # iOS. # OS is not \"linux\" or", "[ 'net_unittests.isolate', ], 'actions': [ { 'action_name': 'isolate', 'inputs': [", "support. 'ENABLE_MEDIA_CODEC_THEORA', ], }, ], [ 'OS == \"linux\"', {", "is not used. The following files are needed though: ['include',", "'tools/quic/test_tools/http_message_test_utils.h', 'tools/quic/test_tools/mock_epoll_server.cc', 'tools/quic/test_tools/mock_epoll_server.h', 'tools/quic/test_tools/quic_test_client.cc', 'tools/quic/test_tools/quic_test_client.h', 'tools/quic/test_tools/quic_test_utils.cc', 'tools/quic/test_tools/quic_test_utils.h', 'tools/quic/test_tools/run_all_unittests.cc', ], }", "lot of # sense. 'dns/dns_config_service_posix_unittest.cc', 'ssl/client_cert_store_impl_unittest.cc', ], 'dependencies': [ 'net_javatests',", "is not in the above list 'sources!': [ 'base/crypto_module_nss.cc', 'base/keygen_handler_nss.cc',", "'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ] }], [ 'OS != \"win\" and", "'ftp/ftp_directory_listing_parser_windows.h', 'ftp/ftp_network_layer.cc', 'ftp/ftp_network_layer.h', 'ftp/ftp_network_session.cc', 'ftp/ftp_network_session.h', 'ftp/ftp_network_transaction.cc', 'ftp/ftp_network_transaction.h', 'ftp/ftp_request_info.h', 'ftp/ftp_response_info.cc', 'ftp/ftp_response_info.h',", "{ 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ],", "OS != \"android\"', { 'targets': [ { 'target_name': 'flip_balsa_and_epoll_library', 'type':", "2013 The Chromium Authors. All rights reserved. # Use of", "'dependencies': [ '../build/linux/system.gyp:dbus', '../dbus/dbus.gyp:dbus_test_support', ], }, ], [ 'OS ==", "'disk_cache/flash/segment.cc', 'disk_cache/flash/segment.h', 'disk_cache/flash/storage.cc', 'disk_cache/flash/storage.h', 'dns/address_sorter.h', 'dns/address_sorter_posix.cc', 'dns/address_sorter_posix.h', 'dns/address_sorter_win.cc', 'dns/dns_client.cc', 'dns/dns_client.h',", "'sources': [ 'tools/flip_server/balsa_enums.h', 'tools/flip_server/balsa_frame.cc', 'tools/flip_server/balsa_frame.h', 'tools/flip_server/balsa_headers.cc', 'tools/flip_server/balsa_headers.h', 'tools/flip_server/balsa_headers_token_utils.cc', 'tools/flip_server/balsa_headers_token_utils.h', 'tools/flip_server/balsa_visitor_interface.h',", "'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/net', }, 'actions': [ { 'action_name': 'net_resources', 'variables': {", "], }, ], [ 'enable_websockets != 1', { 'sources/': [", "\"win\"', { 'sources!': [ 'http/http_auth_handler_ntlm_portable.cc', 'socket/tcp_client_socket_libevent.cc', 'socket/tcp_client_socket_libevent.h', 'socket/tcp_server_socket_libevent.cc', 'socket/tcp_server_socket_libevent.h', 'ssl/client_cert_store_impl_nss.cc',", "'ftp/ftp_directory_listing_parser_unittest.cc', 'ftp/ftp_directory_listing_parser_unittest.h', 'ftp/ftp_directory_listing_parser_vms_unittest.cc', 'ftp/ftp_directory_listing_parser_windows_unittest.cc', 'ftp/ftp_network_transaction_unittest.cc', 'ftp/ftp_util_unittest.cc', 'http/des_unittest.cc', 'http/http_auth_cache_unittest.cc', 'http/http_auth_controller_unittest.cc', 'http/http_auth_filter_unittest.cc',", "mmap-ing the index would not hurt any # existing x86", "or OS==\"ios\"', { # Disable Kerberos on ChromeOS, Android and", "'dns/dns_session.cc', 'dns/dns_session.h', 'dns/dns_socket_pool.cc', 'dns/dns_socket_pool.h', 'dns/dns_transaction.cc', 'dns/dns_transaction.h', 'dns/host_cache.cc', 'dns/host_cache.h', 'dns/host_resolver.cc', 'dns/host_resolver.h',", "gssapi)', ], }, }, { # linux_link_kerberos==0 'defines': [ 'DLOPEN_KERBEROS',", "], },{ 'dependencies': [ '../build/linux/system.gyp:libresolv', ], }], ['OS==\"solaris\"', { 'link_settings':", "'http/http_vary_data.cc', 'http/http_vary_data.h', 'http/http_version.h', 'http/md4.cc', 'http/md4.h', 'http/partial_data.cc', 'http/partial_data.h', 'http/proxy_client_socket.h', 'http/proxy_client_socket.cc', 'http/transport_security_state.cc',", "'quic/quic_blocked_writer_interface.h', 'quic/quic_client_session.cc', 'quic/quic_client_session.h', 'quic/quic_crypto_client_stream.cc', 'quic/quic_crypto_client_stream.h', 'quic/quic_crypto_client_stream_factory.h', 'quic/quic_crypto_server_stream.cc', 'quic/quic_crypto_server_stream.h', 'quic/quic_crypto_stream.cc', 'quic/quic_crypto_stream.h',", "'sources/': [ ['exclude', '^socket_stream/'], ['exclude', '^websockets/'], ['exclude', '^spdy/spdy_websocket_stream_spdy._unittest\\\\.cc$'], ], }],", "['include', '^base/platform_mime_util_mac\\\\.mm$'], # The iOS implementation only partially uses NSS", "'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', 'third_party/mozilla_security_manager/nsPKCS12Blob.h', ], },", "'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', 'url_request/url_fetcher.h', 'url_request/url_fetcher_core.cc', 'url_request/url_fetcher_core.h', 'url_request/url_fetcher_delegate.cc', 'url_request/url_fetcher_delegate.h', 'url_request/url_fetcher_factory.h', 'url_request/url_fetcher_impl.cc', 'url_request/url_fetcher_impl.h',", "else OS != \"android\" 'defines': [ # These are the", "'../build/temp_gyp/googleurl.gyp:googleurl', '../third_party/openssl/openssl.gyp:openssl', 'flip_balsa_and_epoll_library', 'net', ], 'sources': [ 'tools/quic/quic_client.cc', 'tools/quic/quic_client.h', 'tools/quic/quic_client_session.cc',", "], }, { 'target_name': 'crl_set_dump', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base',", "!= \"android\"', { 'sources!': [ 'test/remote_test_server.cc', 'test/remote_test_server.h', 'test/spawner_communicator.cc', 'test/spawner_communicator.h', ],", "['base/mime_util_certificate_type_list.h'], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { 'target_name': 'cert_verify_result_android_java',", "'quic/reliable_quic_stream.cc', 'quic/reliable_quic_stream.h', 'socket/buffered_write_stream_socket.cc', 'socket/buffered_write_stream_socket.h', 'socket/client_socket_factory.cc', 'socket/client_socket_factory.h', 'socket/client_socket_handle.cc', 'socket/client_socket_handle.h', 'socket/client_socket_pool.cc', 'socket/client_socket_pool.h',", "'proxy/proxy_server_mac.cc', 'proxy/proxy_service.cc', 'proxy/proxy_service.h', 'quic/blocked_list.h', 'quic/congestion_control/available_channel_estimator.cc', 'quic/congestion_control/available_channel_estimator.h', 'quic/congestion_control/channel_estimator.cc', 'quic/congestion_control/channel_estimator.h', 'quic/congestion_control/cube_root.cc', 'quic/congestion_control/cube_root.h',", "[ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../build/temp_gyp/googleurl.gyp:googleurl', 'net', ], 'sources': [ 'tools/get_server_time/get_server_time.cc', ],", "'cert/nss_cert_database.cc', 'cert/nss_cert_database.h', 'cert/test_root_certs_nss.cc', 'cert/x509_certificate_nss.cc', 'cert/x509_util_nss.cc', 'cert/x509_util_nss.h', 'ocsp/nss_ocsp.cc', 'ocsp/nss_ocsp.h', 'quic/crypto/aes_128_gcm_decrypter_nss.cc', 'quic/crypto/aes_128_gcm_encrypter_nss.cc',", "'sources': [ 'tools/crl_set_dump/crl_set_dump.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "--libs gssapi)', ], }, }, { # linux_link_kerberos==0 'defines': [", "[ '../build/win_precompile.gypi', ], 'targets': [ { 'target_name': 'net', 'type': '<(component)',", "], }], ['OS==\"solaris\"', { 'link_settings': { 'ldflags': [ '-R/usr/lib/mps', ],", "'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_unittest.cc', 'spdy/spdy_http_stream_spdy3_unittest.cc', 'spdy/spdy_http_stream_spdy2_unittest.cc', 'spdy/spdy_http_utils_unittest.cc', 'spdy/spdy_network_transaction_spdy3_unittest.cc', 'spdy/spdy_network_transaction_spdy2_unittest.cc', 'spdy/spdy_priority_forest_test.cc', 'spdy/spdy_protocol_test.cc',", "'dns/host_resolver_impl.cc', 'dns/host_resolver_impl.h', 'dns/host_resolver_proc.cc', 'dns/host_resolver_proc.h', 'dns/mapped_host_resolver.cc', 'dns/mapped_host_resolver.h', 'dns/notify_watcher_mac.cc', 'dns/notify_watcher_mac.h', 'dns/serial_worker.cc', 'dns/serial_worker.h',", "['chromeos==1', { 'sources!': [ 'base/network_change_notifier_linux.cc', 'base/network_change_notifier_linux.h', 'base/network_change_notifier_netlink_linux.cc', 'base/network_change_notifier_netlink_linux.h', 'proxy/proxy_config_service_linux.cc', 'proxy/proxy_config_service_linux.h'," ]
[ "def init_model(self, char_vocab, hidden_size, n_domain_type, n_layers): pass @abstractmethod def train_model(self,", "torch import torch.nn as nn from abc import ABC, abstractmethod", "def load_model(self, file_path): \"\"\" This function load already saved model", "= torch.load(file_path) model.eval() self.__model = model self.__set_model2cuda() self.__set_optimizer() def save_model(self,", "and sets cuda parameters. :param file_path: File path of a", "saves model to given location. :param file_path: File path to", "function saves model to given location. :param file_path: File path", "model): \"\"\"This function leverages model by setting parallelism parameters. :param", "string \"\"\" model = torch.load(file_path) model.eval() self.__model = model self.__set_model2cuda()", "train_dataset): pass def load_model(self, file_path): \"\"\" This function load already", "already saved model and sets cuda parameters. :param file_path: File", "save_model(self, file_path): \"\"\" This function saves model to given location.", "path to save model. :type file_path: string \"\"\" torch.save(self.model, file_path)", ":param file_path: File path of a model to loaded. :type", "= model self.__set_model2cuda() self.__set_optimizer() def save_model(self, file_path): \"\"\" This function", "model self.__set_model2cuda() self.__set_optimizer() def save_model(self, file_path): \"\"\" This function saves", "GPUs!\" % (gpu_count)) self.__model = nn.DataParallel(self.model) self.__set_model2cuda() else: self.__set_model2cuda() def", "@abstractmethod def predict(self, epoch, train_dataset): pass def load_model(self, file_path): \"\"\"", "leverages model by setting parallelism parameters. :param model: Model instance.", "parameters. :param model: Model instance. :type model: RNNClassifier \"\"\" self.__model", "@abstractmethod def train_model(self, epoch, train_dataset): pass @abstractmethod def predict(self, epoch,", "return self.__model @property def optimizer(self): return self.__optimizer @property def criterion(self):", ") def __set_model2cuda(self): if torch.cuda.is_available(): log.info(\"Setting cuda\") self.model.cuda() def leverage_model(self,", "def save_model(self, file_path): \"\"\" This function saves model to given", "n_layers): pass @abstractmethod def train_model(self, epoch, train_dataset): pass @abstractmethod def", "logging.getLogger(__name__) class Detector(ABC): def __init__(self, lr=0.001): self.lr = lr self.__model", "torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0 ) def __set_model2cuda(self): if torch.cuda.is_available(): log.info(\"Setting", "to save model. :type file_path: string \"\"\" torch.save(self.model, file_path) def", "= torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0 ) def __set_model2cuda(self): if torch.cuda.is_available():", "log.info(\"Setting cuda\") self.model.cuda() def leverage_model(self, model): \"\"\"This function leverages model", "function leverages model by setting parallelism parameters. :param model: Model", "Model instance. :type model: RNNClassifier \"\"\" self.__model = model self.__set_parallelism()", "model. :type file_path: string \"\"\" torch.save(self.model, file_path) def __set_parallelism(self): gpu_count", "import torch import torch.nn as nn from abc import ABC,", "pass @abstractmethod def train_model(self, epoch, train_dataset): pass @abstractmethod def predict(self,", "import torch.nn as nn from abc import ABC, abstractmethod log", "string \"\"\" torch.save(self.model, file_path) def __set_parallelism(self): gpu_count = torch.cuda.device_count() if", "setting parallelism parameters. :param model: Model instance. :type model: RNNClassifier", "torch.load(file_path) model.eval() self.__model = model self.__set_model2cuda() self.__set_optimizer() def save_model(self, file_path):", "lr self.__model = None self.__optimizer = None self.__criterion = nn.CrossEntropyLoss()", ":type file_path: string \"\"\" model = torch.load(file_path) model.eval() self.__model =", "\"\"\" model = torch.load(file_path) model.eval() self.__model = model self.__set_model2cuda() self.__set_optimizer()", "train_model(self, epoch, train_dataset): pass @abstractmethod def predict(self, epoch, train_dataset): pass", "__set_parallelism(self): gpu_count = torch.cuda.device_count() if gpu_count > 1: log.info(\"%s GPUs!\"", "class Detector(ABC): def __init__(self, lr=0.001): self.lr = lr self.__model =", "by setting parallelism parameters. :param model: Model instance. :type model:", "def __set_parallelism(self): gpu_count = torch.cuda.device_count() if gpu_count > 1: log.info(\"%s", "__set_model2cuda(self): if torch.cuda.is_available(): log.info(\"Setting cuda\") self.model.cuda() def leverage_model(self, model): \"\"\"This", "\"\"\" torch.save(self.model, file_path) def __set_parallelism(self): gpu_count = torch.cuda.device_count() if gpu_count", "if torch.cuda.is_available(): log.info(\"Setting cuda\") self.model.cuda() def leverage_model(self, model): \"\"\"This function", "file_path: File path of a model to loaded. :type file_path:", "cuda\") self.model.cuda() def leverage_model(self, model): \"\"\"This function leverages model by", "log = logging.getLogger(__name__) class Detector(ABC): def __init__(self, lr=0.001): self.lr =", "> 1: log.info(\"%s GPUs!\" % (gpu_count)) self.__model = nn.DataParallel(self.model) self.__set_model2cuda()", "given location. :param file_path: File path to save model. :type", "nn.CrossEntropyLoss() @property def model(self): return self.__model @property def optimizer(self): return", "nn.DataParallel(self.model) self.__set_model2cuda() else: self.__set_model2cuda() def __set_optimizer(self): self.__optimizer = torch.optim.RMSprop( self.model.parameters(),", "self.__model = None self.__optimizer = None self.__criterion = nn.CrossEntropyLoss() @property", "self.__set_model2cuda() self.__set_optimizer() def save_model(self, file_path): \"\"\" This function saves model", "File path of a model to loaded. :type file_path: string", "self.model.cuda() def leverage_model(self, model): \"\"\"This function leverages model by setting", "Detector(ABC): def __init__(self, lr=0.001): self.lr = lr self.__model = None", "self.__model = model self.__set_model2cuda() self.__set_optimizer() def save_model(self, file_path): \"\"\" This", "instance. :type model: RNNClassifier \"\"\" self.__model = model self.__set_parallelism() self.__set_optimizer()", "def optimizer(self): return self.__optimizer @property def criterion(self): return self.__criterion @abstractmethod", "init_model(self, char_vocab, hidden_size, n_domain_type, n_layers): pass @abstractmethod def train_model(self, epoch,", "epoch, train_dataset): pass def load_model(self, file_path): \"\"\" This function load", "of a model to loaded. :type file_path: string \"\"\" model", "train_dataset): pass @abstractmethod def predict(self, epoch, train_dataset): pass def load_model(self,", "parallelism parameters. :param model: Model instance. :type model: RNNClassifier \"\"\"", "self.__criterion = nn.CrossEntropyLoss() @property def model(self): return self.__model @property def", "def __set_model2cuda(self): if torch.cuda.is_available(): log.info(\"Setting cuda\") self.model.cuda() def leverage_model(self, model):", "sets cuda parameters. :param file_path: File path of a model", "= nn.DataParallel(self.model) self.__set_model2cuda() else: self.__set_model2cuda() def __set_optimizer(self): self.__optimizer = torch.optim.RMSprop(", "def train_model(self, epoch, train_dataset): pass @abstractmethod def predict(self, epoch, train_dataset):", ":param model: Model instance. :type model: RNNClassifier \"\"\" self.__model =", "file_path: string \"\"\" model = torch.load(file_path) model.eval() self.__model = model", "model(self): return self.__model @property def optimizer(self): return self.__optimizer @property def", "= logging.getLogger(__name__) class Detector(ABC): def __init__(self, lr=0.001): self.lr = lr", "None self.__criterion = nn.CrossEntropyLoss() @property def model(self): return self.__model @property", "def leverage_model(self, model): \"\"\"This function leverages model by setting parallelism", "file_path): \"\"\" This function load already saved model and sets", "@property def optimizer(self): return self.__optimizer @property def criterion(self): return self.__criterion", "file_path) def __set_parallelism(self): gpu_count = torch.cuda.device_count() if gpu_count > 1:", "self.__model = nn.DataParallel(self.model) self.__set_model2cuda() else: self.__set_model2cuda() def __set_optimizer(self): self.__optimizer =", "self.__set_model2cuda() else: self.__set_model2cuda() def __set_optimizer(self): self.__optimizer = torch.optim.RMSprop( self.model.parameters(), self.lr,", "log.info(\"%s GPUs!\" % (gpu_count)) self.__model = nn.DataParallel(self.model) self.__set_model2cuda() else: self.__set_model2cuda()", "file_path): \"\"\" This function saves model to given location. :param", "% (gpu_count)) self.__model = nn.DataParallel(self.model) self.__set_model2cuda() else: self.__set_model2cuda() def __set_optimizer(self):", "model: Model instance. :type model: RNNClassifier \"\"\" self.__model = model", "model by setting parallelism parameters. :param model: Model instance. :type", "lr=0.001): self.lr = lr self.__model = None self.__optimizer = None", "self.lr = lr self.__model = None self.__optimizer = None self.__criterion", "n_domain_type, n_layers): pass @abstractmethod def train_model(self, epoch, train_dataset): pass @abstractmethod", "self.__set_model2cuda() def __set_optimizer(self): self.__optimizer = torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0 )", "optimizer(self): return self.__optimizer @property def criterion(self): return self.__criterion @abstractmethod def", "pass @abstractmethod def predict(self, epoch, train_dataset): pass def load_model(self, file_path):", "weight_decay=0.0 ) def __set_model2cuda(self): if torch.cuda.is_available(): log.info(\"Setting cuda\") self.model.cuda() def", "@property def criterion(self): return self.__criterion @abstractmethod def init_model(self, char_vocab, hidden_size,", "if gpu_count > 1: log.info(\"%s GPUs!\" % (gpu_count)) self.__model =", "hidden_size, n_domain_type, n_layers): pass @abstractmethod def train_model(self, epoch, train_dataset): pass", "This function saves model to given location. :param file_path: File", "def __set_optimizer(self): self.__optimizer = torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0 ) def", "abstractmethod log = logging.getLogger(__name__) class Detector(ABC): def __init__(self, lr=0.001): self.lr", "\"\"\" This function saves model to given location. :param file_path:", "torch.nn as nn from abc import ABC, abstractmethod log =", "import ABC, abstractmethod log = logging.getLogger(__name__) class Detector(ABC): def __init__(self,", "model to given location. :param file_path: File path to save", "char_vocab, hidden_size, n_domain_type, n_layers): pass @abstractmethod def train_model(self, epoch, train_dataset):", "ABC, abstractmethod log = logging.getLogger(__name__) class Detector(ABC): def __init__(self, lr=0.001):", "torch.save(self.model, file_path) def __set_parallelism(self): gpu_count = torch.cuda.device_count() if gpu_count >", "parameters. :param file_path: File path of a model to loaded.", "self.__set_optimizer() def save_model(self, file_path): \"\"\" This function saves model to", "self.__optimizer = torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0 ) def __set_model2cuda(self): if", "model and sets cuda parameters. :param file_path: File path of", "model to loaded. :type file_path: string \"\"\" model = torch.load(file_path)", "= None self.__criterion = nn.CrossEntropyLoss() @property def model(self): return self.__model", "load_model(self, file_path): \"\"\" This function load already saved model and", "load already saved model and sets cuda parameters. :param file_path:", "predict(self, epoch, train_dataset): pass def load_model(self, file_path): \"\"\" This function", "criterion(self): return self.__criterion @abstractmethod def init_model(self, char_vocab, hidden_size, n_domain_type, n_layers):", "pass def load_model(self, file_path): \"\"\" This function load already saved", "save model. :type file_path: string \"\"\" torch.save(self.model, file_path) def __set_parallelism(self):", "= nn.CrossEntropyLoss() @property def model(self): return self.__model @property def optimizer(self):", "self.__model @property def optimizer(self): return self.__optimizer @property def criterion(self): return", "model.eval() self.__model = model self.__set_model2cuda() self.__set_optimizer() def save_model(self, file_path): \"\"\"", "self.__optimizer = None self.__criterion = nn.CrossEntropyLoss() @property def model(self): return", "else: self.__set_model2cuda() def __set_optimizer(self): self.__optimizer = torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0", "self.model.parameters(), self.lr, weight_decay=0.0 ) def __set_model2cuda(self): if torch.cuda.is_available(): log.info(\"Setting cuda\")", "self.__optimizer @property def criterion(self): return self.__criterion @abstractmethod def init_model(self, char_vocab,", "\"\"\" This function load already saved model and sets cuda", "None self.__optimizer = None self.__criterion = nn.CrossEntropyLoss() @property def model(self):", "torch.cuda.is_available(): log.info(\"Setting cuda\") self.model.cuda() def leverage_model(self, model): \"\"\"This function leverages", "return self.__optimizer @property def criterion(self): return self.__criterion @abstractmethod def init_model(self,", "def __init__(self, lr=0.001): self.lr = lr self.__model = None self.__optimizer", "file_path: string \"\"\" torch.save(self.model, file_path) def __set_parallelism(self): gpu_count = torch.cuda.device_count()", "= lr self.__model = None self.__optimizer = None self.__criterion =", "path of a model to loaded. :type file_path: string \"\"\"", "def criterion(self): return self.__criterion @abstractmethod def init_model(self, char_vocab, hidden_size, n_domain_type,", "self.__criterion @abstractmethod def init_model(self, char_vocab, hidden_size, n_domain_type, n_layers): pass @abstractmethod", "a model to loaded. :type file_path: string \"\"\" model =", "model = torch.load(file_path) model.eval() self.__model = model self.__set_model2cuda() self.__set_optimizer() def", "file_path: File path to save model. :type file_path: string \"\"\"", "1: log.info(\"%s GPUs!\" % (gpu_count)) self.__model = nn.DataParallel(self.model) self.__set_model2cuda() else:", "cuda parameters. :param file_path: File path of a model to", "abc import ABC, abstractmethod log = logging.getLogger(__name__) class Detector(ABC): def", "__init__(self, lr=0.001): self.lr = lr self.__model = None self.__optimizer =", "logging import torch import torch.nn as nn from abc import", "import logging import torch import torch.nn as nn from abc", "as nn from abc import ABC, abstractmethod log = logging.getLogger(__name__)", ":type file_path: string \"\"\" torch.save(self.model, file_path) def __set_parallelism(self): gpu_count =", "function load already saved model and sets cuda parameters. :param", "@abstractmethod def init_model(self, char_vocab, hidden_size, n_domain_type, n_layers): pass @abstractmethod def", "gpu_count = torch.cuda.device_count() if gpu_count > 1: log.info(\"%s GPUs!\" %", "__set_optimizer(self): self.__optimizer = torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0 ) def __set_model2cuda(self):", "def predict(self, epoch, train_dataset): pass def load_model(self, file_path): \"\"\" This", "torch.cuda.device_count() if gpu_count > 1: log.info(\"%s GPUs!\" % (gpu_count)) self.__model", "saved model and sets cuda parameters. :param file_path: File path", "self.lr, weight_decay=0.0 ) def __set_model2cuda(self): if torch.cuda.is_available(): log.info(\"Setting cuda\") self.model.cuda()", "loaded. :type file_path: string \"\"\" model = torch.load(file_path) model.eval() self.__model", "= None self.__optimizer = None self.__criterion = nn.CrossEntropyLoss() @property def", "location. :param file_path: File path to save model. :type file_path:", "This function load already saved model and sets cuda parameters.", "to loaded. :type file_path: string \"\"\" model = torch.load(file_path) model.eval()", "epoch, train_dataset): pass @abstractmethod def predict(self, epoch, train_dataset): pass def", "from abc import ABC, abstractmethod log = logging.getLogger(__name__) class Detector(ABC):", "nn from abc import ABC, abstractmethod log = logging.getLogger(__name__) class", "def model(self): return self.__model @property def optimizer(self): return self.__optimizer @property", "= torch.cuda.device_count() if gpu_count > 1: log.info(\"%s GPUs!\" % (gpu_count))", "leverage_model(self, model): \"\"\"This function leverages model by setting parallelism parameters.", "gpu_count > 1: log.info(\"%s GPUs!\" % (gpu_count)) self.__model = nn.DataParallel(self.model)", "\"\"\"This function leverages model by setting parallelism parameters. :param model:", ":param file_path: File path to save model. :type file_path: string", "(gpu_count)) self.__model = nn.DataParallel(self.model) self.__set_model2cuda() else: self.__set_model2cuda() def __set_optimizer(self): self.__optimizer", "return self.__criterion @abstractmethod def init_model(self, char_vocab, hidden_size, n_domain_type, n_layers): pass", "to given location. :param file_path: File path to save model.", "@property def model(self): return self.__model @property def optimizer(self): return self.__optimizer", "File path to save model. :type file_path: string \"\"\" torch.save(self.model," ]
[ "\"criteria\" class Place (models.Model): lat = models.FloatField() lon = models.FloatField()", "\"\"\" score = models.IntegerField() \"\"\" The rating score. 1 means", "return self.__places or self.init_places() def init_places(self): \"\"\" Load two places", "\"\"\" SOURCES = ( ('ip', 'IP Address'), ('html5', 'HTML5 Geolocation", "means that place2 \"wins\". \"\"\" user_info = models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings')", "models.CharField(max_length=256, null=True, blank=True) about_text = models.TextField(null=True, blank=True) about_text_is_html = models.BooleanField(blank=True,", "the user that made this rating. Not required, but useful", "Meta: app_label = 'sites' db_table = 'project_siteconfiguration' class SurveySession (object):", "return self.prompt class Meta: verbose_name_plural = \"criteria\" class Place (models.Model):", "Meta: abstract = True class Rating (TimeStampedModel): criterion = models.ForeignKey('Criterion',", "init_places(self): \"\"\" Load two places at random. TODO: Order the", "random. \"\"\" all_questions = ( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) ) self.__questions =", "self.__places or self.init_places() def init_places(self): \"\"\" Load two places at", "-1 means that place2 \"wins\". \"\"\" user_info = models.ForeignKey('sessions.UserInfo', null=True,", "def __unicode__(self): return self.prompt class Meta: verbose_name_plural = \"criteria\" class", "def init_questions(self): \"\"\" Load a set of questions at random.", "abstract = True class Rating (TimeStampedModel): criterion = models.ForeignKey('Criterion', related_name='ratings')", "'as {0} as', }) return ('Place #{p1} is {rating} place", "self.criterion.prompt class Criterion (models.Model): prompt = models.TextField() \"\"\" The question", "import models class TimeStampedModel (models.Model): \"\"\" Base model class for", "user that made this rating. Not required, but useful for", "self.__questions @classmethod def make_surveys(cls, count=1): # TODO: Choose the places", "of created and updated times for model instances. \"\"\" created_datetime", "that this rating compares \"\"\" score = models.IntegerField() \"\"\" The", "rating compares \"\"\" score = models.IntegerField() \"\"\" The rating score.", "@property def places(self): \"\"\" Get the block for this session.", "related_name='ratings') \"\"\" The information for the user that made this", "a response. \"\"\" return self.criterion.prompt class Criterion (models.Model): prompt =", "(models.Model): site = models.OneToOneField('sites.Site', related_name='config') google_analytics_key = models.CharField(max_length=256, null=True, blank=True)", "prompt, i.e. 'How clean is the street?'. \"\"\" def __unicode__(self):", "('ip', 'IP Address'), ('html5', 'HTML5 Geolocation API'), ) location_source =", "models class TimeStampedModel (models.Model): \"\"\" Base model class for when", "app_label = 'sessions' db_table = 'project_userinfo' verbose_name_plural = 'User info'", "return self.__questions or self.init_questions() @property def places(self): \"\"\" Get the", "models.ForeignKey('Place', related_name='+') \"\"\" The second place that this rating compares", "= models.CharField(max_length=256, null=True, blank=True) addthis_title = models.CharField(max_length=256, null=True, blank=True) about_title", "Order the places by those that have the least questions", "rating is a response. \"\"\" return self.criterion.prompt class Criterion (models.Model):", "Place.objects.all().order_by('?')[:2] self.__places = places return self.__places def init_questions(self): \"\"\" Load", "location_source = models.CharField(max_length=32, choices=SOURCES) location_data = models.CharField(max_length=2048) \"\"\" The method", "models.TextField() \"\"\" The question prompt, i.e. 'How clean is the", "def places(self): \"\"\" Get the block for this session. \"\"\"", "@property def questions(self): \"\"\" Get the set of questions for", "places @property def questions(self): \"\"\" Get the set of questions", "instances. \"\"\" created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) class Meta:", "{1})'.format(self.lat, self.lon) class UserInfo (TimeStampedModel): lat = models.FloatField(null=True) lon =", "all_questions return self.__questions @classmethod def make_surveys(cls, count=1): # TODO: Choose", "defined above (and make them better too). places = list(Place.objects.all().order_by('?')[:(count", "updated times for model instances. \"\"\" created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime", "location. \"\"\" SOURCES = ( ('ip', 'IP Address'), ('html5', 'HTML5", "than', 0: 'as {0} as', }) return ('Place #{p1} is", "class Place (models.Model): lat = models.FloatField() lon = models.FloatField() def", "required to recreate the location. \"\"\" session = models.OneToOneField('sessions.Session') \"\"\"", "random. TODO: Order the places by those that have the", "return self.__places def init_questions(self): \"\"\" Load a set of questions", "= models.OneToOneField('sites.Site', related_name='config') google_analytics_key = models.CharField(max_length=256, null=True, blank=True) addthis_key =", "block for this session. \"\"\" return self.__places or self.init_places() def", "\"\"\" The information for the user that made this rating.", "that have the least questions answered about them first. \"\"\"", "related_name='config') google_analytics_key = models.CharField(max_length=256, null=True, blank=True) addthis_key = models.CharField(max_length=256, null=True,", "\"\"\" place2 = models.ForeignKey('Place', related_name='+') \"\"\" The second place that", "1 means that place1 \"wins\" over place2 for the given", "and any additional information required to recreate the location. \"\"\"", "(object): \"\"\" \"\"\" def __init__(self, questions=None, places=None): self.__questions = questions", "means that place1 \"wins\" over place2 for the given criterion.", "def __unicode__(self): return u'User for session {key}'.format(key=self.session.session_key) class Meta: app_label", "\"\"\" user_info = models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings') \"\"\" The information for", ".annotate(num_ratings=models.Count('ratings')) ) self.__questions = all_questions return self.__questions @classmethod def make_surveys(cls,", "'sites' db_table = 'project_siteconfiguration' class SurveySession (object): \"\"\" \"\"\" def", "first. \"\"\" places = Place.objects.all().order_by('?')[:2] self.__places = places return self.__places", "that this rating compares \"\"\" place2 = models.ForeignKey('Place', related_name='+') \"\"\"", "Place (models.Model): lat = models.FloatField() lon = models.FloatField() def __unicode__(self):", "= ( ('ip', 'IP Address'), ('html5', 'HTML5 Geolocation API'), )", "\"\"\" def __init__(self, questions=None, places=None): self.__questions = questions self.__places =", "default=False) def __unicode__(self): return 'Configuration for {0}'.format(self.site.name) class Meta: app_label", "'less {0} than', 0: 'as {0} as', }) return ('Place", "about_text = models.TextField(null=True, blank=True) about_text_is_html = models.BooleanField(blank=True, default=False) def __unicode__(self):", "= models.OneToOneField('sessions.Session') \"\"\" The Django browser session. \"\"\" def __unicode__(self):", "API'), ) location_source = models.CharField(max_length=32, choices=SOURCES) location_data = models.CharField(max_length=2048) \"\"\"", "({ -1: 'more {0} than', 1: 'less {0} than', 0:", "rating=meaning[self.score].format(self.criterion.prompt)) @property def question(self): \"\"\" The question string to which", "* 2)]) questions = list(Criterion.objects.all()) surveys = [] for i", "= models.DateTimeField(auto_now=True) class Meta: abstract = True class Rating (TimeStampedModel):", "place2 = models.ForeignKey('Place', related_name='+') \"\"\" The second place that this", "import math import random from django.db import models class TimeStampedModel", "model class for when you want to keep track of", "#{p2}').format( p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property def question(self): \"\"\" The question", "more smartly. Use the init_... # methods defined above (and", "place2 = places[2 * i + 1] surveys.append(cls(places=[place1, place2], questions=questions))", "the rating is a response. \"\"\" return self.criterion.prompt class Criterion", "information for the user that made this rating. Not required,", "models.IntegerField() \"\"\" The rating score. 1 means that place1 \"wins\"", "for data analysis. \"\"\" def __unicode__(self): meaning = ({ -1:", "= models.FloatField() def __unicode__(self): return '({0}, {1})'.format(self.lat, self.lon) class UserInfo", "def __unicode__(self): return 'Configuration for {0}'.format(self.site.name) class Meta: app_label =", "#{p1} is {rating} place #{p2}').format( p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property def", "was obtained, and any additional information required to recreate the", "recreate the location. \"\"\" session = models.OneToOneField('sessions.Session') \"\"\" The Django", "__unicode__(self): return 'Configuration for {0}'.format(self.site.name) class Meta: app_label = 'sites'", "this session. \"\"\" return self.__places or self.init_places() def init_places(self): \"\"\"", "= models.CharField(max_length=256, null=True, blank=True) about_title = models.CharField(max_length=256, null=True, blank=True) about_text", "the init_... # methods defined above (and make them better", "a set of questions at random. \"\"\" all_questions = (", "<reponame>openplans/streetscore<filename>street_score/project/models.py import math import random from django.db import models class", "keep track of created and updated times for model instances.", "first place that this rating compares \"\"\" place2 = models.ForeignKey('Place',", "The question prompt, i.e. 'How clean is the street?'. \"\"\"", "\"\"\" session = models.OneToOneField('sessions.Session') \"\"\" The Django browser session. \"\"\"", "rating score. 1 means that place1 \"wins\" over place2 for", "= places @property def questions(self): \"\"\" Get the set of", "__unicode__(self): return self.prompt class Meta: verbose_name_plural = \"criteria\" class Place", "two places at random. TODO: Order the places by those", "obtained, and any additional information required to recreate the location.", "lat = models.FloatField(null=True) lon = models.FloatField(null=True) \"\"\" The user's location.", "\"\"\" return self.__questions or self.init_questions() @property def places(self): \"\"\" Get", "'sessions' db_table = 'project_userinfo' verbose_name_plural = 'User info' class SiteConfiguration", "score = models.IntegerField() \"\"\" The rating score. 1 means that", "questions for this survey. \"\"\" return self.__questions or self.init_questions() @property", "model instances. \"\"\" created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) class", "\"\"\" created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) class Meta: abstract", "'project_siteconfiguration' class SurveySession (object): \"\"\" \"\"\" def __init__(self, questions=None, places=None):", "set of questions for this survey. \"\"\" return self.__questions or", "too). places = list(Place.objects.all().order_by('?')[:(count * 2)]) questions = list(Criterion.objects.all()) surveys", "Rating (TimeStampedModel): criterion = models.ForeignKey('Criterion', related_name='ratings') \"\"\" The criterion that", "the location was obtained, and any additional information required to", "= \"criteria\" class Place (models.Model): lat = models.FloatField() lon =", "questions(self): \"\"\" Get the set of questions for this survey.", "is {rating} place #{p2}').format( p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property def question(self):", "('html5', 'HTML5 Geolocation API'), ) location_source = models.CharField(max_length=32, choices=SOURCES) location_data", "return ('Place #{p1} is {rating} place #{p2}').format( p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt))", "choices=SOURCES) location_data = models.CharField(max_length=2048) \"\"\" The method by which the", "related_name='+') \"\"\" The second place that this rating compares \"\"\"", "class Meta: app_label = 'sessions' db_table = 'project_userinfo' verbose_name_plural =", "# TODO: Choose the places and questions more smartly. Use", "analysis. \"\"\" def __unicode__(self): meaning = ({ -1: 'more {0}", "blank=True) about_title = models.CharField(max_length=256, null=True, blank=True) about_text = models.TextField(null=True, blank=True)", "= list(Place.objects.all().order_by('?')[:(count * 2)]) questions = list(Criterion.objects.all()) surveys = []", "than', 1: 'less {0} than', 0: 'as {0} as', })", "and questions more smartly. Use the init_... # methods defined", "self.__places def init_questions(self): \"\"\" Load a set of questions at", "The second place that this rating compares \"\"\" score =", "(and make them better too). places = list(Place.objects.all().order_by('?')[:(count * 2)])", "def questions(self): \"\"\" Get the set of questions for this", "math import random from django.db import models class TimeStampedModel (models.Model):", "lon = models.FloatField() def __unicode__(self): return '({0}, {1})'.format(self.lat, self.lon) class", "= models.ForeignKey('Place', related_name='+') \"\"\" The second place that this rating", "blank=True) addthis_title = models.CharField(max_length=256, null=True, blank=True) about_title = models.CharField(max_length=256, null=True,", "\"\"\" The first place that this rating compares \"\"\" place2", "Get the block for this session. \"\"\" return self.__places or", "self.init_questions() @property def places(self): \"\"\" Get the block for this", "\"\"\" The question string to which the rating is a", "class UserInfo (TimeStampedModel): lat = models.FloatField(null=True) lon = models.FloatField(null=True) \"\"\"", "places[2 * i + 1] surveys.append(cls(places=[place1, place2], questions=questions)) return surveys", "Meta: app_label = 'sessions' db_table = 'project_userinfo' verbose_name_plural = 'User", "for this session. \"\"\" return self.__places or self.init_places() def init_places(self):", "Base model class for when you want to keep track", "= 'project_siteconfiguration' class SurveySession (object): \"\"\" \"\"\" def __init__(self, questions=None,", "which the rating is a response. \"\"\" return self.criterion.prompt class", "required, but useful for data analysis. \"\"\" def __unicode__(self): meaning", "* i] place2 = places[2 * i + 1] surveys.append(cls(places=[place1,", "self.init_places() def init_places(self): \"\"\" Load two places at random. TODO:", "i.e. 'How clean is the street?'. \"\"\" def __unicode__(self): return", "(models.Model): prompt = models.TextField() \"\"\" The question prompt, i.e. 'How", "list(Place.objects.all().order_by('?')[:(count * 2)]) questions = list(Criterion.objects.all()) surveys = [] for", "at random. \"\"\" all_questions = ( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) ) self.__questions", "browser session. \"\"\" def __unicode__(self): return u'User for session {key}'.format(key=self.session.session_key)", "Use the init_... # methods defined above (and make them", "class for when you want to keep track of created", "session {key}'.format(key=self.session.session_key) class Meta: app_label = 'sessions' db_table = 'project_userinfo'", "The first place that this rating compares \"\"\" place2 =", "= models.FloatField(null=True) \"\"\" The user's location. \"\"\" SOURCES = (", "= models.ForeignKey('Place', related_name='+') \"\"\" The first place that this rating", "places at random. TODO: Order the places by those that", "i] place2 = places[2 * i + 1] surveys.append(cls(places=[place1, place2],", "= list(Criterion.objects.all()) surveys = [] for i in range(count): place1", "models.FloatField() lon = models.FloatField() def __unicode__(self): return '({0}, {1})'.format(self.lat, self.lon)", "verbose_name_plural = \"criteria\" class Place (models.Model): lat = models.FloatField() lon", "above (and make them better too). places = list(Place.objects.all().order_by('?')[:(count *", "in range(count): place1 = places[2 * i] place2 = places[2", "over place2 for the given criterion. -1 means that place2", "self.__questions = all_questions return self.__questions @classmethod def make_surveys(cls, count=1): #", "for session {key}'.format(key=self.session.session_key) class Meta: app_label = 'sessions' db_table =", "\"\"\" The second place that this rating compares \"\"\" score", "Get the set of questions for this survey. \"\"\" return", "def __unicode__(self): meaning = ({ -1: 'more {0} than', 1:", "any additional information required to recreate the location. \"\"\" session", "SiteConfiguration (models.Model): site = models.OneToOneField('sites.Site', related_name='config') google_analytics_key = models.CharField(max_length=256, null=True,", "is for. \"\"\" place1 = models.ForeignKey('Place', related_name='+') \"\"\" The first", "created and updated times for model instances. \"\"\" created_datetime =", "from django.db import models class TimeStampedModel (models.Model): \"\"\" Base model", "this rating is for. \"\"\" place1 = models.ForeignKey('Place', related_name='+') \"\"\"", "compares \"\"\" place2 = models.ForeignKey('Place', related_name='+') \"\"\" The second place", "models.DateTimeField(auto_now=True) class Meta: abstract = True class Rating (TimeStampedModel): criterion", "0: 'as {0} as', }) return ('Place #{p1} is {rating}", "site = models.OneToOneField('sites.Site', related_name='config') google_analytics_key = models.CharField(max_length=256, null=True, blank=True) addthis_key", "models.FloatField() def __unicode__(self): return '({0}, {1})'.format(self.lat, self.lon) class UserInfo (TimeStampedModel):", "@property def question(self): \"\"\" The question string to which the", "return 'Configuration for {0}'.format(self.site.name) class Meta: app_label = 'sites' db_table", "or self.init_places() def init_places(self): \"\"\" Load two places at random.", "criterion = models.ForeignKey('Criterion', related_name='ratings') \"\"\" The criterion that this rating", "created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) class Meta: abstract =", "the set of questions for this survey. \"\"\" return self.__questions", "make_surveys(cls, count=1): # TODO: Choose the places and questions more", "that place2 \"wins\". \"\"\" user_info = models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings') \"\"\"", "= all_questions return self.__questions @classmethod def make_surveys(cls, count=1): # TODO:", "them first. \"\"\" places = Place.objects.all().order_by('?')[:2] self.__places = places return", "questions more smartly. Use the init_... # methods defined above", "places by those that have the least questions answered about", "models.FloatField(null=True) \"\"\" The user's location. \"\"\" SOURCES = ( ('ip',", "score. 1 means that place1 \"wins\" over place2 for the", "of questions for this survey. \"\"\" return self.__questions or self.init_questions()", "blank=True) addthis_key = models.CharField(max_length=256, null=True, blank=True) addthis_title = models.CharField(max_length=256, null=True,", "compares \"\"\" score = models.IntegerField() \"\"\" The rating score. 1", "and updated times for model instances. \"\"\" created_datetime = models.DateTimeField(auto_now_add=True)", "for i in range(count): place1 = places[2 * i] place2", "that this rating is for. \"\"\" place1 = models.ForeignKey('Place', related_name='+')", "The information for the user that made this rating. Not", "for the given criterion. -1 means that place2 \"wins\". \"\"\"", "place that this rating compares \"\"\" score = models.IntegerField() \"\"\"", "models.TextField(null=True, blank=True) about_text_is_html = models.BooleanField(blank=True, default=False) def __unicode__(self): return 'Configuration", "app_label = 'sites' db_table = 'project_siteconfiguration' class SurveySession (object): \"\"\"", "= ({ -1: 'more {0} than', 1: 'less {0} than',", "\"\"\" The rating score. 1 means that place1 \"wins\" over", "prompt = models.TextField() \"\"\" The question prompt, i.e. 'How clean", "places(self): \"\"\" Get the block for this session. \"\"\" return", "= models.CharField(max_length=2048) \"\"\" The method by which the location was", "import random from django.db import models class TimeStampedModel (models.Model): \"\"\"", "user's location. \"\"\" SOURCES = ( ('ip', 'IP Address'), ('html5',", "'Configuration for {0}'.format(self.site.name) class Meta: app_label = 'sites' db_table =", "question prompt, i.e. 'How clean is the street?'. \"\"\" def", "is a response. \"\"\" return self.criterion.prompt class Criterion (models.Model): prompt", "Choose the places and questions more smartly. Use the init_...", "\"\"\" return self.criterion.prompt class Criterion (models.Model): prompt = models.TextField() \"\"\"", "when you want to keep track of created and updated", "init_... # methods defined above (and make them better too).", "questions = list(Criterion.objects.all()) surveys = [] for i in range(count):", "= places[2 * i] place2 = places[2 * i +", "'How clean is the street?'. \"\"\" def __unicode__(self): return self.prompt", "places return self.__places def init_questions(self): \"\"\" Load a set of", "\"\"\" Get the block for this session. \"\"\" return self.__places", "methods defined above (and make them better too). places =", "useful for data analysis. \"\"\" def __unicode__(self): meaning = ({", "for when you want to keep track of created and", "[] for i in range(count): place1 = places[2 * i]", "you want to keep track of created and updated times", "class Meta: verbose_name_plural = \"criteria\" class Place (models.Model): lat =", "places[2 * i] place2 = places[2 * i + 1]", "db_table = 'project_siteconfiguration' class SurveySession (object): \"\"\" \"\"\" def __init__(self,", "p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property def question(self): \"\"\" The question string", "for {0}'.format(self.site.name) class Meta: app_label = 'sites' db_table = 'project_siteconfiguration'", "{0} as', }) return ('Place #{p1} is {rating} place #{p2}').format(", "info' class SiteConfiguration (models.Model): site = models.OneToOneField('sites.Site', related_name='config') google_analytics_key =", "self.__places = places return self.__places def init_questions(self): \"\"\" Load a", "TimeStampedModel (models.Model): \"\"\" Base model class for when you want", "(TimeStampedModel): criterion = models.ForeignKey('Criterion', related_name='ratings') \"\"\" The criterion that this", "clean is the street?'. \"\"\" def __unicode__(self): return self.prompt class", "models.OneToOneField('sessions.Session') \"\"\" The Django browser session. \"\"\" def __unicode__(self): return", "self.__places = places @property def questions(self): \"\"\" Get the set", "all_questions = ( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) ) self.__questions = all_questions return", "the street?'. \"\"\" def __unicode__(self): return self.prompt class Meta: verbose_name_plural", "\"\"\" def __unicode__(self): return u'User for session {key}'.format(key=self.session.session_key) class Meta:", "models.CharField(max_length=2048) \"\"\" The method by which the location was obtained,", "them better too). places = list(Place.objects.all().order_by('?')[:(count * 2)]) questions =", "null=True, related_name='ratings') \"\"\" The information for the user that made", "= 'sessions' db_table = 'project_userinfo' verbose_name_plural = 'User info' class", "location was obtained, and any additional information required to recreate", "The criterion that this rating is for. \"\"\" place1 =", "# methods defined above (and make them better too). places", "answered about them first. \"\"\" places = Place.objects.all().order_by('?')[:2] self.__places =", "the block for this session. \"\"\" return self.__places or self.init_places()", "but useful for data analysis. \"\"\" def __unicode__(self): meaning =", "( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) ) self.__questions = all_questions return self.__questions @classmethod", "= models.FloatField() lon = models.FloatField() def __unicode__(self): return '({0}, {1})'.format(self.lat,", "(TimeStampedModel): lat = models.FloatField(null=True) lon = models.FloatField(null=True) \"\"\" The user's", "The Django browser session. \"\"\" def __unicode__(self): return u'User for", "to keep track of created and updated times for model", "at random. TODO: Order the places by those that have", "Criterion (models.Model): prompt = models.TextField() \"\"\" The question prompt, i.e.", "have the least questions answered about them first. \"\"\" places", "= models.FloatField(null=True) lon = models.FloatField(null=True) \"\"\" The user's location. \"\"\"", "class Criterion (models.Model): prompt = models.TextField() \"\"\" The question prompt,", "self.__questions or self.init_questions() @property def places(self): \"\"\" Get the block", "= 'sites' db_table = 'project_siteconfiguration' class SurveySession (object): \"\"\" \"\"\"", "the places by those that have the least questions answered", "rating is for. \"\"\" place1 = models.ForeignKey('Place', related_name='+') \"\"\" The", "that place1 \"wins\" over place2 for the given criterion. -1", "\"\"\" The Django browser session. \"\"\" def __unicode__(self): return u'User", "True class Rating (TimeStampedModel): criterion = models.ForeignKey('Criterion', related_name='ratings') \"\"\" The", "location. \"\"\" session = models.OneToOneField('sessions.Session') \"\"\" The Django browser session.", "second place that this rating compares \"\"\" score = models.IntegerField()", "lon = models.FloatField(null=True) \"\"\" The user's location. \"\"\" SOURCES =", "about_text_is_html = models.BooleanField(blank=True, default=False) def __unicode__(self): return 'Configuration for {0}'.format(self.site.name)", "Load two places at random. TODO: Order the places by", "which the location was obtained, and any additional information required", "by those that have the least questions answered about them", "times for model instances. \"\"\" created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime =", "blank=True) about_text_is_html = models.BooleanField(blank=True, default=False) def __unicode__(self): return 'Configuration for", "\"\"\" The method by which the location was obtained, and", "def __init__(self, questions=None, places=None): self.__questions = questions self.__places = places", "class Rating (TimeStampedModel): criterion = models.ForeignKey('Criterion', related_name='ratings') \"\"\" The criterion", "\"\"\" The question prompt, i.e. 'How clean is the street?'.", "'HTML5 Geolocation API'), ) location_source = models.CharField(max_length=32, choices=SOURCES) location_data =", "models.CharField(max_length=32, choices=SOURCES) location_data = models.CharField(max_length=2048) \"\"\" The method by which", "as', }) return ('Place #{p1} is {rating} place #{p2}').format( p1=self.place1,", "= models.TextField() \"\"\" The question prompt, i.e. 'How clean is", "= models.CharField(max_length=256, null=True, blank=True) addthis_key = models.CharField(max_length=256, null=True, blank=True) addthis_title", "'project_userinfo' verbose_name_plural = 'User info' class SiteConfiguration (models.Model): site =", "places and questions more smartly. Use the init_... # methods", "\"\"\" def __unicode__(self): meaning = ({ -1: 'more {0} than',", "= models.IntegerField() \"\"\" The rating score. 1 means that place1", "'more {0} than', 1: 'less {0} than', 0: 'as {0}", "Load a set of questions at random. \"\"\" all_questions =", "= Place.objects.all().order_by('?')[:2] self.__places = places return self.__places def init_questions(self): \"\"\"", "= 'User info' class SiteConfiguration (models.Model): site = models.OneToOneField('sites.Site', related_name='config')", "return self.__questions @classmethod def make_surveys(cls, count=1): # TODO: Choose the", "updated_datetime = models.DateTimeField(auto_now=True) class Meta: abstract = True class Rating", "= 'project_userinfo' verbose_name_plural = 'User info' class SiteConfiguration (models.Model): site", "}) return ('Place #{p1} is {rating} place #{p2}').format( p1=self.place1, p2=self.place2,", "= models.BooleanField(blank=True, default=False) def __unicode__(self): return 'Configuration for {0}'.format(self.site.name) class", "null=True, blank=True) addthis_key = models.CharField(max_length=256, null=True, blank=True) addthis_title = models.CharField(max_length=256,", "TODO: Choose the places and questions more smartly. Use the", "null=True, blank=True) about_text = models.TextField(null=True, blank=True) about_text_is_html = models.BooleanField(blank=True, default=False)", "= models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings') \"\"\" The information for the user", "places = Place.objects.all().order_by('?')[:2] self.__places = places return self.__places def init_questions(self):", "self.lon) class UserInfo (TimeStampedModel): lat = models.FloatField(null=True) lon = models.FloatField(null=True)", "db_table = 'project_userinfo' verbose_name_plural = 'User info' class SiteConfiguration (models.Model):", "questions=None, places=None): self.__questions = questions self.__places = places @property def", "about_title = models.CharField(max_length=256, null=True, blank=True) about_text = models.TextField(null=True, blank=True) about_text_is_html", "smartly. Use the init_... # methods defined above (and make", "return u'User for session {key}'.format(key=self.session.session_key) class Meta: app_label = 'sessions'", "about them first. \"\"\" places = Place.objects.all().order_by('?')[:2] self.__places = places", "place1 \"wins\" over place2 for the given criterion. -1 means", "The rating score. 1 means that place1 \"wins\" over place2", "track of created and updated times for model instances. \"\"\"", "meaning = ({ -1: 'more {0} than', 1: 'less {0}", "models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings') \"\"\" The information for the user that", "init_questions(self): \"\"\" Load a set of questions at random. \"\"\"", "this rating compares \"\"\" place2 = models.ForeignKey('Place', related_name='+') \"\"\" The", "{0}'.format(self.site.name) class Meta: app_label = 'sites' db_table = 'project_siteconfiguration' class", "places = list(Place.objects.all().order_by('?')[:(count * 2)]) questions = list(Criterion.objects.all()) surveys =", "TODO: Order the places by those that have the least", "criterion that this rating is for. \"\"\" place1 = models.ForeignKey('Place',", "\"\"\" Base model class for when you want to keep", "\"\"\" Get the set of questions for this survey. \"\"\"", "self.prompt class Meta: verbose_name_plural = \"criteria\" class Place (models.Model): lat", "string to which the rating is a response. \"\"\" return", "-1: 'more {0} than', 1: 'less {0} than', 0: 'as", "class SurveySession (object): \"\"\" \"\"\" def __init__(self, questions=None, places=None): self.__questions", "verbose_name_plural = 'User info' class SiteConfiguration (models.Model): site = models.OneToOneField('sites.Site',", "session = models.OneToOneField('sessions.Session') \"\"\" The Django browser session. \"\"\" def", "addthis_title = models.CharField(max_length=256, null=True, blank=True) about_title = models.CharField(max_length=256, null=True, blank=True)", "= models.ForeignKey('Criterion', related_name='ratings') \"\"\" The criterion that this rating is", "1: 'less {0} than', 0: 'as {0} as', }) return", "question(self): \"\"\" The question string to which the rating is", "__unicode__(self): return u'User for session {key}'.format(key=self.session.session_key) class Meta: app_label =", "lat = models.FloatField() lon = models.FloatField() def __unicode__(self): return '({0},", "\"\"\" The criterion that this rating is for. \"\"\" place1", "(models.Model): lat = models.FloatField() lon = models.FloatField() def __unicode__(self): return", "count=1): # TODO: Choose the places and questions more smartly.", "return '({0}, {1})'.format(self.lat, self.lon) class UserInfo (TimeStampedModel): lat = models.FloatField(null=True)", "= places[2 * i + 1] surveys.append(cls(places=[place1, place2], questions=questions)) return", "\"\"\" all_questions = ( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) ) self.__questions = all_questions", "null=True, blank=True) addthis_title = models.CharField(max_length=256, null=True, blank=True) about_title = models.CharField(max_length=256,", "{0} than', 0: 'as {0} as', }) return ('Place #{p1}", "i in range(count): place1 = places[2 * i] place2 =", "def init_places(self): \"\"\" Load two places at random. TODO: Order", "place2 \"wins\". \"\"\" user_info = models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings') \"\"\" The", "is the street?'. \"\"\" def __unicode__(self): return self.prompt class Meta:", "random from django.db import models class TimeStampedModel (models.Model): \"\"\" Base", "street?'. \"\"\" def __unicode__(self): return self.prompt class Meta: verbose_name_plural =", "\"\"\" def __unicode__(self): return self.prompt class Meta: verbose_name_plural = \"criteria\"", "place #{p2}').format( p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property def question(self): \"\"\" The", "related_name='ratings') \"\"\" The criterion that this rating is for. \"\"\"", "google_analytics_key = models.CharField(max_length=256, null=True, blank=True) addthis_key = models.CharField(max_length=256, null=True, blank=True)", "related_name='+') \"\"\" The first place that this rating compares \"\"\"", "place2 for the given criterion. -1 means that place2 \"wins\".", ") self.__questions = all_questions return self.__questions @classmethod def make_surveys(cls, count=1):", "data analysis. \"\"\" def __unicode__(self): meaning = ({ -1: 'more", "\"\"\" place1 = models.ForeignKey('Place', related_name='+') \"\"\" The first place that", "that made this rating. Not required, but useful for data", "def question(self): \"\"\" The question string to which the rating", "= places return self.__places def init_questions(self): \"\"\" Load a set", "2)]) questions = list(Criterion.objects.all()) surveys = [] for i in", "\"\"\" The user's location. \"\"\" SOURCES = ( ('ip', 'IP", "additional information required to recreate the location. \"\"\" session =", "def make_surveys(cls, count=1): # TODO: Choose the places and questions", "class SiteConfiguration (models.Model): site = models.OneToOneField('sites.Site', related_name='config') google_analytics_key = models.CharField(max_length=256,", "surveys = [] for i in range(count): place1 = places[2", "models.FloatField(null=True) lon = models.FloatField(null=True) \"\"\" The user's location. \"\"\" SOURCES", "models.BooleanField(blank=True, default=False) def __unicode__(self): return 'Configuration for {0}'.format(self.site.name) class Meta:", "by which the location was obtained, and any additional information", "UserInfo (TimeStampedModel): lat = models.FloatField(null=True) lon = models.FloatField(null=True) \"\"\" The", "\"wins\" over place2 for the given criterion. -1 means that", "\"\"\" Load two places at random. TODO: Order the places", "the least questions answered about them first. \"\"\" places =", "places=None): self.__questions = questions self.__places = places @property def questions(self):", "models.CharField(max_length=256, null=True, blank=True) addthis_key = models.CharField(max_length=256, null=True, blank=True) addthis_title =", "Not required, but useful for data analysis. \"\"\" def __unicode__(self):", "\"\"\" \"\"\" def __init__(self, questions=None, places=None): self.__questions = questions self.__places", "for the user that made this rating. Not required, but", "The question string to which the rating is a response.", "Meta: verbose_name_plural = \"criteria\" class Place (models.Model): lat = models.FloatField()", "models.ForeignKey('Place', related_name='+') \"\"\" The first place that this rating compares", "blank=True) about_text = models.TextField(null=True, blank=True) about_text_is_html = models.BooleanField(blank=True, default=False) def", "The method by which the location was obtained, and any", "{rating} place #{p2}').format( p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property def question(self): \"\"\"", "the location. \"\"\" session = models.OneToOneField('sessions.Session') \"\"\" The Django browser", "for model instances. \"\"\" created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True)", "__unicode__(self): meaning = ({ -1: 'more {0} than', 1: 'less", "this rating compares \"\"\" score = models.IntegerField() \"\"\" The rating", "models.CharField(max_length=256, null=True, blank=True) about_title = models.CharField(max_length=256, null=True, blank=True) about_text =", "the given criterion. -1 means that place2 \"wins\". \"\"\" user_info", "those that have the least questions answered about them first.", "better too). places = list(Place.objects.all().order_by('?')[:(count * 2)]) questions = list(Criterion.objects.all())", "this rating. Not required, but useful for data analysis. \"\"\"", "response. \"\"\" return self.criterion.prompt class Criterion (models.Model): prompt = models.TextField()", "= True class Rating (TimeStampedModel): criterion = models.ForeignKey('Criterion', related_name='ratings') \"\"\"", "addthis_key = models.CharField(max_length=256, null=True, blank=True) addthis_title = models.CharField(max_length=256, null=True, blank=True)", "questions at random. \"\"\" all_questions = ( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) )", "'({0}, {1})'.format(self.lat, self.lon) class UserInfo (TimeStampedModel): lat = models.FloatField(null=True) lon", "models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) class Meta: abstract = True class", "to which the rating is a response. \"\"\" return self.criterion.prompt", "The user's location. \"\"\" SOURCES = ( ('ip', 'IP Address'),", "of questions at random. \"\"\" all_questions = ( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings'))", "( ('ip', 'IP Address'), ('html5', 'HTML5 Geolocation API'), ) location_source", "class TimeStampedModel (models.Model): \"\"\" Base model class for when you", ") location_source = models.CharField(max_length=32, choices=SOURCES) location_data = models.CharField(max_length=2048) \"\"\" The", "list(Criterion.objects.all()) surveys = [] for i in range(count): place1 =", "place1 = places[2 * i] place2 = places[2 * i", "SOURCES = ( ('ip', 'IP Address'), ('html5', 'HTML5 Geolocation API'),", "class Meta: abstract = True class Rating (TimeStampedModel): criterion =", "__init__(self, questions=None, places=None): self.__questions = questions self.__places = places @property", "this survey. \"\"\" return self.__questions or self.init_questions() @property def places(self):", "p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property def question(self): \"\"\" The question string to", "class Meta: app_label = 'sites' db_table = 'project_siteconfiguration' class SurveySession", "\"wins\". \"\"\" user_info = models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings') \"\"\" The information", "criterion. -1 means that place2 \"wins\". \"\"\" user_info = models.ForeignKey('sessions.UserInfo',", "models.CharField(max_length=256, null=True, blank=True) addthis_title = models.CharField(max_length=256, null=True, blank=True) about_title =", "= [] for i in range(count): place1 = places[2 *", "made this rating. Not required, but useful for data analysis.", "Address'), ('html5', 'HTML5 Geolocation API'), ) location_source = models.CharField(max_length=32, choices=SOURCES)", "{0} than', 1: 'less {0} than', 0: 'as {0} as',", "= models.TextField(null=True, blank=True) about_text_is_html = models.BooleanField(blank=True, default=False) def __unicode__(self): return", "for. \"\"\" place1 = models.ForeignKey('Place', related_name='+') \"\"\" The first place", "place1 = models.ForeignKey('Place', related_name='+') \"\"\" The first place that this", "\"\"\" return self.__places or self.init_places() def init_places(self): \"\"\" Load two", "models.ForeignKey('Criterion', related_name='ratings') \"\"\" The criterion that this rating is for.", "the places and questions more smartly. Use the init_... #", "u'User for session {key}'.format(key=self.session.session_key) class Meta: app_label = 'sessions' db_table", "\"\"\" Load a set of questions at random. \"\"\" all_questions", "question string to which the rating is a response. \"\"\"", "want to keep track of created and updated times for", "set of questions at random. \"\"\" all_questions = ( Criterion.objects.all()", "(models.Model): \"\"\" Base model class for when you want to", "questions self.__places = places @property def questions(self): \"\"\" Get the", "@classmethod def make_surveys(cls, count=1): # TODO: Choose the places and", "rating. Not required, but useful for data analysis. \"\"\" def", "__unicode__(self): return '({0}, {1})'.format(self.lat, self.lon) class UserInfo (TimeStampedModel): lat =", "questions answered about them first. \"\"\" places = Place.objects.all().order_by('?')[:2] self.__places", "'User info' class SiteConfiguration (models.Model): site = models.OneToOneField('sites.Site', related_name='config') google_analytics_key", "rating compares \"\"\" place2 = models.ForeignKey('Place', related_name='+') \"\"\" The second", "make them better too). places = list(Place.objects.all().order_by('?')[:(count * 2)]) questions", "given criterion. -1 means that place2 \"wins\". \"\"\" user_info =", "= ( Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) ) self.__questions = all_questions return self.__questions", "user_info = models.ForeignKey('sessions.UserInfo', null=True, related_name='ratings') \"\"\" The information for the", "('Place #{p1} is {rating} place #{p2}').format( p1=self.place1, p2=self.place2, rating=meaning[self.score].format(self.criterion.prompt)) @property", "SurveySession (object): \"\"\" \"\"\" def __init__(self, questions=None, places=None): self.__questions =", "= models.CharField(max_length=256, null=True, blank=True) about_text = models.TextField(null=True, blank=True) about_text_is_html =", "least questions answered about them first. \"\"\" places = Place.objects.all().order_by('?')[:2]", "Geolocation API'), ) location_source = models.CharField(max_length=32, choices=SOURCES) location_data = models.CharField(max_length=2048)", "django.db import models class TimeStampedModel (models.Model): \"\"\" Base model class", "\"\"\" places = Place.objects.all().order_by('?')[:2] self.__places = places return self.__places def", "def __unicode__(self): return '({0}, {1})'.format(self.lat, self.lon) class UserInfo (TimeStampedModel): lat", "to recreate the location. \"\"\" session = models.OneToOneField('sessions.Session') \"\"\" The", "survey. \"\"\" return self.__questions or self.init_questions() @property def places(self): \"\"\"", "method by which the location was obtained, and any additional", "'IP Address'), ('html5', 'HTML5 Geolocation API'), ) location_source = models.CharField(max_length=32,", "place that this rating compares \"\"\" place2 = models.ForeignKey('Place', related_name='+')", "= questions self.__places = places @property def questions(self): \"\"\" Get", "information required to recreate the location. \"\"\" session = models.OneToOneField('sessions.Session')", "{key}'.format(key=self.session.session_key) class Meta: app_label = 'sessions' db_table = 'project_userinfo' verbose_name_plural", "or self.init_questions() @property def places(self): \"\"\" Get the block for", "Django browser session. \"\"\" def __unicode__(self): return u'User for session", "return self.criterion.prompt class Criterion (models.Model): prompt = models.TextField() \"\"\" The", "location_data = models.CharField(max_length=2048) \"\"\" The method by which the location", "for this survey. \"\"\" return self.__questions or self.init_questions() @property def", "range(count): place1 = places[2 * i] place2 = places[2 *", "models.OneToOneField('sites.Site', related_name='config') google_analytics_key = models.CharField(max_length=256, null=True, blank=True) addthis_key = models.CharField(max_length=256,", "= models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) class Meta: abstract = True", "session. \"\"\" def __unicode__(self): return u'User for session {key}'.format(key=self.session.session_key) class", "self.__questions = questions self.__places = places @property def questions(self): \"\"\"", "session. \"\"\" return self.__places or self.init_places() def init_places(self): \"\"\" Load", "null=True, blank=True) about_title = models.CharField(max_length=256, null=True, blank=True) about_text = models.TextField(null=True,", "Criterion.objects.all() .annotate(num_ratings=models.Count('ratings')) ) self.__questions = all_questions return self.__questions @classmethod def", "= models.CharField(max_length=32, choices=SOURCES) location_data = models.CharField(max_length=2048) \"\"\" The method by" ]
[ "code must retain the above copyright notice, this list of", "WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES", "except (sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback() raise AppAdderException(\"An error occurred while adding", "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF", "DAMAGE. import os import sqlalchemy.exc from selfdroid.appstorage.AppMetadata import AppMetadata from", "endorse or promote # products derived from this software without", "OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT", "from this software without specific prior written permission. # #", "# Copyright (c) 2021 <NAME>. All rights reserved. # #", "# # Redistribution and use in source and binary forms,", "self._parsed_apk: ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self) -> AppMetadata: \"\"\" :return:", "source code must retain the above copyright notice, this list", "NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE", "without specific prior written permission. # # THIS SOFTWARE IS", "notice, this list of conditions and the # following disclaimer", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR", "the app instead of adding it!\", self._parsed_apk.package_name) raise AppAdderException(html_message) def", "GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS;", "class AppAdder: \"\"\" This class must be instantiated and have", "in this method! # 1. Database db_model = self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model)", "binary forms, with or without modification, are permitted provided that", "from selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser", "have its public methods called in a locked context! \"\"\"", "this list of conditions and the following # disclaimer. #", "A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL", "Icon icon_path = app_metadata.get_icon_path() with open(icon_path, \"wb\") as icon_file: icon_file.write(self._parsed_apk.uniform_png_app_icon)", "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH", "while adding the app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata def _add_app_while_locked_with_exceptions_handled(self)", "an_app_with_the_same_package_name is not None: html_message = WebStatusMessageCollector.format_html_message(\"An app with the", "None: html_message = WebStatusMessageCollector.format_html_message(\"An app with the same package name", "methods called in a locked context! \"\"\" def __init__(self, uploaded_apk_path:", "def add_app_while_locked(self) -> AppMetadata: \"\"\" :return: The metadata of the", "PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE", "ANY WAY OUT OF THE USE # OF THIS SOFTWARE,", "The metadata of the added app. \"\"\" try: app_metadata =", "the # following conditions are met: # 1. Redistributions of", "icon_path = app_metadata.get_icon_path() with open(icon_path, \"wb\") as icon_file: icon_file.write(self._parsed_apk.uniform_png_app_icon) return", "OF SUCH DAMAGE. import os import sqlalchemy.exc from selfdroid.appstorage.AppMetadata import", "(c) 2021 <NAME>. All rights reserved. # # Redistribution and", "and the # following disclaimer in the documentation and/or other", "of source code must retain the above copyright notice, this", "SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR", "class must be instantiated and have its public methods called", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED.", "AppAdderException from selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector from selfdroid import db class", "OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "disclaimer. # 2. Redistributions in binary form must reproduce the", "with the same package name <i>({})</i> is already present on", "AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT,", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name is not None: html_message = WebStatusMessageCollector.format_html_message(\"An app", "ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self) -> AppMetadata: \"\"\" :return: The", "# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "this software without specific prior written permission. # # THIS", "DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "\"\"\" def __init__(self, uploaded_apk_path: str): self._uploaded_apk_path: str = uploaded_apk_path self._parsed_apk:", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE", "provided that the # following conditions are met: # 1.", "# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import", "selfdroid.appstorage.apk.APKParser import APKParser from selfdroid.appstorage.apk.ParsedAPK import ParsedAPK from selfdroid.appstorage.crud.AppAdderException import", "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES;", "derived from this software without specific prior written permission. #", "must retain the above copyright notice, this list of conditions", "= WebStatusMessageCollector.format_html_message(\"An app with the same package name <i>({})</i> is", "THE POSSIBILITY OF SUCH DAMAGE. import os import sqlalchemy.exc from", "copyright holder nor the names of its contributors may be", "update the app instead of adding it!\", self._parsed_apk.package_name) raise AppAdderException(html_message)", "software without specific prior written permission. # # THIS SOFTWARE", "int) app_metadata = AppMetadata.from_db_model(db_model) # 2. APK apk_path = app_metadata.get_apk_path()", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "OUT OF THE USE # OF THIS SOFTWARE, EVEN IF", "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF", "of adding it!\", self._parsed_apk.package_name) raise AppAdderException(html_message) def _perform_app_addition(self) -> AppMetadata:", "os.rename(self._uploaded_apk_path, apk_path) # 3. Icon icon_path = app_metadata.get_icon_path() with open(icon_path,", "2. APK apk_path = app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path) # 3. Icon", "selfdroid.appstorage.apk.ParsedAPK import ParsedAPK from selfdroid.appstorage.crud.AppAdderException import AppAdderException from selfdroid.web.WebStatusMessageCollector import", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "raise AppAdderException(html_message) def _perform_app_addition(self) -> AppMetadata: # An UserReadableException mustn't", "EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO,", "NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "_add_app_while_locked_with_exceptions_handled(self) -> AppMetadata: self._check_if_app_can_be_added() return self._perform_app_addition() def _check_if_app_can_be_added(self) -> None:", "EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR", "distribution. # 3. Neither the name of the copyright holder", "ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED", "-> AppMetadata: # An UserReadableException mustn't be raised in this", "sqlalchemy.exc from selfdroid.appstorage.AppMetadata import AppMetadata from selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel from", "from selfdroid.appstorage.crud.AppAdderException import AppAdderException from selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector from selfdroid", "# 1. Database db_model = self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit() assert isinstance(db_model.id,", "retain the above copyright notice, this list of conditions and", "name of the copyright holder nor the names of its", "selfdroid.appstorage.AppMetadata import AppMetadata from selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer import", "this method! # 1. Database db_model = self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit()", "products derived from this software without specific prior written permission.", "return app_metadata def _add_app_while_locked_with_exceptions_handled(self) -> AppMetadata: self._check_if_app_can_be_added() return self._perform_app_addition() def", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF", "of the added app. \"\"\" try: app_metadata = self._add_app_while_locked_with_exceptions_handled() except", "HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED", "app. \"\"\" try: app_metadata = self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback()", "AppAdderException(\"An error occurred while adding the app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return", "the same package name <i>({})</i> is already present on the", "__init__(self, uploaded_apk_path: str): self._uploaded_apk_path: str = uploaded_apk_path self._parsed_apk: ParsedAPK =", "2021 <NAME>. All rights reserved. # # Redistribution and use", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS", "= uploaded_apk_path self._parsed_apk: ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self) -> AppMetadata:", "Redistributions of source code must retain the above copyright notice,", "the above copyright notice, this list of conditions and the", "POSSIBILITY OF SUCH DAMAGE. import os import sqlalchemy.exc from selfdroid.appstorage.AppMetadata", "public methods called in a locked context! \"\"\" def __init__(self,", "app_metadata = self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback() raise AppAdderException(\"An error", "os import sqlalchemy.exc from selfdroid.appstorage.AppMetadata import AppMetadata from selfdroid.appstorage.AppMetadataDBModel import", "AppAdderException(html_message) def _perform_app_addition(self) -> AppMetadata: # An UserReadableException mustn't be", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR", "SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE", "Redistribution and use in source and binary forms, with or", "LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING", "WebStatusMessageCollector from selfdroid import db class AppAdder: \"\"\" This class", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN", "COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,", "# products derived from this software without specific prior written", "1. Database db_model = self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit() assert isinstance(db_model.id, int)", "nor the names of its contributors may be used to", "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "in binary form must reproduce the above copyright notice, this", "rights reserved. # # Redistribution and use in source and", "uploaded_apk_path: str): self._uploaded_apk_path: str = uploaded_apk_path self._parsed_apk: ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk", "uploaded_apk_path self._parsed_apk: ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self) -> AppMetadata: \"\"\"", "AppMetadata: self._check_if_app_can_be_added() return self._perform_app_addition() def _check_if_app_can_be_added(self) -> None: an_app_with_the_same_package_name =", "raise AppAdderException(\"An error occurred while adding the app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked()", "package name <i>({})</i> is already present on the server! You", "not None: html_message = WebStatusMessageCollector.format_html_message(\"An app with the same package", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY", "str = uploaded_apk_path self._parsed_apk: ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self) ->", "the added app. \"\"\" try: app_metadata = self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError,", "ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT", "IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED", "import APKParser from selfdroid.appstorage.apk.ParsedAPK import ParsedAPK from selfdroid.appstorage.crud.AppAdderException import AppAdderException", "-> AppMetadata: \"\"\" :return: The metadata of the added app.", "self._check_if_app_can_be_added() return self._perform_app_addition() def _check_if_app_can_be_added(self) -> None: an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first()", "-> None: an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name is not None:", "3. Neither the name of the copyright holder nor the", ":return: The metadata of the added app. \"\"\" try: app_metadata", "selfdroid import db class AppAdder: \"\"\" This class must be", "holder nor the names of its contributors may be used", "OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE", "reproduce the above copyright notice, this list of conditions and", "# disclaimer. # 2. Redistributions in binary form must reproduce", "from selfdroid.appstorage.AppMetadata import AppMetadata from selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer", "and the following # disclaimer. # 2. Redistributions in binary", "source and binary forms, with or without modification, are permitted", "ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "are met: # 1. Redistributions of source code must retain", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND", "AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata def _add_app_while_locked_with_exceptions_handled(self) -> AppMetadata: self._check_if_app_can_be_added() return self._perform_app_addition()", "This class must be instantiated and have its public methods", "# 1. Redistributions of source code must retain the above", "import WebStatusMessageCollector from selfdroid import db class AppAdder: \"\"\" This", "in a locked context! \"\"\" def __init__(self, uploaded_apk_path: str): self._uploaded_apk_path:", "def _perform_app_addition(self) -> AppMetadata: # An UserReadableException mustn't be raised", "method! # 1. Database db_model = self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit() assert", "None: an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name is not None: html_message", "# An UserReadableException mustn't be raised in this method! #", "EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import", "WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN", "above copyright notice, this list of conditions and the following", "its public methods called in a locked context! \"\"\" def", "import AppMetadata from selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer", "# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "without modification, are permitted provided that the # following conditions", "the following # disclaimer. # 2. Redistributions in binary form", "BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "server! You should update the app instead of adding it!\",", "in source and binary forms, with or without modification, are", "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #", "OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED", "raised in this method! # 1. Database db_model = self._parsed_apk.create_new_db_model_with_metadata()", "it!\", self._parsed_apk.package_name) raise AppAdderException(html_message) def _perform_app_addition(self) -> AppMetadata: # An", "3. Icon icon_path = app_metadata.get_icon_path() with open(icon_path, \"wb\") as icon_file:", "\"\"\" :return: The metadata of the added app. \"\"\" try:", "AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser import APKParser from", "str): self._uploaded_apk_path: str = uploaded_apk_path self._parsed_apk: ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk def", "import AppAdderException from selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector from selfdroid import db", "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING", "# following disclaimer in the documentation and/or other materials provided", "same package name <i>({})</i> is already present on the server!", "following conditions are met: # 1. Redistributions of source code", "CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN", "permitted provided that the # following conditions are met: #", "list of conditions and the # following disclaimer in the", "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "or without modification, are permitted provided that the # following", "form must reproduce the above copyright notice, this list of", "disclaimer in the documentation and/or other materials provided with the", "# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY", "APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self) -> AppMetadata: \"\"\" :return: The metadata of", "and have its public methods called in a locked context!", "and binary forms, with or without modification, are permitted provided", "from selfdroid.appstorage.apk.APKParser import APKParser from selfdroid.appstorage.apk.ParsedAPK import ParsedAPK from selfdroid.appstorage.crud.AppAdderException", "IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", "# 3. Icon icon_path = app_metadata.get_icon_path() with open(icon_path, \"wb\") as", "name <i>({})</i> is already present on the server! You should", "an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name is not None: html_message =", "used to endorse or promote # products derived from this", "IN ANY WAY OUT OF THE USE # OF THIS", "on the server! You should update the app instead of", "of conditions and the # following disclaimer in the documentation", "the distribution. # 3. Neither the name of the copyright", "mustn't be raised in this method! # 1. Database db_model", "from selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser import APKParser from selfdroid.appstorage.apk.ParsedAPK", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL,", "_perform_app_addition(self) -> AppMetadata: # An UserReadableException mustn't be raised in", "db_model = self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit() assert isinstance(db_model.id, int) app_metadata =", "# following conditions are met: # 1. Redistributions of source", "FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT", "OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY", "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "documentation and/or other materials provided with the distribution. # 3.", "and use in source and binary forms, with or without", "names of its contributors may be used to endorse or", "of the copyright holder nor the names of its contributors", "be instantiated and have its public methods called in a", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE", "add_app_while_locked(self) -> AppMetadata: \"\"\" :return: The metadata of the added", "should update the app instead of adding it!\", self._parsed_apk.package_name) raise", "from selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector from selfdroid import db class AppAdder:", "AppAdder: \"\"\" This class must be instantiated and have its", "binary form must reproduce the above copyright notice, this list", "PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE,", "# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "SUCH DAMAGE. import os import sqlalchemy.exc from selfdroid.appstorage.AppMetadata import AppMetadata", "# 3. Neither the name of the copyright holder nor", "(sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback() raise AppAdderException(\"An error occurred while adding the", "instead of adding it!\", self._parsed_apk.package_name) raise AppAdderException(html_message) def _perform_app_addition(self) ->", "contributors may be used to endorse or promote # products", "apk_path = app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path) # 3. Icon icon_path =", "THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,", "= app_metadata.get_icon_path() with open(icon_path, \"wb\") as icon_file: icon_file.write(self._parsed_apk.uniform_png_app_icon) return app_metadata", "selfdroid.appstorage.crud.AppAdderException import AppAdderException from selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector from selfdroid import", "following disclaimer in the documentation and/or other materials provided with", "APKParser from selfdroid.appstorage.apk.ParsedAPK import ParsedAPK from selfdroid.appstorage.crud.AppAdderException import AppAdderException from", "= AppMetadata.from_db_model(db_model) # 2. APK apk_path = app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path)", "import sqlalchemy.exc from selfdroid.appstorage.AppMetadata import AppMetadata from selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel", "= AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name is not None: html_message = WebStatusMessageCollector.format_html_message(\"An", "ARISING IN ANY WAY OUT OF THE USE # OF", "the app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata def _add_app_while_locked_with_exceptions_handled(self) -> AppMetadata:", "SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2021 <NAME>. All rights", "assert isinstance(db_model.id, int) app_metadata = AppMetadata.from_db_model(db_model) # 2. APK apk_path", "the copyright holder nor the names of its contributors may", "\"\"\" This class must be instantiated and have its public", "AppMetadata: \"\"\" :return: The metadata of the added app. \"\"\"", "# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "def __init__(self, uploaded_apk_path: str): self._uploaded_apk_path: str = uploaded_apk_path self._parsed_apk: ParsedAPK", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE", "TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF", "# # Copyright (c) 2021 <NAME>. All rights reserved. #", "_check_if_app_can_be_added(self) -> None: an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name is not", "to endorse or promote # products derived from this software", "ParsedAPK from selfdroid.appstorage.crud.AppAdderException import AppAdderException from selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector from", "the name of the copyright holder nor the names of", "def _add_app_while_locked_with_exceptions_handled(self) -> AppMetadata: self._check_if_app_can_be_added() return self._perform_app_addition() def _check_if_app_can_be_added(self) ->", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER", "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "conditions are met: # 1. Redistributions of source code must", "AppMetadata.from_db_model(db_model) # 2. APK apk_path = app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path) #", "USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND", "Redistributions in binary form must reproduce the above copyright notice,", "def _check_if_app_can_be_added(self) -> None: an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name is", "BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY,", "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY", "if an_app_with_the_same_package_name is not None: html_message = WebStatusMessageCollector.format_html_message(\"An app with", "# Redistribution and use in source and binary forms, with", "AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN", "selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser import", "modification, are permitted provided that the # following conditions are", "AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,", "copyright notice, this list of conditions and the # following", "return self._perform_app_addition() def _check_if_app_can_be_added(self) -> None: an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS", "adding the app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata def _add_app_while_locked_with_exceptions_handled(self) ->", "self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit() assert isinstance(db_model.id, int) app_metadata = AppMetadata.from_db_model(db_model) #", "from selfdroid.appstorage.apk.ParsedAPK import ParsedAPK from selfdroid.appstorage.crud.AppAdderException import AppAdderException from selfdroid.web.WebStatusMessageCollector", "OSError): db.session.rollback() raise AppAdderException(\"An error occurred while adding the app!\")", "FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO", "locked context! \"\"\" def __init__(self, uploaded_apk_path: str): self._uploaded_apk_path: str =", "metadata of the added app. \"\"\" try: app_metadata = self._add_app_while_locked_with_exceptions_handled()", "promote # products derived from this software without specific prior", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS", "is already present on the server! You should update the", "= self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback() raise AppAdderException(\"An error occurred", "db.session.commit() assert isinstance(db_model.id, int) app_metadata = AppMetadata.from_db_model(db_model) # 2. APK", "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE", "conditions and the # following disclaimer in the documentation and/or", "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "from selfdroid import db class AppAdder: \"\"\" This class must", "OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "db.session.rollback() raise AppAdderException(\"An error occurred while adding the app!\") finally:", "must reproduce the above copyright notice, this list of conditions", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY", "OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA,", "occurred while adding the app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata def", "db.session.add(db_model) db.session.commit() assert isinstance(db_model.id, int) app_metadata = AppMetadata.from_db_model(db_model) # 2.", "INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "this list of conditions and the # following disclaimer in", "WebStatusMessageCollector.format_html_message(\"An app with the same package name <i>({})</i> is already", "notice, this list of conditions and the following # disclaimer.", "list of conditions and the following # disclaimer. # 2.", "HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "be raised in this method! # 1. Database db_model =", "Copyright (c) 2021 <NAME>. All rights reserved. # # Redistribution", "AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT", "ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY,", "adding it!\", self._parsed_apk.package_name) raise AppAdderException(html_message) def _perform_app_addition(self) -> AppMetadata: #", "already present on the server! You should update the app", "following # disclaimer. # 2. Redistributions in binary form must", "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "= app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path) # 3. Icon icon_path = app_metadata.get_icon_path()", "copyright notice, this list of conditions and the following #", "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS", "app_metadata = AppMetadata.from_db_model(db_model) # 2. APK apk_path = app_metadata.get_apk_path() os.rename(self._uploaded_apk_path,", "UserReadableException mustn't be raised in this method! # 1. Database", "self._perform_app_addition() def _check_if_app_can_be_added(self) -> None: an_app_with_the_same_package_name = AppMetadataDBModel.query.filter_by(package_name=self._parsed_apk.package_name).first() if an_app_with_the_same_package_name", "import os import sqlalchemy.exc from selfdroid.appstorage.AppMetadata import AppMetadata from selfdroid.appstorage.AppMetadataDBModel", "isinstance(db_model.id, int) app_metadata = AppMetadata.from_db_model(db_model) # 2. APK apk_path =", "present on the server! You should update the app instead", "error occurred while adding the app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata", "All rights reserved. # # Redistribution and use in source", "and/or other materials provided with the distribution. # 3. Neither", "with or without modification, are permitted provided that the #", "the documentation and/or other materials provided with the distribution. #", "THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR", "finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata def _add_app_while_locked_with_exceptions_handled(self) -> AppMetadata: self._check_if_app_can_be_added() return", "<i>({})</i> is already present on the server! You should update", "<NAME>. All rights reserved. # # Redistribution and use in", "AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser import APKParser from selfdroid.appstorage.apk.ParsedAPK import ParsedAPK from", "THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF", "in the documentation and/or other materials provided with the distribution.", "apk_path) # 3. Icon icon_path = app_metadata.get_icon_path() with open(icon_path, \"wb\")", "of conditions and the following # disclaimer. # 2. Redistributions", "INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY", "use in source and binary forms, with or without modification,", "try: app_metadata = self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback() raise AppAdderException(\"An", "called in a locked context! \"\"\" def __init__(self, uploaded_apk_path: str):", "= self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit() assert isinstance(db_model.id, int) app_metadata = AppMetadata.from_db_model(db_model)", "reserved. # # Redistribution and use in source and binary", "other materials provided with the distribution. # 3. Neither the", "= APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self) -> AppMetadata: \"\"\" :return: The metadata", "ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON", "-> AppMetadata: self._check_if_app_can_be_added() return self._perform_app_addition() def _check_if_app_can_be_added(self) -> None: an_app_with_the_same_package_name", "app_metadata def _add_app_while_locked_with_exceptions_handled(self) -> AppMetadata: self._check_if_app_can_be_added() return self._perform_app_addition() def _check_if_app_can_be_added(self)", "of its contributors may be used to endorse or promote", "app!\") finally: AppStorageConsistencyEnsurer().ensure_consistency_while_locked() return app_metadata def _add_app_while_locked_with_exceptions_handled(self) -> AppMetadata: self._check_if_app_can_be_added()", "forms, with or without modification, are permitted provided that the", "import db class AppAdder: \"\"\" This class must be instantiated", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback() raise AppAdderException(\"An error occurred while", "html_message = WebStatusMessageCollector.format_html_message(\"An app with the same package name <i>({})</i>", "that the # following conditions are met: # 1. Redistributions", "import ParsedAPK from selfdroid.appstorage.crud.AppAdderException import AppAdderException from selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector", "An UserReadableException mustn't be raised in this method! # 1.", "import AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser import APKParser", "APK apk_path = app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path) # 3. Icon icon_path", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"", "self._uploaded_apk_path: str = uploaded_apk_path self._parsed_apk: ParsedAPK = APKParser(self._uploaded_apk_path).parsed_apk def add_app_while_locked(self)", "Database db_model = self._parsed_apk.create_new_db_model_with_metadata() db.session.add(db_model) db.session.commit() assert isinstance(db_model.id, int) app_metadata", "met: # 1. Redistributions of source code must retain the", "selfdroid.web.WebStatusMessageCollector import WebStatusMessageCollector from selfdroid import db class AppAdder: \"\"\"", "materials provided with the distribution. # 3. Neither the name", "context! \"\"\" def __init__(self, uploaded_apk_path: str): self._uploaded_apk_path: str = uploaded_apk_path", "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "be used to endorse or promote # products derived from", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #", "the names of its contributors may be used to endorse", "selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser import APKParser from selfdroid.appstorage.apk.ParsedAPK import", "the # following disclaimer in the documentation and/or other materials", "provided with the distribution. # 3. Neither the name of", "must be instantiated and have its public methods called in", "a locked context! \"\"\" def __init__(self, uploaded_apk_path: str): self._uploaded_apk_path: str", "or promote # products derived from this software without specific", "its contributors may be used to endorse or promote #", "db class AppAdder: \"\"\" This class must be instantiated and", "conditions and the following # disclaimer. # 2. Redistributions in", "import AppStorageConsistencyEnsurer from selfdroid.appstorage.apk.APKParser import APKParser from selfdroid.appstorage.apk.ParsedAPK import ParsedAPK", "1. Redistributions of source code must retain the above copyright", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #", "the server! You should update the app instead of adding", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os", "# 2. APK apk_path = app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path) # 3.", "OF THE POSSIBILITY OF SUCH DAMAGE. import os import sqlalchemy.exc", "AppMetadata: # An UserReadableException mustn't be raised in this method!", "with the distribution. # 3. Neither the name of the", "# SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2021 <NAME>. All", "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, #", "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING,", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER", "CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, #", "app with the same package name <i>({})</i> is already present", "app_metadata.get_apk_path() os.rename(self._uploaded_apk_path, apk_path) # 3. Icon icon_path = app_metadata.get_icon_path() with", "AppMetadata from selfdroid.appstorage.AppMetadataDBModel import AppMetadataDBModel from selfdroid.appstorage.AppStorageConsistencyEnsurer import AppStorageConsistencyEnsurer from", "added app. \"\"\" try: app_metadata = self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError, OSError):", "You should update the app instead of adding it!\", self._parsed_apk.package_name)", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL", "2. Redistributions in binary form must reproduce the above copyright", "app instead of adding it!\", self._parsed_apk.package_name) raise AppAdderException(html_message) def _perform_app_addition(self)", "are permitted provided that the # following conditions are met:", "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT", "PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "\"\"\" try: app_metadata = self._add_app_while_locked_with_exceptions_handled() except (sqlalchemy.exc.SQLAlchemyError, OSError): db.session.rollback() raise", "self._parsed_apk.package_name) raise AppAdderException(html_message) def _perform_app_addition(self) -> AppMetadata: # An UserReadableException", "instantiated and have its public methods called in a locked", "may be used to endorse or promote # products derived", "BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #", "above copyright notice, this list of conditions and the #", "BSD-3-Clause # # Copyright (c) 2021 <NAME>. All rights reserved.", "# 2. Redistributions in binary form must reproduce the above", "Neither the name of the copyright holder nor the names", "is not None: html_message = WebStatusMessageCollector.format_html_message(\"An app with the same" ]
[]
[ "None production = None from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField __url_label__", "<PASSWORD> id = None account_number = None production = None", "'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__ = [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl', ] __url_quote__", "<reponame>Solunest/pyestafeta<filename>estafeta/core/__init__.py from estafeta.core.client import EstafetaClient user = None password =", "= <PASSWORD> id = None account_number = None production =", "] __url_tracking__ = [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl', ] __url_quote__ = [", "estafeta.core.error import EstafetaWrongData, EstafetaEmptyField __url_label__ = [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ]", "user = None password = <PASSWORD> id = None account_number", "from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField __url_label__ = [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl',", "id = None account_number = None production = None from", "'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__ = [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl', ] __url_quote__ =", "estafeta.core.client import EstafetaClient user = None password = <PASSWORD> id", "= None from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField __url_label__ = [", "EstafetaEmptyField __url_label__ = [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__ = [", "= [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl', ] __url_quote__ = [ 'http://frecuenciacotizador.estafeta.com/Service.asmx?wsdl', 'http://frecuenciacotizador.estafeta.com/Service.asmx?wsdl',", "production = None from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField __url_label__ =", "= None password = <PASSWORD> id = None account_number =", "EstafetaWrongData, EstafetaEmptyField __url_label__ = [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__ =", "= [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__ = [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl',", "= None production = None from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField", "account_number = None production = None from estafeta.core.error import EstafetaWrongData,", "None password = <PASSWORD> id = None account_number = None", "EstafetaClient user = None password = <PASSWORD> id = None", "= None account_number = None production = None from estafeta.core.error", "None from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField __url_label__ = [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl',", "from estafeta.core.client import EstafetaClient user = None password = <PASSWORD>", "[ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__ = [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl', ]", "__url_tracking__ = [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl', ] __url_quote__ = [ 'http://frecuenciacotizador.estafeta.com/Service.asmx?wsdl',", "[ 'https://trackingqa.estafeta.com/Service.asmx?wsdl', 'https://tracking.estafeta.com/Service.asmx?wsdl', ] __url_quote__ = [ 'http://frecuenciacotizador.estafeta.com/Service.asmx?wsdl', 'http://frecuenciacotizador.estafeta.com/Service.asmx?wsdl', ]", "import EstafetaClient user = None password = <PASSWORD> id =", "None account_number = None production = None from estafeta.core.error import", "__url_label__ = [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__ = [ 'https://trackingqa.estafeta.com/Service.asmx?wsdl',", "import EstafetaWrongData, EstafetaEmptyField __url_label__ = [ 'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', 'https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl', ] __url_tracking__", "password = <PASSWORD> id = None account_number = None production" ]
[ "keyword = 'flavor' keyword_plural = 'flavors' _columns = ['ID', 'Name',", "base class FlavorManager(base.StandaloneManager): keyword = 'flavor' keyword_plural = 'flavors' _columns", "'flavor' keyword_plural = 'flavors' _columns = ['ID', 'Name', 'VCPU_count', 'VMEM_size',", "['ID', 'Name', 'VCPU_count', 'VMEM_size', 'Disk_size', 'Disk_backend', 'Ext_Bandwidth', 'Int_Bandwidth', 'is_public', 'Description',", "class FlavorManager(base.StandaloneManager): keyword = 'flavor' keyword_plural = 'flavors' _columns =", "yunionclient.common import base class FlavorManager(base.StandaloneManager): keyword = 'flavor' keyword_plural =", "FlavorManager(base.StandaloneManager): keyword = 'flavor' keyword_plural = 'flavors' _columns = ['ID',", "= 'flavors' _columns = ['ID', 'Name', 'VCPU_count', 'VMEM_size', 'Disk_size', 'Disk_backend',", "_columns = ['ID', 'Name', 'VCPU_count', 'VMEM_size', 'Disk_size', 'Disk_backend', 'Ext_Bandwidth', 'Int_Bandwidth',", "= ['ID', 'Name', 'VCPU_count', 'VMEM_size', 'Disk_size', 'Disk_backend', 'Ext_Bandwidth', 'Int_Bandwidth', 'is_public',", "= 'flavor' keyword_plural = 'flavors' _columns = ['ID', 'Name', 'VCPU_count',", "'Name', 'VCPU_count', 'VMEM_size', 'Disk_size', 'Disk_backend', 'Ext_Bandwidth', 'Int_Bandwidth', 'is_public', 'Description', 'Aggregate_strategy',", "keyword_plural = 'flavors' _columns = ['ID', 'Name', 'VCPU_count', 'VMEM_size', 'Disk_size',", "from yunionclient.common import base class FlavorManager(base.StandaloneManager): keyword = 'flavor' keyword_plural", "'VCPU_count', 'VMEM_size', 'Disk_size', 'Disk_backend', 'Ext_Bandwidth', 'Int_Bandwidth', 'is_public', 'Description', 'Aggregate_strategy', 'Flavor_type']", "<gh_stars>1-10 from yunionclient.common import base class FlavorManager(base.StandaloneManager): keyword = 'flavor'", "import base class FlavorManager(base.StandaloneManager): keyword = 'flavor' keyword_plural = 'flavors'", "'flavors' _columns = ['ID', 'Name', 'VCPU_count', 'VMEM_size', 'Disk_size', 'Disk_backend', 'Ext_Bandwidth'," ]
[ "index = line.split() char_map[ch] = int(index) index_map[int(index)+1] = ch index_map[2]", "72 ঐ 73 2 74 0 75 1 76 4", "63 ৭ 64 ড় 65 ঝ 66 ঞ 67 ঔ", "103 j 104 œ 105 8 106 ঢ় 107 k", "for line in char_map_str.strip().split('\\n'): ch, index = line.split() char_map[ch] =", "ড় 65 ঝ 66 ঞ 67 ঔ 68 ঈ 69", "ক 19 ড 20 হ 21 উ 22 প 23", "ঙ 43 খ 44 ঃ 45 ১ 46 ৯ 47", "93 m 94 e 95 ঊ 96 h 97 x", "70 b 71 s 72 ঐ 73 2 74 0", "char_map[ch] = int(index) index_map[int(index)+1] = ch index_map[2] = ' '", "5 100 y 101 9 102 ৗ 103 j 104", "৫ 54 ৪ 55 ফ 56 ৌ 57 ৮ 58", "ট 38 ূ 39 ম 40 ৈ 41 ৃ 42", "40 ৈ 41 ৃ 42 ঙ 43 খ 44 ঃ", "26 স 27 ষ 28 ই 29 আ 30 ছ", "\"\"\" ' 0 <SPACE> 1 ব 2 া 3 ং", "k 108 ৰ 109 \"\"\" # the \"blank\" character is", "18 ক 19 ড 20 হ 21 উ 22 প", "char_map = {} index_map = {} for line in char_map_str.strip().split('\\n'):", "{} index_map = {} for line in char_map_str.strip().split('\\n'): ch, index", "71 s 72 ঐ 73 2 74 0 75 1", "0 <SPACE> 1 ব 2 া 3 ং 4 ল", "ো 34 ও 35 ভ 36 ী 37 ট 38", "35 ভ 36 ী 37 ট 38 ূ 39 ম", "৭ 64 ড় 65 ঝ 66 ঞ 67 ঔ 68", "গ 32 ু 33 ো 34 ও 35 ভ 36", "4 77 f 78 o 79 t 80 a 81", "59 য় 60 ৩ 61 ঢ 62 ঠ 63 ৭", "29 আ 30 ছ 31 গ 32 ু 33 ো", "m 94 e 95 ঊ 96 h 97 x 98", "is mapped to 28 char_map = {} index_map = {}", "98 3 99 5 100 y 101 9 102 ৗ", "11 ত 12 ্ 13 ন 14 এ 15 ধ", "8 য 9 ় 10 ি 11 ত 12 ্", "র 17 ণ 18 ক 19 ড 20 হ 21", "য 9 ় 10 ি 11 ত 12 ্ 13", "১ 46 ৯ 47 ৬ 48 ০ 49 ২ 50", "ী 37 ট 38 ূ 39 ম 40 ৈ 41", "= \"\"\" ' 0 <SPACE> 1 ব 2 া 3", "77 f 78 o 79 t 80 a 81 l", "3 ং 4 ল 5 দ 6 ে 7 শ", "n 89 g 90 ঋ 91 i 92 z 93", "t 80 a 81 l 82 w 83 r 84", "sequences. \"\"\" char_map_str = \"\"\" ' 0 <SPACE> 1 ব", "for converting between text and integer sequences. \"\"\" char_map_str =", "ঐ 73 2 74 0 75 1 76 4 77", "and integer sequences. \"\"\" char_map_str = \"\"\" ' 0 <SPACE>", "g 90 ঋ 91 i 92 z 93 m 94", "integer sequences. \"\"\" char_map_str = \"\"\" ' 0 <SPACE> 1", "৯ 47 ৬ 48 ০ 49 ২ 50 চ 51", "67 ঔ 68 ঈ 69 v 70 b 71 s", "48 ০ 49 ২ 50 চ 51 ঘ 52 ৎ", "ৗ 103 j 104 œ 105 8 106 ঢ় 107", "in char_map_str.strip().split('\\n'): ch, index = line.split() char_map[ch] = int(index) index_map[int(index)+1]", "ছ 31 গ 32 ু 33 ো 34 ও 35", "ন 14 এ 15 ধ 16 র 17 ণ 18", "ৎ 53 ৫ 54 ৪ 55 ফ 56 ৌ 57", "ই 29 আ 30 ছ 31 গ 32 ু 33", "ঠ 63 ৭ 64 ড় 65 ঝ 66 ঞ 67", "39 ম 40 ৈ 41 ৃ 42 ঙ 43 খ", "73 2 74 0 75 1 76 4 77 f", "ঁ 59 য় 60 ৩ 61 ঢ 62 ঠ 63", "66 ঞ 67 ঔ 68 ঈ 69 v 70 b", "8 106 ঢ় 107 k 108 ৰ 109 \"\"\" #", "দ 6 ে 7 শ 8 য 9 ় 10", "51 ঘ 52 ৎ 53 ৫ 54 ৪ 55 ফ", "106 ঢ় 107 k 108 ৰ 109 \"\"\" # the", "ৰ 109 \"\"\" # the \"blank\" character is mapped to", "the \"blank\" character is mapped to 28 char_map = {}", "43 খ 44 ঃ 45 ১ 46 ৯ 47 ৬", "থ 26 স 27 ষ 28 ই 29 আ 30", "ড 20 হ 21 উ 22 প 23 জ 24", "37 ট 38 ূ 39 ম 40 ৈ 41 ৃ", "58 ঁ 59 য় 60 ৩ 61 ঢ 62 ঠ", "82 w 83 r 84 d 85 c 86 u", "to 28 char_map = {} index_map = {} for line", "28 char_map = {} index_map = {} for line in", "101 9 102 ৗ 103 j 104 œ 105 8", "character is mapped to 28 char_map = {} index_map =", "চ 51 ঘ 52 ৎ 53 ৫ 54 ৪ 55", "ঔ 68 ঈ 69 v 70 b 71 s 72", "b 71 s 72 ঐ 73 2 74 0 75", "z 93 m 94 e 95 ঊ 96 h 97", "ষ 28 ই 29 আ 30 ছ 31 গ 32", "char_map_str = \"\"\" ' 0 <SPACE> 1 ব 2 া", "74 0 75 1 76 4 77 f 78 o", "33 ো 34 ও 35 ভ 36 ী 37 ট", "76 4 77 f 78 o 79 t 80 a", "\"blank\" character is mapped to 28 char_map = {} index_map", "9 ় 10 ি 11 ত 12 ্ 13 ন", "two dictionaries for converting between text and integer sequences. \"\"\"", "২ 50 চ 51 ঘ 52 ৎ 53 ৫ 54", "l 82 w 83 r 84 d 85 c 86", "œ 105 8 106 ঢ় 107 k 108 ৰ 109", "line.split() char_map[ch] = int(index) index_map[int(index)+1] = ch index_map[2] = '", "27 ষ 28 ই 29 আ 30 ছ 31 গ", "64 ড় 65 ঝ 66 ঞ 67 ঔ 68 ঈ", "mapped to 28 char_map = {} index_map = {} for", "5 দ 6 ে 7 শ 8 য 9 ়", "3 99 5 100 y 101 9 102 ৗ 103", "খ 44 ঃ 45 ১ 46 ৯ 47 ৬ 48", "55 ফ 56 ৌ 57 ৮ 58 ঁ 59 য়", "শ 8 য 9 ় 10 ি 11 ত 12", "j 104 œ 105 8 106 ঢ় 107 k 108", "dictionaries for converting between text and integer sequences. \"\"\" char_map_str", "17 ণ 18 ক 19 ড 20 হ 21 উ", "e 95 ঊ 96 h 97 x 98 3 99", "34 ও 35 ভ 36 ী 37 ট 38 ূ", "w 83 r 84 d 85 c 86 u 87", "ং 4 ল 5 দ 6 ে 7 শ 8", "65 ঝ 66 ঞ 67 ঔ 68 ঈ 69 v", "99 5 100 y 101 9 102 ৗ 103 j", "2 া 3 ং 4 ল 5 দ 6 ে", "50 চ 51 ঘ 52 ৎ 53 ৫ 54 ৪", "char_map_str.strip().split('\\n'): ch, index = line.split() char_map[ch] = int(index) index_map[int(index)+1] =", "104 œ 105 8 106 ঢ় 107 k 108 ৰ", "প 23 জ 24 অ 25 থ 26 স 27", "ি 11 ত 12 ্ 13 ন 14 এ 15", "42 ঙ 43 খ 44 ঃ 45 ১ 46 ৯", "' 0 <SPACE> 1 ব 2 া 3 ং 4", "1 ব 2 া 3 ং 4 ল 5 দ", "25 থ 26 স 27 ষ 28 ই 29 আ", "108 ৰ 109 \"\"\" # the \"blank\" character is mapped", "20 হ 21 উ 22 প 23 জ 24 অ", "ফ 56 ৌ 57 ৮ 58 ঁ 59 য় 60", "a 81 l 82 w 83 r 84 d 85", "6 ে 7 শ 8 য 9 ় 10 ি", "78 o 79 t 80 a 81 l 82 w", "d 85 c 86 u 87 p 88 n 89", "<SPACE> 1 ব 2 া 3 ং 4 ল 5", "ঘ 52 ৎ 53 ৫ 54 ৪ 55 ফ 56", "ঢ 62 ঠ 63 ৭ 64 ড় 65 ঝ 66", "= {} index_map = {} for line in char_map_str.strip().split('\\n'): ch,", "হ 21 উ 22 প 23 জ 24 অ 25", "ু 33 ো 34 ও 35 ভ 36 ী 37", "৩ 61 ঢ 62 ঠ 63 ৭ 64 ড় 65", "ও 35 ভ 36 ী 37 ট 38 ূ 39", "90 ঋ 91 i 92 z 93 m 94 e", "97 x 98 3 99 5 100 y 101 9", "107 k 108 ৰ 109 \"\"\" # the \"blank\" character", "উ 22 প 23 জ 24 অ 25 থ 26", "০ 49 ২ 50 চ 51 ঘ 52 ৎ 53", "49 ২ 50 চ 51 ঘ 52 ৎ 53 ৫", "79 t 80 a 81 l 82 w 83 r", "88 n 89 g 90 ঋ 91 i 92 z", "ম 40 ৈ 41 ৃ 42 ঙ 43 খ 44", "15 ধ 16 র 17 ণ 18 ক 19 ড", "f 78 o 79 t 80 a 81 l 82", "80 a 81 l 82 w 83 r 84 d", "ণ 18 ক 19 ড 20 হ 21 উ 22", "31 গ 32 ু 33 ো 34 ও 35 ভ", "22 প 23 জ 24 অ 25 থ 26 স", "92 z 93 m 94 e 95 ঊ 96 h", "text and integer sequences. \"\"\" char_map_str = \"\"\" ' 0", "ৃ 42 ঙ 43 খ 44 ঃ 45 ১ 46", "h 97 x 98 3 99 5 100 y 101", "28 ই 29 আ 30 ছ 31 গ 32 ু", "68 ঈ 69 v 70 b 71 s 72 ঐ", "ৈ 41 ৃ 42 ঙ 43 খ 44 ঃ 45", "91 i 92 z 93 m 94 e 95 ঊ", "ঈ 69 v 70 b 71 s 72 ঐ 73", "r 84 d 85 c 86 u 87 p 88", "87 p 88 n 89 g 90 ঋ 91 i", "81 l 82 w 83 r 84 d 85 c", "10 ি 11 ত 12 ্ 13 ন 14 এ", "এ 15 ধ 16 র 17 ণ 18 ক 19", "<reponame>rakib313/Bangla-End2End-Speech-Recognition \"\"\" Defines two dictionaries for converting between text and", "61 ঢ 62 ঠ 63 ৭ 64 ড় 65 ঝ", "between text and integer sequences. \"\"\" char_map_str = \"\"\" '", "o 79 t 80 a 81 l 82 w 83", "96 h 97 x 98 3 99 5 100 y", "য় 60 ৩ 61 ঢ 62 ঠ 63 ৭ 64", "1 76 4 77 f 78 o 79 t 80", "৬ 48 ০ 49 ২ 50 চ 51 ঘ 52", "19 ড 20 হ 21 উ 22 প 23 জ", "line in char_map_str.strip().split('\\n'): ch, index = line.split() char_map[ch] = int(index)", "ভ 36 ী 37 ট 38 ূ 39 ম 40", "ch, index = line.split() char_map[ch] = int(index) index_map[int(index)+1] = ch", "62 ঠ 63 ৭ 64 ড় 65 ঝ 66 ঞ", "38 ূ 39 ম 40 ৈ 41 ৃ 42 ঙ", "ব 2 া 3 ং 4 ল 5 দ 6", "ঢ় 107 k 108 ৰ 109 \"\"\" # the \"blank\"", "= {} for line in char_map_str.strip().split('\\n'): ch, index = line.split()", "100 y 101 9 102 ৗ 103 j 104 œ", "{} for line in char_map_str.strip().split('\\n'): ch, index = line.split() char_map[ch]", "21 উ 22 প 23 জ 24 অ 25 থ", "9 102 ৗ 103 j 104 œ 105 8 106", "v 70 b 71 s 72 ঐ 73 2 74", "জ 24 অ 25 থ 26 স 27 ষ 28", "30 ছ 31 গ 32 ু 33 ো 34 ও", "54 ৪ 55 ফ 56 ৌ 57 ৮ 58 ঁ", "14 এ 15 ধ 16 র 17 ণ 18 ক", "স 27 ষ 28 ই 29 আ 30 ছ 31", "y 101 9 102 ৗ 103 j 104 œ 105", "47 ৬ 48 ০ 49 ২ 50 চ 51 ঘ", "\"\"\" char_map_str = \"\"\" ' 0 <SPACE> 1 ব 2", "44 ঃ 45 ১ 46 ৯ 47 ৬ 48 ০", "45 ১ 46 ৯ 47 ৬ 48 ০ 49 ২", "i 92 z 93 m 94 e 95 ঊ 96", "4 ল 5 দ 6 ে 7 শ 8 য", "ত 12 ্ 13 ন 14 এ 15 ধ 16", "105 8 106 ঢ় 107 k 108 ৰ 109 \"\"\"", "24 অ 25 থ 26 স 27 ষ 28 ই", "converting between text and integer sequences. \"\"\" char_map_str = \"\"\"", "41 ৃ 42 ঙ 43 খ 44 ঃ 45 ১", "53 ৫ 54 ৪ 55 ফ 56 ৌ 57 ৮", "36 ী 37 ট 38 ূ 39 ম 40 ৈ", "p 88 n 89 g 90 ঋ 91 i 92", "94 e 95 ঊ 96 h 97 x 98 3", "\"\"\" # the \"blank\" character is mapped to 28 char_map", "95 ঊ 96 h 97 x 98 3 99 5", "75 1 76 4 77 f 78 o 79 t", "অ 25 থ 26 স 27 ষ 28 ই 29", "7 শ 8 য 9 ় 10 ি 11 ত", "57 ৮ 58 ঁ 59 য় 60 ৩ 61 ঢ", "13 ন 14 এ 15 ধ 16 র 17 ণ", "69 v 70 b 71 s 72 ঐ 73 2", "ৌ 57 ৮ 58 ঁ 59 য় 60 ৩ 61", "# the \"blank\" character is mapped to 28 char_map =", "া 3 ং 4 ল 5 দ 6 ে 7", "c 86 u 87 p 88 n 89 g 90", "102 ৗ 103 j 104 œ 105 8 106 ঢ়", "় 10 ি 11 ত 12 ্ 13 ন 14", "৪ 55 ফ 56 ৌ 57 ৮ 58 ঁ 59", "\"\"\" Defines two dictionaries for converting between text and integer", "52 ৎ 53 ৫ 54 ৪ 55 ফ 56 ৌ", "56 ৌ 57 ৮ 58 ঁ 59 য় 60 ৩", "109 \"\"\" # the \"blank\" character is mapped to 28", "32 ু 33 ো 34 ও 35 ভ 36 ী", "ঃ 45 ১ 46 ৯ 47 ৬ 48 ০ 49", "ে 7 শ 8 য 9 ় 10 ি 11", "৮ 58 ঁ 59 য় 60 ৩ 61 ঢ 62", "ঝ 66 ঞ 67 ঔ 68 ঈ 69 v 70", "Defines two dictionaries for converting between text and integer sequences.", "= line.split() char_map[ch] = int(index) index_map[int(index)+1] = ch index_map[2] =", "ূ 39 ম 40 ৈ 41 ৃ 42 ঙ 43", "23 জ 24 অ 25 থ 26 স 27 ষ", "84 d 85 c 86 u 87 p 88 n", "86 u 87 p 88 n 89 g 90 ঋ", "u 87 p 88 n 89 g 90 ঋ 91", "ঞ 67 ঔ 68 ঈ 69 v 70 b 71", "x 98 3 99 5 100 y 101 9 102", "12 ্ 13 ন 14 এ 15 ধ 16 র", "index_map = {} for line in char_map_str.strip().split('\\n'): ch, index =", "46 ৯ 47 ৬ 48 ০ 49 ২ 50 চ", "60 ৩ 61 ঢ 62 ঠ 63 ৭ 64 ড়", "2 74 0 75 1 76 4 77 f 78", "আ 30 ছ 31 গ 32 ু 33 ো 34", "85 c 86 u 87 p 88 n 89 g", "s 72 ঐ 73 2 74 0 75 1 76", "্ 13 ন 14 এ 15 ধ 16 র 17", "16 র 17 ণ 18 ক 19 ড 20 হ", "83 r 84 d 85 c 86 u 87 p", "ঋ 91 i 92 z 93 m 94 e 95", "ঊ 96 h 97 x 98 3 99 5 100", "ধ 16 র 17 ণ 18 ক 19 ড 20", "ল 5 দ 6 ে 7 শ 8 য 9", "89 g 90 ঋ 91 i 92 z 93 m", "0 75 1 76 4 77 f 78 o 79" ]
[ "flask import Blueprint from flask_restful import Api # from restful", "Api from resources.Hello import CategoryResource api_bp = Blueprint('api', __name__) api", "from restful import Api from resources.Hello import CategoryResource api_bp =", "import Api # from restful import Api from resources.Hello import", "resources.Hello import CategoryResource api_bp = Blueprint('api', __name__) api = Api(api_bp)", "Api # from restful import Api from resources.Hello import CategoryResource", "import Blueprint from flask_restful import Api # from restful import", "CategoryResource api_bp = Blueprint('api', __name__) api = Api(api_bp) # Route", "import Api from resources.Hello import CategoryResource api_bp = Blueprint('api', __name__)", "from flask_restful import Api # from restful import Api from", "# from restful import Api from resources.Hello import CategoryResource api_bp", "api_bp = Blueprint('api', __name__) api = Api(api_bp) # Route api.add_resource(CategoryResource,", "= Blueprint('api', __name__) api = Api(api_bp) # Route api.add_resource(CategoryResource, '/Hello')", "from resources.Hello import CategoryResource api_bp = Blueprint('api', __name__) api =", "import CategoryResource api_bp = Blueprint('api', __name__) api = Api(api_bp) #", "Blueprint from flask_restful import Api # from restful import Api", "from flask import Blueprint from flask_restful import Api # from", "restful import Api from resources.Hello import CategoryResource api_bp = Blueprint('api',", "flask_restful import Api # from restful import Api from resources.Hello" ]
[ "= GLib.MainLoop() loop.run() @app.route('/') def index(): return ''' <html> <head>", "type=\"text/javascript\" charset=\"utf-8\"> var socket = io.connect('http://' + document.domain + ':'", "bus.subscribe(iface = 'org.ofono.VoiceCall', signal_fired = cb_server_signal_emission) loop = GLib.MainLoop() loop.run()", "message = {'unknown_signal': args } elif 'ofono.VoiceCallManager' in iface: if", "message = {'unknown_signal': args } elif 'ofono.VoiceCall' in iface: if", "'call_added', 'device': makedev(args[1]), 'properties': args[4][1] } elif 'CallRemoved' in args[3]:", "args } socketio.emit('message', json.dumps(message)) def dbus_monitor(): bus.subscribe(iface = 'org.ofono.Modem', signal_fired", "args[4][0], 'property_value': args[4][1] } else: message = {'unknown_signal': args }", "elif 'ofono.VoiceCall' in iface: if 'PropertyChanged' in args[3]: message =", "def index(): return ''' <html> <head> <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script", "' + message); var t = document.getElementById(\"logbox\"); t.value = t.value", "event') def handle_my_custom_event(arg1): emit('message', {'data': 42}) if __name__ == '__main__':", "else: message = {'unknown_signal': args } elif 'org.ofono.NetworkRegistration' in iface:", "'source': 'callmgr', 'event': 'call_added', 'device': makedev(args[1]), 'properties': args[4][1] } elif", "src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\" charset=\"utf-8\"> var socket = io.connect('http://' + document.domain", "'ofono.VoiceCallManager' in iface: if 'CallAdded' in args[3]: message = {", "#Data: Powered bus = SystemBus() def cb_server_signal_emission(*args): print(\"Message: \", args)", "@app.route('/') def index(): return ''' <html> <head> <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script>", "'device': makedev(args[1]), 'properties': args[4][1] } elif 'CallRemoved' in args[3]: message", "SocketIO, emit from pydbus import SystemBus from gi.repository import GLib", "args } elif 'ofono.VoiceCallManager' in iface: if 'CallAdded' in args[3]:", "document.domain + ':' + location.port); socket.on('connect', function() { socket.emit('connected', {data:", "= args[2] if 'org.ofono.Modem' in iface: if 'PropertyChanged' in args[3]:", "Flask, render_template, json from flask_socketio import SocketIO, emit from pydbus", "''' <html> <head> <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\" charset=\"utf-8\"> var", "iface = args[2] if 'org.ofono.Modem' in iface: if 'PropertyChanged' in", "from flask import Flask, render_template, json from flask_socketio import SocketIO,", "} else: message = {'unknown_signal': args } elif 'org.ofono.NetworkRegistration' in", "'callmgr', 'event': 'call_removed', 'device': makedev(args[1]) } else: message = {'unknown_signal':", "'event': 'call_removed', 'device': makedev(args[1]) } else: message = {'unknown_signal': args", "lambda path : path.split('/')[-1] iface = args[2] if 'org.ofono.Modem' in", "function(message) { console.log('The server has a message for you: '", "makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1] } else: message = {'unknown_signal':", "} else: message = {'unknown_signal': args } elif 'ofono.VoiceCall' in", "args[4][1] } else: message = {'unknown_signal': args } elif 'org.ofono.NetworkRegistration'", "iface: if 'PropertyChanged' in args[3]: message = { 'source': 'network',", "args[4][1] } else: message = {'unknown_signal': args } socketio.emit('message', json.dumps(message))", "</head> <body> <textarea id=\"logbox\" width=\"100\" rows=\"10\"></textarea> <br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body>", "async_mode='threading') #socketio = SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered',", "if 'PropertyChanged' in args[3]: message = { 'source': 'network', 'event':", "'/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered', False)) #Data: Powered bus = SystemBus()", "iface: if 'PropertyChanged' in args[3]: message = { 'source': 'modem',", "import SocketIO, emit from pydbus import SystemBus from gi.repository import", "args[3]: message = { 'source': 'call', 'event': 'property_change', 'device': makedev(args[1]),", "= Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode='threading') #socketio", "#socketio = SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered', False))", "= SocketIO(app, async_mode='threading') #socketio = SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem',", "loop.run() @app.route('/') def index(): return ''' <html> <head> <script type=\"text/javascript\"", ": path.split('/')[-1] iface = args[2] if 'org.ofono.Modem' in iface: if", "</body> </html> ''' @socketio.on('my event') def handle_my_custom_event(arg1): emit('message', {'data': 42})", "elif 'CallRemoved' in args[3]: message = { 'source': 'callmgr', 'event':", "gevent import monkey #monkey.patch_all() from flask import Flask, render_template, json", "message); var t = document.getElementById(\"logbox\"); t.value = t.value + 'MESSAGE:", "('Powered', False)) #Data: Powered bus = SystemBus() def cb_server_signal_emission(*args): print(\"Message:", "makedev = lambda path : path.split('/')[-1] iface = args[2] if", "'property': args[4][0], 'property_value': args[4][1] } else: message = {'unknown_signal': args", "else: message = {'unknown_signal': args } elif 'ofono.VoiceCallManager' in iface:", "+ location.port); socket.on('connect', function() { socket.emit('connected', {data: 'Client connected!'}); });", "} elif 'ofono.VoiceCallManager' in iface: if 'CallAdded' in args[3]: message", "else: message = {'unknown_signal': args } socketio.emit('message', json.dumps(message)) def dbus_monitor():", "import json app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio =", "app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode='threading')", "rows=\"10\"></textarea> <br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html> ''' @socketio.on('my event') def", "message = {'unknown_signal': args } socketio.emit('message', json.dumps(message)) def dbus_monitor(): bus.subscribe(iface", "cb_server_signal_emission) bus.subscribe(iface = 'org.ofono.NetworkRegistration', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface =", "'property_value': args[4][1] } else: message = {'unknown_signal': args } elif", "'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1] } else: message", "{ 'source': 'callmgr', 'event': 'call_removed', 'device': makedev(args[1]) } else: message", "'ofono.VoiceCall' in iface: if 'PropertyChanged' in args[3]: message = {", "socket.on('message', function(message) { console.log('The server has a message for you:", "'call_removed', 'device': makedev(args[1]) } else: message = {'unknown_signal': args }", "if 'PropertyChanged' in args[3]: message = { 'source': 'modem', 'event':", "server has a message for you: ' + message); var", "'source': 'callmgr', 'event': 'call_removed', 'device': makedev(args[1]) } else: message =", "args[3]: message = { 'source': 'callmgr', 'event': 'call_added', 'device': makedev(args[1]),", "elif 'org.ofono.NetworkRegistration' in iface: if 'PropertyChanged' in args[3]: message =", "message = {'unknown_signal': args } elif 'org.ofono.NetworkRegistration' in iface: if", "'network', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1] }", "bus.subscribe(iface = 'org.ofono.Modem', signal_fired = cb_server_signal_emission) bus.subscribe(iface = 'org.ofono.NetworkRegistration', signal_fired", "= cb_server_signal_emission) bus.subscribe(iface = 'org.ofono.NetworkRegistration', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface", "connected!'}); }); socket.on('message', function(message) { console.log('The server has a message", "GLib.MainLoop() loop.run() @app.route('/') def index(): return ''' <html> <head> <script", "} elif 'org.ofono.NetworkRegistration' in iface: if 'PropertyChanged' in args[3]: message", "<script type=\"text/javascript\" charset=\"utf-8\"> var socket = io.connect('http://' + document.domain +", "import Flask, render_template, json from flask_socketio import SocketIO, emit from", "pydbus import SystemBus from gi.repository import GLib import threading import", "{'unknown_signal': args } elif 'ofono.VoiceCallManager' in iface: if 'CallAdded' in", "'property_value': args[4][1] } else: message = {'unknown_signal': args } socketio.emit('message',", "+ document.domain + ':' + location.port); socket.on('connect', function() { socket.emit('connected',", "'org.ofono.Modem' in iface: if 'PropertyChanged' in args[3]: message = {", "+ 'MESSAGE: ' + message + '\\\\n'; }); </script> </head>", "a message for you: ' + message); var t =", "id=\"logbox\" width=\"100\" rows=\"10\"></textarea> <br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html> ''' @socketio.on('my", "'modem', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1] }", "args[3]: message = { 'source': 'callmgr', 'event': 'call_removed', 'device': makedev(args[1])", "var t = document.getElementById(\"logbox\"); t.value = t.value + 'MESSAGE: '", "''' @socketio.on('my event') def handle_my_custom_event(arg1): emit('message', {'data': 42}) if __name__", "flask import Flask, render_template, json from flask_socketio import SocketIO, emit", "'org.ofono.NetworkRegistration', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCallManager', signal_fired =", "console.log('The server has a message for you: ' + message);", "in args[3]: message = { 'source': 'callmgr', 'event': 'call_added', 'device':", "(':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered', False)) #Data: Powered bus =", "SystemBus from gi.repository import GLib import threading import json app", "= { 'source': 'modem', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0],", "</html> ''' @socketio.on('my event') def handle_my_custom_event(arg1): emit('message', {'data': 42}) if", "loop = GLib.MainLoop() loop.run() @app.route('/') def index(): return ''' <html>", "<html> <head> <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\" charset=\"utf-8\"> var socket", "= 'org.ofono.NetworkRegistration', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCallManager', signal_fired", "'source': 'call', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1]", "if __name__ == '__main__': t = threading.Thread(target=dbus_monitor) t.daemon = True", "emit from pydbus import SystemBus from gi.repository import GLib import", "has a message for you: ' + message); var t", "args) makedev = lambda path : path.split('/')[-1] iface = args[2]", "function() { socket.emit('connected', {data: 'Client connected!'}); }); socket.on('message', function(message) {", "makedev(args[1]), 'properties': args[4][1] } elif 'CallRemoved' in args[3]: message =", "'source': 'modem', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1]", "GLib import threading import json app = Flask(__name__) app.config['SECRET_KEY'] =", "'device': makedev(args[1]) } else: message = {'unknown_signal': args } elif", "t = threading.Thread(target=dbus_monitor) t.daemon = True t.start() socketio.run(app, host='0.0.0.0', port=5001)", "= { 'source': 'callmgr', 'event': 'call_added', 'device': makedev(args[1]), 'properties': args[4][1]", "print(bus) bus.subscribe(iface = 'org.ofono.VoiceCall', signal_fired = cb_server_signal_emission) loop = GLib.MainLoop()", "= document.getElementById(\"logbox\"); t.value = t.value + 'MESSAGE: ' + message", "t.value = t.value + 'MESSAGE: ' + message + '\\\\n';", "json.dumps(message)) def dbus_monitor(): bus.subscribe(iface = 'org.ofono.Modem', signal_fired = cb_server_signal_emission) bus.subscribe(iface", "= SystemBus() def cb_server_signal_emission(*args): print(\"Message: \", args) makedev = lambda", "= { 'source': 'call', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0],", "} else: message = {'unknown_signal': args } socketio.emit('message', json.dumps(message)) def", "bus.subscribe(iface = 'org.ofono.NetworkRegistration', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCallManager',", "in args[3]: message = { 'source': 'modem', 'event': 'property_change', 'device':", "{data: 'Client connected!'}); }); socket.on('message', function(message) { console.log('The server has", "width=\"100\" rows=\"10\"></textarea> <br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html> ''' @socketio.on('my event')", "<br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html> ''' @socketio.on('my event') def handle_my_custom_event(arg1):", "'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1] } else: message =", "charset=\"utf-8\"> var socket = io.connect('http://' + document.domain + ':' +", "}); </script> </head> <body> <textarea id=\"logbox\" width=\"100\" rows=\"10\"></textarea> <br> <button", "if 'org.ofono.Modem' in iface: if 'PropertyChanged' in args[3]: message =", "= cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCall', signal_fired = cb_server_signal_emission) loop", "}); socket.on('message', function(message) { console.log('The server has a message for", "= t.value + 'MESSAGE: ' + message + '\\\\n'; });", "{ socket.emit('connected', {data: 'Client connected!'}); }); socket.on('message', function(message) { console.log('The", "'org.ofono.Modem', 'PropertyChanged', ('Powered', False)) #Data: Powered bus = SystemBus() def", "message for you: ' + message); var t = document.getElementById(\"logbox\");", "from flask_socketio import SocketIO, emit from pydbus import SystemBus from", "cb_server_signal_emission(*args): print(\"Message: \", args) makedev = lambda path : path.split('/')[-1]", "makedev(args[1]) } else: message = {'unknown_signal': args } elif 'ofono.VoiceCall'", "in iface: if 'PropertyChanged' in args[3]: message = { 'source':", "{'unknown_signal': args } elif 'ofono.VoiceCall' in iface: if 'PropertyChanged' in", "flask_socketio import SocketIO, emit from pydbus import SystemBus from gi.repository", "'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1] } else:", "message = { 'source': 'network', 'event': 'property_change', 'device': makedev(args[1]), 'property':", "<script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\" charset=\"utf-8\"> var socket = io.connect('http://'", "42}) if __name__ == '__main__': t = threading.Thread(target=dbus_monitor) t.daemon =", "'callmgr', 'event': 'call_added', 'device': makedev(args[1]), 'properties': args[4][1] } elif 'CallRemoved'", "bus.subscribe(iface = 'org.ofono.VoiceCallManager', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCall',", "message = { 'source': 'modem', 'event': 'property_change', 'device': makedev(args[1]), 'property':", "signal_fired = cb_server_signal_emission) loop = GLib.MainLoop() loop.run() @app.route('/') def index():", "message = { 'source': 'callmgr', 'event': 'call_removed', 'device': makedev(args[1]) }", "'org.ofono.VoiceCall', signal_fired = cb_server_signal_emission) loop = GLib.MainLoop() loop.run() @app.route('/') def", "__name__ == '__main__': t = threading.Thread(target=dbus_monitor) t.daemon = True t.start()", "'PropertyChanged' in args[3]: message = { 'source': 'modem', 'event': 'property_change',", "cb_server_signal_emission) loop = GLib.MainLoop() loop.run() @app.route('/') def index(): return '''", "= 'org.ofono.Modem', signal_fired = cb_server_signal_emission) bus.subscribe(iface = 'org.ofono.NetworkRegistration', signal_fired =", "SocketIO(app, async_mode='threading') #socketio = SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged',", "'properties': args[4][1] } elif 'CallRemoved' in args[3]: message = {", "cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCall', signal_fired = cb_server_signal_emission) loop =", "= cb_server_signal_emission) loop = GLib.MainLoop() loop.run() @app.route('/') def index(): return", "False)) #Data: Powered bus = SystemBus() def cb_server_signal_emission(*args): print(\"Message: \",", "path : path.split('/')[-1] iface = args[2] if 'org.ofono.Modem' in iface:", "= 'org.ofono.VoiceCall', signal_fired = cb_server_signal_emission) loop = GLib.MainLoop() loop.run() @app.route('/')", "render_template, json from flask_socketio import SocketIO, emit from pydbus import", "def cb_server_signal_emission(*args): print(\"Message: \", args) makedev = lambda path :", "Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode='threading') #socketio =", "'secret!' socketio = SocketIO(app, async_mode='threading') #socketio = SocketIO(app) #Message: (':1.654',", "args[4][1] } elif 'CallRemoved' in args[3]: message = { 'source':", "socket.on('connect', function() { socket.emit('connected', {data: 'Client connected!'}); }); socket.on('message', function(message)", "json app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app,", "args } elif 'org.ofono.NetworkRegistration' in iface: if 'PropertyChanged' in args[3]:", "'org.ofono.NetworkRegistration' in iface: if 'PropertyChanged' in args[3]: message = {", "io.connect('http://' + document.domain + ':' + location.port); socket.on('connect', function() {", "+ '\\\\n'; }); </script> </head> <body> <textarea id=\"logbox\" width=\"100\" rows=\"10\"></textarea>", "path.split('/')[-1] iface = args[2] if 'org.ofono.Modem' in iface: if 'PropertyChanged'", "import GLib import threading import json app = Flask(__name__) app.config['SECRET_KEY']", "SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered', False)) #Data: Powered", "'CallRemoved' in args[3]: message = { 'source': 'callmgr', 'event': 'call_removed',", "def handle_my_custom_event(arg1): emit('message', {'data': 42}) if __name__ == '__main__': t", "SystemBus() def cb_server_signal_emission(*args): print(\"Message: \", args) makedev = lambda path", "args[2] if 'org.ofono.Modem' in iface: if 'PropertyChanged' in args[3]: message", "{'data': 42}) if __name__ == '__main__': t = threading.Thread(target=dbus_monitor) t.daemon", "\", args) makedev = lambda path : path.split('/')[-1] iface =", "'Client connected!'}); }); socket.on('message', function(message) { console.log('The server has a", "args[3]: message = { 'source': 'modem', 'event': 'property_change', 'device': makedev(args[1]),", "from gi.repository import GLib import threading import json app =", "Powered bus = SystemBus() def cb_server_signal_emission(*args): print(\"Message: \", args) makedev", "print(\"Message: \", args) makedev = lambda path : path.split('/')[-1] iface", "{ 'source': 'modem', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value':", "'event': 'call_added', 'device': makedev(args[1]), 'properties': args[4][1] } elif 'CallRemoved' in", "cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCallManager', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface", "= lambda path : path.split('/')[-1] iface = args[2] if 'org.ofono.Modem'", "t = document.getElementById(\"logbox\"); t.value = t.value + 'MESSAGE: ' +", "#from gevent import monkey #monkey.patch_all() from flask import Flask, render_template,", "} elif 'CallRemoved' in args[3]: message = { 'source': 'callmgr',", "{ 'source': 'callmgr', 'event': 'call_added', 'device': makedev(args[1]), 'properties': args[4][1] }", "= {'unknown_signal': args } socketio.emit('message', json.dumps(message)) def dbus_monitor(): bus.subscribe(iface =", "= { 'source': 'callmgr', 'event': 'call_removed', 'device': makedev(args[1]) } else:", "+ ':' + location.port); socket.on('connect', function() { socket.emit('connected', {data: 'Client", "= 'org.ofono.VoiceCallManager', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCall', signal_fired", "{'unknown_signal': args } socketio.emit('message', json.dumps(message)) def dbus_monitor(): bus.subscribe(iface = 'org.ofono.Modem',", "else: message = {'unknown_signal': args } elif 'ofono.VoiceCall' in iface:", "= io.connect('http://' + document.domain + ':' + location.port); socket.on('connect', function()", "= { 'source': 'network', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0],", "+ message); var t = document.getElementById(\"logbox\"); t.value = t.value +", "'PropertyChanged', ('Powered', False)) #Data: Powered bus = SystemBus() def cb_server_signal_emission(*args):", "in iface: if 'CallAdded' in args[3]: message = { 'source':", "socketio = SocketIO(app, async_mode='threading') #socketio = SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99',", "= {'unknown_signal': args } elif 'ofono.VoiceCall' in iface: if 'PropertyChanged'", "'PropertyChanged' in args[3]: message = { 'source': 'call', 'event': 'property_change',", "message = { 'source': 'callmgr', 'event': 'call_added', 'device': makedev(args[1]), 'properties':", "args } elif 'ofono.VoiceCall' in iface: if 'PropertyChanged' in args[3]:", "location.port); socket.on('connect', function() { socket.emit('connected', {data: 'Client connected!'}); }); socket.on('message',", "handle_my_custom_event(arg1): emit('message', {'data': 42}) if __name__ == '__main__': t =", "== '__main__': t = threading.Thread(target=dbus_monitor) t.daemon = True t.start() socketio.run(app,", "threading import json app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio", "print(bus) bus.subscribe(iface = 'org.ofono.VoiceCallManager', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface =", "'\\\\n'; }); </script> </head> <body> <textarea id=\"logbox\" width=\"100\" rows=\"10\"></textarea> <br>", "gi.repository import GLib import threading import json app = Flask(__name__)", "'org.ofono.VoiceCallManager', signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCall', signal_fired =", "emit('message', {'data': 42}) if __name__ == '__main__': t = threading.Thread(target=dbus_monitor)", "<button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html> ''' @socketio.on('my event') def handle_my_custom_event(arg1): emit('message',", "in args[3]: message = { 'source': 'network', 'event': 'property_change', 'device':", "'call', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1] }", "elif 'ofono.VoiceCallManager' in iface: if 'CallAdded' in args[3]: message =", "def dbus_monitor(): bus.subscribe(iface = 'org.ofono.Modem', signal_fired = cb_server_signal_emission) bus.subscribe(iface =", "if 'CallAdded' in args[3]: message = { 'source': 'callmgr', 'event':", "= {'unknown_signal': args } elif 'ofono.VoiceCallManager' in iface: if 'CallAdded'", "return ''' <html> <head> <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\" charset=\"utf-8\">", "<head> <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\" charset=\"utf-8\"> var socket =", "import SystemBus from gi.repository import GLib import threading import json", "for you: ' + message); var t = document.getElementById(\"logbox\"); t.value", "type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\" charset=\"utf-8\"> var socket = io.connect('http://' +", "document.getElementById(\"logbox\"); t.value = t.value + 'MESSAGE: ' + message +", "socket = io.connect('http://' + document.domain + ':' + location.port); socket.on('connect',", "t.value + 'MESSAGE: ' + message + '\\\\n'; }); </script>", "{ console.log('The server has a message for you: ' +", "= 'secret!' socketio = SocketIO(app, async_mode='threading') #socketio = SocketIO(app) #Message:", "@socketio.on('my event') def handle_my_custom_event(arg1): emit('message', {'data': 42}) if __name__ ==", "from pydbus import SystemBus from gi.repository import GLib import threading", "signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCall', signal_fired = cb_server_signal_emission)", "#Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered', False)) #Data: Powered bus", "message + '\\\\n'; }); </script> </head> <body> <textarea id=\"logbox\" width=\"100\"", "if 'PropertyChanged' in args[3]: message = { 'source': 'call', 'event':", "'CallAdded' in args[3]: message = { 'source': 'callmgr', 'event': 'call_added',", "{'unknown_signal': args } elif 'org.ofono.NetworkRegistration' in iface: if 'PropertyChanged' in", "var socket = io.connect('http://' + document.domain + ':' + location.port);", "json from flask_socketio import SocketIO, emit from pydbus import SystemBus", "= cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCallManager', signal_fired = cb_server_signal_emission) print(bus)", "<body> <textarea id=\"logbox\" width=\"100\" rows=\"10\"></textarea> <br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html>", "signal_fired = cb_server_signal_emission) print(bus) bus.subscribe(iface = 'org.ofono.VoiceCallManager', signal_fired = cb_server_signal_emission)", "monkey #monkey.patch_all() from flask import Flask, render_template, json from flask_socketio", "import threading import json app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!'", "'PropertyChanged' in args[3]: message = { 'source': 'network', 'event': 'property_change',", "{ 'source': 'network', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value':", "} else: message = {'unknown_signal': args } elif 'ofono.VoiceCallManager' in", "'source': 'network', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value': args[4][1]", "} elif 'ofono.VoiceCall' in iface: if 'PropertyChanged' in args[3]: message", "iface: if 'PropertyChanged' in args[3]: message = { 'source': 'call',", "import monkey #monkey.patch_all() from flask import Flask, render_template, json from", "in args[3]: message = { 'source': 'call', 'event': 'property_change', 'device':", "'org.ofono.Modem', signal_fired = cb_server_signal_emission) bus.subscribe(iface = 'org.ofono.NetworkRegistration', signal_fired = cb_server_signal_emission)", "iface: if 'CallAdded' in args[3]: message = { 'source': 'callmgr',", "':' + location.port); socket.on('connect', function() { socket.emit('connected', {data: 'Client connected!'});", "+ message + '\\\\n'; }); </script> </head> <body> <textarea id=\"logbox\"", "</script> </head> <body> <textarea id=\"logbox\" width=\"100\" rows=\"10\"></textarea> <br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button>", "app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode='threading') #socketio = SocketIO(app)", "bus = SystemBus() def cb_server_signal_emission(*args): print(\"Message: \", args) makedev =", "} socketio.emit('message', json.dumps(message)) def dbus_monitor(): bus.subscribe(iface = 'org.ofono.Modem', signal_fired =", "'__main__': t = threading.Thread(target=dbus_monitor) t.daemon = True t.start() socketio.run(app, host='0.0.0.0',", "'MESSAGE: ' + message + '\\\\n'; }); </script> </head> <body>", "you: ' + message); var t = document.getElementById(\"logbox\"); t.value =", "socketio.emit('message', json.dumps(message)) def dbus_monitor(): bus.subscribe(iface = 'org.ofono.Modem', signal_fired = cb_server_signal_emission)", "= {'unknown_signal': args } elif 'org.ofono.NetworkRegistration' in iface: if 'PropertyChanged'", "= SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered', False)) #Data:", "{ 'source': 'call', 'event': 'property_change', 'device': makedev(args[1]), 'property': args[4][0], 'property_value':", "args[4][1] } else: message = {'unknown_signal': args } elif 'ofono.VoiceCallManager'", "socket.emit('connected', {data: 'Client connected!'}); }); socket.on('message', function(message) { console.log('The server", "args[3]: message = { 'source': 'network', 'event': 'property_change', 'device': makedev(args[1]),", "dbus_monitor(): bus.subscribe(iface = 'org.ofono.Modem', signal_fired = cb_server_signal_emission) bus.subscribe(iface = 'org.ofono.NetworkRegistration',", "' + message + '\\\\n'; }); </script> </head> <body> <textarea", "#monkey.patch_all() from flask import Flask, render_template, json from flask_socketio import", "<textarea id=\"logbox\" width=\"100\" rows=\"10\"></textarea> <br> <button onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html> '''", "onclick=\"document.getElementById('logbox').value='';\">Clear</button> </body> </html> ''' @socketio.on('my event') def handle_my_custom_event(arg1): emit('message', {'data':", "index(): return ''' <html> <head> <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js\"></script> <script type=\"text/javascript\"", "message = { 'source': 'call', 'event': 'property_change', 'device': makedev(args[1]), 'property':", "signal_fired = cb_server_signal_emission) bus.subscribe(iface = 'org.ofono.NetworkRegistration', signal_fired = cb_server_signal_emission) print(bus)", "in args[3]: message = { 'source': 'callmgr', 'event': 'call_removed', 'device':" ]
[ "'separator', ':').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world',", "O}') \\ .equal([2, 'doc1', ['t', 'f o,F O'], 'doc2', ['t',", "'idx', 't').equal([['foo', [3, 4]]]) # read from the cursor res,", "'foo']]) env.expect('FT.SEARCH', 'idx1', '@t:{foo}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2',", "r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{HELLO WORLD}', 'NOCONTENT')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH',", "_ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@tags:{HELLO", "'text', 'tags', 'tag', 'separator', \"foo\") with env.assertResponseError(): r.execute_command( 'ft.create', 'idx',", "'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster()", "'idx4', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f o,F", "1} @tags:{foo bar}', 'slop', '0', 'inorder') env.assertEqual(1, res[0]) for n", "'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'bar') conn.execute_command('HSET',", "tags = 30 conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0')", "'idx', 'doc%d' % n, 1.0, 'fields', 'title', 'hello world term%d'", "can be used after being empty conn.execute_command('HSET', 'doc4', 't', 'foo')", "[3, 4]]]) # read from the cursor res, cursor =", "5, 6]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['f o', [4, 6]], ['F", "'tags', 'tag', 'separator', ',').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title',", "'doc2', ['t', 'FOO']]) env.expect('FT.SEARCH', 'idx2', '@t:{foo}') \\ .equal([2, 'doc1', ['t',", "_ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in ('@tags:{hello world}',", "# delete two tags conn.execute_command('DEL', 'doc1') conn.execute_command('DEL', 'doc2') forceInvokeGC(env, 'idx')", "'hello world term%d' % n, 'tags', 'foo bar,xxx,tag %d' %", "'doc3', ['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,f\\\\", "'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', \"\")", "'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') pl =", "env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\ o}') \\ .equal([3, 'doc1', ['t', 'f o,F", "'x') alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d' % n, 1.0,", "'t', 'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1]], ['bar', [2]], ['baz',", "['jell', [1]]]) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q", "env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\ o}') \\ .equal([2, 'doc1', ['t', 'f o,F", "'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O\\\\,F\\\\ O}')", "SCHEMA t TAG').ok() env.expect('FT.CREATE idx2 SCHEMA t TAG CASESENSITIVE').ok() env.expect('FT.CREATE", "casesensitive env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([1, 'doc1', ['t',", "'0') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['foo', [1, 2, 3]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "FIELDS title \"work\"').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"hello\"').error()", "o,F O'], 'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']])", "'foo bar') env.assertEqual(0, res[0]) res = env.cmd('ft.search', 'idx', '@tags:{foo bar}')", "n, 'x') alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d' % n,", ".equal([['hell', [1]], ['hello world', [1]], ['hello-world', [1]], ['jell', [1]]]) for", "% n, 'nocontent') env.assertEqual(1, res[0]) res = env.cmd( 'ft.search', 'idx',", "['t', 'FOO']]) env.expect('FT.SEARCH', 'idx2', '@t:{foo}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'],", "myIdx doc2 1.0 FIELDS title \"work\"').ok() env.expect('FT.ADD myIdx doc2 1.0", "'t').equal([]) # read from the cursor res, cursor = env.cmd('FT.CURSOR',", "res = py2sorted(res[1:]) env.assertEqual('doc%d' % n, res[0]) env.assertEqual('doc%d' % (n", "TAG').ok() env.expect('FT.CREATE idx2 SCHEMA t TAG CASESENSITIVE').ok() env.expect('FT.CREATE idx3 SCHEMA", "'t').equal([['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0]) # delete last tag conn.execute_command('DEL',", "# inorder should not affect tags res = env.cmd( 'ft.search',", "cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # read from the cursor", "syntax with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title',", "'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O}') \\ .equal([2, 'doc2',", "'separator') with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title',", "O'], 'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH',", "conn.execute_command('HSET', 'doc1', 't', 'f o,F O') conn.execute_command('HSET', 'doc2', 't', 'F", "'idx', 'title').raiseError() def testSearchNotExistsTagValue(env): # this test basically make sure", "empty conn.execute_command('HSET', 'doc4', 't', 'foo') conn.execute_command('HSET', 'doc5', 't', 'foo') env.expect('FT.SEARCH',", "'t').equal([['foo', [3, 4]]]) # read from the cursor res, cursor", "SCHEMA t TAG SORTABLE').ok() env.expect('FT.SEARCH idx @t:{val}').equal([0]) def testIssue1305(env): env.expect('FT.CREATE", "[1]], ['FOO', [2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['foo', [3]], ['foo,FOO', [1]],", "WORLD,FOO BAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') env.assertListEqual([0], r.execute_command(", "o']]) # casesensitive env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\ O}') \\ .equal([2, 'doc1',", "{'doc1' : ['inf', ['title', '\"hello,work\"']], 'doc3' : ['inf', ['title', '\"hello\"']],", "'separator', \"foo\") with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema',", "# invalid syntax with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH',", "'@t:{F\\\\ O}') \\ .equal([2, 'doc1', ['t', 'f o,F O'], 'doc2',", "from the cursor res, cursor = conn.execute_command('FT.CURSOR', 'READ', 'idx', cursor)", "title TAG').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"work\"').ok() env.expect('FT.ADD", "o', [4, 6]], ['F O', [4, 5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3',", "[3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.SEARCH', 'idx1', '@t:{FOO}') \\ .equal([3,", "res[0]) env.assertEqual('doc%d' % (n + 1), res[1]) res = env.cmd(", "2 + 1, len(res)) env.assertEqual(alltags, set(res)) res = r.execute_command('ft.tagvals', 'idx',", "'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator') with env.assertResponseError(): r.execute_command(", "'DUMP_TAGIDX', 'idx', 't').equal([['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0]) # delete last", "'tags', ','.join(tags), 'othertags', 'baz %d' % int(n // 2))) for", "[3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['foo', [3]],", "%d' % n, 'x') alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d'", "FIELDS title \"hello,work\"').ok() expectedRes = {'doc1' : ['inf', ['title', '\"hello,work\"']],", "'t', 'tag{}'.format(x)) pl.execute() for j in range(tags): pl.execute_command('DEL', 'doc{}'.format(j +", "n, 1.0, 'fields', 'tags', ','.join(tags), 'othertags', 'baz %d' % int(n", "'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx2', '@t:{FOO}') \\", "'idx5', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.SEARCH', 'idx1', '@t:{FOO}')", "'idx', '@TAgs:{HELLO WORLD}', 'NOCONTENT')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{foo", "n, 'tags', 'foo bar,xxx,tag %d' % n).ok() for _ in", "_ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = r.execute_command('ft.tagvals', 'idx', 'tags')", "res[0]) res = env.cmd('ft.search', 'idx', '@tags:{foo bar}') env.assertEqual(N, res[0]) #", "bar}', 'NOCONTENT')) env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@TAGS:{foo bar}', 'NOCONTENT')) def", "'idx', 'idx').raiseError() env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError() env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError() env.expect('ft.tagvals', 'idx',", "'othertags', 'baz %d' % int(n // 2))) for _ in", "'t', 'f o,F O') conn.execute_command('HSET', 'doc2', 't', 'F O') conn.execute_command('HSET',", "('@tags:{hello world}', '@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'): res = env.cmd('ft.search', 'idx', q)", "res = env.cmd('ft.search', 'idx', q) env.assertEqual(res[0], 1) def testTagFieldCase(env): r", "[]]) @unstable def testEmptyTagLeak(env): env.skipOnCluster() cycles = 1 tags =", "forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0])", "'schema', 'title', 'text', 'tags', 'tag', 'separator') with env.assertResponseError(): r.execute_command( 'ft.create',", "are not leaking env.expect('FT.CREATE idx ON HASH SCHEMA t TAG", "'slop', '0', 'inorder') env.assertEqual(1, res[0]) for n in range(N -", "res, cursor = env.cmd('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor,", "'t').equal([['foo', [1, 3]], ['FOO', [1, 2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['foo',", "'title', 'text', 'tags', 'tag').ok() N = 10 for n in", "'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'othertags', 'tag')", "HASH SCHEMA t TAG SORTABLE').ok() env.expect('FT.SEARCH idx @t:{val}').equal([0]) def testIssue1305(env):", "env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1]], ['bar', [2]], ['baz', [3]]]) env.expect('FT.SEARCH',", "1: i + 3] for i in range(0, len(res), 3)}", "env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@TAGS:{foo bar}', 'NOCONTENT')) def testInvalidSyntax(env): r", "[1, 2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['foo', [2, 3]], ['foo,foo', [1]]])", "'@t:{foo}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc3', ['t', 'foo']]) conn.execute_command('HSET',", "includes import * from common import * def search(env, r,", "forceInvokeGC(env, 'idx') # make sure the inverted index was cleaned", "'t', 'foo') conn.execute_command('HSET', 'doc2', 't', 'bar') conn.execute_command('HSET', 'doc3', 't', 'baz')", "for j in range(tags): x = j + i *", "sure we are not leaking env.expect('FT.CREATE idx ON HASH SCHEMA", "'t').equal([]) # check term can be used after being empty", "'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,f\\\\ o}') \\", "'tags') \\ .equal([['hell', [1]], ['hello world', [1]], ['hello-world', [1]], ['jell',", "'t', 'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'bar')", "'doc%d' % n, 1.0, 'fields', 'tags', ','.join(tags), 'othertags', 'baz %d'", "= env.cmd( 'ft.search', 'idx', '@tags:{tag %d}' % n, 'nocontent') env.assertEqual(1,", "'f o') if not env.is_cluster(): forceInvokeGC(env, 'idx1') forceInvokeGC(env, 'idx2') forceInvokeGC(env,", "env r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags',", "'idx3', 't').equal([['f o', [5, 6]], ['f o,f o', [4]]]) env.expect('FT.DEBUG',", "i + 3] for i in range(0, len(res), 3)} env.assertEqual(res,", "['title', '\"hello\"']], 'doc2' : ['inf', ['title', '\"work\"']]} res = env.cmd('ft.search',", "r = env env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title',", "'t').equal([['foo', [1, 2]]]) res, cursor = env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}', 'WITHCURSOR',", "used after being empty conn.execute_command('HSET', 'doc4', 't', 'foo') conn.execute_command('HSET', 'doc5',", "env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # check term can be used", "def testEmptyTagLeak(env): env.skipOnCluster() cycles = 1 tags = 30 conn", "forceInvokeGC(env, 'idx4') forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['f o', [4,", "pl.execute_command('DEL', 'doc{}'.format(j + i * tags)) pl.execute() forceInvokeGC(env, 'idx') env.expect('FT.DEBUG',", "[4]], ['F O', [5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['f o', [6]],", ": ['inf', ['title', '\"work\"']]} res = env.cmd('ft.search', 'myIdx', '~@title:{wor} ~@title:{hell}',", "env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\ O}') \\ .equal([3, 'doc1', ['t', 'f o,F", "% n, 'tags', 'foo bar,xxx,tag %d' % n).ok() for _", "casesensitive env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\ O}') \\ .equal([3, 'doc1', ['t', 'f", "\\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\", "'idx', 't').equal([['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0]) # delete last tag", "for n in range(N): env.expect('ft.add', 'idx', 'doc%d' % n, 1.0,", "env.expect('FT.CREATE myIdx ON HASH SCHEMA title TAG').ok() env.expect('FT.ADD myIdx doc2", "= env.cmd( 'ft.search', 'idx', '@tags:{tag 1} @tags:{foo bar}', 'slop', '0',", "to clean 'foo' inverted index env.expect('DEL', 'doc1').equal(1) env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env,", "1.0, 'fields', 'title', 'hello world', 'tags', 'x:hello world: fooz bar:foo,bar:BOO", "search(env, r, *args): return r.execute_command('ft.search', *args) def testTagIndex(env): r =", "[1]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]])", "env.expect('DEL', 'doc1').equal(1) env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env, 'idx') # make sure the", "testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE',", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.DEBUG',", "n, 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) res =", "r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = env.cmd('ft.search', 'idx', 'hello world') env.assertEqual(10,", "'idx2', '@t:{f\\\\ o}') \\ .equal([2, 'doc1', ['t', 'f o,F O'],", "env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o}') \\ .equal([2, 'doc2', ['t', 'F O'],", "'t', 'foo,FOO') conn.execute_command('HSET', 'doc2', 't', 'FOO') conn.execute_command('HSET', 'doc3', 't', 'foo')", "'ft.search', 'idx', '@tags:{tag %d}' % n, 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d'", "inverted index env.expect('DEL', 'doc1').equal(1) env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env, 'idx') # make", "\"hello,work\"').ok() expectedRes = {'doc1' : ['inf', ['title', '\"hello,work\"']], 'doc3' :", "conn.execute_command('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) # ensure", "'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', \"\") def", "sure the inverted index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([])", "% n, res[0]) env.assertEqual('doc%d' % (n + 1), res[1]) res", "not env.is_cluster(): forceInvokeGC(env, 'idx1') forceInvokeGC(env, 'idx2') forceInvokeGC(env, 'idx3') forceInvokeGC(env, 'idx4')", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['f o', [5, 6]], ['f o,f o',", "'text', 'TAgs', 'tag').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello", "in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = r.execute_command('ft.tagvals', 'idx', 'tags') env.assertEqual(N", "= env.cmd( 'ft.search', 'idx', 'term%d @tags:{tag %d}' % (n, n),", "res[0]) for n in range(N - 1): res = env.cmd(", "= getConnectionByEnv(env) env.expect('FT.CREATE idx1 SCHEMA t TAG').ok() env.expect('FT.CREATE idx2 SCHEMA", "'idx', 'SCHEMA', 't', 'TAG') pl = conn.pipeline() for i in", "alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields', 'tags', ','.join(tags),", "res[0]) env.assertEqual('doc%d' % n, res[1]) res = env.cmd( 'ft.search', 'idx',", "in ('@tags:{hello world}', '@tags:{fooz bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}', '@tags:{x}'): res", "= conn.execute_command('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) #", "res = env.cmd( 'ft.search', 'idx', '@tags:{tag 1} @tags:{foo bar}', 'slop',", "res[0]) def testTagPrefix(env): env.skipOnCluster() r = env env.expect( 'ft.create', 'idx',", "'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,F\\\\ O}')", "was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # read from the", "title \"hello,work\"').ok() expectedRes = {'doc1' : ['inf', ['title', '\"hello,work\"']], 'doc3'", "r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in ('@tags:{hello world}', '@tags:{fooz bar}',", "the cursor res, cursor = env.cmd('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res,", "res = env.cmd('ft.search', 'myIdx', '~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:] res = {res[i]:res[i", "= env.cmd('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) def", "'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o}')", "'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx3',", "env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0]) # delete last tag conn.execute_command('DEL', 'doc3') forceInvokeGC(env,", "'DUMP_TAGIDX', 'idx', 't').equal([['foo', [3, 4]]]) # read from the cursor", "env.assertEqual(N, res[0]) # inorder should not affect tags res =", "conn.execute_command('HSET', 'doc2', 't', 'F O') conn.execute_command('HSET', 'doc3', 't', 'f o')", "'idx3') forceInvokeGC(env, 'idx4') forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['f o',", "res = r.execute_command('ft.tagvals', 'idx', 'tags') env.assertEqual(N * 2 + 1,", "'schema', 'title', 'text', 'TAgs', 'tag').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields',", "'schema', 'title', 'text', 'tags', 'tag', 'separator', ',').ok() env.expect('ft.add', 'idx', 'doc1',", "'dump_tagidx', 'idx5', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.SEARCH', 'idx1',", "['t', 'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\", "tag conn.execute_command('DEL', 'doc3') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) #", "env # invalid syntax with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON',", "pl.execute_command('HSET', 'doc{}'.format(x), 't', 'tag{}'.format(x)) pl.execute() for j in range(tags): pl.execute_command('DEL',", "1.0, 'fields', 'title', 'hello world term%d' % n, 'tags', 'foo", "env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"work\"').ok() env.expect('FT.ADD myIdx doc2", "q in ('@tags:{hello world}', '@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'): res = env.cmd('ft.search',", "['t', 'F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o}') \\ .equal([1, 'doc3',", "'t', 'foo') if not env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG',", "'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', \"foo\") with env.assertResponseError():", "o}') \\ .equal([2, 'doc1', ['t', 'f o,F O'], 'doc3', ['t',", "\\ .equal([2, 'doc1', ['t', 'f o,F O'], 'doc3', ['t', 'f", "o}') \\ .equal([2, 'doc2', ['t', 'F O'], 'doc3', ['t', 'f", "'dump_tagidx', 'idx1', 't').equal([['f o', [4, 5, 6]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2',", "\\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO']]) env.expect('FT.SEARCH', 'idx2',", "'idx3', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f o,F", "for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = env.cmd('ft.search', 'idx',", ".equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O\\\\,F\\\\", "'f o,F O'], 'doc3', ['t', 'f o']]) # not casesensitive", "'HASH', 'schema', 'title', 'text', 'TAgs', 'tag').ok() env.expect('ft.add', 'idx', 'doc1', 1.0,", "'idx', '@tags:{tag %d}' % n, 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' %", "'nocontent') env.assertEqual(1, res[0]) res = env.cmd( 'ft.search', 'idx', 'hello world", "env.cmd('ft.search', 'myIdx', '~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:] res = {res[i]:res[i + 1:", "'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') pl = conn.pipeline()", ".equal([2, 'doc1', ['t', 'f o,F O'], 'doc2', ['t', 'F O']])", "'title', 'hello world', 'tags', 'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx', 'idx', 'tags')", "env.assertEqual(res[0], 1) def testTagFieldCase(env): r = env env.expect( 'ft.create', 'idx',", "'idx', 't').equal([]) # check term can be used after being", "the cursor res, cursor = conn.execute_command('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res,", "TAG CASESENSITIVE').ok() env.expect('FT.CREATE idx3 SCHEMA t TAG SEPARATOR .').ok() env.expect('FT.CREATE", "testIssue1305(env): env.expect('FT.CREATE myIdx ON HASH SCHEMA title TAG').ok() env.expect('FT.ADD myIdx", "o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O}') \\ .equal([2, 'doc2', ['t',", "'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', ':').ok() env.expect('ft.add', 'idx',", "env.skipOnCluster() cycles = 1 tags = 30 conn = getConnectionByEnv(env)", "'tag').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'TAgs',", "\\ .equal([2, 'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']])", "@tags:{tag %d}' % (n, n), 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' %", "# read from the cursor res, cursor = conn.execute_command('FT.CURSOR', 'READ',", "o', [5, 6]], ['f o,f o', [4]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4',", "o', [4, 5, 6]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['f o', [4,", "getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG')", "[5, 6]], ['f o,f o', [4]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['f", "'doc1', 1.0, 'fields', 'title', 'hello world', 'TAgs', 'HELLO WORLD,FOO BAR').ok()", "pl = conn.pipeline() for i in range(cycles): for j in", "for q in ('@tags:{hello world}', '@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'): res =", "['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,f\\\\ o}')", "6]], ['F O', [4, 5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['f o',", "env.assertEqual(alltags, set(res)) res = r.execute_command('ft.tagvals', 'idx', 'othertags') env.assertEqual(N / 2,", "['t', 'F O']]) env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\ o}') \\ .equal([2, 'doc1',", "'text', 'tags', 'tag', 'separator', \"\") def testTagVals(env): r = env", "env.assertEqual('doc%d' % (n + 1), res[1]) res = env.cmd( 'ft.search',", "\\ .equal([1, 'doc3', ['t', 'f o']]) def testTagGCClearEmpty(env): env.skipOnCluster() conn", "'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', ':').ok() env.expect('ft.add',", "env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # add data conn.execute_command('HSET', 'doc3', 't',", "for j in range(tags): pl.execute_command('DEL', 'doc{}'.format(j + i * tags))", "n).ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = env.cmd('ft.search',", "'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'tags', 'hello world,hello-world,hell,jell').ok()", "'idx3', '@t:{f\\\\ o}') \\ .equal([2, 'doc2', ['t', 'F O'], 'doc3',", "'myIdx', '~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:] res = {res[i]:res[i + 1: i", ".equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,F\\\\", "['t', 'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\", "idx ON HASH SCHEMA t TAG SORTABLE').ok() env.expect('FT.SEARCH idx @t:{val}').equal([0])", "1.0 FIELDS title \"hello\"').ok() env.expect('FT.ADD myIdx doc1 1.0 FIELDS title", "['FOO', [2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO',", "\\ .equal([3, 'doc1', ['t', 'f o,F O'], 'doc2', ['t', 'F", "res[1]) res = env.cmd( 'ft.search', 'idx', '@tags:{tag\\\\ %d}' % n,", "+ 3] for i in range(0, len(res), 3)} env.assertEqual(res, expectedRes)", "for q in ('@tags:{hello world}', '@tags:{fooz bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}',", "O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O}') \\ .equal([2, 'doc2', ['t', 'F", "testTagGCClearEmpty(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE',", "['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx1', '@t:{foo}') \\ .equal([3,", "far}', '@tags:{x}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(1, res[0]) def", "env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'tags', 'hello", "'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') conn.execute_command('HSET', 'doc1',", "env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) res = env.cmd( 'ft.search',", "'t', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1, 2]]]) res, cursor", "world @tags:{tag\\\\ %d|tag %d}' % (n, n + 1), 'nocontent')", "env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0]) # delete", "(n, n), 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) def", "'t').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.SEARCH', 'idx1', '@t:{FOO}') \\", "'idx5') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['f o', [4, 5, 6]]]) env.expect('FT.DEBUG',", "r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{foo bar}', 'NOCONTENT')) env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx',", "'doc{}'.format(x), 't', 'tag{}'.format(x)) pl.execute() for j in range(tags): pl.execute_command('DEL', 'doc{}'.format(j", ".equal([2, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO']]) env.expect('FT.SEARCH', 'idx2', '@t:{foo}')", "'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o}') \\ .equal([2,", "'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # check term can be", "'foo']]) def testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD',", "'doc1') conn.execute_command('DEL', 'doc2') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['baz', [3]]])", "4]]]) # read from the cursor res, cursor = conn.execute_command('FT.CURSOR',", "'NOCONTENT')) def testInvalidSyntax(env): r = env # invalid syntax with", "\"foo\") with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title',", "# ensure later documents with same tag are read res", "in range(cycles): for j in range(tags): x = j +", "env.assertEqual(1, res[0]) res = env.cmd( 'ft.search', 'idx', 'hello world @tags:{tag\\\\", "read from the cursor res, cursor = env.cmd('FT.CURSOR', 'READ', 'idx',", "term can be used after being empty conn.execute_command('HSET', 'doc4', 't',", "[2]], ['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1, 'doc1', ['t', 'foo']]) #", "forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # check term can", "delete last tag conn.execute_command('DEL', 'doc3') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx',", "n in range(N): env.expect('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields',", "this test basically make sure we are not leaking env.expect('FT.CREATE", "O}') \\ .equal([3, 'doc1', ['t', 'f o,F O'], 'doc2', ['t',", "'f o']]) # not casesensitive env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,f\\\\ o}')", "'schema', 'title', 'text', 'tags', 'tag', 'separator', ':').ok() env.expect('ft.add', 'idx', 'doc1',", "[1]], ['bar', [2]], ['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1, 'doc1', ['t',", "cursor res, cursor = env.cmd('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0])", "'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['foo', [1, 2, 3]]])", "env.assertEqual(res, [0]) env.assertEqual(cursor, 0) def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn = getConnectionByEnv(env)", "'doc3', ['t', 'f o']]) # not casesensitive env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\", "'idx3', '@t:{F\\\\ O}') \\ .equal([2, 'doc2', ['t', 'F O'], 'doc3',", "'doc4', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [3, 4]]]) #", "'dump_tagidx', 'idx', 'tags') \\ .equal([['hell', [1]], ['hello world', [1]], ['hello-world',", "'hello world') env.assertEqual(10, res[0]) res = env.cmd('ft.search', 'idx', 'foo bar')", "'title', 'text', 'TAgs', 'tag').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title',", "basically make sure we are not leaking env.expect('FT.CREATE idx ON", "'separator', ',').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world',", "for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = r.execute_command('ft.tagvals', 'idx',", "cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) # ensure later documents with", "testTagIndex(env): r = env env.expect('ft.create', 'idx', 'ON', 'HASH','schema', 'title', 'text',", "env.cmd('ft.search', 'idx', q) env.assertEqual(1, res[0]) def testTagPrefix(env): env.skipOnCluster() r =", "env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'TAgs', 'HELLO", "'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) # ensure later", "%d|tag %d}' % (n, n + 1), 'nocontent') env.assertEqual(2, res[0])", "'f o']]) def testTagGCClearEmpty(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET',", "should not affect tags res = env.cmd( 'ft.search', 'idx', '@tags:{tag", "[1]], ['hello-world', [1]], ['jell', [1]]]) for _ in r.retry_with_rdb_reload(): waitForIndex(r,", "term%d' % n, 'tags', 'foo bar,xxx,tag %d' % n).ok() for", "'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'TAgs', 'HELLO WORLD,FOO", "'doc2', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1, 2]]]) res,", "world}', '@tags:{fooz bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}', '@tags:{x}'): res = env.cmd('ft.search',", "# make sure the inverted index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX',", "O'], 'doc3', ['t', 'f o']]) # not casesensitive env.expect('FT.SEARCH', 'idx3',", "env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{HELLO WORLD}', 'NOCONTENT')) env.assertListEqual([1, 'doc1'],", "1), 'nocontent') env.assertEqual(2, res[0]) res = py2sorted(res[1:]) env.assertEqual('doc%d' % n,", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['f o', [4, 5, 6]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "'bar %d' % n, 'x') alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx',", "'idx') for q in ('@tags:{hello world}', '@tags:{fooz bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\", "'@TAgs:{foo bar}', 'NOCONTENT')) env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@TAGS:{foo bar}', 'NOCONTENT'))", "[3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0]) # delete last tag conn.execute_command('DEL', 'doc3')", "'idx', q) env.assertEqual(res[0], 1) def testTagFieldCase(env): r = env env.expect(", "two tags conn.execute_command('DEL', 'doc1') conn.execute_command('DEL', 'doc2') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX',", "for n in range(N): tags = ('foo %d' % n,", "'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\ O}') \\ .equal([2,", "'idx4', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O}')", "env.expect('ft.tagvals', 'idx', 'title').raiseError() def testSearchNotExistsTagValue(env): # this test basically make", "'tags', 'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx', 'idx', 'tags') \\ .equal([['hell', [1]],", "'ft.search', 'idx', 'term%d @tags:{tag %d}' % (n, n), 'nocontent') env.assertEqual(1,", "['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx2', '@t:{FOO}') \\ .equal([2,", "-*- coding: utf-8 -*- from includes import * from common", "'ON', 'HASH','schema', 'title', 'text', 'tags', 'tag').ok() N = 10 for", "2, 3]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['foo', [1, 3]], ['FOO', [1,", "'idx2', '@t:{F\\\\ O}') \\ .equal([2, 'doc1', ['t', 'f o,F O'],", "'idx').raiseError() env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError() env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError() env.expect('ft.tagvals', 'idx', 'title').raiseError()", "O\\\\,F\\\\ O}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O}') \\ .equal([1,", "waitForIndex(r, 'idx') res = env.cmd('ft.search', 'idx', 'hello world') env.assertEqual(10, res[0])", "['hello world', [1]], ['hello-world', [1]], ['jell', [1]]]) for _ in", "O']]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o}') \\ .equal([1, 'doc3', ['t', 'f", "'idx', '@t:{foo}') env.assertEqual(res, [1, [], []]) @unstable def testEmptyTagLeak(env): env.skipOnCluster()", "add data conn.execute_command('HSET', 'doc3', 't', 'foo') conn.execute_command('HSET', 'doc4', 't', 'foo')", "'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator') with env.assertResponseError():", "'doc1', ['t', 'f o,F O'], 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH',", "'idx') res = env.cmd('ft.search', 'idx', 'hello world') env.assertEqual(10, res[0]) res", "':').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'tags',", "= ('foo %d' % n, 'bar %d' % n, 'x')", "= {res[i]:res[i + 1: i + 3] for i in", "# add data conn.execute_command('HSET', 'doc3', 't', 'foo') conn.execute_command('HSET', 'doc4', 't',", "(n + 1), res[1]) res = env.cmd( 'ft.search', 'idx', 'term%d", "[6]], ['f o,F O', [4]], ['F O', [5]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "1.0, 'fields', 'title', 'hello world', 'TAgs', 'HELLO WORLD,FOO BAR').ok() for", "= j + i * tags pl.execute_command('HSET', 'doc{}'.format(x), 't', 'tag{}'.format(x))", "in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in ('@tags:{hello world}', '@tags:{hel*}',", "N = 100 alltags = set() for n in range(N):", "'F O') conn.execute_command('HSET', 'doc3', 't', 'f o') if not env.is_cluster():", "'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn", "set(res)) res = r.execute_command('ft.tagvals', 'idx', 'othertags') env.assertEqual(N / 2, len(res))", "@tags:{tag\\\\ %d|tag %d}' % (n, n + 1), 'nocontent') env.assertEqual(2,", ": ['inf', ['title', '\"hello\"']], 'doc2' : ['inf', ['title', '\"work\"']]} res", "the GC to clean 'foo' inverted index env.expect('DEL', 'doc1').equal(1) env.expect('DEL',", "'f o']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o}') \\ .equal([2, 'doc2', ['t',", "myIdx doc3 1.0 FIELDS title \"hello\"').ok() env.expect('FT.ADD myIdx doc1 1.0", "conn.execute_command('DEL', 'doc2') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['baz', [3]]]) env.expect('FT.SEARCH',", "conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX',", "'idx', '@t:{foo}').equal([1, 'doc1', ['t', 'foo']]) # delete two tags conn.execute_command('DEL',", "SEPARATOR . CASESENSITIVE').ok() env.expect('FT.CREATE idx5 SCHEMA t TAG CASESENSITIVE SEPARATOR", "same tag are read res = conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}') env.assertEqual(res,", "\\ .equal([1, 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o}')", "affect tags res = env.cmd( 'ft.search', 'idx', '@tags:{tag 1} @tags:{foo", "in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@tags:{HELLO WORLD}'))", "[1, [], []]) @unstable def testEmptyTagLeak(env): env.skipOnCluster() cycles = 1", "2, len(res)) env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals', 'idx', 'idx', 'idx').raiseError() env.expect('ft.tagvals', 'fake_idx',", "_ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = env.cmd('ft.search', 'idx', 'hello", "'idx', '@tags:{HELLO WORLD}')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{HELLO WORLD}',", "env.expect('FT.CREATE idx3 SCHEMA t TAG SEPARATOR .').ok() env.expect('FT.CREATE idx4 SCHEMA", "= env.cmd( 'ft.search', 'idx', 'hello world @tags:{tag\\\\ %d|tag %d}' %", "with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text',", "'inorder') env.assertEqual(1, res[0]) for n in range(N - 1): res", "'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'bar') conn.execute_command('HSET', 'doc3', 't',", "set() for n in range(N): tags = ('foo %d' %", "documents with same tag are read res = conn.execute_command('FT.AGGREGATE', 'idx',", "r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in ('@tags:{hello world}', '@tags:{hel*}', '@tags:{hello\\\\-*}',", "make sure we are not leaking env.expect('FT.CREATE idx ON HASH", "'@tags:{tag\\\\ %d}' % n, 'nocontent') env.assertEqual(1, res[0]) res = env.cmd(", "range(tags): pl.execute_command('DEL', 'doc{}'.format(j + i * tags)) pl.execute() forceInvokeGC(env, 'idx')", "# not casesensitive env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([1,", "'fields', 'title', 'hello world', 'tags', 'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx', 'idx',", "'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) def testSeparator(env): r", "in range(tags): x = j + i * tags pl.execute_command('HSET',", "conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') conn.execute_command('HSET',", "'idx', '@TAgs:{foo bar}', 'NOCONTENT')) env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@TAGS:{foo bar}',", ".equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O}') \\ .equal([1, 'doc2', ['t', 'F", "% n, 1.0, 'fields', 'title', 'hello world term%d' % n,", "'idx', '@tags:{tag 1} @tags:{foo bar}', 'slop', '0', 'inorder') env.assertEqual(1, res[0])", "[5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['f o', [6]], ['f o,F O',", "TAG').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"work\"').ok() env.expect('FT.ADD myIdx", "r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = r.execute_command('ft.tagvals', 'idx', 'tags') env.assertEqual(N *", "'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O\\\\,F\\\\ O}')", "\\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O}') \\ .equal([1, 'doc2', ['t',", "world}', '@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(res[0],", "'@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f o,F O']])", "def testTagVals(env): r = env r.execute_command( 'ft.create', 'idx', 'ON', 'HASH',", "and run the GC to clean 'foo' inverted index env.expect('DEL',", "env.expect('FT.CREATE idx5 SCHEMA t TAG CASESENSITIVE SEPARATOR .').ok() conn.execute_command('HSET', 'doc1',", "tags res = env.cmd( 'ft.search', 'idx', '@tags:{tag 1} @tags:{foo bar}',", "'t', 'foo') conn.execute_command('HSET', 'doc4', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo',", "ON HASH SCHEMA title TAG').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS", "[1]]]) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in", "res = env.cmd('ft.search', 'idx', '@tags:{foo bar}') env.assertEqual(N, res[0]) # inorder", "be used after being empty conn.execute_command('HSET', 'doc4', 't', 'foo') conn.execute_command('HSET',", "inverted index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # add", "def testTagGCClearEmpty(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0')", "'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o}') \\ .equal([1,", "['t', 'F O'], 'doc3', ['t', 'f o']]) # casesensitive env.expect('FT.SEARCH',", "testTagPrefix(env): env.skipOnCluster() r = env env.expect( 'ft.create', 'idx', 'ON', 'HASH',", "'SCHEMA', 't', 'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't',", "'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) # ensure later documents", "env.assertEqual(cursor, 0) def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET',", "'NOCONTENT')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{foo bar}', 'NOCONTENT')) env.assertListEqual([0],", "o', [6]], ['f o,F O', [4]], ['F O', [5]]]) #", "%d' % int(n // 2))) for _ in r.retry_with_rdb_reload(): waitForIndex(r,", ".equal([2, 'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH',", "'@tags:{foo bar}') env.assertEqual(N, res[0]) # inorder should not affect tags", "'idx', '@tags:{tag\\\\ %d}' % n, 'nocontent') env.assertEqual(1, res[0]) res =", "env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f", "'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', \"foo\")", "o,F O', [4]], ['F O', [5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['f", "res[1]) res = env.cmd( 'ft.search', 'idx', 'term%d @tags:{tag %d}' %", "TAG SEPARATOR . CASESENSITIVE').ok() env.expect('FT.CREATE idx5 SCHEMA t TAG CASESENSITIVE", "\"work\"').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"hello\"').error() env.expect('FT.ADD myIdx", "read from the cursor res, cursor = conn.execute_command('FT.CURSOR', 'READ', 'idx',", "WORLD}')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{HELLO WORLD}', 'NOCONTENT')) env.assertListEqual([1,", "'idx1', 't').equal([['foo', [1, 2, 3]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['foo', [1,", "range(N): tags = ('foo %d' % n, 'bar %d' %", "[2, 3]], ['foo,foo', [1]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['foo', [3]], ['foo,FOO',", "both documents and run the GC to clean 'foo' inverted", "o']]) # not casesensitive env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,f\\\\ o}') \\", "= py2sorted(res[1:]) env.assertEqual('doc%d' % n, res[0]) env.assertEqual('doc%d' % (n +", "= {'doc1' : ['inf', ['title', '\"hello,work\"']], 'doc3' : ['inf', ['title',", "['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,F\\\\ O}') \\", "'bar') conn.execute_command('HSET', 'doc3', 't', 'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1]],", "n, res[1]) def testSeparator(env): r = env env.expect( 'ft.create', 'idx',", "leaking env.expect('FT.CREATE idx ON HASH SCHEMA t TAG SORTABLE').ok() env.expect('FT.SEARCH", "env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O}') \\ .equal([1, 'doc2', ['t', 'F O']])", "2]]]) res, cursor = env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}', 'WITHCURSOR', 'COUNT', '1')", ".equal([3, 'doc1', ['t', 'f o,F O'], 'doc2', ['t', 'F O'],", "TAG SORTABLE').ok() env.expect('FT.SEARCH idx @t:{val}').equal([0]) def testIssue1305(env): env.expect('FT.CREATE myIdx ON", "'t').equal([]) # add data conn.execute_command('HSET', 'doc3', 't', 'foo') conn.execute_command('HSET', 'doc4',", "['inf', ['title', '\"hello,work\"']], 'doc3' : ['inf', ['title', '\"hello\"']], 'doc2' :", "world') env.assertEqual(10, res[0]) res = env.cmd('ft.search', 'idx', 'foo bar') env.assertEqual(0,", "'idx4', '@t:{F\\\\ O}') \\ .equal([1, 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH',", "BAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') env.assertListEqual([0], r.execute_command( 'FT.SEARCH',", "tag are read res = conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}') env.assertEqual(res, [1,", "'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1]], ['bar', [2]], ['baz', [3]]]) env.expect('FT.SEARCH', 'idx',", "res[0]) env.assertEqual('doc%d' % n, res[1]) def testSeparator(env): r = env", "conn.execute_command('DEL', 'doc1') conn.execute_command('DEL', 'doc2') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['baz',", "res = env.cmd( 'ft.search', 'idx', '@tags:{tag\\\\ %d}' % n, 'nocontent')", "TAG CASESENSITIVE SEPARATOR .').ok() conn.execute_command('HSET', 'doc1', 't', 'foo,FOO') conn.execute_command('HSET', 'doc2',", "# casesensitive env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([0]) env.expect('FT.SEARCH',", "range(0, len(res), 3)} env.assertEqual(res, expectedRes) def testTagCaseSensitive(env): conn = getConnectionByEnv(env)", "# this test basically make sure we are not leaking", "return r.execute_command('ft.search', *args) def testTagIndex(env): r = env env.expect('ft.create', 'idx',", "o', [4]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['f o', [6]], ['f o,F", "100 alltags = set() for n in range(N): tags =", "'dump_tagidx', 'idx3', 't').equal([['f o', [5, 6]], ['f o,f o', [4]]])", "env.assertEqual(0, res[0]) res = env.cmd('ft.search', 'idx', '@tags:{foo bar}') env.assertEqual(N, res[0])", "conn.execute_command('HSET', 'doc2', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1, 2]]])", "'tag', 'separator') with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema',", "'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx1',", "['t', 'foo']]) # delete two tags conn.execute_command('DEL', 'doc1') conn.execute_command('DEL', 'doc2')", "env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError() env.expect('ft.tagvals', 'idx', 'title').raiseError() def testSearchNotExistsTagValue(env): # this", "conn.execute_command('HSET', 'doc3', 't', 'foo') if not env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD',", "'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH',", "['t', 'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx2',", "'idx1', '@t:{FOO}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO'],", "conn.execute_command('HSET', 'doc3', 't', 'f o') if not env.is_cluster(): forceInvokeGC(env, 'idx1')", "range(cycles): for j in range(tags): x = j + i", "'fake_tags').raiseError() env.expect('ft.tagvals', 'idx', 'title').raiseError() def testSearchNotExistsTagValue(env): # this test basically", "o}') \\ .equal([3, 'doc1', ['t', 'f o,F O'], 'doc2', ['t',", "'doc4', ['t', 'foo'], 'doc5', ['t', 'foo']]) def testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn", "'doc1', 't', 'foo,FOO') conn.execute_command('HSET', 'doc2', 't', 'FOO') conn.execute_command('HSET', 'doc3', 't',", "\"\") def testTagVals(env): r = env r.execute_command( 'ft.create', 'idx', 'ON',", "'tags', 'tag').ok() N = 10 for n in range(N): env.expect('ft.add',", ".equal([2, 'doc4', ['t', 'foo'], 'doc5', ['t', 'foo']]) def testTagGCClearEmptyWithCursor(env): env.skipOnCluster()", "O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t',", "= env r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text',", "res = env.cmd( 'ft.search', 'idx', 'hello world @tags:{tag\\\\ %d|tag %d}'", "'doc3', ['t', 'foo']]) conn.execute_command('HSET', 'doc1', 't', 'f o,F O') conn.execute_command('HSET',", "env.expect('FT.CREATE idx ON HASH SCHEMA t TAG SORTABLE').ok() env.expect('FT.SEARCH idx", "in range(0, len(res), 3)} env.assertEqual(res, expectedRes) def testTagCaseSensitive(env): conn =", "not leaking env.expect('FT.CREATE idx ON HASH SCHEMA t TAG SORTABLE').ok()", "res = env.cmd('ft.search', 'idx', q) env.assertEqual(1, res[0]) def testTagPrefix(env): env.skipOnCluster()", "'idx', 'foo bar') env.assertEqual(0, res[0]) res = env.cmd('ft.search', 'idx', '@tags:{foo", "'@t:{foo}').equal([0]) # delete last tag conn.execute_command('DEL', 'doc3') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG',", "'foo']]) # delete two tags conn.execute_command('DEL', 'doc1') conn.execute_command('DEL', 'doc2') forceInvokeGC(env,", "'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'TAgs', 'tag').ok() env.expect('ft.add', 'idx',", "['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O\\\\,F\\\\ O}') \\", "'\"work\"']]} res = env.cmd('ft.search', 'myIdx', '~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:] res =", "1.0 FIELDS title \"hello,work\"').ok() expectedRes = {'doc1' : ['inf', ['title',", "'idx4') forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['f o', [4, 5,", "'doc1', ['t', 'foo']]) # delete two tags conn.execute_command('DEL', 'doc1') conn.execute_command('DEL',", "'idx') for q in ('@tags:{hello world}', '@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'): res", "'doc2') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['baz', [3]]]) env.expect('FT.SEARCH', 'idx',", "make sure the inverted index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx',", "'~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:] res = {res[i]:res[i + 1: i +", "'doc3', 't', 'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1]], ['bar', [2]],", "6]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['f o', [4, 6]], ['F O',", "o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1',", "n + 1), 'nocontent') env.assertEqual(2, res[0]) res = py2sorted(res[1:]) env.assertEqual('doc%d'", "env.assertEqual(N * 2 + 1, len(res)) env.assertEqual(alltags, set(res)) res =", "'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) res = env.cmd(", "cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # add data conn.execute_command('HSET', 'doc3',", "% n, 1.0, 'fields', 'tags', ','.join(tags), 'othertags', 'baz %d' %", "res = env.cmd( 'ft.search', 'idx', 'term%d @tags:{tag %d}' % (n,", "res[1]) def testSeparator(env): r = env env.expect( 'ft.create', 'idx', 'ON',", "'hello world', 'TAgs', 'HELLO WORLD,FOO BAR').ok() for _ in r.retry_with_rdb_reload():", "n), 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) def testSeparator(env):", "casesensitive env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4',", "r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag',", "['t', 'foo']]) def testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET',", "= conn.pipeline() for i in range(cycles): for j in range(tags):", "1): res = env.cmd( 'ft.search', 'idx', '@tags:{tag %d}' % n,", "ensure later documents with same tag are read res =", "HASH SCHEMA title TAG').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title", "SCHEMA title TAG').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"work\"').ok()", "# casesensitive env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\ O}') \\ .equal([2, 'doc1', ['t',", "'@t:{foo}').equal([1, 'doc1', ['t', 'foo']]) # delete two tags conn.execute_command('DEL', 'doc1')", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['f o', [4, 6]], ['F O', [4,", "WORLD}', 'NOCONTENT')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{foo bar}', 'NOCONTENT'))", "def search(env, r, *args): return r.execute_command('ft.search', *args) def testTagIndex(env): r", "env.expect('ft.tagvals', 'idx', 'idx', 'idx').raiseError() env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError() env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError()", "index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # add data", "env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\", "['t', 'f o,F O'], 'doc2', ['t', 'F O'], 'doc3', ['t',", "= env.cmd('ft.search', 'idx', 'foo bar') env.assertEqual(0, res[0]) res = env.cmd('ft.search',", "world', 'tags', 'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx', 'idx', 'tags') \\ .equal([['hell',", "'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{foo bar}', 'NOCONTENT')) env.assertListEqual([0], r.execute_command( 'FT.SEARCH',", "'DUMP_TAGIDX', 'idx', 't').equal([]) # read from the cursor res, cursor", "n, 1.0, 'fields', 'title', 'hello world term%d' % n, 'tags',", "\"hello\"').error() env.expect('FT.ADD myIdx doc3 1.0 FIELDS title \"hello\"').ok() env.expect('FT.ADD myIdx", "'dump_tagidx', 'idx2', 't').equal([['foo', [1, 3]], ['FOO', [1, 2]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'TAgs', 'tag').ok() env.expect('ft.add',", "r.execute_command('ft.search', *args) def testTagIndex(env): r = env env.expect('ft.create', 'idx', 'ON',", "[1, 2, 3]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['foo', [1, 3]], ['FOO',", "env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError() env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError() env.expect('ft.tagvals', 'idx', 'title').raiseError() def", "'FT.SEARCH', 'idx', '@TAgs:{HELLO WORLD}', 'NOCONTENT')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx',", "'ft.search', 'idx', 'hello world @tags:{tag\\\\ %d|tag %d}' % (n, n", "'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'othertags', 'tag') N =", "check term can be used after being empty conn.execute_command('HSET', 'doc4',", "% n, 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) res", "'tags').raiseError() env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError() env.expect('ft.tagvals', 'idx', 'title').raiseError() def testSearchNotExistsTagValue(env): #", "'idx1', 't').equal([['f o', [4, 5, 6]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['f", "'idx2', '@t:{foo}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc3', ['t', 'foo']])", "# -*- coding: utf-8 -*- from includes import * from", "n, 'bar %d' % n, 'x') alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add',", "1.0, 'fields', 'tags', ','.join(tags), 'othertags', 'baz %d' % int(n //", "'FOO') conn.execute_command('HSET', 'doc3', 't', 'foo') if not env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET',", "'idx4', 't').equal([['f o', [6]], ['f o,F O', [4]], ['F O',", "= env.cmd('ft.search', 'myIdx', '~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:] res = {res[i]:res[i +", "'WITHSCORES')[1:] res = {res[i]:res[i + 1: i + 3] for", "r, *args): return r.execute_command('ft.search', *args) def testTagIndex(env): r = env", "env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env, 'idx') # make sure the inverted index", "myIdx doc2 1.0 FIELDS title \"hello\"').error() env.expect('FT.ADD myIdx doc3 1.0", "t TAG SEPARATOR . CASESENSITIVE').ok() env.expect('FT.CREATE idx5 SCHEMA t TAG", "['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.SEARCH', 'idx1', '@t:{FOO}') \\ .equal([3, 'doc1',", "r.execute_command('ft.tagvals', 'idx', 'othertags') env.assertEqual(N / 2, len(res)) env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals',", "O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\ o}') \\", "'@tags:{fooz bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}', '@tags:{x}'): res = env.cmd('ft.search', 'idx',", "not affect tags res = env.cmd( 'ft.search', 'idx', '@tags:{tag 1}", "@t:{val}').equal([0]) def testIssue1305(env): env.expect('FT.CREATE myIdx ON HASH SCHEMA title TAG').ok()", "'idx', 'ON', 'HASH','schema', 'title', 'text', 'tags', 'tag').ok() N = 10", "'tag') N = 100 alltags = set() for n in", "O', [4, 5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['f o', [5, 6]],", "['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1, 'doc1', ['t', 'foo']]) # delete", "'@tags:{boo\\\\ far}', '@tags:{x}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(1, res[0])", "'@tags:{hello\\\\-*}', '@tags:{he*}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(res[0], 1) def", "FIELDS title \"hello\"').ok() env.expect('FT.ADD myIdx doc1 1.0 FIELDS title \"hello,work\"').ok()", "testTagVals(env): r = env r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema',", "CASESENSITIVE').ok() env.expect('FT.CREATE idx3 SCHEMA t TAG SEPARATOR .').ok() env.expect('FT.CREATE idx4", "'t').equal([['f o', [5, 6]], ['f o,f o', [4]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "'DUMP_TAGIDX', 'idx', 't').equal([]) # add data conn.execute_command('HSET', 'doc3', 't', 'foo')", "env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx',", "['title', '\"work\"']]} res = env.cmd('ft.search', 'myIdx', '~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:] res", "['t', 'foo']]) conn.execute_command('HSET', 'doc1', 't', 'f o,F O') conn.execute_command('HSET', 'doc2',", "testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE',", "O}') \\ .equal([1, 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\", "'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1, 2]]]) res, cursor =", "'foo']]) conn.execute_command('HSET', 'doc1', 't', 'f o,F O') conn.execute_command('HSET', 'doc2', 't',", "'foo') conn.execute_command('HSET', 'doc2', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1,", "SCHEMA t TAG CASESENSITIVE').ok() env.expect('FT.CREATE idx3 SCHEMA t TAG SEPARATOR", "[4]], ['F O', [5]]]) # not casesensitive env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\", "for n in range(N - 1): res = env.cmd( 'ft.search',", "TAG SEPARATOR .').ok() env.expect('FT.CREATE idx4 SCHEMA t TAG SEPARATOR .", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['foo', [1, 2, 3]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2',", "\\ .equal([2, 'doc1', ['t', 'f o,F O'], 'doc2', ['t', 'F", "SEPARATOR .').ok() env.expect('FT.CREATE idx4 SCHEMA t TAG SEPARATOR . CASESENSITIVE').ok()", "'foo bar,xxx,tag %d' % n).ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r,", "'1') env.assertEqual(res, [1, []]) # delete both documents and run", "1 tags = 30 conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD',", "def testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0')", "invalid syntax with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema',", "t TAG CASESENSITIVE SEPARATOR .').ok() conn.execute_command('HSET', 'doc1', 't', 'foo,FOO') conn.execute_command('HSET',", "FIELDS title \"hello\"').error() env.expect('FT.ADD myIdx doc3 1.0 FIELDS title \"hello\"').ok()", "in range(N - 1): res = env.cmd( 'ft.search', 'idx', '@tags:{tag", "'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', \"foo\") with", "['t', 'f o,F O'], 'doc3', ['t', 'f o']]) # not", "def testTagIndex(env): r = env env.expect('ft.create', 'idx', 'ON', 'HASH','schema', 'title',", "'t', 'bar') conn.execute_command('HSET', 'doc3', 't', 'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo',", "[3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1, 'doc1', ['t', 'foo']]) # delete two", "['FOO', [2]]]) env.expect('FT.SEARCH', 'idx1', '@t:{FOO}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'],", "'idx', 'doc%d' % n, 1.0, 'fields', 'tags', ','.join(tags), 'othertags', 'baz", "myIdx doc1 1.0 FIELDS title \"hello,work\"').ok() expectedRes = {'doc1' :", "'tag', 'othertags', 'tag') N = 100 alltags = set() for", "conn.execute_command('HSET', 'doc1', 't', 'foo,FOO') conn.execute_command('HSET', 'doc2', 't', 'FOO') conn.execute_command('HSET', 'doc3',", "env.expect('FT.SEARCH', 'idx1', '@t:{FOO}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t',", "env.cmd('ft.search', 'idx', q) env.assertEqual(res[0], 1) def testTagFieldCase(env): r = env", "O', [5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['f o', [6]], ['f o,F", "'title', 'text', 'tags', 'tag', 'separator', \"foo\") with env.assertResponseError(): r.execute_command( 'ft.create',", "* def search(env, r, *args): return r.execute_command('ft.search', *args) def testTagIndex(env):", "'idx', 'tags') env.assertEqual(N * 2 + 1, len(res)) env.assertEqual(alltags, set(res))", "cursor res, cursor = conn.execute_command('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0])", "o}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1,", "% (n, n), 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1])", "conn.execute_command('HSET', 'doc2', 't', 'FOO') conn.execute_command('HSET', 'doc3', 't', 'foo') if not", "o', [6]], ['f o,F O', [4]], ['F O', [5]]]) env.expect('FT.DEBUG',", "'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx2', '@t:{FOO}') \\ .equal([2, 'doc1',", "'dump_tagidx', 'idx4', 't').equal([['f o', [6]], ['f o,F O', [4]], ['F", "'0', 'inorder') env.assertEqual(1, res[0]) for n in range(N - 1):", "= env.cmd('ft.search', 'idx', q) env.assertEqual(1, res[0]) def testTagPrefix(env): env.skipOnCluster() r", "for i in range(cycles): for j in range(tags): x =", "'idx', 'othertags') env.assertEqual(N / 2, len(res)) env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals', 'idx',", "'TAG') pl = conn.pipeline() for i in range(cycles): for j", "o']]) def testTagGCClearEmpty(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD',", "= 1 tags = 30 conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET',", "\\ .equal([2, 'doc4', ['t', 'foo'], 'doc5', ['t', 'foo']]) def testTagGCClearEmptyWithCursor(env):", "expectedRes) def testTagCaseSensitive(env): conn = getConnectionByEnv(env) env.expect('FT.CREATE idx1 SCHEMA t", "'doc2').equal(1) forceInvokeGC(env, 'idx') # make sure the inverted index was", "def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0')", "- 1): res = env.cmd( 'ft.search', 'idx', '@tags:{tag %d}' %", "'baz %d' % int(n // 2))) for _ in r.retry_with_rdb_reload():", "conn = getConnectionByEnv(env) env.expect('FT.CREATE idx1 SCHEMA t TAG').ok() env.expect('FT.CREATE idx2", "'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx1', '@t:{foo}')", "'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\ o}') \\ .equal([3,", "'SCHEMA', 't', 'TAG') pl = conn.pipeline() for i in range(cycles):", "env.assertEqual(1, res[0]) for n in range(N - 1): res =", "'doc3', ['t', 'f o']]) def testTagGCClearEmpty(env): env.skipOnCluster() conn = getConnectionByEnv(env)", "o,F O'], 'doc3', ['t', 'f o']]) # not casesensitive env.expect('FT.SEARCH',", "'doc1', ['t', 'f o,F O'], 'doc3', ['t', 'f o']]) #", "import * def search(env, r, *args): return r.execute_command('ft.search', *args) def", "tags pl.execute_command('HSET', 'doc{}'.format(x), 't', 'tag{}'.format(x)) pl.execute() for j in range(tags):", "data conn.execute_command('HSET', 'doc3', 't', 'foo') conn.execute_command('HSET', 'doc4', 't', 'foo') env.expect('FT.DEBUG',", "ON HASH SCHEMA t TAG SORTABLE').ok() env.expect('FT.SEARCH idx @t:{val}').equal([0]) def", "'hello world @tags:{tag\\\\ %d|tag %d}' % (n, n + 1),", "% (n, n + 1), 'nocontent') env.assertEqual(2, res[0]) res =", "env.cmd('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) def testTagGCClearEmptyWithCursorAndMoreData(env):", "[]]) # delete both documents and run the GC to", "'@t:{f\\\\ o}') \\ .equal([2, 'doc1', ['t', 'f o,F O'], 'doc3',", "fooz bar:foo,bar:BOO FAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for", "title \"hello\"').error() env.expect('FT.ADD myIdx doc3 1.0 FIELDS title \"hello\"').ok() env.expect('FT.ADD", "# delete both documents and run the GC to clean", "%d' % n).ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res", "t TAG SEPARATOR .').ok() env.expect('FT.CREATE idx4 SCHEMA t TAG SEPARATOR", "'doc1', 1.0, 'fields', 'title', 'hello world', 'tags', 'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG',", ".equal([2, 'doc1', ['t', 'foo,FOO'], 'doc3', ['t', 'foo']]) conn.execute_command('HSET', 'doc1', 't',", "env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O}') \\ .equal([2, 'doc2', ['t', 'F O'],", "waitForIndex(r, 'idx') for q in ('@tags:{hello world}', '@tags:{fooz bar}', '@tags:{foo\\\\,bar}',", "N = 10 for n in range(N): env.expect('ft.add', 'idx', 'doc%d'", "tags conn.execute_command('DEL', 'doc1') conn.execute_command('DEL', 'doc2') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx',", "env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\ O}') \\ .equal([2, 'doc1', ['t', 'f o,F", "'foo') conn.execute_command('HSET', 'doc5', 't', 'foo') env.expect('FT.SEARCH', 'idx', '@t:{foo}') \\ .equal([2,", "env.assertEqual(res, [0]) env.assertEqual(cursor, 0) # ensure later documents with same", "range(N): env.expect('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields', 'title', 'hello", "'tags', 'x:hello world: fooz bar:foo,bar:BOO FAR').ok() for _ in r.retry_with_rdb_reload():", "O\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH',", "conn.execute_command('HSET', 'doc3', 't', 'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1]], ['bar',", "o,F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([0]) env.expect('FT.SEARCH',", "env.assertEqual(10, res[0]) res = env.cmd('ft.search', 'idx', 'foo bar') env.assertEqual(0, res[0])", "'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator')", "'idx3', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([1, 'doc1', ['t', 'f o,F", "bar}', 'NOCONTENT')) def testInvalidSyntax(env): r = env # invalid syntax", "3]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['foo', [1, 3]], ['FOO', [1, 2]]])", "res = r.execute_command('ft.tagvals', 'idx', 'othertags') env.assertEqual(N / 2, len(res)) env.expect('ft.tagvals',", "'idx', 'hello world @tags:{tag\\\\ %d|tag %d}' % (n, n +", "3]], ['foo,foo', [1]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['foo', [3]], ['foo,FOO', [1]],", "env env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags',", "',').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'tags',", "myIdx ON HASH SCHEMA title TAG').ok() env.expect('FT.ADD myIdx doc2 1.0", "'doc3', 't', 'f o') if not env.is_cluster(): forceInvokeGC(env, 'idx1') forceInvokeGC(env,", "n, res[1]) res = env.cmd( 'ft.search', 'idx', '@tags:{tag\\\\ %d}' %", "'t').equal([['foo', [2, 3]], ['foo,foo', [1]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['foo', [3]],", "conn.execute_command('HSET', 'doc3', 't', 'foo') conn.execute_command('HSET', 'doc4', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX',", "SCHEMA t TAG CASESENSITIVE SEPARATOR .').ok() conn.execute_command('HSET', 'doc1', 't', 'foo,FOO')", "env.expect('FT.SEARCH', 'idx2', '@t:{FOO}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t',", "'tag', 'separator', ':').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello", "'@tags:{HELLO WORLD}')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{HELLO WORLD}', 'NOCONTENT'))", "['t', 'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx1',", "env.assertEqual(res, expectedRes) def testTagCaseSensitive(env): conn = getConnectionByEnv(env) env.expect('FT.CREATE idx1 SCHEMA", "'foo,FOO'], 'doc2', ['t', 'FOO']]) env.expect('FT.SEARCH', 'idx2', '@t:{foo}') \\ .equal([2, 'doc1',", "env.cmd( 'ft.search', 'idx', '@tags:{tag 1} @tags:{foo bar}', 'slop', '0', 'inorder')", "[1]], ['hello world', [1]], ['hello-world', [1]], ['jell', [1]]]) for _", "O', [4]], ['F O', [5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['f o',", ".equal([2, 'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']]) #", "'idx', 'tags') \\ .equal([['hell', [1]], ['hello world', [1]], ['hello-world', [1]],", "'idx2') forceInvokeGC(env, 'idx3') forceInvokeGC(env, 'idx4') forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1',", "env.expect('FT.ADD myIdx doc3 1.0 FIELDS title \"hello\"').ok() env.expect('FT.ADD myIdx doc1", "'dump_tagidx', 'idx2', 't').equal([['f o', [4, 6]], ['F O', [4, 5]]])", "idx @t:{val}').equal([0]) def testIssue1305(env): env.expect('FT.CREATE myIdx ON HASH SCHEMA title", "'dump_tagidx', 'idx3', 't').equal([['foo', [2, 3]], ['foo,foo', [1]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4',", "[1, 2]]]) res, cursor = env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}', 'WITHCURSOR', 'COUNT',", "= env # invalid syntax with env.assertResponseError(): r.execute_command( 'ft.create', 'idx',", "int(n // 2))) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res", "0) def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD',", "'@tags:{tag %d}' % n, 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n,", "'COUNT', '1') env.assertEqual(res, [1, []]) # delete both documents and", "o,F O', [4]], ['F O', [5]]]) # not casesensitive env.expect('FT.SEARCH',", "['title', '\"hello,work\"']], 'doc3' : ['inf', ['title', '\"hello\"']], 'doc2' : ['inf',", "coding: utf-8 -*- from includes import * from common import", "('foo %d' % n, 'bar %d' % n, 'x') alltags.add(tags[0])", "% n, 'x') alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d' %", "'idx') res = r.execute_command('ft.tagvals', 'idx', 'tags') env.assertEqual(N * 2 +", "after being empty conn.execute_command('HSET', 'doc4', 't', 'foo') conn.execute_command('HSET', 'doc5', 't',", "conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') pl", "'idx', 'idx', 'idx').raiseError() env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError() env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError() env.expect('ft.tagvals',", "res = conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}') env.assertEqual(res, [1, [], []]) @unstable", "'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1, 2]]]) res, cursor = env.cmd('FT.AGGREGATE', 'idx',", "'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', ',').ok() env.expect('ft.add',", "~@title:{hell}', 'WITHSCORES')[1:] res = {res[i]:res[i + 1: i + 3]", "= 30 conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE',", "'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx2', '@t:{FOO}') \\ .equal([2, 'doc1', ['t',", "env.assertEqual(2, res[0]) res = py2sorted(res[1:]) env.assertEqual('doc%d' % n, res[0]) env.assertEqual('doc%d'", "env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{foo bar}', 'NOCONTENT')) env.assertListEqual([0], r.execute_command(", "conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET',", "3] for i in range(0, len(res), 3)} env.assertEqual(res, expectedRes) def", "'doc3' : ['inf', ['title', '\"hello\"']], 'doc2' : ['inf', ['title', '\"work\"']]}", "'t').equal([['f o', [6]], ['f o,F O', [4]], ['F O', [5]]])", "'idx').raiseError() env.expect('ft.tagvals', 'idx', 'idx', 'idx').raiseError() env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError() env.expect('ft.tagvals', 'idx',", "'doc3', ['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\ O}')", "% n).ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res =", "'tag', 'separator', ',').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello", "'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'tags', 'x:hello world:", "'doc2' : ['inf', ['title', '\"work\"']]} res = env.cmd('ft.search', 'myIdx', '~@title:{wor}", "= env env.expect('ft.create', 'idx', 'ON', 'HASH','schema', 'title', 'text', 'tags', 'tag').ok()", "30 conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx',", "1.0, 'fields', 'title', 'hello world', 'tags', 'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx',", "r.execute_command( 'FT.SEARCH', 'idx', '@TAGS:{foo bar}', 'NOCONTENT')) def testInvalidSyntax(env): r =", "'WITHCURSOR', 'COUNT', '1') env.assertEqual(res, [1, []]) # delete both documents", "6]], ['f o,f o', [4]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['f o',", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.SEARCH',", "2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['foo', [2, 3]], ['foo,foo', [1]]]) env.expect('FT.DEBUG',", "'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', \"\") def testTagVals(env):", "in range(N): tags = ('foo %d' % n, 'bar %d'", "% n, res[1]) def testSeparator(env): r = env env.expect( 'ft.create',", "'t', 'foo') env.expect('FT.SEARCH', 'idx', '@t:{foo}') \\ .equal([2, 'doc4', ['t', 'foo'],", "'@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([1, 'doc1', ['t', 'f o,F O']])", "['inf', ['title', '\"hello\"']], 'doc2' : ['inf', ['title', '\"work\"']]} res =", "['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O\\\\,F\\\\ O}') \\", "O', [5]]]) # not casesensitive env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\ O}') \\", "testSeparator(env): r = env env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema',", "\\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1',", "'idx1') forceInvokeGC(env, 'idx2') forceInvokeGC(env, 'idx3') forceInvokeGC(env, 'idx4') forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG',", "'HELLO WORLD,FOO BAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') env.assertListEqual([0],", "title \"hello\"').ok() env.expect('FT.ADD myIdx doc1 1.0 FIELDS title \"hello,work\"').ok() expectedRes", "O']]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4',", "'0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo')", "testTagFieldCase(env): r = env env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema',", "env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@tags:{HELLO WORLD}')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH',", "'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'othertags',", "'title', 'text', 'tags', 'tag', 'othertags', 'tag') N = 100 alltags", "env.cmd( 'ft.search', 'idx', 'term%d @tags:{tag %d}' % (n, n), 'nocontent')", "j + i * tags pl.execute_command('HSET', 'doc{}'.format(x), 't', 'tag{}'.format(x)) pl.execute()", "'idx2', '@t:{FOO}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO']])", "env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\", "'DUMP_TAGIDX', 'idx', 't').equal([]) # check term can be used after", "['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\ O}') \\", "not casesensitive env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([1, 'doc1',", "O') conn.execute_command('HSET', 'doc2', 't', 'F O') conn.execute_command('HSET', 'doc3', 't', 'f", "doc3 1.0 FIELDS title \"hello\"').ok() env.expect('FT.ADD myIdx doc1 1.0 FIELDS", "'@t:{foo}') \\ .equal([2, 'doc4', ['t', 'foo'], 'doc5', ['t', 'foo']]) def", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx', 'tags') \\ .equal([['hell', [1]], ['hello world', [1]],", "2))) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = r.execute_command('ft.tagvals',", "we are not leaking env.expect('FT.CREATE idx ON HASH SCHEMA t", "'@tags:{x}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(1, res[0]) def testTagPrefix(env):", "['inf', ['title', '\"work\"']]} res = env.cmd('ft.search', 'myIdx', '~@title:{wor} ~@title:{hell}', 'WITHSCORES')[1:]", "o']]) env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\ o}') \\ .equal([3, 'doc1', ['t', 'f", "O}') \\ .equal([2, 'doc2', ['t', 'F O'], 'doc3', ['t', 'f", "idx3 SCHEMA t TAG SEPARATOR .').ok() env.expect('FT.CREATE idx4 SCHEMA t", "['F O', [5]]]) # not casesensitive env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\ O}')", "env.cmd('ft.search', 'idx', 'foo bar') env.assertEqual(0, res[0]) res = env.cmd('ft.search', 'idx',", "'TAgs', 'tag').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world',", "'x:hello world: fooz bar:foo,bar:BOO FAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r,", "'idx', 't').equal([['foo', [1, 2]]]) res, cursor = env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}',", "['F O', [4, 5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['f o', [5,", "[0]) env.assertEqual(cursor, 0) # ensure later documents with same tag", "1) def testTagFieldCase(env): r = env env.expect( 'ft.create', 'idx', 'ON',", "'idx4', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,F\\\\", "o') if not env.is_cluster(): forceInvokeGC(env, 'idx1') forceInvokeGC(env, 'idx2') forceInvokeGC(env, 'idx3')", "'idx1', '@t:{f\\\\ o}') \\ .equal([3, 'doc1', ['t', 'f o,F O'],", "env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'TAgs', 'tag').ok()", "t TAG CASESENSITIVE').ok() env.expect('FT.CREATE idx3 SCHEMA t TAG SEPARATOR .').ok()", ".equal([2, 'doc1', ['t', 'f o,F O'], 'doc3', ['t', 'f o']])", "'doc5', 't', 'foo') env.expect('FT.SEARCH', 'idx', '@t:{foo}') \\ .equal([2, 'doc4', ['t',", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['foo', [2, 3]], ['foo,foo', [1]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "if not env.is_cluster(): forceInvokeGC(env, 'idx1') forceInvokeGC(env, 'idx2') forceInvokeGC(env, 'idx3') forceInvokeGC(env,", "in ('@tags:{hello world}', '@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'): res = env.cmd('ft.search', 'idx',", "bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}', '@tags:{x}'): res = env.cmd('ft.search', 'idx', q)", "env.expect('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields', 'title', 'hello world", "def testSearchNotExistsTagValue(env): # this test basically make sure we are", "conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'bar') conn.execute_command('HSET', 'doc3',", "'idx4', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5',", "{res[i]:res[i + 1: i + 3] for i in range(0,", "[4, 6]], ['F O', [4, 5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['f", "env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields', 'tags', ','.join(tags), 'othertags',", "'@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(res[0], 1)", "i * tags)) pl.execute() forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([])", "'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'othertags', 'tag') N", "def testIssue1305(env): env.expect('FT.CREATE myIdx ON HASH SCHEMA title TAG').ok() env.expect('FT.ADD", "%d}' % n, 'nocontent') env.assertEqual(1, res[0]) res = env.cmd( 'ft.search',", "env.cmd( 'ft.search', 'idx', '@tags:{tag %d}' % n, 'nocontent') env.assertEqual(1, res[0])", "x = j + i * tags pl.execute_command('HSET', 'doc{}'.format(x), 't',", "[1, 3]], ['FOO', [1, 2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['foo', [2,", "%d' % n, 'bar %d' % n, 'x') alltags.add(tags[0]) alltags.add(tags[1])", "1.0 FIELDS title \"work\"').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title", "'title', 'hello world term%d' % n, 'tags', 'foo bar,xxx,tag %d'", "env.cmd('ft.search', 'idx', 'hello world') env.assertEqual(10, res[0]) res = env.cmd('ft.search', 'idx',", "res = {res[i]:res[i + 1: i + 3] for i", "q) env.assertEqual(1, res[0]) def testTagPrefix(env): env.skipOnCluster() r = env env.expect(", "'t').equal([['f o', [4, 5, 6]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['f o',", "'FT.SEARCH', 'idx', '@TAgs:{foo bar}', 'NOCONTENT')) env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@TAGS:{foo", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['f o', [6]], ['f o,F O', [4]],", "env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1, 2]]]) res, cursor = env.cmd('FT.AGGREGATE',", "['t', 'f o,F O'], 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx2',", "= env.cmd('ft.search', 'idx', 'hello world') env.assertEqual(10, res[0]) res = env.cmd('ft.search',", "SORTABLE').ok() env.expect('FT.SEARCH idx @t:{val}').equal([0]) def testIssue1305(env): env.expect('FT.CREATE myIdx ON HASH", "in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res = env.cmd('ft.search', 'idx', 'hello world')", "'idx', '@tags:{foo bar}') env.assertEqual(N, res[0]) # inorder should not affect", "bar:foo,bar:BOO FAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q", "[1]], ['jell', [1]]]) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for", "env.assertEqual(res, [1, [], []]) @unstable def testEmptyTagLeak(env): env.skipOnCluster() cycles =", "'idx3', 't').equal([['foo', [2, 3]], ['foo,foo', [1]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['foo',", "env.assertEqual('doc%d' % n, res[1]) def testSeparator(env): r = env env.expect(", "env.is_cluster(): forceInvokeGC(env, 'idx1') forceInvokeGC(env, 'idx2') forceInvokeGC(env, 'idx3') forceInvokeGC(env, 'idx4') forceInvokeGC(env,", "['t', 'f o']]) # not casesensitive env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,f\\\\", ".equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t',", "'text', 'tags', 'tag', 'othertags', 'tag') N = 100 alltags =", "not casesensitive env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\ O}') \\ .equal([3, 'doc1', ['t',", "[5]]]) # not casesensitive env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\ O}') \\ .equal([3,", "'nocontent') env.assertEqual(2, res[0]) res = py2sorted(res[1:]) env.assertEqual('doc%d' % n, res[0])", "doc2 1.0 FIELDS title \"work\"').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS", "'idx5', 't').equal([['f o', [6]], ['f o,F O', [4]], ['F O',", "O}') \\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3',", "'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['foo', [1, 2, 3]]]) env.expect('FT.DEBUG',", "'t').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['foo',", "'idx3', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f o,F", "['t', 'foo'], 'doc5', ['t', 'foo']]) def testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn =", "'othertags') env.assertEqual(N / 2, len(res)) env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals', 'idx', 'idx',", "range(tags): x = j + i * tags pl.execute_command('HSET', 'doc{}'.format(x),", "idx2 SCHEMA t TAG CASESENSITIVE').ok() env.expect('FT.CREATE idx3 SCHEMA t TAG", "'@t:{foo}') env.assertEqual(res, [1, [], []]) @unstable def testEmptyTagLeak(env): env.skipOnCluster() cycles", "@unstable def testEmptyTagLeak(env): env.skipOnCluster() cycles = 1 tags = 30", "\\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\", "= env.cmd('ft.search', 'idx', '@tags:{foo bar}') env.assertEqual(N, res[0]) # inorder should", "forceInvokeGC(env, 'idx3') forceInvokeGC(env, 'idx4') forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['f", "testInvalidSyntax(env): r = env # invalid syntax with env.assertResponseError(): r.execute_command(", "test basically make sure we are not leaking env.expect('FT.CREATE idx", "env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"hello\"').error() env.expect('FT.ADD myIdx doc3", "conn.execute_command('DEL', 'doc3') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # check", "res, cursor = env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}', 'WITHCURSOR', 'COUNT', '1') env.assertEqual(res,", "in range(tags): pl.execute_command('DEL', 'doc{}'.format(j + i * tags)) pl.execute() forceInvokeGC(env,", "env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['foo', [1,", "'ON', 'HASH', 'schema', 'title', 'text', 'TAgs', 'tag').ok() env.expect('ft.add', 'idx', 'doc1',", "idx1 SCHEMA t TAG').ok() env.expect('FT.CREATE idx2 SCHEMA t TAG CASESENSITIVE').ok()", "o']]) # casesensitive env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([0])", "'foo,FOO') conn.execute_command('HSET', 'doc2', 't', 'FOO') conn.execute_command('HSET', 'doc3', 't', 'foo') if", "'@t:{FOO}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO']]) env.expect('FT.SEARCH',", "'t').equal([['foo', [1]], ['bar', [2]], ['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1, 'doc1',", "'text', 'tags', 'tag', 'separator', ',').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields',", "[1]], ['FOO', [2]]]) env.expect('FT.SEARCH', 'idx1', '@t:{FOO}') \\ .equal([3, 'doc1', ['t',", "O') conn.execute_command('HSET', 'doc3', 't', 'f o') if not env.is_cluster(): forceInvokeGC(env,", "'doc3', 't', 'foo') if not env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0')", "doc1 1.0 FIELDS title \"hello,work\"').ok() expectedRes = {'doc1' : ['inf',", "'tags', 'foo bar,xxx,tag %d' % n).ok() for _ in r.retry_with_rdb_reload():", "[4, 5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['f o', [5, 6]], ['f", ".').ok() conn.execute_command('HSET', 'doc1', 't', 'foo,FOO') conn.execute_command('HSET', 'doc2', 't', 'FOO') conn.execute_command('HSET',", "'@t:{FOO}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3',", "testEmptyTagLeak(env): env.skipOnCluster() cycles = 1 tags = 30 conn =", "for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx',", "'FT.SEARCH', 'idx', '@tags:{HELLO WORLD}')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{HELLO", "'tag').ok() N = 10 for n in range(N): env.expect('ft.add', 'idx',", "'idx', 't').equal([['foo', [1]], ['bar', [2]], ['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1,", "'t', 'foo') conn.execute_command('HSET', 'doc5', 't', 'foo') env.expect('FT.SEARCH', 'idx', '@t:{foo}') \\", "'foo,FOO'], 'doc3', ['t', 'foo']]) conn.execute_command('HSET', 'doc1', 't', 'f o,F O')", "* 2 + 1, len(res)) env.assertEqual(alltags, set(res)) res = r.execute_command('ft.tagvals',", "'foo') conn.execute_command('HSET', 'doc4', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [3,", "'foo') conn.execute_command('HSET', 'doc2', 't', 'bar') conn.execute_command('HSET', 'doc3', 't', 'baz') env.expect('FT.DEBUG',", "'f o,F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([0])", "O', [4]], ['F O', [5]]]) # not casesensitive env.expect('FT.SEARCH', 'idx1',", "'text', 'tags', 'tag', 'separator', ':').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields',", "r = env # invalid syntax with env.assertResponseError(): r.execute_command( 'ft.create',", "env.assertEqual(cursor, 0) # ensure later documents with same tag are", "'tags', 'tag', 'separator', ':').ok() env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title',", "'F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o}') \\ .equal([1, 'doc3', ['t',", "'idx', 'hello world') env.assertEqual(10, res[0]) res = env.cmd('ft.search', 'idx', 'foo", "read res = conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}') env.assertEqual(res, [1, [], []])", "delete both documents and run the GC to clean 'foo'", "+ i * tags)) pl.execute() forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx',", "\"hello\"').ok() env.expect('FT.ADD myIdx doc1 1.0 FIELDS title \"hello,work\"').ok() expectedRes =", "'foo') env.expect('FT.SEARCH', 'idx', '@t:{foo}') \\ .equal([2, 'doc4', ['t', 'foo'], 'doc5',", "testTagCaseSensitive(env): conn = getConnectionByEnv(env) env.expect('FT.CREATE idx1 SCHEMA t TAG').ok() env.expect('FT.CREATE", "'@t:{F\\\\ O}') \\ .equal([3, 'doc1', ['t', 'f o,F O'], 'doc2',", "'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']]) # casesensitive", "O}') \\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx4',", "res = env.cmd( 'ft.search', 'idx', '@tags:{tag %d}' % n, 'nocontent')", "FAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in", "env.assertEqual(1, res[0]) def testTagPrefix(env): env.skipOnCluster() r = env env.expect( 'ft.create',", "'fields', 'title', 'hello world', 'tags', 'x:hello world: fooz bar:foo,bar:BOO FAR').ok()", "+ 1), res[1]) res = env.cmd( 'ft.search', 'idx', 'term%d @tags:{tag", "'tags', 'tag', 'separator', \"foo\") with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON',", "# check term can be used after being empty conn.execute_command('HSET',", "'0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') pl = conn.pipeline() for", "env.cmd( 'ft.search', 'idx', '@tags:{tag\\\\ %d}' % n, 'nocontent') env.assertEqual(1, res[0])", "res[0]) # inorder should not affect tags res = env.cmd(", "o}') \\ .equal([1, 'doc3', ['t', 'f o']]) def testTagGCClearEmpty(env): env.skipOnCluster()", "n, 'nocontent') env.assertEqual(1, res[0]) res = env.cmd( 'ft.search', 'idx', 'hello", "'idx2', 't').equal([['foo', [1, 3]], ['FOO', [1, 2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3',", "'ft.search', 'idx', '@tags:{tag\\\\ %d}' % n, 'nocontent') env.assertEqual(1, res[0]) res", "# not casesensitive env.expect('FT.SEARCH', 'idx1', '@t:{F\\\\ O}') \\ .equal([3, 'doc1',", "world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx', 'idx', 'tags') \\ .equal([['hell', [1]], ['hello world',", "env.expect('FT.CREATE idx1 SCHEMA t TAG').ok() env.expect('FT.CREATE idx2 SCHEMA t TAG", "O}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O}') \\ .equal([1, 'doc2',", "%d}' % (n, n), 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n,", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['f o', [6]], ['f o,F O', [4]],", "was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # add data conn.execute_command('HSET',", "delete two tags conn.execute_command('DEL', 'doc1') conn.execute_command('DEL', 'doc2') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG',", "= 10 for n in range(N): env.expect('ft.add', 'idx', 'doc%d' %", "'doc1', 1.0, 'fields', 'title', 'hello world', 'tags', 'x:hello world: fooz", "n, res[0]) env.assertEqual('doc%d' % (n + 1), res[1]) res =", "'doc5', ['t', 'foo']]) def testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG',", ".equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O\\\\,F\\\\", "'t').equal([['foo', [1, 2, 3]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['foo', [1, 3]],", "'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator') with", "'idx', 'fake_tags').raiseError() env.expect('ft.tagvals', 'idx', 'title').raiseError() def testSearchNotExistsTagValue(env): # this test", "'@t:{F\\\\ O}') \\ .equal([2, 'doc2', ['t', 'F O'], 'doc3', ['t',", "env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # read from the cursor res,", "'dump_tagidx', 'idx4', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "o,f o', [4]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['f o', [6]], ['f", "(n, n + 1), 'nocontent') env.assertEqual(2, res[0]) res = py2sorted(res[1:])", "'tag', 'separator', \"foo\") with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH',", "'idx') # make sure the inverted index was cleaned env.expect('FT.DEBUG',", "'NOCONTENT')) env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@TAGS:{foo bar}', 'NOCONTENT')) def testInvalidSyntax(env):", "run the GC to clean 'foo' inverted index env.expect('DEL', 'doc1').equal(1)", "env.assertEqual(res, [1, []]) # delete both documents and run the", "% int(n // 2))) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx')", "index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # read from", "world', [1]], ['hello-world', [1]], ['jell', [1]]]) for _ in r.retry_with_rdb_reload():", "% n, res[1]) res = env.cmd( 'ft.search', 'idx', '@tags:{tag\\\\ %d}'", "cursor = env.cmd('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0)", "['t', 'foo']]) env.expect('FT.SEARCH', 'idx2', '@t:{FOO}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'],", "'schema', 'title', 'text', 'tags', 'tag', 'separator', \"\") def testTagVals(env): r", "waitForIndex(r, 'idx') for q in ('@tags:{hello world}', '@tags:{hel*}', '@tags:{hello\\\\-*}', '@tags:{he*}'):", "['f o,F O', [4]], ['F O', [5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5',", "for i in range(0, len(res), 3)} env.assertEqual(res, expectedRes) def testTagCaseSensitive(env):", "inverted index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # read", "%d}' % n, 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1])", "bar') env.assertEqual(0, res[0]) res = env.cmd('ft.search', 'idx', '@tags:{foo bar}') env.assertEqual(N,", "'foo' inverted index env.expect('DEL', 'doc1').equal(1) env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env, 'idx') #", "'idx', q) env.assertEqual(1, res[0]) def testTagPrefix(env): env.skipOnCluster() r = env", "getConnectionByEnv(env) env.expect('FT.CREATE idx1 SCHEMA t TAG').ok() env.expect('FT.CREATE idx2 SCHEMA t", "env.cmd('ft.search', 'idx', '@tags:{foo bar}') env.assertEqual(N, res[0]) # inorder should not", "= env.cmd('ft.search', 'idx', q) env.assertEqual(res[0], 1) def testTagFieldCase(env): r =", "env.cmd( 'ft.search', 'idx', 'hello world @tags:{tag\\\\ %d|tag %d}' % (n,", "'idx', 't').equal([]) # read from the cursor res, cursor =", "'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx1', '@t:{foo}') \\ .equal([3, 'doc1',", "len(res), 3)} env.assertEqual(res, expectedRes) def testTagCaseSensitive(env): conn = getConnectionByEnv(env) env.expect('FT.CREATE", "O'], 'doc3', ['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\", "[4, 5, 6]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['f o', [4, 6]],", "% n, 'bar %d' % n, 'x') alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2])", "env.expect('FT.CREATE idx4 SCHEMA t TAG SEPARATOR . CASESENSITIVE').ok() env.expect('FT.CREATE idx5", "'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'foo') env.expect('FT.DEBUG',", "1, len(res)) env.assertEqual(alltags, set(res)) res = r.execute_command('ft.tagvals', 'idx', 'othertags') env.assertEqual(N", "the inverted index was cleaned env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) #", "q) env.assertEqual(res[0], 1) def testTagFieldCase(env): r = env env.expect( 'ft.create',", "'foo']]) env.expect('FT.SEARCH', 'idx2', '@t:{FOO}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc2',", "'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx', 'idx', 'tags') \\ .equal([['hell', [1]], ['hello", "'doc3') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([]) # check term", "waitForIndex(r, 'idx') env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@tags:{HELLO WORLD}')) env.assertListEqual([1, 'doc1'],", "'othertags', 'tag') N = 100 alltags = set() for n", "range(N - 1): res = env.cmd( 'ft.search', 'idx', '@tags:{tag %d}'", "alltags = set() for n in range(N): tags = ('foo", "'idx2', 't').equal([['f o', [4, 6]], ['F O', [4, 5]]]) env.expect('FT.DEBUG',", "'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([0]) #", "'idx') env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@tags:{HELLO WORLD}')) env.assertListEqual([1, 'doc1'], r.execute_command(", "in range(N): env.expect('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields', 'title',", "'title', 'text', 'tags', 'tag', 'separator') with env.assertResponseError(): r.execute_command( 'ft.create', 'idx',", "env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['foo', [1, 3]], ['FOO', [1, 2]]]) env.expect('FT.DEBUG',", "world', 'tags', 'x:hello world: fooz bar:foo,bar:BOO FAR').ok() for _ in", "@tags:{foo bar}', 'slop', '0', 'inorder') env.assertEqual(1, res[0]) for n in", "'dump_tagidx', 'idx5', 't').equal([['f o', [6]], ['f o,F O', [4]], ['F", "['t', 'f o']]) env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\ o}') \\ .equal([3, 'doc1',", "res, cursor = conn.execute_command('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor,", "'schema', 'title', 'text', 'tags', 'tag', 'separator', \"foo\") with env.assertResponseError(): r.execute_command(", "'f o,F O'], 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\", "cursor = env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}', 'WITHCURSOR', 'COUNT', '1') env.assertEqual(res, [1,", "10 for n in range(N): env.expect('ft.add', 'idx', 'doc%d' % n,", "from the cursor res, cursor = env.cmd('FT.CURSOR', 'READ', 'idx', cursor)", ".').ok() env.expect('FT.CREATE idx4 SCHEMA t TAG SEPARATOR . CASESENSITIVE').ok() env.expect('FT.CREATE", "'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO']]) env.expect('FT.SEARCH', 'idx2', '@t:{foo}') \\", "'fields', 'tags', ','.join(tags), 'othertags', 'baz %d' % int(n // 2)))", "'idx', '@TAGS:{foo bar}', 'NOCONTENT')) def testInvalidSyntax(env): r = env #", "CASESENSITIVE SEPARATOR .').ok() conn.execute_command('HSET', 'doc1', 't', 'foo,FOO') conn.execute_command('HSET', 'doc2', 't',", "= env.cmd( 'ft.search', 'idx', '@tags:{tag\\\\ %d}' % n, 'nocontent') env.assertEqual(1,", "'doc1', 't', 'f o,F O') conn.execute_command('HSET', 'doc2', 't', 'F O')", "'fields', 'title', 'hello world term%d' % n, 'tags', 'foo bar,xxx,tag", "forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['f o', [4, 5, 6]]])", "common import * def search(env, r, *args): return r.execute_command('ft.search', *args)", "idx5 SCHEMA t TAG CASESENSITIVE SEPARATOR .').ok() conn.execute_command('HSET', 'doc1', 't',", "documents and run the GC to clean 'foo' inverted index", "'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx1', '@t:{foo}') \\", "['foo,foo', [1]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO',", "'idx', '@t:{foo}').equal([0]) # delete last tag conn.execute_command('DEL', 'doc3') forceInvokeGC(env, 'idx')", "['t', 'foo,FOO'], 'doc2', ['t', 'FOO']]) env.expect('FT.SEARCH', 'idx2', '@t:{foo}') \\ .equal([2,", ": ['inf', ['title', '\"hello,work\"']], 'doc3' : ['inf', ['title', '\"hello\"']], 'doc2'", "1), res[1]) res = env.cmd( 'ft.search', 'idx', 'term%d @tags:{tag %d}'", "['t', 'f o']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o}') \\ .equal([2, 'doc2',", "def testTagPrefix(env): env.skipOnCluster() r = env env.expect( 'ft.create', 'idx', 'ON',", "n in range(N): tags = ('foo %d' % n, 'bar", "'fields', 'title', 'hello world', 'TAgs', 'HELLO WORLD,FOO BAR').ok() for _", "def testInvalidSyntax(env): r = env # invalid syntax with env.assertResponseError():", "['FOO', [1, 2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['foo', [2, 3]], ['foo,foo',", "O']]) env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\ o}') \\ .equal([2, 'doc1', ['t', 'f", "+ i * tags pl.execute_command('HSET', 'doc{}'.format(x), 't', 'tag{}'.format(x)) pl.execute() for", "r.retry_with_rdb_reload(): waitForIndex(r, 'idx') env.assertListEqual([0], r.execute_command( 'FT.SEARCH', 'idx', '@tags:{HELLO WORLD}')) env.assertListEqual([1,", "for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in ('@tags:{hello", "utf-8 -*- from includes import * from common import *", "o\\\\,f\\\\ o}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,F\\\\ O}') \\", "if not env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1',", "'doc2', 't', 'F O') conn.execute_command('HSET', 'doc3', 't', 'f o') if", "['t', 'f o']]) def testTagGCClearEmpty(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG',", "i * tags pl.execute_command('HSET', 'doc{}'.format(x), 't', 'tag{}'.format(x)) pl.execute() for j", "// 2))) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') res =", "\\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc3', ['t', 'foo']]) conn.execute_command('HSET', 'doc1',", "inorder should not affect tags res = env.cmd( 'ft.search', 'idx',", "'idx1', '@t:{F\\\\ O}') \\ .equal([3, 'doc1', ['t', 'f o,F O'],", "alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields', 'tags',", "env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f", "'@tags:{tag 1} @tags:{foo bar}', 'slop', '0', 'inorder') env.assertEqual(1, res[0]) for", "'HASH','schema', 'title', 'text', 'tags', 'tag').ok() N = 10 for n", "'@t:{F\\\\ O}') \\ .equal([1, 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx4',", "'tags', 'tag', 'othertags', 'tag') N = 100 alltags = set()", "'t', 'TAG') pl = conn.pipeline() for i in range(cycles): for", "conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA',", "'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [3, 4]]]) # read from", "bar}', 'slop', '0', 'inorder') env.assertEqual(1, res[0]) for n in range(N", "'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx1', '@t:{foo}') \\ .equal([3, 'doc1', ['t',", "['f o,f o', [4]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['f o', [6]],", "r.execute_command('ft.tagvals', 'idx', 'tags') env.assertEqual(N * 2 + 1, len(res)) env.assertEqual(alltags,", "'idx', 't').equal([]) # add data conn.execute_command('HSET', 'doc3', 't', 'foo') conn.execute_command('HSET',", "conn.execute_command('HSET', 'doc2', 't', 'bar') conn.execute_command('HSET', 'doc3', 't', 'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX',", "bar,xxx,tag %d' % n).ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx')", "[2]]]) env.expect('FT.SEARCH', 'idx1', '@t:{FOO}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2',", "not env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['foo',", "conn.pipeline() for i in range(cycles): for j in range(tags): x", "env.assertEqual('doc%d' % n, res[0]) env.assertEqual('doc%d' % (n + 1), res[1])", "+ 1: i + 3] for i in range(0, len(res),", "+ 1), 'nocontent') env.assertEqual(2, res[0]) res = py2sorted(res[1:]) env.assertEqual('doc%d' %", "['F O', [5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['f o', [6]], ['f", "'doc4', 't', 'foo') conn.execute_command('HSET', 'doc5', 't', 'foo') env.expect('FT.SEARCH', 'idx', '@t:{foo}')", "t TAG').ok() env.expect('FT.CREATE idx2 SCHEMA t TAG CASESENSITIVE').ok() env.expect('FT.CREATE idx3", "'doc%d' % n, 1.0, 'fields', 'title', 'hello world term%d' %", "expectedRes = {'doc1' : ['inf', ['title', '\"hello,work\"']], 'doc3' : ['inf',", "'idx1', '@t:{foo}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO'],", "q in ('@tags:{hello world}', '@tags:{fooz bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}', '@tags:{x}'):", "'doc1', ['t', 'foo,FOO'], 'doc3', ['t', 'foo']]) conn.execute_command('HSET', 'doc1', 't', 'f", "'\"hello,work\"']], 'doc3' : ['inf', ['title', '\"hello\"']], 'doc2' : ['inf', ['title',", "conn.execute_command('HSET', 'doc4', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [3, 4]]])", "* tags pl.execute_command('HSET', 'doc{}'.format(x), 't', 'tag{}'.format(x)) pl.execute() for j in", "title \"work\"').ok() env.expect('FT.ADD myIdx doc2 1.0 FIELDS title \"hello\"').error() env.expect('FT.ADD", "'title', 'hello world', 'TAgs', 'HELLO WORLD,FOO BAR').ok() for _ in", "alltags.add(tags[0]) alltags.add(tags[1]) alltags.add(tags[2]) env.assertOk(r.execute_command('ft.add', 'idx', 'doc%d' % n, 1.0, 'fields',", "'title', 'text', 'tags', 'tag', 'separator', \"\") def testTagVals(env): r =", "o,F O') conn.execute_command('HSET', 'doc2', 't', 'F O') conn.execute_command('HSET', 'doc3', 't',", "in r.retry_with_rdb_reload(): waitForIndex(r, 'idx') for q in ('@tags:{hello world}', '@tags:{fooz", "later documents with same tag are read res = conn.execute_command('FT.AGGREGATE',", "res = env.cmd('ft.search', 'idx', 'foo bar') env.assertEqual(0, res[0]) res =", "env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals', 'idx', 'idx', 'idx').raiseError() env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError() env.expect('ft.tagvals',", "'dump_tagidx', 'idx1', 't').equal([['foo', [1, 2, 3]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx2', 't').equal([['foo',", "'doc2', 't', 'FOO') conn.execute_command('HSET', 'doc3', 't', 'foo') if not env.is_cluster():", "[4]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx4', 't').equal([['f o', [6]], ['f o,F O',", "env.assertEqual('doc%d' % n, res[1]) res = env.cmd( 'ft.search', 'idx', '@tags:{tag\\\\", ".equal([1, 'doc3', ['t', 'f o']]) def testTagGCClearEmpty(env): env.skipOnCluster() conn =", "env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1, 'doc1', ['t', 'foo']]) # delete two tags", "['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O}') \\ .equal([2,", "env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag',", "*args) def testTagIndex(env): r = env env.expect('ft.create', 'idx', 'ON', 'HASH','schema',", "'tags') env.assertEqual(N * 2 + 1, len(res)) env.assertEqual(alltags, set(res)) res", "'@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f o,F O']])", "env.expect('FT.CREATE idx2 SCHEMA t TAG CASESENSITIVE').ok() env.expect('FT.CREATE idx3 SCHEMA t", "<filename>tests/pytests/test_tags.py # -*- coding: utf-8 -*- from includes import *", "t TAG SORTABLE').ok() env.expect('FT.SEARCH idx @t:{val}').equal([0]) def testIssue1305(env): env.expect('FT.CREATE myIdx", "'hello world', 'tags', 'hello world,hello-world,hell,jell').ok() env.expect('FT.DEBUG', 'dump_tagidx', 'idx', 'tags') \\", "'idx', 'SCHEMA', 't', 'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2',", "'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', ',').ok() env.expect('ft.add', 'idx',", "'t', 'f o') if not env.is_cluster(): forceInvokeGC(env, 'idx1') forceInvokeGC(env, 'idx2')", "\\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3', ['t',", "env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([1, 'doc1', ['t', 'f", "['foo,FOO', [1]], ['FOO', [2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['foo', [3]], ['foo,FOO',", "'@TAgs:{HELLO WORLD}', 'NOCONTENT')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{foo bar}',", "CASESENSITIVE').ok() env.expect('FT.CREATE idx5 SCHEMA t TAG CASESENSITIVE SEPARATOR .').ok() conn.execute_command('HSET',", "conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG', 'dump_tagidx', 'idx1', 't').equal([['foo', [1, 2,", "import * from common import * def search(env, r, *args):", "'@t:{f\\\\ o}') \\ .equal([2, 'doc2', ['t', 'F O'], 'doc3', ['t',", "'t', 'FOO') conn.execute_command('HSET', 'doc3', 't', 'foo') if not env.is_cluster(): conn.execute_command('FT.CONFIG',", "'foo'], 'doc5', ['t', 'foo']]) def testTagGCClearEmptyWithCursor(env): env.skipOnCluster() conn = getConnectionByEnv(env)", "env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f", "'@t:{f\\\\ o}') \\ .equal([3, 'doc1', ['t', 'f o,F O'], 'doc2',", "env.expect('FT.SEARCH idx @t:{val}').equal([0]) def testIssue1305(env): env.expect('FT.CREATE myIdx ON HASH SCHEMA", "= getConnectionByEnv(env) conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't',", "# delete last tag conn.execute_command('DEL', 'doc3') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX',", "+ 1, len(res)) env.assertEqual(alltags, set(res)) res = r.execute_command('ft.tagvals', 'idx', 'othertags')", "'@t:{f\\\\ o}') \\ .equal([1, 'doc3', ['t', 'f o']]) def testTagGCClearEmpty(env):", "'title', 'hello world', 'tags', 'x:hello world: fooz bar:foo,bar:BOO FAR').ok() for", "'ft.search', 'idx', '@tags:{tag 1} @tags:{foo bar}', 'slop', '0', 'inorder') env.assertEqual(1,", "1.0 FIELDS title \"hello\"').error() env.expect('FT.ADD myIdx doc3 1.0 FIELDS title", "'\"hello\"']], 'doc2' : ['inf', ['title', '\"work\"']]} res = env.cmd('ft.search', 'myIdx',", "'term%d @tags:{tag %d}' % (n, n), 'nocontent') env.assertEqual(1, res[0]) env.assertEqual('doc%d'", "O'], 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\ o}') \\", "'FOO']]) env.expect('FT.SEARCH', 'idx2', '@t:{foo}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc3',", "clean 'foo' inverted index env.expect('DEL', 'doc1').equal(1) env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env, 'idx')", "\\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\", "o}') \\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3',", "j in range(tags): pl.execute_command('DEL', 'doc{}'.format(j + i * tags)) pl.execute()", "'@TAGS:{foo bar}', 'NOCONTENT')) def testInvalidSyntax(env): r = env # invalid", "r = env r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title',", "'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']]) env.expect('FT.SEARCH', 'idx2', '@t:{FOO}')", "'t').equal([['f o', [4, 6]], ['F O', [4, 5]]]) env.expect('FT.DEBUG', 'dump_tagidx',", "idx4 SCHEMA t TAG SEPARATOR . CASESENSITIVE').ok() env.expect('FT.CREATE idx5 SCHEMA", "['hello-world', [1]], ['jell', [1]]]) for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx')", "casesensitive env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\ O}') \\ .equal([2, 'doc1', ['t', 'f", "len(res)) env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals', 'idx', 'idx', 'idx').raiseError() env.expect('ft.tagvals', 'fake_idx', 'tags').raiseError()", "doc2 1.0 FIELDS title \"hello\"').error() env.expect('FT.ADD myIdx doc3 1.0 FIELDS", "'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [1]], ['bar', [2]], ['baz', [3]]])", "'F O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\ o}')", "env.expect('FT.ADD myIdx doc1 1.0 FIELDS title \"hello,work\"').ok() expectedRes = {'doc1'", "'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([1,", "5]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['f o', [5, 6]], ['f o,f", "'title', 'text', 'tags', 'tag', 'separator', ':').ok() env.expect('ft.add', 'idx', 'doc1', 1.0,", "o,F O'], 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\ o}')", "[1, []]) # delete both documents and run the GC", "'schema', 'title', 'text', 'tags', 'tag', 'othertags', 'tag') N = 100", "'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator',", "env.assertEqual(1, res[0]) env.assertEqual('doc%d' % n, res[1]) def testSeparator(env): r =", "* from common import * def search(env, r, *args): return", "[0]) env.assertEqual(cursor, 0) def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG',", "'fake_idx', 'tags').raiseError() env.expect('ft.tagvals', 'idx', 'fake_tags').raiseError() env.expect('ft.tagvals', 'idx', 'title').raiseError() def testSearchNotExistsTagValue(env):", "world term%d' % n, 'tags', 'foo bar,xxx,tag %d' % n).ok()", "forceInvokeGC(env, 'idx1') forceInvokeGC(env, 'idx2') forceInvokeGC(env, 'idx3') forceInvokeGC(env, 'idx4') forceInvokeGC(env, 'idx5')", "def testSeparator(env): r = env env.expect( 'ft.create', 'idx', 'ON', 'HASH',", "o\\\\,f\\\\ o}') \\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH',", "res = env.cmd('ft.search', 'idx', 'hello world') env.assertEqual(10, res[0]) res =", "'FT.SEARCH', 'idx', '@TAGS:{foo bar}', 'NOCONTENT')) def testInvalidSyntax(env): r = env", "conn.execute_command('HSET', 'doc5', 't', 'foo') env.expect('FT.SEARCH', 'idx', '@t:{foo}') \\ .equal([2, 'doc4',", "are read res = conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}') env.assertEqual(res, [1, [],", "[2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx5', 't').equal([['foo', [3]], ['foo,FOO', [1]], ['FOO', [2]]])", "from includes import * from common import * def search(env,", "'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx',", "0) # ensure later documents with same tag are read", "env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags',", "GC to clean 'foo' inverted index env.expect('DEL', 'doc1').equal(1) env.expect('DEL', 'doc2').equal(1)", "= r.execute_command('ft.tagvals', 'idx', 'othertags') env.assertEqual(N / 2, len(res)) env.expect('ft.tagvals', 'idx').raiseError()", "def testTagFieldCase(env): r = env env.expect( 'ft.create', 'idx', 'ON', 'HASH',", "testSearchNotExistsTagValue(env): # this test basically make sure we are not", "'doc1').equal(1) env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env, 'idx') # make sure the inverted", "'foo') if not env.is_cluster(): conn.execute_command('FT.CONFIG', 'SET', 'FORK_GC_CLEAN_THRESHOLD', '0') env.expect('FT.DEBUG', 'dump_tagidx',", "'t', 'TAG') conn.execute_command('HSET', 'doc1', 't', 'foo') conn.execute_command('HSET', 'doc2', 't', 'foo')", ". CASESENSITIVE').ok() env.expect('FT.CREATE idx5 SCHEMA t TAG CASESENSITIVE SEPARATOR .').ok()", "res[0]) res = py2sorted(res[1:]) env.assertEqual('doc%d' % n, res[0]) env.assertEqual('doc%d' %", "'@t:{f\\\\ o\\\\,f\\\\ o}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o\\\\,F\\\\ O}')", "'doc1'], r.execute_command( 'FT.SEARCH', 'idx', '@TAgs:{HELLO WORLD}', 'NOCONTENT')) env.assertListEqual([1, 'doc1'], r.execute_command(", "%d}' % (n, n + 1), 'nocontent') env.assertEqual(2, res[0]) res", "'tags', 'tag', 'separator') with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON', 'HASH',", "cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0) def testTagGCClearEmptyWithCursorAndMoreData(env): env.skipOnCluster() conn =", "env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}', 'WITHCURSOR', 'COUNT', '1') env.assertEqual(res, [1, []]) #", "\\ .equal([['hell', [1]], ['hello world', [1]], ['hello-world', [1]], ['jell', [1]]])", "o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([1, 'doc1',", "'title', 'text', 'tags', 'tag', 'separator', ',').ok() env.expect('ft.add', 'idx', 'doc1', 1.0,", "% (n + 1), res[1]) res = env.cmd( 'ft.search', 'idx',", "['t', 'foo']]) env.expect('FT.SEARCH', 'idx1', '@t:{foo}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'],", "from common import * def search(env, r, *args): return r.execute_command('ft.search',", "'text', 'tags', 'tag').ok() N = 10 for n in range(N):", "forceInvokeGC(env, 'idx2') forceInvokeGC(env, 'idx3') forceInvokeGC(env, 'idx4') forceInvokeGC(env, 'idx5') env.expect('FT.DEBUG', 'dump_tagidx',", "'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\ o}') \\ .equal([2,", "= conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}') env.assertEqual(res, [1, [], []]) @unstable def", "'text', 'tags', 'tag', 'separator') with env.assertResponseError(): r.execute_command( 'ft.create', 'idx', 'ON',", "'@t:{foo}', 'WITHCURSOR', 'COUNT', '1') env.assertEqual(res, [1, []]) # delete both", "'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1,", "py2sorted(res[1:]) env.assertEqual('doc%d' % n, res[0]) env.assertEqual('doc%d' % (n + 1),", "'t', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [3, 4]]]) # read", "'idx', '@t:{foo}', 'WITHCURSOR', 'COUNT', '1') env.assertEqual(res, [1, []]) # delete", "[], []]) @unstable def testEmptyTagLeak(env): env.skipOnCluster() cycles = 1 tags", "env env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'TAgs',", "env env.expect('ft.create', 'idx', 'ON', 'HASH','schema', 'title', 'text', 'tags', 'tag').ok() N", "def testTagCaseSensitive(env): conn = getConnectionByEnv(env) env.expect('FT.CREATE idx1 SCHEMA t TAG').ok()", "env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o}') \\ .equal([1, 'doc3', ['t', 'f o']])", "'idx', 'term%d @tags:{tag %d}' % (n, n), 'nocontent') env.assertEqual(1, res[0])", "SCHEMA t TAG SEPARATOR .').ok() env.expect('FT.CREATE idx4 SCHEMA t TAG", "i in range(cycles): for j in range(tags): x = j", "i in range(0, len(res), 3)} env.assertEqual(res, expectedRes) def testTagCaseSensitive(env): conn", "res[0]) res = env.cmd('ft.search', 'idx', 'foo bar') env.assertEqual(0, res[0]) res", "env.assertEqual(N / 2, len(res)) env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals', 'idx', 'idx', 'idx').raiseError()", "('@tags:{hello world}', '@tags:{fooz bar}', '@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}', '@tags:{x}'): res =", "SCHEMA t TAG SEPARATOR . CASESENSITIVE').ok() env.expect('FT.CREATE idx5 SCHEMA t", "SEPARATOR .').ok() conn.execute_command('HSET', 'doc1', 't', 'foo,FOO') conn.execute_command('HSET', 'doc2', 't', 'FOO')", "env.expect('FT.SEARCH', 'idx1', '@t:{foo}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t',", ".equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O}')", "waitForIndex(r, 'idx') res = r.execute_command('ft.tagvals', 'idx', 'tags') env.assertEqual(N * 2", "env.expect('ft.add', 'idx', 'doc1', 1.0, 'fields', 'title', 'hello world', 'tags', 'x:hello", "conn.execute_command('HSET', 'doc4', 't', 'foo') conn.execute_command('HSET', 'doc5', 't', 'foo') env.expect('FT.SEARCH', 'idx',", "= env.cmd('FT.AGGREGATE', 'idx', '@t:{foo}', 'WITHCURSOR', 'COUNT', '1') env.assertEqual(res, [1, []])", "last tag conn.execute_command('DEL', 'doc3') forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([])", "'@tags:{he*}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(res[0], 1) def testTagFieldCase(env):", "'f o']]) env.expect('FT.SEARCH', 'idx1', '@t:{f\\\\ o}') \\ .equal([3, 'doc1', ['t',", "O'], 'doc3', ['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx2', '@t:{F\\\\", "-*- from includes import * from common import * def", "'idx4', '@t:{f\\\\ o}') \\ .equal([1, 'doc3', ['t', 'f o']]) def", "env.skipOnCluster() r = env env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema',", "= set() for n in range(N): tags = ('foo %d'", "'doc1', ['t', 'f o,F O'], 'doc2', ['t', 'F O'], 'doc3',", "# read from the cursor res, cursor = env.cmd('FT.CURSOR', 'READ',", "conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') pl = conn.pipeline() for i", "r = env env.expect('ft.create', 'idx', 'ON', 'HASH','schema', 'title', 'text', 'tags',", "len(res)) env.assertEqual(alltags, set(res)) res = r.execute_command('ft.tagvals', 'idx', 'othertags') env.assertEqual(N /", "'hello world', 'tags', 'x:hello world: fooz bar:foo,bar:BOO FAR').ok() for _", "'f o,F O') conn.execute_command('HSET', 'doc2', 't', 'F O') conn.execute_command('HSET', 'doc3',", "env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo', [3, 4]]]) # read from the", "'t', 'F O') conn.execute_command('HSET', 'doc3', 't', 'f o') if not", ".equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3', ['t', 'foo']])", "o']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o}') \\ .equal([2, 'doc2', ['t', 'F", "[6]], ['f o,F O', [4]], ['F O', [5]]]) # not", "env.expect('FT.SEARCH', 'idx2', '@t:{foo}') \\ .equal([2, 'doc1', ['t', 'foo,FOO'], 'doc3', ['t',", "'tag{}'.format(x)) pl.execute() for j in range(tags): pl.execute_command('DEL', 'doc{}'.format(j + i", "with same tag are read res = conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}')", "'tag', 'separator', \"\") def testTagVals(env): r = env r.execute_command( 'ft.create',", "being empty conn.execute_command('HSET', 'doc4', 't', 'foo') conn.execute_command('HSET', 'doc5', 't', 'foo')", "r.execute_command( 'FT.SEARCH', 'idx', '@tags:{HELLO WORLD}')) env.assertListEqual([1, 'doc1'], r.execute_command( 'FT.SEARCH', 'idx',", "/ 2, len(res)) env.expect('ft.tagvals', 'idx').raiseError() env.expect('ft.tagvals', 'idx', 'idx', 'idx').raiseError() env.expect('ft.tagvals',", ".equal([1, 'doc2', ['t', 'F O']]) env.expect('FT.SEARCH', 'idx4', '@t:{f\\\\ o}') \\", "['f o,F O', [4]], ['F O', [5]]]) # not casesensitive", "world: fooz bar:foo,bar:BOO FAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx')", "= env env.expect( 'ft.create', 'idx', 'ON', 'HASH', 'schema', 'title', 'text',", "= 100 alltags = set() for n in range(N): tags", "tags = ('foo %d' % n, 'bar %d' % n,", "'t', 'foo') conn.execute_command('HSET', 'doc2', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx', 't').equal([['foo',", "O'], 'doc2', ['t', 'F O'], 'doc3', ['t', 'f o']]) #", "env.expect('FT.SEARCH', 'idx', '@t:{foo}') \\ .equal([2, 'doc4', ['t', 'foo'], 'doc5', ['t',", "bar}') env.assertEqual(N, res[0]) # inorder should not affect tags res", "= r.execute_command('ft.tagvals', 'idx', 'tags') env.assertEqual(N * 2 + 1, len(res))", "'doc2', 't', 'bar') conn.execute_command('HSET', 'doc3', 't', 'baz') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx',", "'@tags:{foo\\\\,bar}', '@tags:{boo\\\\ far}', '@tags:{x}'): res = env.cmd('ft.search', 'idx', q) env.assertEqual(1,", "'TAgs', 'HELLO WORLD,FOO BAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r, 'idx')", "index env.expect('DEL', 'doc1').equal(1) env.expect('DEL', 'doc2').equal(1) forceInvokeGC(env, 'idx') # make sure", "'F O'], 'doc3', ['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx4',", "'F O']]) env.expect('FT.SEARCH', 'idx2', '@t:{f\\\\ o}') \\ .equal([2, 'doc1', ['t',", "'separator', \"\") def testTagVals(env): r = env r.execute_command( 'ft.create', 'idx',", "'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', ':').ok()", "'f o,F O'], 'doc2', ['t', 'F O'], 'doc3', ['t', 'f", "conn.execute_command('FT.AGGREGATE', 'idx', '@t:{foo}') env.assertEqual(res, [1, [], []]) @unstable def testEmptyTagLeak(env):", "j in range(tags): x = j + i * tags", "3]], ['FOO', [1, 2]]]) env.expect('FT.DEBUG', 'dump_tagidx', 'idx3', 't').equal([['foo', [2, 3]],", "'@t:{F\\\\ O\\\\,F\\\\ O}') \\ .equal([0]) env.expect('FT.SEARCH', 'idx4', '@t:{F\\\\ O}') \\", "res[0]) res = env.cmd( 'ft.search', 'idx', 'hello world @tags:{tag\\\\ %d|tag", "cycles = 1 tags = 30 conn = getConnectionByEnv(env) conn.execute_command('FT.CONFIG',", "['t', 'foo,FOO'], 'doc3', ['t', 'foo']]) conn.execute_command('HSET', 'doc1', 't', 'f o,F", "'idx', '@t:{foo}') \\ .equal([2, 'doc4', ['t', 'foo'], 'doc5', ['t', 'foo']])", "'F O'], 'doc3', ['t', 'f o']]) # casesensitive env.expect('FT.SEARCH', 'idx2',", "'idx', 'ON', 'HASH', 'schema', 'title', 'text', 'tags', 'tag', 'separator', ',').ok()", "O']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t',", "'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH', 'idx3', '@t:{F\\\\ O}') \\", "env.expect('ft.create', 'idx', 'ON', 'HASH','schema', 'title', 'text', 'tags', 'tag').ok() N =", "O'], 'doc3', ['t', 'f o']]) env.expect('FT.SEARCH', 'idx3', '@t:{f\\\\ o}') \\", "o\\\\,F\\\\ O}') \\ .equal([1, 'doc1', ['t', 'f o,F O']]) env.expect('FT.SEARCH',", "'doc{}'.format(j + i * tags)) pl.execute() forceInvokeGC(env, 'idx') env.expect('FT.DEBUG', 'DUMP_TAGIDX',", "'doc3', 't', 'foo') conn.execute_command('HSET', 'doc4', 't', 'foo') env.expect('FT.DEBUG', 'DUMP_TAGIDX', 'idx',", "world', 'TAgs', 'HELLO WORLD,FOO BAR').ok() for _ in r.retry_with_rdb_reload(): waitForIndex(r,", "','.join(tags), 'othertags', 'baz %d' % int(n // 2))) for _", "*args): return r.execute_command('ft.search', *args) def testTagIndex(env): r = env env.expect('ft.create',", "cursor = conn.execute_command('FT.CURSOR', 'READ', 'idx', cursor) env.assertEqual(res, [0]) env.assertEqual(cursor, 0)", "'FORK_GC_CLEAN_THRESHOLD', '0') conn.execute_command('FT.CREATE', 'idx', 'SCHEMA', 't', 'TAG') conn.execute_command('HSET', 'doc1', 't',", "3)} env.assertEqual(res, expectedRes) def testTagCaseSensitive(env): conn = getConnectionByEnv(env) env.expect('FT.CREATE idx1", "'tags', 'tag', 'separator', \"\") def testTagVals(env): r = env r.execute_command(", "n in range(N - 1): res = env.cmd( 'ft.search', 'idx',", "pl.execute() for j in range(tags): pl.execute_command('DEL', 'doc{}'.format(j + i *", "['bar', [2]], ['baz', [3]]]) env.expect('FT.SEARCH', 'idx', '@t:{foo}').equal([1, 'doc1', ['t', 'foo']])", "'title').raiseError() def testSearchNotExistsTagValue(env): # this test basically make sure we", "'@t:{foo}') \\ .equal([3, 'doc1', ['t', 'foo,FOO'], 'doc2', ['t', 'FOO'], 'doc3'," ]
[ "also triggered at the start of the game for the", "is not available any more, get all other places if", "= th return owned def can_feed(self, unit_type: UnitTypeId) -> bool:", "elif self.race == Race.Protoss: self.warp_gate_count: int = state.common.warp_gate_count self.idle_worker_count: int", "Unit for order in egg.orders: abilities_amount[order.ability] += 1 if self.race", "be called before _prepare_step.\"\"\" if self.townhalls: self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps,", "-> bool: \"\"\"Tests if a building can be placed in", "1 return abilities_amount def already_pending(self, unit_type: Union[UpgradeId, UnitTypeId], all_units: bool", "in production, counts double for terran \"\"\" abilities_amount = Counter()", "Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict = dict() self._previous_upgrades: Set[UpgradeId] = set() self.units:", "rounding bug self._correct_zerg_supply() elif self.race == Race.Protoss: self.warp_gate_count: int =", "- on_unit_destroyed - on_building_construction_complete \"\"\" await self._issue_unit_dead_events() await self._issue_unit_added_events() for", "class for bots.\"\"\" EXPANSION_GAP_THRESHOLD = 15 def __init__(self): # Specific", "(ramp for ramp in self.game_info.map_ramps if len(ramp.upper) in {4, 9}),", "location.\"\"\" building_type = type(building) assert building_type in {AbilityData, AbilityId, UnitTypeId}", "location: Optional[Point2] = None ): \"\"\" Not recommended as this", "a unit has an ability available and enough energy to", ".units import Units logger = logging.getLogger(__name__) class BotAI: \"\"\"Base class", "to be a valid enum name return True # Check", "# perfect amount of workers, skip mining place if not", "point: sum(point.distance_to(resource) for resource in resources)) centers[result] = resources return", "self.units.filter(lambda unit: unit.is_structure and unit.is_ready): for order in structure.orders: if", "from \"not structure.is_ready\") for unit in self.units.structure.not_ready: # type: Unit", "async def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20,", "only_check_energy_and_cooldown: return True cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range ability_target = self._game_data.abilities[ability_id.value]._proto.target #", "+ 1, placement_step)] ) ] res = await self._client.query_building_placement(building, possible_positions)", "extraction site, go there if current_place.vespene_contents: actions.append(worker.gather(current_place)) # if current", "\"\"\" Triggered at the end of a game. \"\"\" class", "from .cache import property_cache_forever, property_cache_once_per_frame from .data import ActionResult, Alert,", "enough resources to build a unit or cast an ability.\"\"\"", "if workers: for worker in workers.sorted_by_distance_to(pos).prefer_idle: if ( not worker.orders", "for order in structure.orders: if order.ability.id is creationAbilityID: if level", "None or not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p))", "return self._game_info.player_start_location @property def enemy_start_locations(self) -> List[Point2]: \"\"\"Possible start locations", "action.unit.orders[0] if current_action.ability.id != action.ability: # different action, return true", "def action_result(self): if not self.can_afford_vespene: return ActionResult.NotEnoughVespene elif not self.can_afford_minerals:", "game_info self._game_data: GameData = game_data self.player_id: int = player_id self.race:", "VespeneExhausted WarpInComplete \"\"\" assert isinstance(alert_code, Alert), f\"alert_code {alert_code} is no", "the merging process as long as we change something found_something", "any more. \"\"\" async def on_unit_created(self, unit: Unit): \"\"\" Override", "any more, get all other places if not possible_mining_places: possible_mining_places", "# reset cached values self.cached_known_enemy_structures = None self.cached_known_enemy_units = None", "find closest mining place current_place = min(deficit_mining_places, key=lambda place: place.distance_to(worker))", "units: Union[List[Unit], Units], ignore_resource_requirements=False ) -> List[List[AbilityId]]: \"\"\" Returns available", "Check if an upgrade is being researched Return values: 0:", "return unit_prev = self._units_previous_map[unit.tag] if unit_prev.build_progress < 1: await self.on_building_construction_complete(unit)", "you should write your own distribution function. For example long", "self.units(race_townhalls[self.race]) self.geysers: Units = self.units(race_gas[self.race]) self.minerals: int = state.common.minerals self.vespene:", "and unit.distance_to(target) <= cast_range ): return True return False def", "isinstance(building, (AbilityId, UnitTypeId)) assert isinstance(near, Point2) if isinstance(building, UnitTypeId): building", "self.minerals: int = state.common.minerals self.vespene: int = state.common.vespene self.supply_army: int", "int = state.common.idle_worker_count self.army_count: int = state.common.army_count # reset cached", "= await self.get_next_expansion() await self.build(building, near=location, max_distance=max_distance, random_alternative=False, placement_step=1) async", "building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative:", "el in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD th", "are no deficit mining places and worker is not idle", "- self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades = self.state.upgrades async def _issue_unit_added_events(self):", "assert isinstance(message, str), f\"{message} is no string\" await self._client.chat_send(message, False)", "supply rounding bug self._correct_zerg_supply() elif self.race == Race.Protoss: self.warp_gate_count: int", "owned def can_feed(self, unit_type: UnitTypeId) -> bool: \"\"\" Checks if", "Union[int, float]: \"\"\" Returns time in seconds, assumes the game", "vespene geyser) as value. \"\"\" # Idea: create a group", "nothing elif worker.is_idle and all_minerals_near_base: target_mineral = min(all_minerals_near_base, key=lambda mineral:", "NukeComplete NydusWormDetected ResearchComplete TrainError TrainUnitComplete TrainWorkerComplete TransformationComplete UnitUnderAttack UpgradeComplete VespeneExhausted", "Cache for the already_pending function, includes protoss units warping in,", "<= RESOURCE_SPREAD_THRESHOLD for resource_a, resource_b in itertools.product(group_a, group_b) ): #", "will NOT will geysers on its own. NOTE: This function", "ActionResult, Attribute, Race, race_worker, race_townhalls, race_gas, Target, Result from .game_data", "cast_range ): return True return False def select_build_worker(self, pos: Union[Unit,", "random from collections import Counter from typing import Any, Dict,", "order, and once from \"not structure.is_ready\") for unit in self.units.structure.not_ready:", "in self.units.structure.not_ready: # type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount", "self.state.vespene_geyser # Create a group for every resource resource_groups =", "5 upper points, and most other maps have 2 upper", "to the mineral field that is near and has the", "move him pass await self.do_actions(actions) @property def owned_expansions(self) -> Dict[Point2,", "worker in worker_pool: # as long as have workers and", "bool = True) -> int: \"\"\" Returns a number of", "[ mineral for mineral in self.state.mineral_field if mineral.distance_to(current_place) <= 8", "in resources) ) # Choose best fitting point result =", "cost.minerals self.vespene -= cost.vespene else: logger.error(f\"Error: {r} (action: {action})\") return", "bots.\"\"\" EXPANSION_GAP_THRESHOLD = 15 def __init__(self): # Specific opponent bot", "Union[List[Unit], Units], ignore_resource_requirements=False ) -> List[List[AbilityId]]: \"\"\" Returns available abilities", "Returns True if a unit can pass through a grid", "= have_enough_supply def __bool__(self): return self.can_afford_minerals and self.can_afford_vespene and self.have_enough_supply", "is en route to build it. This also includes queued", "r = await self._client.query_building_placement(building, [position]) return r[0] == ActionResult.Success async", "reason for len(ramp.upper) in {2, 5} is: # ParaSite map", "is also triggered at the start of the game for", "distribute every worker in the pool for worker in worker_pool:", "{AbilityId.MOVE, AbilityId.HARVEST_GATHER} ): return worker return workers.random if force else", "True try: if current_action.target == action.target.tag: # same action, remove", "unit_type: UnitTypeId) -> bool: \"\"\" Checks if you have enough", "expansion points amount = len(resources) # Calculate center, round and", "= None self.cached_known_enemy_structures = None self.cached_known_enemy_units = None @property def", "@property def game_info(self) -> \"GameInfo\": return self._game_info def alert(self, alert_code:", "long as we change something found_something = True while found_something:", "Unit)) pos = pos.position.to2.rounded return self.state.creep[pos] == 1 def _prepare_start(self,", "are on their way back from it local_workers = self.workers.filter(", "ability_id: AbilityId, target: Optional[Union[Unit, Point2, Point3]] = None, only_check_energy_and_cooldown: bool", "+ 32 * self._game_info.terrain_height[pos] / 255 def in_placement_grid(self, pos: Union[Point2,", "can be built on if self._game_info.placement_grid[point.rounded] == 1 # Check", "import UpgradeId from .pixel_map import PixelMap from .position import Point2,", "Check if any pair of resource of these groups is", "to use ability on a position elif ( ability_target in", "a grid point. \"\"\" # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos,", "self.get_available_abilities(self.units) or units_abilities = await self.get_available_abilities([self.units.random]) \"\"\" return await self._client.query_available_abilities(units,", "minerals left else: local_minerals = [ mineral for mineral in", "points, and most other maps have 2 upper points at", "+= correction self.supply_army += correction self.supply_left -= correction async def", "is only for workers that need to be moved anyways,", "mining_place.surplus_harvesters # perfect amount of workers, skip mining place if", "near possible_points = ( point for point in possible_points #", "= None distance = math.inf for el in self.expansion_locations: def", "building = start_townhall_type[self.race] assert isinstance(building, UnitTypeId) if not location: location", "back from it local_workers = self.workers.filter( lambda unit: unit.order_target ==", "workers in production self.supply_cap: Union[float, int] = None self.supply_used: Union[float,", "for worker in self.workers: # type: Unit for order in", "= min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else: # there are", "in self.units for o in u.orders]) else: amount += sum([o.ability", "and triggers the following functions: - on_unit_created - on_unit_destroyed -", ".data import ActionResult, Alert, Race, Result, Target, race_gas, race_townhalls, race_worker", ".ids.upgrade_id import UpgradeId from .pixel_map import PixelMap from .position import", "group to find expansion position offset_range = 7 offsets =", "== 2 def has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool:", "def prevent_double_actions(self, action): # always add actions if queued if", "self.find_placement(building, near.rounded, max_distance, random_alternative, placement_step) if p is None: return", "self.on_unit_created(unit) for unit in self.units.structure: if unit.tag not in self._units_previous_map:", "distribute than free mining spots # send to closest if", "start_townhall_type = { Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY, }", "# choose only mineral fields first if current mineral to", "worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER} ): return worker return workers.random if", "get_available_abilities( self, units: Union[List[Unit], Units], ignore_resource_requirements=False ) -> List[List[AbilityId]]: \"\"\"", "if all resources have enough space to point and all(point.distance_to(resource)", "in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD th =", "placement location for building.\"\"\" assert isinstance(building, (AbilityId, UnitTypeId)) assert isinstance(near,", "action in actions: cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene", "best fitting point result = min(possible_points, key=lambda point: sum(point.distance_to(resource) for", "import itertools import logging import math import random from collections", "set() self.units: Units = Units([]) def _prepare_first_step(self): \"\"\"First step extra", "GameData, AbilityData from .ids.ability_id import AbilityId from .ids.unit_typeid import UnitTypeId", "game so your bot can \"adapt\" to the opponent self.opponent_id:", "Units = self.units(race_townhalls[self.race]) self.geysers: Units = self.units(race_gas[self.race]) self.minerals: int =", "on_upgrade_complete(self, upgrade: UpgradeId): \"\"\" Override this in your bot class.", "more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3, Unit)) pos =", "unit.is_structure: # If an SCV is constructing a building, already_pending", "(self.state) are available. \"\"\" async def on_step(self, iteration: int): \"\"\"Ran", "bases = self.townhalls.ready geysers = self.geysers.ready # list of places", "site local_workers = self.workers.filter( lambda unit: unit.order_target in local_minerals_tags or", "abilities_amount[order.ability] += 1 if not unit.is_ready: if self.race != Race.Terran", "# Distance offsets we apply to center of each resource", "min(deficit_mining_places, key=lambda place: place.distance_to(worker)) # remove it from the list", "cost = self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals <= self.minerals, cost.vespene <= self.vespene,", "from \"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount @property_cache_once_per_frame def", "mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else: # there are no deficit mining places", "Unit]) -> bool: \"\"\" Returns True if you can place", "# Check every combination of two groups for group_a, group_b", "expansion via 'self.get_next_expansion()'. If the target expansion is blocked (e.g.", "float]: \"\"\" Returns time in seconds, assumes the game is", "can_feed(self, unit_type: UnitTypeId) -> bool: \"\"\" Checks if you have", "\"\"\" if not building: # self.race is never Race.Random start_townhall_type", "if current_place.vespene_contents: actions.append(worker.gather(current_place)) # if current place is a gas", "# See game_state.py # update pathing grid self._game_info.pathing_grid: PixelMap =", "self.geysers: Units = self.units(race_gas[self.race]) self.minerals: int = state.common.minerals self.vespene: int", "for x in self.townhalls if is_near_to_expansion(x)), None) if th: owned[el]", "return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if unit is", "if able to use ability on a position elif (", "= math.inf for el in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el)", "self.geysers: Units = None self.minerals: int = None self.vespene: int", "AddOnComplete BuildingComplete BuildingUnderAttack LarvaHatched MergeComplete MineralsExhausted MorphComplete MothershipComplete MULEExpired NuclearLaunchDetected", "iteration of game_state (self.state) are available. \"\"\" async def on_step(self,", "import PixelMap from .position import Point2, Point3 from .unit import", "resource in resources) ) # Choose best fitting point result", "a building, already_pending would count this structure twice (once from", "ramp in self.game_info.map_ramps if len(ramp.upper) in {2, 5}), key=lambda r:", "5}), key=lambda r: self.start_location.distance_to(r.top_center), ) except ValueError: # Hardcoded hotfix", "function uses 'self.do' (reduces performance). Finds the next possible expansion", "self._game_info.terrain_height[pos] # returns int def get_terrain_z_height(self, pos: Union[Point2, Point3, Unit])", "and once from \"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount", "found_something: found_something = False # Check every combination of two", "# get workers that work at that gather site local_workers", "return Race(self._game_info.player_races[self.enemy_id]) @property def time(self) -> Union[int, float]: \"\"\" Returns", "in self.workers.idle] bases = self.townhalls.ready geysers = self.geysers.ready # list", "of other units (such as Carriers (Interceptors) or Oracles (Stasis", "not actions: return None if prevent_double: actions = list(filter(self.prevent_double_actions, actions))", "see ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert isinstance(pos, (Point2, Point3, Unit))", "a position. Remember, buildings usually use 2x2, 3x3 or 5x5", "units already in progress, or if a worker is en", "in the pool for worker in worker_pool: # as long", "set game and player data.\"\"\" self._client: \"Client\" = client self._game_info:", "= next((x for x in self.townhalls if is_near_to_expansion(x)), None) if", "abilities = (await self.get_available_abilities([unit]))[0] if ability_id in abilities: if only_check_energy_and_cooldown:", "self.can_afford_minerals = can_afford_minerals self.can_afford_vespene = can_afford_vespene self.have_enough_supply = have_enough_supply def", "Unit) and unit.distance_to(target) <= cast_range ): return True # Check", "ability = self._game_data.units[unit_type.value].creation_ability amount = len(self.units(unit_type).not_ready) if all_units: amount +=", "import Units logger = logging.getLogger(__name__) class BotAI: \"\"\"Base class for", "logger.error(f\"Error: {r} (action: {action})\") return r async def do_actions(self, actions:", "int] = None self.supply_workers: Union[float, int] = None # Doesn't", "prepare all minerals near a base if we have too", "Returns a number of buildings or units already in progress,", "Tuple, Union # mypy type checking from .cache import property_cache_forever,", "is available. \"\"\" async def on_start_async(self): \"\"\" This function is", "main-ramp to start location. Look in game_info.py for more information", "await self.get_available_abilities(self.units) or units_abilities = await self.get_available_abilities([self.units.random]) \"\"\" return await", "def enemy_start_locations(self) -> List[Point2]: \"\"\"Possible start locations for enemies.\"\"\" return", "are inside the boundries of the map size. def get_terrain_height(self,", "# Distance we group resources by RESOURCE_SPREAD_THRESHOLD = 8.5 geysers", "// 60):02}:{int(t % 60):02}\" @property def game_info(self) -> \"GameInfo\": return", "can be placed in the given location.\"\"\" building_type = type(building)", "cost.vespene else: logger.error(f\"Error: {r} (action: {action})\") return r async def", "of zerglings and banelings. This function corrects the bad values.", "current_place.vespene_contents: actions.append(worker.gather(current_place)) # if current place is a gas extraction", "= d closest = el return closest async def distribute_workers(self,", "if prevent_double: actions = list(filter(self.prevent_double_actions, actions)) for action in actions:", "= near.to2 else: return p = await self.find_placement(building, near.rounded, max_distance,", "for resource in self.state.resources] # Loop the merging process as", "mypy type checking from .cache import property_cache_forever, property_cache_once_per_frame from .data", "egg in self.units(UnitTypeId.EGG)]) return amount async def build(self, building: UnitTypeId,", "not instantly subtract minerals and vespene. \"\"\" if not actions:", "the boundries of the map size. def get_terrain_height(self, pos: Union[Point2,", "on_start(self): \"\"\" Allows initializing the bot when the game data", "self._game_info.start_locations @property_cache_once_per_frame def known_enemy_units(self) -> Units: \"\"\"List of known enemy", "unit_type: Union[UpgradeId, UnitTypeId], all_units: bool = True) -> int: \"\"\"", "counts double for terran \"\"\" abilities_amount = Counter() for worker", "a self cast like stimpack) if ( ability_target == 1", "# TODO / FIXME: SCV building a structure might be", "UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY, } building = start_townhall_type[self.race] assert isinstance(building, UnitTypeId)", "abilities = cached_abilities_of_unit else: abilities = (await self.get_available_abilities([unit]))[0] if ability_id", "every game step (looped in realtime mode).\"\"\" raise NotImplementedError def", "target_mineral = min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else: # there", "available and enough energy to cast it. See data_pb2.py (line", "if action.target.x == current_action.target.x and action.target.y == current_action.target.y: # same", "action, return true return True try: if current_action.target == action.target.tag:", "any( resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD for resource_a, resource_b in itertools.product(group_a, group_b)", "len(ramp.upper) in {2, 5} is: # ParaSite map has 5", "+ 0.5 possible_points = (Point2((offset[0] + center_x, offset[1] + center_y))", "Check if all resources have enough space to point and", "= self.geysers.ready # list of places that need more workers", "has an ability available and enough energy to cast it.", "if all_units: amount += sum([o.ability == ability for u in", "returns int def get_terrain_z_height(self, pos: Union[Point2, Point3, Unit]) -> int:", "local_workers = self.workers.filter( lambda unit: unit.order_target == mining_place.tag or (unit.is_carrying_vespene", "The client incorrectly rounds zerg supply down instead of up", "1 if not unit.is_ready: if self.race != Race.Terran or not", "closest = None distance = math.inf for el in self.expansion_locations:", "queued orders for workers and build queues of buildings. If", "return await self._client.actions(actions) def prevent_double_actions(self, action): # always add actions", "mining places if deficit_mining_places: # choose only mineral fields first", "= [] worker_pool = [worker for worker in self.workers.idle] bases", "in game_info.py for more information \"\"\" if hasattr(self, \"cached_main_base_ramp\"): return", "can have # tags of the minerals he could mine", "# imports for mypy and pycharm autocomplete from .game_state import", "sum([o.ability == ability for u in self.units for o in", "Point3], max_distance: int = 20, random_alternative: bool = True, placement_step:", "@property def owned_expansions(self) -> Dict[Point2, Unit]: \"\"\"List of expansions owned", "race_worker, race_townhalls, race_gas, Target, Result from .game_data import AbilityData, GameData", "in self.state.dead_units: await self.on_unit_destroyed(unit_tag) async def on_unit_destroyed(self, unit_tag): \"\"\" Override", "if alert is triggered in the current step. Example use:", "the Ramp instance of the closest main-ramp to start location.", "and banelings. This function corrects the bad values. \"\"\" #", "w.distance_to(pos) < 20) or self.workers ) if workers: for worker", "self.geysers.ready # list of places that need more workers deficit_mining_places", "add 0.5 because expansion location will have (x.5, y.5) #", "if cached_abilities_of_unit: abilities = cached_abilities_of_unit else: abilities = (await self.get_available_abilities([unit]))[0]", "not in self._units_previous_map: await self.on_building_construction_started(unit) async def _issue_building_complete_event(self, unit): if", "if len(ramp.upper) in {2, 5}), key=lambda r: self.start_location.distance_to(r.top_center), ) except", "with inbase natural self.cached_main_base_ramp = min( (ramp for ramp in", "than threshold together if any( resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD for resource_a,", "return near if max_distance == 0: return None for distance", "resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD for resource_a, resource_b in itertools.product(group_a, group_b) ):", "None distance = math.inf for el in self.expansion_locations: def is_near_to_expansion(t):", "bool = True, placement_step: int = 2, ) -> Optional[Point2]:", "% 60):02}\" @property def game_info(self) -> \"GameInfo\": return self._game_info def", "= await self._client.query_pathing(startp, el) if d is None: continue if", "not self.workers or not self.townhalls.ready: return actions = [] worker_pool", "able to use ability on a unit elif ( ability_target", "possible: continue if random_alternative: return random.choice(possible) else: return min(possible, key=lambda", "= None self.army_count: int = None self.warp_gate_count: int = None", "\"\"\" abilities_amount = Counter() for worker in self.workers: # type:", "enough_supply) async def can_cast( self, unit: Unit, ability_id: AbilityId, target:", "== Race.Zerg: for egg in self.units(UnitTypeId.EGG): # type: Unit for", "or (unit.is_carrying_vespene and unit.order_target == bases.closest_to(mining_place).tag) ) else: # get", "== mining_place.tag or (unit.is_carrying_vespene and unit.order_target == bases.closest_to(mining_place).tag) ) else:", "tags a worker can have # tags of the minerals", "isinstance(near, Unit): near = near.position.to2 elif near is not None:", "current_action.target.x and action.target.y == current_action.target.y: # same action, remove action", "6) for resource in resources) ) # Choose best fitting", "a number of buildings or units already in progress, or", "UpgradeId): return self.already_pending_upgrade(unit_type) ability = self._game_data.units[unit_type.value].creation_ability amount = len(self.units(unit_type).not_ready) if", "\"\"\" assert isinstance(alert_code, Alert), f\"alert_code {alert_code} is no Alert\" return", "game_state.py # update pathing grid self._game_info.pathing_grid: PixelMap = PixelMap( proto_game_info.game_info.start_raw.pathing_grid,", "unit in self.units.not_structure: if unit.tag not in self._units_previous_map: await self.on_unit_created(unit)", "in abilities: if only_check_energy_and_cooldown: return True cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range ability_target", "egg.orders: abilities_amount[order.ability] += 1 if self.race != Race.Terran: # If", "assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.pathing_grid[pos]", "main_base_ramp(self) -> \"Ramp\": \"\"\" Returns the Ramp instance of the", "\"adapt\" to the opponent self.opponent_id: int = None self.units: Units", "Idea: create a group for every resource, then merge these", "Optional[Point2] = None ): \"\"\" Not recommended as this function", "supply down instead of up (see https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used and", "for unit in self.units} self.units: Units = state.own_units self.workers: Units", "= pos.position.to2.rounded return self._game_info.terrain_height[pos] # returns int def get_terrain_z_height(self, pos:", "current_action: UnitOrder current_action = action.unit.orders[0] if current_action.ability.id != action.ability: #", "self.race != Race.Terran or not unit.is_structure: # If an SCV", "self.vespene -= cost.vespene else: logger.error(f\"Error: {r} (action: {action})\") return r", ") # Choose best fitting point result = min(possible_points, key=lambda", "self._game_data.abilities[ability_id.value]._proto.target # Check if target is in range (or is", "race_townhalls, race_gas, Target, Result from .game_data import AbilityData, GameData #", "return p = await self.find_placement(building, near.rounded, max_distance, random_alternative, placement_step) if", "{r} (action: {action})\") return r async def do_actions(self, actions: List[\"UnitCommand\"],", "inside the boundries of the map size. def get_terrain_height(self, pos:", "f\"pos is not of type Point2, Point3 or Unit\" pos", "bot class. \"\"\" async def on_building_construction_complete(self, unit: Unit): \"\"\" Override", "\"\"\" Returns True if you can place something at a", "pos.position.to2.rounded return self._game_info.placement_grid[pos] == 1 def in_pathing_grid(self, pos: Union[Point2, Point3,", "time as string in min:sec format \"\"\" t = self.time", "Race.Zerg: UnitTypeId.HATCHERY, } building = start_townhall_type[self.race] assert isinstance(building, UnitTypeId) if", "pos.position.to2.rounded return self._game_info.terrain_height[pos] # returns int def get_terrain_z_height(self, pos: Union[Point2,", "up (see https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used and friends return the wrong", "self.race is never Race.Random start_townhall_type = { Race.Protoss: UnitTypeId.NEXUS, Race.Terran:", "self.supply_left: int = self.supply_cap - self.supply_used if self.race == Race.Zerg:", "def main_base_ramp(self) -> \"Ramp\": \"\"\" Returns the Ramp instance of", "the given location.\"\"\" building_type = type(building) assert building_type in {AbilityData,", "else prefer gas else: possible_mining_places = [place for place in", "+ [(dx, distance) for dx in range(-distance, distance + 1,", "being researched Return values: 0: not started 0 < x", "return self.cached_main_base_ramp @property_cache_forever def expansion_locations(self) -> Dict[Point2, Units]: \"\"\" Returns", "UnitTypeId.HATCHERY, } building = start_townhall_type[self.race] assert isinstance(building, UnitTypeId) if not", "is no string\" await self._client.chat_send(message, False) # For the functions", "import logging import math import random from collections import Counter", "assert isinstance(near, Point2) if isinstance(building, UnitTypeId): building = self._game_data.units[building.value].creation_ability else:", "= set() self.units: Units = Units([]) def _prepare_first_step(self): \"\"\"First step", "go there if current_place.vespene_contents: actions.append(worker.gather(current_place)) # if current place is", "(ramp for ramp in self.game_info.map_ramps if len(ramp.upper) in {2, 5}),", "want to return centers = {} # For every resource", "= int(sum(resource.position.y for resource in resources) / amount) + 0.5", "mineral fields first if current mineral to gas ratio is", "def do_actions(self, actions: List[\"UnitCommand\"], prevent_double=True): \"\"\" Unlike 'self.do()', this function", "resources) / amount) + 0.5 possible_points = (Point2((offset[0] + center_x,", "(or is a self cast like stimpack) if ( ability_target", "for point in possible_points # Check if point can be", "int = state.common.food_cap self.supply_used: int = state.common.food_used self.supply_left: int =", "as long as have workers and mining places if deficit_mining_places:", "Point3, Unit)), f\"pos is not of type Point2, Point3 or", "expansion position Point2 object as key, resources (mineral field and", "then merge these groups if # any resource in a", "1 or ability_target == Target.PointOrNone.value and isinstance(target, (Point2, Point3)) and", "Units = self.units(race_worker[self.race]) self.townhalls: Units = self.units(race_townhalls[self.race]) self.geysers: Units =", "from sc2.data import Alert if self.alert(Alert.AddOnComplete): print(\"Addon Complete\") Alert codes:", "( [(dx, -distance) for dx in range(-distance, distance + 1,", "instance of the closest main-ramp to start location. Look in", "queues of other units (such as Carriers (Interceptors) or Oracles", "position). try: self.cached_main_base_ramp = min( (ramp for ramp in self.game_info.map_ramps", "workers deficit_mining_places = [] for mining_place in bases | geysers:", "the SCV order, and once from \"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] +=", "Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.pathing_grid[pos] == 1 def", "single groups and add the merged group resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a", "building_type = type(building) assert building_type in {AbilityData, AbilityId, UnitTypeId} if", "ignore_resource_requirements=False ) -> List[List[AbilityId]]: \"\"\" Returns available abilities of one", "if a base was killed are not being handled. WARNING:", "int] = None self.supply_left: Union[float, int] = None self.idle_worker_count: int", "\"\"\" # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3, Unit))", "else: deficit_mining_places += [mining_place for _ in range(-difference)] # prepare", "that work at that gather site local_workers = self.workers.filter( lambda", "reset cached values self.cached_known_enemy_structures = None self.cached_known_enemy_units = None async", "+= sum([o.ability == ability for u in self.units for o", "self.state.alerts @property def start_location(self) -> Point2: return self._game_info.player_start_location @property def", "ability for w in self.workers for o in w.orders]) amount", "raise NotImplementedError def on_end(self, game_result: Result): \"\"\" Triggered at the", "for more information \"\"\" if hasattr(self, \"cached_main_base_ramp\"): return self.cached_main_base_ramp #", "import property_cache_forever, property_cache_once_per_frame from .data import ActionResult, Alert, Race, Result,", "= pos.position.to2.rounded return self.state.creep[pos] == 1 def _prepare_start(self, client, player_id,", "Unit): \"\"\" Override this in your bot class. Note that", "terrain z-height at a position. \"\"\" assert isinstance(pos, (Point2, Point3,", "self.can_afford_minerals and self.can_afford_vespene and self.have_enough_supply @property def action_result(self): if not", "place something at a position. Remember, buildings usually use 2x2,", "> 0: for worker in local_workers[:difference]: worker_pool.append(worker) # too few", "game start to set game and player data.\"\"\" self._client: \"Client\"", "units, including structures.\"\"\" return self.state.enemy_units @property_cache_once_per_frame def known_enemy_structures(self) -> Units:", "few workers # add mining place to deficit bases for", "w.orders]) amount += sum([egg.orders[0].ability == ability for egg in self.units(UnitTypeId.EGG)])", "a worker can have # tags of the minerals he", "= resources return centers def _correct_zerg_supply(self): \"\"\" The client incorrectly", "mining places and worker is not idle # so dont", "check if unit has enough energy to cast or if", "in your bot class. Note that this function uses unit", "combination of two groups for group_a, group_b in itertools.combinations(resource_groups, 2):", "them to the closest patch if len(worker_pool) > len(deficit_mining_places): all_minerals_near_base", "function is also triggered at the start of the game", "type: Unit for order in unit.orders: abilities_amount[order.ability] += 1 if", "async def _issue_building_complete_event(self, unit): if unit.build_progress < 1: return if", "group resources by RESOURCE_SPREAD_THRESHOLD = 8.5 geysers = self.state.vespene_geyser #", "minerals around expansion local_minerals_tags = { mineral.tag for mineral in", "UpgradeId, AbilityId], check_supply_cost: bool = True ) -> \"CanAffordWrapper\": \"\"\"Tests", "= False # Check every combination of two groups for", "# Set attributes from new state before on_step.\"\"\" self.state: GameState", "= self.can_feed(item_id) elif isinstance(item_id, UpgradeId): cost = self._game_data.upgrades[item_id.value].cost else: cost", "worker in self.workers: # type: Unit for order in worker.orders:", "MothershipComplete MULEExpired NuclearLaunchDetected NukeComplete NydusWormDetected ResearchComplete TrainError TrainUnitComplete TrainWorkerComplete TransformationComplete", "for dx in range(-distance, distance + 1, placement_step)] + [(-distance,", "pos = pos.position.to2.rounded return self.state.visibility[pos] == 2 def has_creep(self, pos:", "Point2, Point3 from .unit import Unit from .units import Units", "not difference: continue if mining_place.is_vespene_geyser: # get all workers that", "the wrong ramp (which is closest to the start position).", "units warping in, and all units in production, and all", "do_actions(self, actions: List[\"UnitCommand\"], prevent_double=True): \"\"\" Unlike 'self.do()', this function does", "if not self.can_afford(action): logger.warning(f\"Cannot afford action {action}\") return ActionResult.Error r", "in self.units.filter(lambda unit: unit.is_structure and unit.is_ready): for order in structure.orders:", "wrong value when there are an odd number of zerglings", "in offsets) # Filter out points that are too near", "if same target position return False except AttributeError: pass return", "action, remove action if same target unit return False except", "orders for workers and build queues of buildings. If all_units==True,", "self.state.resources] # Loop the merging process as long as we", "resource of these groups is closer than threshold together if", "cast it. See data_pb2.py (line 161) for the numbers 1-5", "if able to use ability on a unit elif (", "async def on_upgrade_complete(self, upgrade: UpgradeId): \"\"\" Override this in your", "field and vespene geyser) as value. \"\"\" # Idea: create", "self.units(UnitTypeId.EGG)]) return amount async def build(self, building: UnitTypeId, near: Union[Point2,", "enough space to point and all(point.distance_to(resource) > (7 if resource", "def expand_now( self, building: UnitTypeId = None, max_distance: Union[int, float]", "if any(mineral.distance_to(base) <= 8 for base in self.townhalls.ready) ] #", "unit.is_ready): for order in structure.orders: if order.ability.id is creationAbilityID: if", "a large main base ramp with inbase natural self.cached_main_base_ramp =", "# returns int def get_terrain_z_height(self, pos: Union[Point2, Point3, Unit]) ->", "min( (ramp for ramp in self.game_info.map_ramps if len(ramp.upper) in {2,", "bool = True ) -> \"CanAffordWrapper\": \"\"\"Tests if the player", "self._client.query_building_placement(building, possible_positions) possible = [p for r, p in zip(res,", "near a base if we have too many workers #", "'self.get_next_expansion()'. If the target expansion is blocked (e.g. an enemy", "Unit): near = near.position.to2 elif near is not None: near", "functions below, make sure you are inside the boundries of", "if not place.vespene_contents] # else prefer gas else: possible_mining_places =", "number of buildings or units already in progress, or if", "range(-distance, distance + 1, placement_step)] ) ] res = await", "pos = pos.position.to2.rounded return self._game_info.pathing_grid[pos] == 1 def is_visible(self, pos:", "bool: \"\"\" Returns True if there is creep on the", "print(\"Addon Complete\") Alert codes: AlertError AddOnComplete BuildingComplete BuildingUnderAttack LarvaHatched MergeComplete", "isinstance(ability_id, AbilityId) assert isinstance(target, (type(None), Unit, Point2, Point3)) # check", "is triggered in the current step. Example use: from sc2.data", "import Alert if self.alert(Alert.AddOnComplete): print(\"Addon Complete\") Alert codes: AlertError AddOnComplete", "self.can_afford_vespene and self.have_enough_supply @property def action_result(self): if not self.can_afford_vespene: return", "resource in self.state.resources] # Loop the merging process as long", "mineral for mineral in self.state.mineral_field if mineral.distance_to(current_place) <= 8 ]", "not unit.is_structure: # If an SCV is constructing a building,", "and isinstance(target, Unit) and unit.distance_to(target) <= cast_range ): return True", "a base if we have too many workers # and", "ResearchComplete TrainError TrainUnitComplete TrainWorkerComplete TransformationComplete UnitUnderAttack UpgradeComplete VespeneExhausted WarpInComplete \"\"\"", "8 for base in self.townhalls.ready) ] # distribute every worker", "(Point2, Point3)) and unit.distance_to(target) <= cast_range ): # cant replace", "random_alternative: return random.choice(possible) else: return min(possible, key=lambda p: p.distance_to_point2(near)) return", "self.units(race_gas[self.race]) self.minerals: int = state.common.minerals self.vespene: int = state.common.vespene self.supply_army:", "Triggered at the end of a game. \"\"\" class CanAffordWrapper:", "= (Point2((offset[0] + center_x, offset[1] + center_y)) for offset in", "if level and order.ability.button_name[-1] != level: return 0 return order.progress", "] target_mineral = max(local_minerals, key=lambda mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral)) # more", "def on_unit_created(self, unit: Unit): \"\"\" Override this in your bot", "Counter() for worker in self.workers: # type: Unit for order", "return ActionResult.NotEnoughMinerals elif not self.have_enough_supply: return ActionResult.NotEnoughFood else: return None", "able to use ability on a position elif ( ability_target", "\"\"\" Cache for the already_pending function, includes protoss units warping", "5x5 of these grid points. Caution: some x and y", "unit is None or not self.can_afford(building): return ActionResult.Error return await", "near): return near if max_distance == 0: return None for", "1-5 to make sense\"\"\" assert isinstance(unit, Unit) assert isinstance(ability_id, AbilityId)", "build queues of other units (such as Carriers (Interceptors) or", "groups for group_a, group_b in itertools.combinations(resource_groups, 2): # Check if", "pos = pos.position.to2.rounded return self.state.creep[pos] == 1 def _prepare_start(self, client,", "self.on_unit_destroyed(unit_tag) async def on_unit_destroyed(self, unit_tag): \"\"\" Override this in your", "information \"\"\" if hasattr(self, \"cached_main_base_ramp\"): return self.cached_main_base_ramp # The reason", "UpgradeId) if upgrade_type in self.state.upgrades: return 1 level = None", "] res = await self._client.query_building_placement(building, possible_positions) possible = [p for", ".position import Point2, Point3 from .unit import Unit from .units", "placement_step)] + [(distance, dy) for dy in range(-distance, distance +", "\"\"\" class CanAffordWrapper: def __init__(self, can_afford_minerals, can_afford_vespene, have_enough_supply): self.can_afford_minerals =", "random_alternative=False, placement_step=1) async def get_next_expansion(self) -> Optional[Point2]: \"\"\"Find next expansion", "{4, 9}), key=lambda r: self.start_location.distance_to(r.top_center), ) return self.cached_main_base_ramp @property_cache_forever def", "ability.\"\"\" enough_supply = True if isinstance(item_id, UnitTypeId): unit = self._game_data.units[item_id.value]", "Units = Units([]) def _prepare_first_step(self): \"\"\"First step extra preparations. Must", "dx in range(-distance, distance + 1, placement_step)] + [(dx, distance)", "class. \"\"\" async def on_building_construction_started(self, unit: Unit): \"\"\" Override this", "f\"{message} is no string\" await self._client.chat_send(message, False) # For the", "def do(self, action): if not self.can_afford(action): logger.warning(f\"Cannot afford action {action}\")", "triggered in the current step. Example use: from sc2.data import", "worker_pool = [worker for worker in self.workers.idle] bases = self.townhalls.ready", "is doing nothing elif worker.is_idle and all_minerals_near_base: target_mineral = min(all_minerals_near_base,", "on_unit_created - on_unit_destroyed - on_building_construction_complete \"\"\" await self._issue_unit_dead_events() await self._issue_unit_added_events()", "if self.race != Race.Terran: # If an SCV is constructing", "end of a game. \"\"\" class CanAffordWrapper: def __init__(self, can_afford_minerals,", "\"\"\" Returns time as string in min:sec format \"\"\" t", "geysers: difference = mining_place.surplus_harvesters # perfect amount of workers, skip", "ActionResult.Error return await self.do(unit.build(building, p)) async def do(self, action): if", "property_cache_forever, property_cache_once_per_frame from .data import ActionResult, Alert, Race, Result, Target,", "another group # Distance we group resources by RESOURCE_SPREAD_THRESHOLD =", "+= 1 if self.race == Race.Zerg: for egg in self.units(UnitTypeId.EGG):", "could mine at that base # get workers that work", "abilities_amount[order.ability] += 1 if self.race == Race.Zerg: for egg in", "in_bits=True, mirrored=False ) # Required for events self._units_previous_map: Dict =", "for len(ramp.upper) in {2, 5} is: # ParaSite map has", "code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos =", "at the start of the game for the starting base", "workers # and need to send them to the closest", "the following functions: - on_unit_created - on_unit_destroyed - on_building_construction_complete \"\"\"", "taken. Keyword `resource_ratio` takes a float. If the current minerals", "= None @property def enemy_race(self) -> Race: assert len(self._game_info.player_races) ==", "self.townhalls)): # already taken continue startp = self._game_info.player_start_location d =", "for offset in offsets) # Filter out points that are", "in realtime mode).\"\"\" raise NotImplementedError def on_end(self, game_result: Result): \"\"\"", "key=lambda place: place.distance_to(worker)) # remove it from the list deficit_mining_places.remove(current_place)", "found_something = True break # Distance offsets we apply to", "every missing worker else: deficit_mining_places += [mining_place for _ in", "# check if unit has enough energy to cast or", "if isinstance(building, UnitTypeId): building = self._game_data.units[building.value].creation_ability else: # AbilityId building", "action.queue: return True if action.unit.orders: # action: UnitCommand # current_action:", "actions.append(worker.gather(current_place)) # if current place is a gas extraction site,", "cached_abilities_of_unit: abilities = cached_abilities_of_unit else: abilities = (await self.get_available_abilities([unit]))[0] if", "EXPANSION_GAP_THRESHOLD = 15 def __init__(self): # Specific opponent bot ID", "is in range (or is a self cast like stimpack)", "None @property def enemy_race(self) -> Race: assert len(self._game_info.player_races) == 2,", "double for terran \"\"\" abilities_amount = Counter() for worker in", "this function uses unit tags because the unit does not", "return True return False def select_build_worker(self, pos: Union[Unit, Point2, Point3],", "worker is doing nothing elif worker.is_idle and all_minerals_near_base: target_mineral =", "actions if queued if action.queue: return True if action.unit.orders: #", "unit_prev.build_progress < 1: await self.on_building_construction_complete(unit) async def _issue_unit_dead_events(self): for unit_tag", "or Oracles (Stasis Ward)) are also included. \"\"\" # TODO", "\"CanAffordWrapper\": \"\"\"Tests if the player has enough resources to build", "ability_target in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit) and unit.distance_to(target) <=", "your bot class. \"\"\" def on_start(self): \"\"\" Allows initializing the", "\"\"\" Not recommended as this function uses 'self.do' (reduces performance).", "Point3]] = None, only_check_energy_and_cooldown: bool = False, cached_abilities_of_unit: List[AbilityId] =", "/ amount) + 0.5 center_y = int(sum(resource.position.y for resource in", "Returns available abilities of one or more units. Right know", "have vision on a grid point. \"\"\" # more info:", "do(self, action): if not self.can_afford(action): logger.warning(f\"Cannot afford action {action}\") return", "= self.state.upgrades async def _issue_unit_added_events(self): for unit in self.units.not_structure: if", "/ 255 def in_placement_grid(self, pos: Union[Point2, Point3, Unit]) -> bool:", "(which is closest to the start position). try: self.cached_main_base_ramp =", "abilities_amount @property_cache_once_per_frame def _abilities_workers_and_eggs(self) -> Counter: \"\"\" Cache for the", "dont move him pass await self.do_actions(actions) @property def owned_expansions(self) ->", "doing nothing elif worker.is_idle and all_minerals_near_base: target_mineral = min(all_minerals_near_base, key=lambda", "Point2, Point3]] = None, only_check_energy_and_cooldown: bool = False, cached_abilities_of_unit: List[AbilityId]", "upgrade_type.name[-1] creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id for structure in self.units.filter(lambda unit: unit.is_structure", "in_placement_grid(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True", "distribute_workers(self, resource_ratio: float = 2): \"\"\" Distributes workers across all", "and worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER} ): return worker return workers.random", "Remember, buildings usually use 2x2, 3x3 or 5x5 of these", "or multiple bases. \"\"\" if not self.state.mineral_field or not self.workers", "== ActionResult.Success async def find_placement( self, building: UnitTypeId, near: Union[Unit,", "below, make sure you are inside the boundries of the", "self.workers ) if workers: for worker in workers.sorted_by_distance_to(pos).prefer_idle: if (", "None self.supply_workers: Union[float, int] = None # Doesn't include workers", "center, round and add 0.5 because expansion location will have", "Finds the next possible expansion via 'self.get_next_expansion()'. If the target", "point for point in possible_points # Check if point can", "-> bool: \"\"\" Returns True if you can place something", "len(self.units(unit_type).not_ready) if all_units: amount += sum([o.ability == ability for u", "no deficit mining places and worker is not idle #", "place: place.distance_to(worker)) # remove it from the list deficit_mining_places.remove(current_place) #", "worker_pool.append(worker) # too few workers # add mining place to", "== 1 and worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER} ): return worker", "closer than 6 to any resource of another group #", "self.supply_used if self.race == Race.Zerg: self.larva_count: int = state.common.larva_count #", "= Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict = dict() self._previous_upgrades: Set[UpgradeId] = set()", "self._game_data.abilities[ability_id.value]._proto.cast_range ability_target = self._game_data.abilities[ability_id.value]._proto.target # Check if target is in", "building: UnitTypeId = None, max_distance: Union[int, float] = 10, location:", "remove when Blizzard/sc2client-proto#123 gets fixed. half_supply_units = { UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED,", "actions)) for action in actions: cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -=", "true return True try: if current_action.target == action.target.tag: # same", "across all the bases taken. Keyword `resource_ratio` takes a float.", "group for every resource resource_groups = [[resource] for resource in", "Point2 object as key, resources (mineral field and vespene geyser)", "once from \"not structure.is_ready\") for unit in self.units.structure.not_ready: # type:", "buildings or units already in progress, or if a worker", "def _issue_building_complete_event(self, unit): if unit.build_progress < 1: return if unit.tag", "# Specific opponent bot ID used in sc2ai ladder games", "= state.common.food_used self.supply_left: int = self.supply_cap - self.supply_used if self.race", "Alert\" return alert_code.value in self.state.alerts @property def start_location(self) -> Point2:", "height at a position. Caution: terrain height is different from", "twice (once from the SCV order, and once from \"not", "!= len(self.state.upgrades): for upgrade_completed in self.state.upgrades - self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed)", "Override this in your bot class. \"\"\" async def on_building_construction_started(self,", "return ActionResult.NotEnoughVespene elif not self.can_afford_minerals: return ActionResult.NotEnoughMinerals elif not self.have_enough_supply:", "if not building: # self.race is never Race.Random start_townhall_type =", "worker.orders: abilities_amount[order.ability] += 1 if self.race == Race.Zerg: for egg", "if preferred type is not available any more, get all", "in self.state.upgrades - self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades = self.state.upgrades async", "If an SCV is constructing a building, already_pending would count", "function, includes all worker orders (including pending). Zerg units in", "in actions: cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -=", "this in your bot class. \"\"\" async def on_building_construction_started(self, unit:", "= [ Point2(p).offset(near).to2 for p in ( [(dx, -distance) for", "def get_available_abilities( self, units: Union[List[Unit], Units], ignore_resource_requirements=False ) -> List[List[AbilityId]]:", "of a game. \"\"\" class CanAffordWrapper: def __init__(self, can_afford_minerals, can_afford_vespene,", "len(self._previous_upgrades) != len(self.state.upgrades): for upgrade_completed in self.state.upgrades - self._previous_upgrades: await", "that need to be moved anyways, it will NOT will", "self._game_data.units[building.value].creation_ability elif building_type == AbilityId: building = self._game_data.abilities[building.value] r =", "will stay the same each game so your bot can", "await self._client.query_available_abilities(units, ignore_resource_requirements) async def expand_now( self, building: UnitTypeId =", "resource in resources) / amount) + 0.5 center_y = int(sum(resource.position.y", "as have workers and mining places if deficit_mining_places: # choose", "in {AbilityData, AbilityId, UnitTypeId} if building_type == UnitTypeId: building =", "if point can be built on if self._game_info.placement_grid[point.rounded] == 1", "is far from optimal, if you really want to have", "is lower, it will prefer sending workers to minerals first.", "fixed. half_supply_units = { UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, }", "} # get all target tags a worker can have", "self.larva_count: int = None self.cached_known_enemy_structures = None self.cached_known_enemy_units = None", "enough free supply to build the unit \"\"\" required =", "force else None async def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId],", "build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None,", "ability available and enough energy to cast it. See data_pb2.py", "(w.is_gathering or w.is_idle) and w.distance_to(pos) < 20) or self.workers )", "prevent_double_actions(self, action): # always add actions if queued if action.queue:", "from optimal, if you really want to have refined worker", "Optional[Point2]: \"\"\"Finds a placement location for building.\"\"\" assert isinstance(building, (AbilityId,", "action.target.y == current_action.target.y: # same action, remove action if same", "cached values self.cached_known_enemy_structures = None self.cached_known_enemy_units = None async def", "bool=True, placement_step: int=2): \"\"\"Build a building.\"\"\" if isinstance(near, Unit): near", "structure twice # (once from the SCV order, and once", "Union[AbilityData, AbilityId, UnitTypeId], position: Point2) -> bool: \"\"\"Tests if a", "so dont move him pass await self.do_actions(actions) @property def owned_expansions(self)", "If all_units==True, then build queues of other units (such as", "-> Union[int, float]: \"\"\" Returns time in seconds, assumes the", "bool: \"\"\" Returns True if you have vision on a", "state.own_units self.workers: Units = self.units(race_worker[self.race]) self.townhalls: Units = self.units(race_townhalls[self.race]) self.geysers:", "pos: Union[Point2, Point3, Unit]) -> int: \"\"\" Returns terrain z-height", "key=lambda p: p.distance_to_point2(near)) return None def already_pending_upgrade(self, upgrade_type: UpgradeId) ->", "= None self.cached_known_enemy_units = None @property def enemy_race(self) -> Race:", "games http://sc2ai.net/ # The bot ID will stay the same", "self.state.enemy_units @property_cache_once_per_frame def known_enemy_structures(self) -> Units: \"\"\"List of known enemy", "Target.PointOrNone.value and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range ):", "x and y offset might be required, see ramp code:", "= await self._client.query_building_placement(building, possible_positions) possible = [p for r, p", "if self.vespene and self.minerals / self.vespene < resource_ratio: possible_mining_places =", "isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range ): return True", "el in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD if", "if self.race == Race.Zerg: for egg in self.units(UnitTypeId.EGG): # type:", "AttributeError: pass try: if action.target.x == current_action.target.x and action.target.y ==", "assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self.state.creep[pos]", "bases. \"\"\" if not self.state.mineral_field or not self.workers or not", "len(worker_pool) > len(deficit_mining_places): all_minerals_near_base = [ mineral for mineral in", "True while found_something: found_something = False # Check every combination", "state.common.food_cap self.supply_used: int = state.common.food_used self.supply_left: int = self.supply_cap -", "int = state.common.vespene self.supply_army: int = state.common.food_army self.supply_workers: int =", "distance = d closest = el return closest async def", "float = 2): \"\"\" Distributes workers across all the bases", "startp = self._game_info.player_start_location d = await self._client.query_pathing(startp, el) if d", "state.common.army_count # reset cached values self.cached_known_enemy_structures = None self.cached_known_enemy_units =", "# TODO: remove when Blizzard/sc2client-proto#123 gets fixed. half_supply_units = {", "cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene return", "these groups if # any resource in a group is", "ID used in sc2ai ladder games http://sc2ai.net/ # The bot", "this in your bot class. \"\"\" async def on_building_construction_complete(self, unit:", "= await self._client.query_building_placement(building, [position]) return r[0] == ActionResult.Success async def", "if max_distance == 0: return None for distance in range(placement_step,", "key=lambda mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral)) # more workers to distribute than", "for worker in workers.sorted_by_distance_to(pos).prefer_idle: if ( not worker.orders or len(worker.orders)", "cast_range ): # cant replace 1 with \"Target.None.value\" because \".None\"", "workers that target the gas extraction site # or are", "self.vespene < resource_ratio: possible_mining_places = [place for place in deficit_mining_places", "== ability for u in self.units for o in u.orders])", "creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id for structure in self.units.filter(lambda unit: unit.is_structure and", "15 def __init__(self): # Specific opponent bot ID used in", "https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used and friends return the wrong value when", "expand_now( self, building: UnitTypeId = None, max_distance: Union[int, float] =", "required def can_afford( self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool", "values: 0: not started 0 < x < 1: researching", "pass try: if action.target.x == current_action.target.x and action.target.y == current_action.target.y:", "Union[float, int] = None self.idle_worker_count: int = None self.army_count: int", "int] = None self.idle_worker_count: int = None self.army_count: int =", "def in_placement_grid(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns", "unit can pass through a grid point. \"\"\" assert isinstance(pos,", "action: UnitCommand # current_action: UnitOrder current_action = action.unit.orders[0] if current_action.ability.id", "def has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns", "have_enough_supply): self.can_afford_minerals = can_afford_minerals self.can_afford_vespene = can_afford_vespene self.have_enough_supply = have_enough_supply", "geysers = self.state.vespene_geyser # Create a group for every resource", "(such as Carriers (Interceptors) or Oracles (Stasis Ward)) are also", "+= sum([egg.orders[0].ability == ability for egg in self.units(UnitTypeId.EGG)]) return amount", "Union # mypy type checking from .cache import property_cache_forever, property_cache_once_per_frame", "and worker is not idle # so dont move him", "True cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range ability_target = self._game_data.abilities[ability_id.value]._proto.target # Check if", "Honorgrounds LE map, as that map has a large main", "self.minerals / self.vespene < resource_ratio: possible_mining_places = [place for place", "| geysers: difference = mining_place.surplus_harvesters # perfect amount of workers,", "unit: unit.order_target == mining_place.tag or (unit.is_carrying_vespene and unit.order_target == bases.closest_to(mining_place).tag)", "are an odd number of zerglings and banelings. This function", "async def _issue_unit_dead_events(self): for unit_tag in self.state.dead_units: await self.on_unit_destroyed(unit_tag) async", "already_pending would count this structure twice # (once from the", "is blocked (e.g. an enemy unit), it will misplace the", "if len(ramp.upper) in {4, 9}), key=lambda r: self.start_location.distance_to(r.top_center), ) return", "the bases taken. Keyword `resource_ratio` takes a float. If the", "assert isinstance(unit, Unit) assert isinstance(ability_id, AbilityId) assert isinstance(target, (type(None), Unit,", "game_state (self.state) are available. \"\"\" async def on_step(self, iteration: int):", "filling geysers first, if it is lower, it will prefer", "@property def main_base_ramp(self) -> \"Ramp\": \"\"\" Returns the Ramp instance", "has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True", "if unit has enough energy to cast or if ability", "else: logger.error(f\"Error: {r} (action: {action})\") return r async def do_actions(self,", "= self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self, state, proto_game_info): # Set attributes from", "The reason for len(ramp.upper) in {2, 5} is: # ParaSite", "to build a building with.\"\"\" workers = ( self.workers.filter(lambda w:", "if len(self._previous_upgrades) != len(self.state.upgrades): for upgrade_completed in self.state.upgrades - self._previous_upgrades:", "in {4, 9}), key=lambda r: self.start_location.distance_to(r.top_center), ) return self.cached_main_base_ramp @property_cache_forever", "hotfix for Honorgrounds LE map, as that map has a", "that is near and has the most minerals left else:", "\"\"\" Checks if you have enough free supply to build", "Zerg supply rounding bug self._correct_zerg_supply() elif self.race == Race.Protoss: self.warp_gate_count:", "each resource group to find expansion position offset_range = 7", "near = near.to2 else: return p = await self.find_placement(building, near.rounded,", "Union[float, int] = None self.supply_used: Union[float, int] = None self.supply_left:", "have enough free supply to build the unit \"\"\" required", ".game_data import AbilityData, GameData # imports for mypy and pycharm", "ParaSite map has 5 upper points, and most other maps", "\"\"\" Override this in your bot class. Note that this", "via 'self.get_next_expansion()'. If the target expansion is blocked (e.g. an", "want to have refined worker control, you should write your", "of the closest main-ramp to start location. Look in game_info.py", "an ability available and enough energy to cast it. See", "( ability_target in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit) and unit.distance_to(target)", "researching 1: finished \"\"\" assert isinstance(upgrade_type, UpgradeId) if upgrade_type in", "Optional, Set, Tuple, Union # mypy type checking from .cache", "else: # AbilityId building = self._game_data.abilities[building.value] if await self.can_place(building, near):", "UnitTypeId: building = self._game_data.units[building.value].creation_ability elif building_type == AbilityId: building =", "map, as that map has a large main base ramp", "Must not be called before _prepare_step.\"\"\" if self.townhalls: self._game_info.player_start_location =", "include workers in production self.supply_cap: Union[float, int] = None self.supply_used:", "the correct expansion position Point2 object as key, resources (mineral", "all(point.distance_to(resource) > (7 if resource in geysers else 6) for", "= self.units(half_supply_units).amount % 2 self.supply_used += correction self.supply_army += correction", "Point2: return self._game_info.player_start_location @property def enemy_start_locations(self) -> List[Point2]: \"\"\"Possible start", "for place in deficit_mining_places if place.vespene_contents] # if preferred type", "= dict() self._previous_upgrades: Set[UpgradeId] = set() self.units: Units = Units([])", "distance + 1, placement_step)] + [(-distance, dy) for dy in", "is played on 'faster' \"\"\" return self.state.game_loop / 22.4 #", "[place for place in deficit_mining_places if place.vespene_contents] # if preferred", "self.townhalls: Units = None self.geysers: Units = None self.minerals: int", "seconds, assumes the game is played on 'faster' \"\"\" return", "on_unit_destroyed - on_building_construction_complete \"\"\" await self._issue_unit_dead_events() await self._issue_unit_added_events() for unit", "near if max_distance == 0: return None for distance in", "!= Race.Terran or not unit.is_structure: # If an SCV is", "the numbers 1-5 to make sense\"\"\" assert isinstance(unit, Unit) assert", "\"\"\"List of expansions owned by the player.\"\"\" owned = {}", "Caution: some x and y offset might be required, see", "center_x = int(sum(resource.position.x for resource in resources) / amount) +", "worker can have # tags of the minerals he could", "0 @property_cache_once_per_frame def _abilities_all_units(self) -> Counter: \"\"\" Cache for the", "self.townhalls.ready) ] # distribute every worker in the pool for", "worker in self.workers.idle] bases = self.townhalls.ready geysers = self.geysers.ready #", "[(dx, -distance) for dx in range(-distance, distance + 1, placement_step)]", "cooldown if cached_abilities_of_unit: abilities = cached_abilities_of_unit else: abilities = (await", "logger.warning(f\"Cannot afford action {action}\") return ActionResult.Error r = await self._client.actions(action)", "in {AbilityId.MOVE, AbilityId.HARVEST_GATHER} ): return worker return workers.random if force", "worker to build a building with.\"\"\" workers = ( self.workers.filter(lambda", "if isinstance(item_id, UnitTypeId): unit = self._game_data.units[item_id.value] cost = self._game_data.calculate_ability_cost(unit.creation_ability) if", "= [p for r, p in zip(res, possible_positions) if r", "UnitTypeId], position: Point2) -> bool: \"\"\"Tests if a building can", "] # Dict we want to return centers = {}", "_ in range(-difference)] # prepare all minerals near a base", "if self.race != Race.Terran or not unit.is_structure: # If an", "abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount @property_cache_once_per_frame def _abilities_workers_and_eggs(self) -> Counter:", "this in your bot class. Note that this function is", "\"\"\" return self.state.game_loop / 22.4 # / (1/1.4) * (1/16)", "your own distribution function. For example long distance mining control", "self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self, state,", "None: return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if unit", "step extra preparations. Must not be called before _prepare_step.\"\"\" if", "lambda unit: unit.order_target == mining_place.tag or (unit.is_carrying_vespene and unit.order_target ==", "in self.state.mineral_field if mineral.distance_to(mining_place) <= 8 } # get all", "in possible_points # Check if point can be built on", "something at a position. Remember, buildings usually use 2x2, 3x3", "the list deficit_mining_places.remove(current_place) # if current place is a gas", "lambda unit: unit.order_target in local_minerals_tags or (unit.is_carrying_minerals and unit.order_target ==", "# list of places that need more workers deficit_mining_places =", "# so dont move him pass await self.do_actions(actions) @property def", "actions: cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene", "self.can_place(building, near): return near if max_distance == 0: return None", "sending workers to minerals first. This is only for workers", "far from optimal, if you really want to have refined", "a building with.\"\"\" workers = ( self.workers.filter(lambda w: (w.is_gathering or", "pos = pos.position.to2.rounded return -16 + 32 * self._game_info.terrain_height[pos] /", "sum([egg.orders[0].ability == ability for egg in self.units(UnitTypeId.EGG)]) return amount async", "z-coordinate. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)), f\"pos is not", "amount) + 0.5 center_y = int(sum(resource.position.y for resource in resources)", "return r[0] == ActionResult.Success async def find_placement( self, building: UnitTypeId,", "# already taken continue startp = self._game_info.player_start_location d = await", "moving workers if a base was killed are not being", "target tags a worker can have # tags of the", "type(building) assert building_type in {AbilityData, AbilityId, UnitTypeId} if building_type ==", "\"\"\"Tests if the player has enough resources to build a", "self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene return await self._client.actions(actions)", "= self._units_previous_map[unit.tag] if unit_prev.build_progress < 1: await self.on_building_construction_complete(unit) async def", "game_data): \"\"\"Ran until game start to set game and player", "mineral.mineral_contents) actions.append(worker.gather(target_mineral)) # more workers to distribute than free mining", "known enemy units, structures only.\"\"\" return self.state.enemy_units.structure @property def main_base_ramp(self)", "= None self.units: Units = None self.workers: Units = None", "self.EXPANSION_GAP_THRESHOLD th = next((x for x in self.townhalls if is_near_to_expansion(x)),", "starting base building.\"\"\" async def on_upgrade_complete(self, upgrade: UpgradeId): \"\"\" Override", "0: for worker in local_workers[:difference]: worker_pool.append(worker) # too few workers", "assert isinstance(building, UnitTypeId) if not location: location = await self.get_next_expansion()", "for unit in self.units.not_structure: if unit.tag not in self._units_previous_map: await", "Check if target is in range (or is a self", "base was killed are not being handled. WARNING: This is", "+= [mining_place for _ in range(-difference)] # prepare all minerals", "different from a unit's z-coordinate. \"\"\" assert isinstance(pos, (Point2, Point3,", "start_location(self) -> Point2: return self._game_info.player_start_location @property def enemy_start_locations(self) -> List[Point2]:", "unit: unit.order_target in local_minerals_tags or (unit.is_carrying_minerals and unit.order_target == mining_place.tag)", "len(ramp.upper) in {2, 5}), key=lambda r: self.start_location.distance_to(r.top_center), ) except ValueError:", "min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else: # there are no", "import AbilityId from .ids.unit_typeid import UnitTypeId from .ids.upgrade_id import UpgradeId", "for the starting base building.\"\"\" async def on_upgrade_complete(self, upgrade: UpgradeId):", "-> Units: \"\"\"List of known enemy units, structures only.\"\"\" return", "no string\" await self._client.chat_send(message, False) # For the functions below,", "@property_cache_once_per_frame def _abilities_all_units(self) -> Counter: \"\"\" Cache for the already_pending", "in ( [(dx, -distance) for dx in range(-distance, distance +", "format \"\"\" t = self.time return f\"{int(t // 60):02}:{int(t %", "if queued if action.queue: return True if action.unit.orders: # action:", "= can_afford_vespene self.have_enough_supply = have_enough_supply def __bool__(self): return self.can_afford_minerals and", "\"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return", ".game_data import GameData, AbilityData from .ids.ability_id import AbilityId from .ids.unit_typeid", "deficit_mining_places if not place.vespene_contents] # else prefer gas else: possible_mining_places", "and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range ): return", "RESOURCE_SPREAD_THRESHOLD = 8.5 geysers = self.state.vespene_geyser # Create a group", "{action}\") return ActionResult.Error r = await self._client.actions(action) if not r:", "resource in a group is closer than 6 to any", "== 1 def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool:", "for resource_a, resource_b in itertools.product(group_a, group_b) ): # Remove the", "current_action.target == action.target.tag: # same action, remove action if same", "perfect amount of workers, skip mining place if not difference:", "vision on a grid point. \"\"\" # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19", "= {} for el in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el)", "Result, Target, race_gas, race_townhalls, race_worker from .data import ActionResult, Attribute,", "create a group for every resource, then merge these groups", "https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded", "2 def has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\"", "game. \"\"\" class CanAffordWrapper: def __init__(self, can_afford_minerals, can_afford_vespene, have_enough_supply): self.can_afford_minerals", "in sc2ai ladder games http://sc2ai.net/ # The bot ID will", "(1/16) @property def time_formatted(self) -> str: \"\"\" Returns time as", "group is closer than 6 to any resource of another", "have size 5. center_x = int(sum(resource.position.x for resource in resources)", "to point and all(point.distance_to(resource) > (7 if resource in geysers", "ActionResult.Success async def find_placement( self, building: UnitTypeId, near: Union[Unit, Point2,", "bool: \"\"\"Tests if a unit has an ability available and", "bug self._correct_zerg_supply() elif self.race == Race.Protoss: self.warp_gate_count: int = state.common.warp_gate_count", "merging process as long as we change something found_something =", "`resource_ratio`, this function prefer filling geysers first, if it is", "Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True if you", "if unit.tag not in self._units_previous_map: return unit_prev = self._units_previous_map[unit.tag] if", "isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.placement_grid[pos] ==", "already_pending(self, unit_type: Union[UpgradeId, UnitTypeId], all_units: bool = True) -> int:", "in itertools.combinations(resource_groups, 2): # Check if any pair of resource", "self.workers: Units = None self.townhalls: Units = None self.geysers: Units", "def can_feed(self, unit_type: UnitTypeId) -> bool: \"\"\" Checks if you", "None self.cached_known_enemy_units = None async def issue_events(self): \"\"\" This function", "every resource group: for resources in resource_groups: # Possible expansion", "self._issue_unit_added_events() for unit in self.units.structure: await self._issue_building_complete_event(unit) if len(self._previous_upgrades) !=", "WARNING: This is quite slow when there are lots of", "from the SCV order, and once from \"not structure.is_ready\") for", "-> int: \"\"\" Returns terrain z-height at a position. \"\"\"", "the player has enough resources to build a unit or", "False except AttributeError: pass return True return True async def", "and self.have_enough_supply @property def action_result(self): if not self.can_afford_vespene: return ActionResult.NotEnoughVespene", "has been researched. Example usage: units_abilities = await self.get_available_abilities(self.units) or", "Union[float, int] = None self.supply_left: Union[float, int] = None self.idle_worker_count:", "more. \"\"\" async def on_unit_created(self, unit: Unit): \"\"\" Override this", "of another group # Distance we group resources by RESOURCE_SPREAD_THRESHOLD", "-> Counter: \"\"\" Cache for the already_pending function, includes protoss", "is closer than threshold together if any( resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD", "energy cost, and whether the ability has been researched. Example", "resource of another group # Distance we group resources by", "will geysers on its own. NOTE: This function is far", "= [place for place in deficit_mining_places if not place.vespene_contents] #", "range (or is a self cast like stimpack) if (", "if not possible: continue if random_alternative: return random.choice(possible) else: return", "in resources) / amount) + 0.5 center_y = int(sum(resource.position.y for", "Unit]) -> bool: \"\"\" Returns True if you have vision", "+= sum([o.ability == ability for w in self.workers for o", "== Race.Protoss: self.warp_gate_count: int = state.common.warp_gate_count self.idle_worker_count: int = state.common.idle_worker_count", "known_enemy_units(self) -> Units: \"\"\"List of known enemy units, including structures.\"\"\"", "unit.tag not in self._units_previous_map: await self.on_unit_created(unit) for unit in self.units.structure:", "building = self._game_data.units[building.value].creation_ability else: # AbilityId building = self._game_data.abilities[building.value] if", "add mining place to deficit bases for every missing worker", "assert isinstance(upgrade_type, UpgradeId) if upgrade_type in self.state.upgrades: return 1 level", "we change something found_something = True while found_something: found_something =", "in w.orders]) amount += sum([egg.orders[0].ability == ability for egg in", "return worker return workers.random if force else None async def", "if resource in geysers else 6) for resource in resources)", "than 6 to any resource of another group # Distance", "for the already_pending function, includes protoss units warping in, and", "the already_pending function, includes all worker orders (including pending). Zerg", "ratio is bigger than `resource_ratio`, this function prefer filling geysers", "if you have enough free supply to build the unit", "current_action.target.y: # same action, remove action if same target position", "difference = mining_place.surplus_harvesters # perfect amount of workers, skip mining", "Race, race_worker, race_townhalls, race_gas, Target, Result from .game_data import AbilityData,", "ratio if self.vespene and self.minerals / self.vespene < resource_ratio: possible_mining_places", "action.ability: # different action, return true return True try: if", "points amount = len(resources) # Calculate center, round and add", "The bot ID will stay the same each game so", "for r, p in zip(res, possible_positions) if r == ActionResult.Success]", "self.idle_worker_count: int = state.common.idle_worker_count self.army_count: int = state.common.army_count # reset", "return actions = [] worker_pool = [worker for worker in", "first if current mineral to gas ratio is less than", "build it. This also includes queued orders for workers and", "# action: UnitCommand # current_action: UnitOrder current_action = action.unit.orders[0] if", "# Loop the merging process as long as we change", "optimal, if you really want to have refined worker control,", "is constructing a building, already_pending would count this structure twice", ".game_state import GameState from .game_data import GameData, AbilityData from .ids.ability_id", "amount += sum([o.ability == ability for w in self.workers for", "# Dict we want to return centers = {} #", "# go to the mineral field that is near and", "lower, it will prefer sending workers to minerals first. This", "in bases | geysers: difference = mining_place.surplus_harvesters # perfect amount", "= int(sum(resource.position.x for resource in resources) / amount) + 0.5", "map Acolyte has 4 upper points at the wrong ramp", "\"\"\"Finds a placement location for building.\"\"\" assert isinstance(building, (AbilityId, UnitTypeId))", "offsets = [ (x, y) for x, y in itertools.product(range(-offset_range,", "resources have enough space to point and all(point.distance_to(resource) > (7", "== Target.PointOrNone.value and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range", "near and has the most minerals left else: local_minerals =", "self._units_previous_map: await self.on_building_construction_started(unit) async def _issue_building_complete_event(self, unit): if unit.build_progress <", "point in possible_points # Check if point can be built", "and moving workers if a base was killed are not", "/ amount) + 0.5 possible_points = (Point2((offset[0] + center_x, offset[1]", "x in self.townhalls if is_near_to_expansion(x)), None) if th: owned[el] =", "return the wrong value when there are an odd number", "Point3)) and unit.distance_to(target) <= cast_range ): # cant replace 1", "self.already_pending_upgrade(unit_type) ability = self._game_data.units[unit_type.value].creation_ability amount = len(self.units(unit_type).not_ready) if all_units: amount", "not self.townhalls.ready: return actions = [] worker_pool = [worker for", "self._client.query_available_abilities(units, ignore_resource_requirements) async def expand_now( self, building: UnitTypeId = None,", "this function is also triggered at the start of the", "possible_mining_places = deficit_mining_places # find closest mining place current_place =", "workers that need to be moved anyways, it will NOT", "return False except AttributeError: pass return True return True async", "includes queued orders for workers and build queues of buildings.", ") -> Optional[Point2]: \"\"\"Finds a placement location for building.\"\"\" assert", "else: amount += sum([o.ability == ability for w in self.workers", "has a large main base ramp with inbase natural self.cached_main_base_ramp", "own. NOTE: This function is far from optimal, if you", "action): # always add actions if queued if action.queue: return", "called before _prepare_step.\"\"\" if self.townhalls: self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers", "= self.state.vespene_geyser # Create a group for every resource resource_groups", "in egg.orders: abilities_amount[order.ability] += 1 if self.race != Race.Terran: #", "en route to build it. This also includes queued orders", "unit has enough energy to cast or if ability is", "except AttributeError: pass return True return True async def chat_send(self,", "not available any more, get all other places if not", "includes protoss units warping in, and all units in production,", "def expansion_locations(self) -> Dict[Point2, Units]: \"\"\" Returns dict with the", "def time(self) -> Union[int, float]: \"\"\" Returns time in seconds,", "Point2, Point3 or Unit\" pos = pos.position.to2.rounded return -16 +", "# Workaround Zerg supply rounding bug self._correct_zerg_supply() elif self.race ==", "\"\"\" if not self.state.mineral_field or not self.workers or not self.townhalls.ready:", "get tags of minerals around expansion local_minerals_tags = { mineral.tag", "self.vespene -= cost.vespene return await self._client.actions(actions) def prevent_double_actions(self, action): #", "UnitTypeId} if building_type == UnitTypeId: building = self._game_data.units[building.value].creation_ability elif building_type", "22.4 # / (1/1.4) * (1/16) @property def time_formatted(self) ->", "return await self.do(unit.build(building, p)) async def do(self, action): if not", "too near possible_points = ( point for point in possible_points", "UnitTypeId) -> bool: \"\"\" Checks if you have enough free", "@property_cache_once_per_frame def known_enemy_structures(self) -> Units: \"\"\"List of known enemy units,", "workers if difference > 0: for worker in local_workers[:difference]: worker_pool.append(worker)", "on if self._game_info.placement_grid[point.rounded] == 1 # Check if all resources", "True if isinstance(item_id, UnitTypeId): unit = self._game_data.units[item_id.value] cost = self._game_data.calculate_ability_cost(unit.creation_ability)", "use 2x2, 3x3 or 5x5 of these grid points. Caution:", "might be counted as two units if isinstance(unit_type, UpgradeId): return", "max_distance=max_distance, random_alternative=False, placement_step=1) async def get_next_expansion(self) -> Optional[Point2]: \"\"\"Find next", "d = await self._client.query_pathing(startp, el) if d is None: continue", "* self._game_info.terrain_height[pos] / 255 def in_placement_grid(self, pos: Union[Point2, Point3, Unit])", "= pos.position.to2.rounded return self._game_info.placement_grid[pos] == 1 def in_pathing_grid(self, pos: Union[Point2,", "if not unit.is_ready: if self.race != Race.Terran or not unit.is_structure:", "len(deficit_mining_places): all_minerals_near_base = [ mineral for mineral in self.state.mineral_field if", "target is in range (or is a self cast like", "client self._game_info: \"GameInfo\" = game_info self._game_data: GameData = game_data self.player_id:", "+ 1, placement_step)] + [(dx, distance) for dx in range(-distance,", "\"\"\" # TODO: remove when Blizzard/sc2client-proto#123 gets fixed. half_supply_units =", "abilities_amount[order.ability] += 1 if self.race != Race.Terran: # If an", "ability for u in self.units for o in u.orders]) else:", "energy to cast or if ability is on cooldown if", "): # cant replace 1 with \"Target.None.value\" because \".None\" doesnt", "from main.py and triggers the following functions: - on_unit_created -", "await self._issue_unit_added_events() for unit in self.units.structure: await self._issue_building_complete_event(unit) if len(self._previous_upgrades)", "from .data import ActionResult, Attribute, Race, race_worker, race_townhalls, race_gas, Target,", "gas else: possible_mining_places = [place for place in deficit_mining_places if", "o in w.orders]) amount += sum([egg.orders[0].ability == ability for egg", "(see https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used and friends return the wrong value", "Race = Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict = dict() self._previous_upgrades: Set[UpgradeId] =", "= self._game_data.abilities[building.value] if await self.can_place(building, near): return near if max_distance", "gas extraction site, go there if current_place.vespene_contents: actions.append(worker.gather(current_place)) # if", "Point2, Point3], force: bool = False) -> Optional[Unit]: \"\"\"Select a", "self._game_info.player_start_location @property def enemy_start_locations(self) -> List[Point2]: \"\"\"Possible start locations for", "will be automatically run from main.py and triggers the following", "unit for unit in self.units} self.units: Units = state.own_units self.workers:", "-> List[Point2]: \"\"\"Possible start locations for enemies.\"\"\" return self._game_info.start_locations @property_cache_once_per_frame", "current_place = min(deficit_mining_places, key=lambda place: place.distance_to(worker)) # remove it from", "if any( resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD for resource_a, resource_b in itertools.product(group_a,", "and build queues of buildings. If all_units==True, then build queues", "gather site local_workers = self.workers.filter( lambda unit: unit.order_target in local_minerals_tags", "Point2, Point3 or Unit\" pos = pos.position.to2.rounded return self._game_info.terrain_height[pos] #", "in production self.supply_cap: Union[float, int] = None self.supply_used: Union[float, int]", "place is a gas extraction site, # go to the", "# The map Acolyte has 4 upper points at the", "= state.common.idle_worker_count self.army_count: int = state.common.army_count # reset cached values", "Units = None self.workers: Units = None self.townhalls: Units =", "structure.orders: if order.ability.id is creationAbilityID: if level and order.ability.button_name[-1] !=", "also includes queued orders for workers and build queues of", "to return centers = {} # For every resource group:", "2 self.supply_used += correction self.supply_army += correction self.supply_left -= correction", "build a unit or cast an ability.\"\"\" enough_supply = True", "# add mining place to deficit bases for every missing", "return self._game_info.terrain_height[pos] # returns int def get_terrain_z_height(self, pos: Union[Point2, Point3,", "not self.can_afford(action): logger.warning(f\"Cannot afford action {action}\") return ActionResult.Error r =", "int = self.supply_cap - self.supply_used if self.race == Race.Zerg: self.larva_count:", "if only_check_energy_and_cooldown: return True cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range ability_target = self._game_data.abilities[ability_id.value]._proto.target", "gas extraction site, # go to the mineral field that", "\"\"\" assert isinstance(message, str), f\"{message} is no string\" await self._client.chat_send(message,", "continue startp = self._game_info.player_start_location d = await self._client.query_pathing(startp, el) if", "Check if point can be built on if self._game_info.placement_grid[point.rounded] ==", "< distance: distance = d closest = el return closest", "morphs \"\"\" abilities_amount = Counter() for unit in self.units: #", "\"\"\" Returns terrain height at a position. Caution: terrain height", "/ FIXME: SCV building a structure might be counted as", "if a unit can pass through a grid point. \"\"\"", "= { UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, } correction =", "await self._client.query_building_placement(building, possible_positions) possible = [p for r, p in", "resource_b in itertools.product(group_a, group_b) ): # Remove the single groups", "in your bot class. \"\"\" def on_start(self): \"\"\" Allows initializing", "self.have_enough_supply = have_enough_supply def __bool__(self): return self.can_afford_minerals and self.can_afford_vespene and", "= state.common.minerals self.vespene: int = state.common.vespene self.supply_army: int = state.common.food_army", "= state.own_units self.workers: Units = self.units(race_worker[self.race]) self.townhalls: Units = self.units(race_townhalls[self.race])", "centers def _correct_zerg_supply(self): \"\"\" The client incorrectly rounds zerg supply", "\"\"\" abilities_amount = Counter() for unit in self.units: # type:", "would count this structure twice (once from the SCV order,", "# mypy type checking from .cache import property_cache_forever, property_cache_once_per_frame from", "to center of each resource group to find expansion position", "sum(point.distance_to(resource) for resource in resources)) centers[result] = resources return centers", "for every resource, then merge these groups if # any", "self.state.mineral_field if mineral.distance_to(mining_place) <= 8 } # get all target", "return random.choice(possible) else: return min(possible, key=lambda p: p.distance_to_point2(near)) return None", "or not self.workers or not self.townhalls.ready: return actions = []", "function corrects the bad values. \"\"\" # TODO: remove when", "async def get_available_abilities( self, units: Union[List[Unit], Units], ignore_resource_requirements=False ) ->", "isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self.state.visibility[pos] ==", "SCV order, and once from \"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1", "issue_events(self): \"\"\" This function will be automatically run from main.py", "for group_a, group_b in itertools.combinations(resource_groups, 2): # Check if any", "offset might be required, see ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert", "\"\"\" Send a chat message. \"\"\" assert isinstance(message, str), f\"{message}", "workers in production self.supply_cap: int = state.common.food_cap self.supply_used: int =", "dy in range(-distance, distance + 1, placement_step)] + [(distance, dy)", "Point3], force: bool = False) -> Optional[Unit]: \"\"\"Select a worker", "= { Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY, } building", "building, already_pending would count this structure twice # (once from", "data.\"\"\" self._client: \"Client\" = client self._game_info: \"GameInfo\" = game_info self._game_data:", "building: # self.race is never Race.Random start_townhall_type = { Race.Protoss:", "return amount async def build(self, building: UnitTypeId, near: Union[Point2, Point3],", "min(possible_points, key=lambda point: sum(point.distance_to(resource) for resource in resources)) centers[result] =", "d closest = el return closest async def distribute_workers(self, resource_ratio:", "point. \"\"\" # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3,", "this in your bot class. \"\"\" def on_start(self): \"\"\" Allows", "{ Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY, } building =", "the gas extraction site # or are on their way", "= deficit_mining_places # find closest mining place current_place = min(deficit_mining_places,", "(Point2, Point3, Unit)) pos = pos.position.to2.rounded return self.state.visibility[pos] == 2", "w: (w.is_gathering or w.is_idle) and w.distance_to(pos) < 20) or self.workers", "Acolyte has 4 upper points at the wrong ramp (which", "on_start_async(self): \"\"\" This function is run after \"on_start\". At this", "action if same target unit return False except AttributeError: pass", "= logging.getLogger(__name__) class BotAI: \"\"\"Base class for bots.\"\"\" EXPANSION_GAP_THRESHOLD =", "Check every combination of two groups for group_a, group_b in", "state, proto_game_info): # Set attributes from new state before on_step.\"\"\"", "worker is en route to build it. This also includes", "if th: owned[el] = th return owned def can_feed(self, unit_type:", "use: from sc2.data import Alert if self.alert(Alert.AddOnComplete): print(\"Addon Complete\") Alert", "= pos.position.to2.rounded return self.state.visibility[pos] == 2 def has_creep(self, pos: Union[Point2,", "* (1/16) @property def time_formatted(self) -> str: \"\"\" Returns time", "self.start_location.distance_to(r.top_center), ) except ValueError: # Hardcoded hotfix for Honorgrounds LE", "Example usage: units_abilities = await self.get_available_abilities(self.units) or units_abilities = await", "if it is lower, it will prefer sending workers to", "+ center_x, offset[1] + center_y)) for offset in offsets) #", "possible_mining_places: possible_mining_places = deficit_mining_places # find closest mining place current_place", "mineral.distance_to(current_place) <= 8 ] target_mineral = max(local_minerals, key=lambda mineral: mineral.mineral_contents)", "building_type == AbilityId: building = self._game_data.abilities[building.value] r = await self._client.query_building_placement(building,", "return -16 + 32 * self._game_info.terrain_height[pos] / 255 def in_placement_grid(self,", "class. \"\"\" def on_start(self): \"\"\" Allows initializing the bot when", "itertools import logging import math import random from collections import", "near is not None: near = near.to2 else: return p", "more units. Right know only checks cooldown, energy cost, and", "Doesn't include workers in production self.supply_cap: Union[float, int] = None", "count this structure twice (once from the SCV order, and", "Union[int, float] = 10, location: Optional[Point2] = None ): \"\"\"", "is a gas extraction site, go there if current_place.vespene_contents: actions.append(worker.gather(current_place))", "if current_action.ability.id != action.ability: # different action, return true return", "grid points. Caution: some x and y offset might be", "to cast it. See data_pb2.py (line 161) for the numbers", "numbers 1-5 to make sense\"\"\" assert isinstance(unit, Unit) assert isinstance(ability_id,", "closest async def distribute_workers(self, resource_ratio: float = 2): \"\"\" Distributes", "self.units(half_supply_units).amount % 2 self.supply_used += correction self.supply_army += correction self.supply_left", "not in self._units_previous_map: await self.on_unit_created(unit) for unit in self.units.structure: if", "self.cached_main_base_ramp # The reason for len(ramp.upper) in {2, 5} is:", "self._client: \"Client\" = client self._game_info: \"GameInfo\" = game_info self._game_data: GameData", "self.townhalls: self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self,", "isinstance(target, (type(None), Unit, Point2, Point3)) # check if unit has", "Race.Terran or not unit.is_structure: # If an SCV is constructing", "structures in production, counts double for terran \"\"\" abilities_amount =", "we want to return centers = {} # For every", "async def on_start_async(self): \"\"\" This function is run after \"on_start\".", "on the grid point. \"\"\" assert isinstance(pos, (Point2, Point3, Unit))", "None self.vespene: int = None self.supply_army: Union[float, int] = None", "in self.game_info.map_ramps if len(ramp.upper) in {2, 5}), key=lambda r: self.start_location.distance_to(r.top_center),", "\"\"\" if hasattr(self, \"cached_main_base_ramp\"): return self.cached_main_base_ramp # The reason for", "for workers and build queues of buildings. If all_units==True, then", "int = None self.larva_count: int = None self.cached_known_enemy_structures = None", "queens and morphing units) and structures in production, counts double", "in self.townhalls if is_near_to_expansion(x)), None) if th: owned[el] = th", "cost = self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost: enough_supply = self.can_feed(item_id) elif isinstance(item_id,", "to be moved anyways, it will NOT will geysers on", "(AbilityId, UnitTypeId)) assert isinstance(near, Point2) if isinstance(building, UnitTypeId): building =", "Units([]) def _prepare_first_step(self): \"\"\"First step extra preparations. Must not be", "self.units.structure: await self._issue_building_complete_event(unit) if len(self._previous_upgrades) != len(self.state.upgrades): for upgrade_completed in", "SCV order, and once from \"not structure.is_ready\") for unit in", "the main ramp. # The map Acolyte has 4 upper", "ability_target = self._game_data.abilities[ability_id.value]._proto.target # Check if target is in range", "before _prepare_step.\"\"\" if self.townhalls: self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers =", "point result = min(possible_points, key=lambda point: sum(point.distance_to(resource) for resource in", "control, you should write your own distribution function. For example", "remove it from the list deficit_mining_places.remove(current_place) # if current place", "None self.geysers: Units = None self.minerals: int = None self.vespene:", "r: self.start_location.distance_to(r.top_center), ) except ValueError: # Hardcoded hotfix for Honorgrounds", "cached_abilities_of_unit else: abilities = (await self.get_available_abilities([unit]))[0] if ability_id in abilities:", "less than target ratio if self.vespene and self.minerals / self.vespene", "point. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded", "triggers the following functions: - on_unit_created - on_unit_destroyed - on_building_construction_complete", "async def on_unit_created(self, unit: Unit): \"\"\" Override this in your", "same action, remove action if same target position return False", "the minerals he could mine at that base # get", "Override this in your bot class. Note that this function", "you have enough free supply to build the unit \"\"\"", "minerals near a base if we have too many workers", ") # Required for events self._units_previous_map: Dict = {unit.tag: unit", "for distance in range(placement_step, max_distance, placement_step): possible_positions = [ Point2(p).offset(near).to2", "zerglings and banelings. This function corrects the bad values. \"\"\"", "expansion. \"\"\" if not building: # self.race is never Race.Random", "await self._issue_unit_dead_events() await self._issue_unit_added_events() for unit in self.units.structure: await self._issue_building_complete_event(unit)", "used in sc2ai ladder games http://sc2ai.net/ # The bot ID", "self.can_afford_vespene = can_afford_vespene self.have_enough_supply = have_enough_supply def __bool__(self): return self.can_afford_minerals", "TransformationComplete UnitUnderAttack UpgradeComplete VespeneExhausted WarpInComplete \"\"\" assert isinstance(alert_code, Alert), f\"alert_code", "work at that gather site local_workers = self.workers.filter( lambda unit:", "p)) async def do(self, action): if not self.can_afford(action): logger.warning(f\"Cannot afford", "placed in the given location.\"\"\" building_type = type(building) assert building_type", "bases for every missing worker else: deficit_mining_places += [mining_place for", "and unit.order_target == bases.closest_to(mining_place).tag) ) else: # get tags of", "import AbilityData, GameData # imports for mypy and pycharm autocomplete", "if not actions: return None if prevent_double: actions = list(filter(self.prevent_double_actions,", "following functions: - on_unit_created - on_unit_destroyed - on_building_construction_complete \"\"\" await", "isinstance(unit, Unit) assert isinstance(ability_id, AbilityId) assert isinstance(target, (type(None), Unit, Point2,", "AbilityId], check_supply_cost: bool = True ) -> \"CanAffordWrapper\": \"\"\"Tests if", "self.state.mineral_field if mineral.distance_to(current_place) <= 8 ] target_mineral = max(local_minerals, key=lambda", "def _prepare_start(self, client, player_id, game_info, game_data): \"\"\"Ran until game start", "sense\"\"\" assert isinstance(unit, Unit) assert isinstance(ability_id, AbilityId) assert isinstance(target, (type(None),", "= None self.vespene: int = None self.supply_army: Union[float, int] =", "= self._game_data.abilities[ability_id.value]._proto.target # Check if target is in range (or", "units. Right know only checks cooldown, energy cost, and whether", "Point3, Unit]) -> bool: \"\"\" Returns True if you have", "return 0 return order.progress return 0 @property_cache_once_per_frame def _abilities_all_units(self) ->", "available. \"\"\" async def on_start_async(self): \"\"\" This function is run", "# too few workers # add mining place to deficit", "True # Check if able to use ability on a", "position offset_range = 7 offsets = [ (x, y) for", "None self.townhalls: Units = None self.geysers: Units = None self.minerals:", "= state.common.army_count # reset cached values self.cached_known_enemy_structures = None self.cached_known_enemy_units", "to the opponent self.opponent_id: int = None self.units: Units =", "See game_state.py # update pathing grid self._game_info.pathing_grid: PixelMap = PixelMap(", "# Required for events self._units_previous_map: Dict = {unit.tag: unit for", "group: for resources in resource_groups: # Possible expansion points amount", "step. Example use: from sc2.data import Alert if self.alert(Alert.AddOnComplete): print(\"Addon", "units, structures only.\"\"\" return self.state.enemy_units.structure @property def main_base_ramp(self) -> \"Ramp\":", "return None for distance in range(placement_step, max_distance, placement_step): possible_positions =", "Unit)), f\"pos is not of type Point2, Point3 or Unit\"", "pycharm autocomplete from .game_state import GameState from .game_data import GameData,", "of type Point2, Point3 or Unit\" pos = pos.position.to2.rounded return", "Distributes workers across all the bases taken. Keyword `resource_ratio` takes", "Point3, Unit]) -> int: \"\"\" Returns terrain height at a", "than `resource_ratio`, this function prefer filling geysers first, if it", "UnitTypeId): unit = self._game_data.units[item_id.value] cost = self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost: enough_supply", "Point2) if isinstance(building, UnitTypeId): building = self._game_data.units[building.value].creation_ability else: # AbilityId", "r == ActionResult.Success] if not possible: continue if random_alternative: return", "would count this structure twice # (once from the SCV", "\"\"\" Allows initializing the bot when the game data is", "# Idea: create a group for every resource, then merge", "GameData # imports for mypy and pycharm autocomplete from .game_state", "If the current minerals to gas ratio is bigger than", "for worker in local_workers[:difference]: worker_pool.append(worker) # too few workers #", "def select_build_worker(self, pos: Union[Unit, Point2, Point3], force: bool = False)", "AbilityId building = self._game_data.abilities[building.value] if await self.can_place(building, near): return near", "1: researching 1: finished \"\"\" assert isinstance(upgrade_type, UpgradeId) if upgrade_type", "None if \"LEVEL\" in upgrade_type.name: level = upgrade_type.name[-1] creationAbilityID =", "self.supply_used += correction self.supply_army += correction self.supply_left -= correction async", "production self.supply_cap: Union[float, int] = None self.supply_used: Union[float, int] =", "not exist any more. \"\"\" async def on_unit_created(self, unit: Unit):", "< self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion, self.townhalls)): # already taken continue startp", "includes all worker orders (including pending). Zerg units in production", "Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool = True ) -> \"CanAffordWrapper\":", "self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene else: logger.error(f\"Error: {r}", "# same action, remove action if same target position return", "return self._game_info.placement_grid[pos] == 1 def in_pathing_grid(self, pos: Union[Point2, Point3, Unit])", "resource, then merge these groups if # any resource in", "self._game_data.abilities[building.value] if await self.can_place(building, near): return near if max_distance ==", "int = None self.cached_known_enemy_structures = None self.cached_known_enemy_units = None @property", "chat_send(self, message: str): \"\"\" Send a chat message. \"\"\" assert", "int = state.common.food_army self.supply_workers: int = state.common.food_workers # Doesn't include", "to cast or if ability is on cooldown if cached_abilities_of_unit:", "try: if current_action.target == action.target.tag: # same action, remove action", "in your bot class. Note that this function is also", "= min( (ramp for ramp in self.game_info.map_ramps if len(ramp.upper) in", "building_type in {AbilityData, AbilityId, UnitTypeId} if building_type == UnitTypeId: building", "merge these groups if # any resource in a group", "self.workers.filter(lambda w: (w.is_gathering or w.is_idle) and w.distance_to(pos) < 20) or", "the opponent self.opponent_id: int = None self.units: Units = None", "if ( ability_target == 1 or ability_target == Target.PointOrNone.value and", "get_next_expansion(self) -> Optional[Point2]: \"\"\"Find next expansion location.\"\"\" closest = None", "or (unit.is_carrying_minerals and unit.order_target == mining_place.tag) ) # too many", "BuildingUnderAttack LarvaHatched MergeComplete MineralsExhausted MorphComplete MothershipComplete MULEExpired NuclearLaunchDetected NukeComplete NydusWormDetected", "\"GameInfo\" = game_info self._game_data: GameData = game_data self.player_id: int =", "self.cached_known_enemy_structures = None self.cached_known_enemy_units = None @property def enemy_race(self) ->", "MineralsExhausted MorphComplete MothershipComplete MULEExpired NuclearLaunchDetected NukeComplete NydusWormDetected ResearchComplete TrainError TrainUnitComplete", "list of places that need more workers deficit_mining_places = []", "\"on_start\". At this point, game_data, game_info and the first iteration", "correction self.supply_army += correction self.supply_left -= correction async def get_available_abilities(", "int = state.common.larva_count # Workaround Zerg supply rounding bug self._correct_zerg_supply()", "= min(deficit_mining_places, key=lambda place: place.distance_to(worker)) # remove it from the", "game step (looped in realtime mode).\"\"\" raise NotImplementedError def on_end(self,", "Returns True if there is creep on the grid point.", "in self.game_info.map_ramps if len(ramp.upper) in {4, 9}), key=lambda r: self.start_location.distance_to(r.top_center),", "can_cast( self, unit: Unit, ability_id: AbilityId, target: Optional[Union[Unit, Point2, Point3]]", "5} is: # ParaSite map has 5 upper points, and", "return await self._client.query_available_abilities(units, ignore_resource_requirements) async def expand_now( self, building: UnitTypeId", "_prepare_step.\"\"\" if self.townhalls: self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers()", "This function corrects the bad values. \"\"\" # TODO: remove", "for unit in self.units.structure: if unit.tag not in self._units_previous_map: await", "to the start position). try: self.cached_main_base_ramp = min( (ramp for", "-> Units: \"\"\"List of known enemy units, including structures.\"\"\" return", "the pool for worker in worker_pool: # as long as", "Keyword `resource_ratio` takes a float. If the current minerals to", "left else: local_minerals = [ mineral for mineral in self.state.mineral_field", "long distance mining control and moving workers if a base", "def _abilities_all_units(self) -> Counter: \"\"\" Cache for the already_pending function,", "y) for x, y in itertools.product(range(-offset_range, offset_range + 1), repeat=2)", "workers across all the bases taken. Keyword `resource_ratio` takes a", "isinstance(unit_type, UpgradeId): return self.already_pending_upgrade(unit_type) ability = self._game_data.units[unit_type.value].creation_ability amount = len(self.units(unit_type).not_ready)", "building = self._game_data.abilities[building.value] r = await self._client.query_building_placement(building, [position]) return r[0]", "ability has been researched. Example usage: units_abilities = await self.get_available_abilities(self.units)", "count this structure twice # (once from the SCV order,", "different action, return true return True try: if current_action.target ==", "ability is on cooldown if cached_abilities_of_unit: abilities = cached_abilities_of_unit else:", "( not worker.orders or len(worker.orders) == 1 and worker.orders[0].ability.id in", "self.race: Race = Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict = dict() self._previous_upgrades: Set[UpgradeId]", "= self.workers.filter( lambda unit: unit.order_target in local_minerals_tags or (unit.is_carrying_minerals and", "workers and mining places if deficit_mining_places: # choose only mineral", "type Point2, Point3 or Unit\" pos = pos.position.to2.rounded return self._game_info.terrain_height[pos]", "grid self._game_info.pathing_grid: PixelMap = PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False ) #", "+= 1 return abilities_amount @property_cache_once_per_frame def _abilities_workers_and_eggs(self) -> Counter: \"\"\"", "Carriers (Interceptors) or Oracles (Stasis Ward)) are also included. \"\"\"", "if not location: location = await self.get_next_expansion() await self.build(building, near=location,", "== ActionResult.Success] if not possible: continue if random_alternative: return random.choice(possible)", "MorphComplete MothershipComplete MULEExpired NuclearLaunchDetected NukeComplete NydusWormDetected ResearchComplete TrainError TrainUnitComplete TrainWorkerComplete", "for el in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD", "every combination of two groups for group_a, group_b in itertools.combinations(resource_groups,", "same target unit return False except AttributeError: pass try: if", "is near and has the most minerals left else: local_minerals", "if r == ActionResult.Success] if not possible: continue if random_alternative:", "unit.orders: abilities_amount[order.ability] += 1 if not unit.is_ready: if self.race !=", "Units: \"\"\"List of known enemy units, structures only.\"\"\" return self.state.enemy_units.structure", "have enough space to point and all(point.distance_to(resource) > (7 if", "self.cached_known_enemy_units = None @property def enemy_race(self) -> Race: assert len(self._game_info.player_races)", ".pixel_map import PixelMap from .position import Point2, Point3 from .unit", "@property_cache_once_per_frame def known_enemy_units(self) -> Units: \"\"\"List of known enemy units,", "False except AttributeError: pass try: if action.target.x == current_action.target.x and", "for resource in resources) / amount) + 0.5 possible_points =", "in structure.orders: if order.ability.id is creationAbilityID: if level and order.ability.button_name[-1]", "first iteration of game_state (self.state) are available. \"\"\" async def", "self.workers.filter( lambda unit: unit.order_target == mining_place.tag or (unit.is_carrying_vespene and unit.order_target", "(type(None), Unit, Point2, Point3)) # check if unit has enough", "self._client.chat_send(message, False) # For the functions below, make sure you", "r async def do_actions(self, actions: List[\"UnitCommand\"], prevent_double=True): \"\"\" Unlike 'self.do()',", "Allows initializing the bot when the game data is available.", "if self.alert(Alert.AddOnComplete): print(\"Addon Complete\") Alert codes: AlertError AddOnComplete BuildingComplete BuildingUnderAttack", "-> List[List[AbilityId]]: \"\"\" Returns available abilities of one or more", "self.supply_cap - self.supply_used if self.race == Race.Zerg: self.larva_count: int =", "\"\"\"Tests if a building can be placed in the given", "can_afford_vespene self.have_enough_supply = have_enough_supply def __bool__(self): return self.can_afford_minerals and self.can_afford_vespene", "r: self.start_location.distance_to(r.top_center), ) return self.cached_main_base_ramp @property_cache_forever def expansion_locations(self) -> Dict[Point2,", "position elif ( ability_target in {Target.Point.value, Target.PointOrUnit.value} and isinstance(target, (Point2,", "is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True", "every worker in the pool for worker in worker_pool: #", "unit.order_target == mining_place.tag) ) # too many workers if difference", "building can be placed in the given location.\"\"\" building_type =", ".ids.unit_typeid import UnitTypeId from .ids.upgrade_id import UpgradeId from .pixel_map import", "all resources have enough space to point and all(point.distance_to(resource) >", "# get all workers that target the gas extraction site", "worker.is_idle and all_minerals_near_base: target_mineral = min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral))", "start position). try: self.cached_main_base_ramp = min( (ramp for ramp in", "position. Caution: terrain height is different from a unit's z-coordinate.", "use ability on a position elif ( ability_target in {Target.Point.value,", "0: not started 0 < x < 1: researching 1:", "return CanAffordWrapper(cost.minerals <= self.minerals, cost.vespene <= self.vespene, enough_supply) async def", "async def on_step(self, iteration: int): \"\"\"Ran on every game step", "researched Return values: 0: not started 0 < x <", "/ (1/1.4) * (1/16) @property def time_formatted(self) -> str: \"\"\"", "prevent_double: actions = list(filter(self.prevent_double_actions, actions)) for action in actions: cost", "2): \"\"\" Distributes workers across all the bases taken. Keyword", "self._client.actions(action) if not r: # success cost = self._game_data.calculate_ability_cost(action.ability) self.minerals", "for order in egg.orders: abilities_amount[order.ability] += 1 if self.race !=", "offset_range + 1), repeat=2) if math.hypot(x, y) <= 8 ]", "if check_supply_cost: enough_supply = self.can_feed(item_id) elif isinstance(item_id, UpgradeId): cost =", "ramp in self.game_info.map_ramps if len(ramp.upper) in {4, 9}), key=lambda r:", "continue if d < distance: distance = d closest =", "level = None if \"LEVEL\" in upgrade_type.name: level = upgrade_type.name[-1]", "ability on a position elif ( ability_target in {Target.Point.value, Target.PointOrUnit.value}", "actions: List[\"UnitCommand\"], prevent_double=True): \"\"\" Unlike 'self.do()', this function does not", "instantly subtract minerals and vespene. \"\"\" if not actions: return", "Returns time as string in min:sec format \"\"\" t =", "self._units_previous_map[unit.tag] if unit_prev.build_progress < 1: await self.on_building_construction_complete(unit) async def _issue_unit_dead_events(self):", "if mineral.distance_to(current_place) <= 8 ] target_mineral = max(local_minerals, key=lambda mineral:", "all_units: bool = True) -> int: \"\"\" Returns a number", "len(self._game_info.player_races) == 2, \"enemy_race not available\" self.enemy_id = 3 -", "self.townhalls: Units = self.units(race_townhalls[self.race]) self.geysers: Units = self.units(race_gas[self.race]) self.minerals: int", "o in u.orders]) else: amount += sum([o.ability == ability for", "\"\"\"Base class for bots.\"\"\" EXPANSION_GAP_THRESHOLD = 15 def __init__(self): #", "from .game_data import GameData, AbilityData from .ids.ability_id import AbilityId from", "self.vespene: int = None self.supply_army: Union[float, int] = None self.supply_workers:", "structure twice (once from the SCV order, and once from", "we have too many workers # and need to send", "UnitTypeId = None, max_distance: Union[int, float] = 10, location: Optional[Point2]", "el) if d is None: continue if d < distance:", "= self.time return f\"{int(t // 60):02}:{int(t % 60):02}\" @property def", "moved anyways, it will NOT will geysers on its own.", "already_pending would count this structure twice (once from the SCV", "expansions owned by the player.\"\"\" owned = {} for el", "= await self.get_available_abilities(self.units) or units_abilities = await self.get_available_abilities([self.units.random]) \"\"\" return", "self._game_info def alert(self, alert_code: Alert) -> bool: \"\"\" Check if", "self.units.structure.not_ready: # type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount def", "-= correction async def get_available_abilities( self, units: Union[List[Unit], Units], ignore_resource_requirements=False", "Ramp instance of the closest main-ramp to start location. Look", "that gather site local_workers = self.workers.filter( lambda unit: unit.order_target in", "Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY, } building = start_townhall_type[self.race] assert isinstance(building,", "# tags of the minerals he could mine at that", "a grid point. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos", "in zip(res, possible_positions) if r == ActionResult.Success] if not possible:", "= True break # Distance offsets we apply to center", "= state.common.food_cap self.supply_used: int = state.common.food_used self.supply_left: int = self.supply_cap", "UnitTypeId) if not location: location = await self.get_next_expansion() await self.build(building,", "UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True,", "for building.\"\"\" assert isinstance(building, (AbilityId, UnitTypeId)) assert isinstance(near, Point2) if", "you can place something at a position. Remember, buildings usually", "unit: unit.is_structure and unit.is_ready): for order in structure.orders: if order.ability.id", "WarpInComplete \"\"\" assert isinstance(alert_code, Alert), f\"alert_code {alert_code} is no Alert\"", "Units = None self.townhalls: Units = None self.geysers: Units =", "or not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) async", "a position. Caution: terrain height is different from a unit's", "Unit for order in unit.orders: abilities_amount[order.ability] += 1 if not", "unit: Unit): \"\"\" Override this in your bot class. \"\"\"", "+ [(-distance, dy) for dy in range(-distance, distance + 1,", "elif building_type == AbilityId: building = self._game_data.abilities[building.value] r = await", "pos = pos.position.to2.rounded return self._game_info.terrain_height[pos] # returns int def get_terrain_z_height(self,", "= self.units(race_gas[self.race]) self.minerals: int = state.common.minerals self.vespene: int = state.common.vespene", "or if a worker is en route to build it.", "\"\"\" Distributes workers across all the bases taken. Keyword `resource_ratio`", "to gas ratio is less than target ratio if self.vespene", "found_something = True while found_something: found_something = False # Check", "random_alternative, placement_step) if p is None: return ActionResult.CantFindPlacementLocation unit =", "a building can be placed in the given location.\"\"\" building_type", "self.have_enough_supply @property def action_result(self): if not self.can_afford_vespene: return ActionResult.NotEnoughVespene elif", "points at the main ramp. # The map Acolyte has", ") return self.cached_main_base_ramp @property_cache_forever def expansion_locations(self) -> Dict[Point2, Units]: \"\"\"", "resources) / amount) + 0.5 center_y = int(sum(resource.position.y for resource", "the most minerals left else: local_minerals = [ mineral for", "be a valid enum name return True # Check if", "_issue_building_complete_event(self, unit): if unit.build_progress < 1: return if unit.tag not", "= 20, random_alternative: bool = True, placement_step: int = 2,", "unit.distance_to(target) <= cast_range ): return True # Check if able", "structures.\"\"\" return self.state.enemy_units @property_cache_once_per_frame def known_enemy_structures(self) -> Units: \"\"\"List of", "a placement location for building.\"\"\" assert isinstance(building, (AbilityId, UnitTypeId)) assert", "recommended as this function uses 'self.do' (reduces performance). Finds the", "is creationAbilityID: if level and order.ability.button_name[-1] != level: return 0", "+= correction self.supply_left -= correction async def get_available_abilities( self, units:", "place to deficit bases for every missing worker else: deficit_mining_places", "self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost: enough_supply = self.can_feed(item_id) elif isinstance(item_id, UpgradeId): cost", "Unit]) -> bool: \"\"\" Returns True if a unit can", "-= cost.vespene else: logger.error(f\"Error: {r} (action: {action})\") return r async", "value. \"\"\" # Idea: create a group for every resource,", "odd number of zerglings and banelings. This function corrects the", "try: self.cached_main_base_ramp = min( (ramp for ramp in self.game_info.map_ramps if", "Not recommended as this function uses 'self.do' (reduces performance). Finds", "@property def enemy_start_locations(self) -> List[Point2]: \"\"\"Possible start locations for enemies.\"\"\"", "<= cast_range ): # cant replace 1 with \"Target.None.value\" because", "in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit) and unit.distance_to(target) <= cast_range", "True break # Distance offsets we apply to center of", "action if same target position return False except AttributeError: pass", "production, counts double for terran \"\"\" abilities_amount = Counter() for", "in_pathing_grid(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True", "target unit return False except AttributeError: pass try: if action.target.x", "http://sc2ai.net/ # The bot ID will stay the same each", "as we change something found_something = True while found_something: found_something", "closer than threshold together if any( resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD for", "= mining_place.surplus_harvesters # perfect amount of workers, skip mining place", "pair of resource of these groups is closer than threshold", "return abilities_amount def already_pending(self, unit_type: Union[UpgradeId, UnitTypeId], all_units: bool =", "codes: AlertError AddOnComplete BuildingComplete BuildingUnderAttack LarvaHatched MergeComplete MineralsExhausted MorphComplete MothershipComplete", "already taken continue startp = self._game_info.player_start_location d = await self._client.query_pathing(startp,", "random.choice(possible) else: return min(possible, key=lambda p: p.distance_to_point2(near)) return None def", "current minerals to gas ratio is bigger than `resource_ratio`, this", "around expansion local_minerals_tags = { mineral.tag for mineral in self.state.mineral_field", "alert(self, alert_code: Alert) -> bool: \"\"\" Check if alert is", "for every missing worker else: deficit_mining_places += [mining_place for _", "CanAffordWrapper(cost.minerals <= self.minerals, cost.vespene <= self.vespene, enough_supply) async def can_cast(", "= state # See game_state.py # update pathing grid self._game_info.pathing_grid:", "= ( self.workers.filter(lambda w: (w.is_gathering or w.is_idle) and w.distance_to(pos) <", "return True if action.unit.orders: # action: UnitCommand # current_action: UnitOrder", "def get_terrain_z_height(self, pos: Union[Point2, Point3, Unit]) -> int: \"\"\" Returns", "= [ mineral for mineral in self.state.mineral_field if any(mineral.distance_to(base) <=", "find expansion position offset_range = 7 offsets = [ (x,", "places if not possible_mining_places: possible_mining_places = deficit_mining_places # find closest", "and mining places if deficit_mining_places: # choose only mineral fields", "unit return False except AttributeError: pass try: if action.target.x ==", "2, ) -> Optional[Point2]: \"\"\"Finds a placement location for building.\"\"\"", "< 1: return if unit.tag not in self._units_previous_map: return unit_prev", "+ 1, placement_step)] + [(distance, dy) for dy in range(-distance,", "= None ): \"\"\" Not recommended as this function uses", "many workers if difference > 0: for worker in local_workers[:difference]:", "def _prepare_step(self, state, proto_game_info): # Set attributes from new state", "None async def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId], position: Point2)", "cost, and whether the ability has been researched. Example usage:", "FIXME: SCV building a structure might be counted as two", "owned_expansions(self) -> Dict[Point2, Unit]: \"\"\"List of expansions owned by the", "misplace the expansion. \"\"\" if not building: # self.race is", "bases taken. Keyword `resource_ratio` takes a float. If the current", "\"\"\"List of known enemy units, including structures.\"\"\" return self.state.enemy_units @property_cache_once_per_frame", "in deficit_mining_places if not place.vespene_contents] # else prefer gas else:", "self._game_info.pathing_grid[pos] == 1 def is_visible(self, pos: Union[Point2, Point3, Unit]) ->", "owned[el] = th return owned def can_feed(self, unit_type: UnitTypeId) ->", "# / (1/1.4) * (1/16) @property def time_formatted(self) -> str:", "self.workers.idle] bases = self.townhalls.ready geysers = self.geysers.ready # list of", "any(map(is_near_to_expansion, self.townhalls)): # already taken continue startp = self._game_info.player_start_location d", "unit in self.units} self.units: Units = state.own_units self.workers: Units =", "self.time return f\"{int(t // 60):02}:{int(t % 60):02}\" @property def game_info(self)", "-> Counter: \"\"\" Cache for the already_pending function, includes all", "self.supply_left -= correction async def get_available_abilities( self, units: Union[List[Unit], Units],", "def on_start(self): \"\"\" Allows initializing the bot when the game", "start location. Look in game_info.py for more information \"\"\" if", "self.townhalls.ready geysers = self.geysers.ready # list of places that need", "pass await self.do_actions(actions) @property def owned_expansions(self) -> Dict[Point2, Unit]: \"\"\"List", "force: bool = False) -> Optional[Unit]: \"\"\"Select a worker to", "resource_groups = [[resource] for resource in self.state.resources] # Loop the", "for the numbers 1-5 to make sense\"\"\" assert isinstance(unit, Unit)", "in range(-distance, distance + 1, placement_step)] + [(distance, dy) for", "a unit's z-coordinate. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)), f\"pos", "None: continue if d < distance: distance = d closest", "return True async def chat_send(self, message: str): \"\"\" Send a", "add actions if queued if action.queue: return True if action.unit.orders:", "at a position. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)), f\"pos", "imports for mypy and pycharm autocomplete from .game_state import GameState", "for ramp in self.game_info.map_ramps if len(ramp.upper) in {4, 9}), key=lambda", "0.5 possible_points = (Point2((offset[0] + center_x, offset[1] + center_y)) for", "wrong ramp (which is closest to the start position). try:", "Right know only checks cooldown, energy cost, and whether the", "# Check if able to use ability on a unit", "not started 0 < x < 1: researching 1: finished", "Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.placement_grid[pos] == 1 def", "def alert(self, alert_code: Alert) -> bool: \"\"\" Check if alert", "UnitTypeId, near: Union[Unit, Point2, Point3], max_distance: int = 20, random_alternative:", "unit in self.units.structure.not_ready: # type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return", "UnitTypeId)) assert isinstance(near, Point2) if isinstance(building, UnitTypeId): building = self._game_data.units[building.value].creation_ability", "hasattr(self, \"cached_main_base_ramp\"): return self.cached_main_base_ramp # The reason for len(ramp.upper) in", "any pair of resource of these groups is closer than", "half_supply_units = { UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, } correction", "-> \"GameInfo\": return self._game_info def alert(self, alert_code: Alert) -> bool:", "usage: units_abilities = await self.get_available_abilities(self.units) or units_abilities = await self.get_available_abilities([self.units.random])", "killed are not being handled. WARNING: This is quite slow", "checks cooldown, energy cost, and whether the ability has been", "math.inf for el in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) <", "elif isinstance(item_id, UpgradeId): cost = self._game_data.upgrades[item_id.value].cost else: cost = self._game_data.calculate_ability_cost(item_id)", "closest main-ramp to start location. Look in game_info.py for more", "in deficit_mining_places if place.vespene_contents] # if preferred type is not", "self.state.mineral_field or not self.workers or not self.townhalls.ready: return actions =", "place in deficit_mining_places if not place.vespene_contents] # else prefer gas", "} correction = self.units(half_supply_units).amount % 2 self.supply_used += correction self.supply_army", "not building: # self.race is never Race.Random start_townhall_type = {", "free mining spots # send to closest if worker is", "self.workers for o in w.orders]) amount += sum([egg.orders[0].ability == ability", "async def on_building_construction_started(self, unit: Unit): \"\"\" Override this in your", "if unit.tag not in self._units_previous_map: await self.on_unit_created(unit) for unit in", "str: \"\"\" Returns time as string in min:sec format \"\"\"", ".unit import Unit from .units import Units logger = logging.getLogger(__name__)", "# Check if point can be built on if self._game_info.placement_grid[point.rounded]", "Oracles (Stasis Ward)) are also included. \"\"\" # TODO /", "return self.state.visibility[pos] == 2 def has_creep(self, pos: Union[Point2, Point3, Unit])", "p: p.distance_to_point2(near)) return None def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int,", "all workers that target the gas extraction site # or", "None if prevent_double: actions = list(filter(self.prevent_double_actions, actions)) for action in", "proto_game_info): # Set attributes from new state before on_step.\"\"\" self.state:", "int = state.common.food_used self.supply_left: int = self.supply_cap - self.supply_used if", "enemy_start_locations(self) -> List[Point2]: \"\"\"Possible start locations for enemies.\"\"\" return self._game_info.start_locations", "# Calculate center, round and add 0.5 because expansion location", "centers[result] = resources return centers def _correct_zerg_supply(self): \"\"\" The client", "if the player has enough resources to build a unit", "-distance) for dx in range(-distance, distance + 1, placement_step)] +", "1 def _prepare_start(self, client, player_id, game_info, game_data): \"\"\"Ran until game", "\"\"\" Check if alert is triggered in the current step.", "def _prepare_first_step(self): \"\"\"First step extra preparations. Must not be called", "on cooldown if cached_abilities_of_unit: abilities = cached_abilities_of_unit else: abilities =", "class. Note that this function uses unit tags because the", "function will be automatically run from main.py and triggers the", "Unit]: \"\"\"List of expansions owned by the player.\"\"\" owned =", "AbilityData, GameData # imports for mypy and pycharm autocomplete from", "async def do_actions(self, actions: List[\"UnitCommand\"], prevent_double=True): \"\"\" Unlike 'self.do()', this", "logging.getLogger(__name__) class BotAI: \"\"\"Base class for bots.\"\"\" EXPANSION_GAP_THRESHOLD = 15", "main base ramp with inbase natural self.cached_main_base_ramp = min( (ramp", "self.minerals -= cost.minerals self.vespene -= cost.vespene return await self._client.actions(actions) def", "import ActionResult, Attribute, Race, race_worker, race_townhalls, race_gas, Target, Result from", "= self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self, state, proto_game_info):", "game_info and the first iteration of game_state (self.state) are available.", "message. \"\"\" assert isinstance(message, str), f\"{message} is no string\" await", "is not idle # so dont move him pass await", "# and need to send them to the closest patch", "8.5 geysers = self.state.vespene_geyser # Create a group for every", "self.game_info.map_ramps if len(ramp.upper) in {4, 9}), key=lambda r: self.start_location.distance_to(r.top_center), )", "extra preparations. Must not be called before _prepare_step.\"\"\" if self.townhalls:", "exist any more. \"\"\" async def on_unit_created(self, unit: Unit): \"\"\"", "= self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene else: logger.error(f\"Error:", "points. Caution: some x and y offset might be required,", "more, get all other places if not possible_mining_places: possible_mining_places =", "UnitCommand # current_action: UnitOrder current_action = action.unit.orders[0] if current_action.ability.id !=", "Target.PointOrUnit.value} and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range ):", "if any(map(is_near_to_expansion, self.townhalls)): # already taken continue startp = self._game_info.player_start_location", "same each game so your bot can \"adapt\" to the", "await self.do(unit.build(building, p)) async def do(self, action): if not self.can_afford(action):", "expansion position offset_range = 7 offsets = [ (x, y)", "Alert if self.alert(Alert.AddOnComplete): print(\"Addon Complete\") Alert codes: AlertError AddOnComplete BuildingComplete", "1 with \"Target.None.value\" because \".None\" doesnt seem to be a", "usually use 2x2, 3x3 or 5x5 of these grid points.", "return centers = {} # For every resource group: for", "random_alternative: bool=True, placement_step: int=2): \"\"\"Build a building.\"\"\" if isinstance(near, Unit):", "Returns True if you have vision on a grid point.", "Unit)) pos = pos.position.to2.rounded return self._game_info.placement_grid[pos] == 1 def in_pathing_grid(self,", "because bases have size 5. center_x = int(sum(resource.position.x for resource", "int(sum(resource.position.x for resource in resources) / amount) + 0.5 center_y", "near=location, max_distance=max_distance, random_alternative=False, placement_step=1) async def get_next_expansion(self) -> Optional[Point2]: \"\"\"Find", "not possible_mining_places: possible_mining_places = deficit_mining_places # find closest mining place", "int: \"\"\" Returns terrain z-height at a position. \"\"\" assert", "@property def time_formatted(self) -> str: \"\"\" Returns time as string", "player data.\"\"\" self._client: \"Client\" = client self._game_info: \"GameInfo\" = game_info", "= None async def issue_events(self): \"\"\" This function will be", "= 2, ) -> Optional[Point2]: \"\"\"Finds a placement location for", "all target tags a worker can have # tags of", "when the game data is available. \"\"\" async def on_start_async(self):", "{Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit) and unit.distance_to(target) <= cast_range ):", "== 0 or self.supply_left >= required def can_afford( self, item_id:", "in range(-distance, distance + 1, placement_step)] ) ] res =", "as string in min:sec format \"\"\" t = self.time return", "upper points at the wrong ramp (which is closest to", "alert_code.value in self.state.alerts @property def start_location(self) -> Point2: return self._game_info.player_start_location", "know only checks cooldown, energy cost, and whether the ability", "get all other places if not possible_mining_places: possible_mining_places = deficit_mining_places", "Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount def already_pending(self, unit_type: Union[UpgradeId,", "distance = math.inf for el in self.expansion_locations: def is_near_to_expansion(t): return", "[(dx, distance) for dx in range(-distance, distance + 1, placement_step)]", "\"\"\" Returns available abilities of one or more units. Right", "1 if self.race == Race.Zerg: for egg in self.units(UnitTypeId.EGG): #", "False) -> Optional[Unit]: \"\"\"Select a worker to build a building", "str): \"\"\" Send a chat message. \"\"\" assert isinstance(message, str),", "def on_unit_destroyed(self, unit_tag): \"\"\" Override this in your bot class.", "cant replace 1 with \"Target.None.value\" because \".None\" doesnt seem to", "opponent self.opponent_id: int = None self.units: Units = None self.workers:", "large main base ramp with inbase natural self.cached_main_base_ramp = min(", "self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) async def do(self,", "u.orders]) else: amount += sum([o.ability == ability for w in", "on_building_construction_complete(self, unit: Unit): \"\"\" Override this in your bot class.", "or self.supply_left >= required def can_afford( self, item_id: Union[UnitTypeId, UpgradeId,", "= {} # For every resource group: for resources in", "GameData = game_data self.player_id: int = player_id self.race: Race =", "until game start to set game and player data.\"\"\" self._client:", "-= cost.vespene return await self._client.actions(actions) def prevent_double_actions(self, action): # always", "This is quite slow when there are lots of workers", "in u.orders]) else: amount += sum([o.ability == ability for w", "action.target.x == current_action.target.x and action.target.y == current_action.target.y: # same action,", "\"\"\" Check if an upgrade is being researched Return values:", "if deficit_mining_places: # choose only mineral fields first if current", "self._game_data.units[item_id.value] cost = self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost: enough_supply = self.can_feed(item_id) elif", "mineral.distance_to(mining_place) <= 8 } # get all target tags a", "import math import random from collections import Counter from typing", "first. This is only for workers that need to be", "UpgradeId): cost = self._game_data.upgrades[item_id.value].cost else: cost = self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals", "Set[UpgradeId] = set() self.units: Units = Units([]) def _prepare_first_step(self): \"\"\"First", "math import random from collections import Counter from typing import", "Example use: from sc2.data import Alert if self.alert(Alert.AddOnComplete): print(\"Addon Complete\")", "client, player_id, game_info, game_data): \"\"\"Ran until game start to set", "PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False ) # Required for events self._units_previous_map:", "round and add 0.5 because expansion location will have (x.5,", "# more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3, Unit)) pos", "some x and y offset might be required, see ramp", "a float. If the current minerals to gas ratio is", "else: return min(possible, key=lambda p: p.distance_to_point2(near)) return None def already_pending_upgrade(self,", "key=lambda r: self.start_location.distance_to(r.top_center), ) except ValueError: # Hardcoded hotfix for", "action, remove action if same target position return False except", "int = None self.army_count: int = None self.warp_gate_count: int =", "int def get_terrain_z_height(self, pos: Union[Point2, Point3, Unit]) -> int: \"\"\"", "= None self.warp_gate_count: int = None self.larva_count: int = None", "of these grid points. Caution: some x and y offset", "{ mineral.tag for mineral in self.state.mineral_field if mineral.distance_to(mining_place) <= 8", "assert building_type in {AbilityData, AbilityId, UnitTypeId} if building_type == UnitTypeId:", "action.target.tag: # same action, remove action if same target unit", "min(possible, key=lambda p: p.distance_to_point2(near)) return None def already_pending_upgrade(self, upgrade_type: UpgradeId)", "def start_location(self) -> Point2: return self._game_info.player_start_location @property def enemy_start_locations(self) ->", "+= 1 if self.race != Race.Terran: # If an SCV", "bool: \"\"\" Check if alert is triggered in the current", "{alert_code} is no Alert\" return alert_code.value in self.state.alerts @property def", "group_b) found_something = True break # Distance offsets we apply", "Calculate center, round and add 0.5 because expansion location will", "in self.state.mineral_field if any(mineral.distance_to(base) <= 8 for base in self.townhalls.ready)", "False # Check every combination of two groups for group_a,", "ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if unit is None", "from collections import Counter from typing import Any, Dict, List,", "NuclearLaunchDetected NukeComplete NydusWormDetected ResearchComplete TrainError TrainUnitComplete TrainWorkerComplete TransformationComplete UnitUnderAttack UpgradeComplete", "the player.\"\"\" owned = {} for el in self.expansion_locations: def", "him pass await self.do_actions(actions) @property def owned_expansions(self) -> Dict[Point2, Unit]:", "to deficit bases for every missing worker else: deficit_mining_places +=", "level and order.ability.button_name[-1] != level: return 0 return order.progress return", "are lots of workers or multiple bases. \"\"\" if not", "required, see ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert isinstance(pos, (Point2, Point3,", "# there are no deficit mining places and worker is", "# if current place is a gas extraction site, #", "local_workers[:difference]: worker_pool.append(worker) # too few workers # add mining place", "int] = None self.supply_used: Union[float, int] = None self.supply_left: Union[float,", "self.army_count: int = None self.warp_gate_count: int = None self.larva_count: int", "from .position import Point2, Point3 from .unit import Unit from", "Send a chat message. \"\"\" assert isinstance(message, str), f\"{message} is", "# The reason for len(ramp.upper) in {2, 5} is: #", "assert isinstance(ability_id, AbilityId) assert isinstance(target, (type(None), Unit, Point2, Point3)) #", "not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) async def", "if d < distance: distance = d closest = el", "mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else: # there are no deficit mining", "def _issue_unit_dead_events(self): for unit_tag in self.state.dead_units: await self.on_unit_destroyed(unit_tag) async def", "LarvaHatched MergeComplete MineralsExhausted MorphComplete MothershipComplete MULEExpired NuclearLaunchDetected NukeComplete NydusWormDetected ResearchComplete", "offsets) # Filter out points that are too near possible_points", "game_data self.player_id: int = player_id self.race: Race = Race(self._game_info.player_races[self.player_id]) self._units_previous_map:", "def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD th = next((x for", "Unit]) -> int: \"\"\" Returns terrain z-height at a position.", "researched. Example usage: units_abilities = await self.get_available_abilities(self.units) or units_abilities =", "[] for mining_place in bases | geysers: difference = mining_place.surplus_harvesters", "def chat_send(self, message: str): \"\"\" Send a chat message. \"\"\"", "after \"on_start\". At this point, game_data, game_info and the first", "Race.Zerg: for egg in self.units(UnitTypeId.EGG): # type: Unit for order", "GameState = state # See game_state.py # update pathing grid", "self._previous_upgrades = self.state.upgrades async def _issue_unit_added_events(self): for unit in self.units.not_structure:", "f\"{int(t // 60):02}:{int(t % 60):02}\" @property def game_info(self) -> \"GameInfo\":", "self.do_actions(actions) @property def owned_expansions(self) -> Dict[Point2, Unit]: \"\"\"List of expansions", "<= cast_range ): return True # Check if able to", "buildings. If all_units==True, then build queues of other units (such", "unit \"\"\" required = self._game_data.units[unit_type.value]._proto.food_required return required == 0 or", "possible_positions) possible = [p for r, p in zip(res, possible_positions)", "{unit.tag: unit for unit in self.units} self.units: Units = state.own_units", "self.state.mineral_field if any(mineral.distance_to(base) <= 8 for base in self.townhalls.ready) ]", "unit's z-coordinate. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)), f\"pos is", "or are on their way back from it local_workers =", "build a building with.\"\"\" workers = ( self.workers.filter(lambda w: (w.is_gathering", "this in your bot class. Note that this function uses", "self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self, state, proto_game_info): #", "Required for events self._units_previous_map: Dict = {unit.tag: unit for unit", "\"\"\" # Idea: create a group for every resource, then", "upgrade_type.name: level = upgrade_type.name[-1] creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id for structure in", "(x.5, y.5) # coordinates because bases have size 5. center_x", "Unit\" pos = pos.position.to2.rounded return -16 + 32 * self._game_info.terrain_height[pos]", "return self.can_afford_minerals and self.can_afford_vespene and self.have_enough_supply @property def action_result(self): if", "if await self.can_place(building, near): return near if max_distance == 0:", "True async def chat_send(self, message: str): \"\"\" Send a chat", "valid enum name return True # Check if able to", "in self.townhalls.ready) ] # distribute every worker in the pool", "self.state: GameState = state # See game_state.py # update pathing", "for workers that need to be moved anyways, it will", "on_unit_created(self, unit: Unit): \"\"\" Override this in your bot class.", "Target.PointOrUnit.value} and isinstance(target, Unit) and unit.distance_to(target) <= cast_range ): return", "4 upper points at the wrong ramp (which is closest", "and all structures, and all morphs \"\"\" abilities_amount = Counter()", "self.workers or not self.townhalls.ready: return actions = [] worker_pool =", "the map size. def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) ->", "something found_something = True while found_something: found_something = False #", "< resource_ratio: possible_mining_places = [place for place in deficit_mining_places if", "0.5 center_y = int(sum(resource.position.y for resource in resources) / amount)", "use ability on a unit elif ( ability_target in {Target.Unit.value,", "self.cached_known_enemy_structures = None self.cached_known_enemy_units = None async def issue_events(self): \"\"\"", "resource_a, resource_b in itertools.product(group_a, group_b) ): # Remove the single", "of workers, skip mining place if not difference: continue if", "the bad values. \"\"\" # TODO: remove when Blizzard/sc2client-proto#123 gets", "never Race.Random start_townhall_type = { Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg:", "data is available. \"\"\" async def on_start_async(self): \"\"\" This function", "3x3 or 5x5 of these grid points. Caution: some x", "Units]: \"\"\" Returns dict with the correct expansion position Point2", "self._units_previous_map: await self.on_unit_created(unit) for unit in self.units.structure: if unit.tag not", "get_terrain_z_height(self, pos: Union[Point2, Point3, Unit]) -> int: \"\"\" Returns terrain", "unit): if unit.build_progress < 1: return if unit.tag not in", "# send to closest if worker is doing nothing elif", "-> Optional[Point2]: \"\"\"Finds a placement location for building.\"\"\" assert isinstance(building,", "and pycharm autocomplete from .game_state import GameState from .game_data import", "Target, Result from .game_data import AbilityData, GameData # imports for", "self._game_data.units[building.value].creation_ability else: # AbilityId building = self._game_data.abilities[building.value] if await self.can_place(building,", "state.common.food_army self.supply_workers: int = state.common.food_workers # Doesn't include workers in", "minerals he could mine at that base # get workers", "at that gather site local_workers = self.workers.filter( lambda unit: unit.order_target", "int): \"\"\"Ran on every game step (looped in realtime mode).\"\"\"", "ActionResult, Alert, Race, Result, Target, race_gas, race_townhalls, race_worker from .data", "def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int: \"\"\" Returns", "abilities: if only_check_energy_and_cooldown: return True cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range ability_target =", "[position]) return r[0] == ActionResult.Success async def find_placement( self, building:", "placement_step): possible_positions = [ Point2(p).offset(near).to2 for p in ( [(dx,", "closest if worker is doing nothing elif worker.is_idle and all_minerals_near_base:", "type checking from .cache import property_cache_forever, property_cache_once_per_frame from .data import", "the functions below, make sure you are inside the boundries", "return self.already_pending_upgrade(unit_type) ability = self._game_data.units[unit_type.value].creation_ability amount = len(self.units(unit_type).not_ready) if all_units:", "or cast an ability.\"\"\" enough_supply = True if isinstance(item_id, UnitTypeId):", "once from \"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount @property_cache_once_per_frame", "Remove the single groups and add the merged group resource_groups.remove(group_a)", "all_minerals_near_base = [ mineral for mineral in self.state.mineral_field if any(mineral.distance_to(base)", "run from main.py and triggers the following functions: - on_unit_created", "key=lambda r: self.start_location.distance_to(r.top_center), ) return self.cached_main_base_ramp @property_cache_forever def expansion_locations(self) ->", "# Choose best fitting point result = min(possible_points, key=lambda point:", "def time_formatted(self) -> str: \"\"\" Returns time as string in", "else 6) for resource in resources) ) # Choose best", "enough energy to cast it. See data_pb2.py (line 161) for", "point and all(point.distance_to(resource) > (7 if resource in geysers else", ">= required def can_afford( self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost:", "@property def enemy_race(self) -> Race: assert len(self._game_info.player_races) == 2, \"enemy_race", "units in production (except queens and morphing units) and structures", "your bot can \"adapt\" to the opponent self.opponent_id: int =", "a structure might be counted as two units if isinstance(unit_type,", "attributes from new state before on_step.\"\"\" self.state: GameState = state", "self._client.query_building_placement(building, [position]) return r[0] == ActionResult.Success async def find_placement( self,", "skip mining place if not difference: continue if mining_place.is_vespene_geyser: #", "too many workers # and need to send them to", "all units in production, and all structures, and all morphs", "every resource resource_groups = [[resource] for resource in self.state.resources] #", "available abilities of one or more units. Right know only", "<= 8 ] # Dict we want to return centers", "await self.can_place(building, near): return near if max_distance == 0: return", "max_distance, placement_step): possible_positions = [ Point2(p).offset(near).to2 for p in (", "of each resource group to find expansion position offset_range =", "return abilities_amount @property_cache_once_per_frame def _abilities_workers_and_eggs(self) -> Counter: \"\"\" Cache for", "isinstance(message, str), f\"{message} is no string\" await self._client.chat_send(message, False) #", "add the merged group resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a + group_b) found_something", "lots of workers or multiple bases. \"\"\" if not self.state.mineral_field", "point can be built on if self._game_info.placement_grid[point.rounded] == 1 #", "because \".None\" doesnt seem to be a valid enum name", "race_gas, Target, Result from .game_data import AbilityData, GameData # imports", "a group for every resource, then merge these groups if", "This function is far from optimal, if you really want", "upgrade is being researched Return values: 0: not started 0", "might be required, see ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert isinstance(pos,", "= start_townhall_type[self.race] assert isinstance(building, UnitTypeId) if not location: location =", "on_step.\"\"\" self.state: GameState = state # See game_state.py # update", "Union[Point2, Point3, Unit]) -> int: \"\"\" Returns terrain z-height at", "Doesn't include workers in production self.supply_cap: int = state.common.food_cap self.supply_used:", "closest patch if len(worker_pool) > len(deficit_mining_places): all_minerals_near_base = [ mineral", "return required == 0 or self.supply_left >= required def can_afford(", "itertools.product(range(-offset_range, offset_range + 1), repeat=2) if math.hypot(x, y) <= 8", "-> int: \"\"\" Returns terrain height at a position. Caution:", "def _correct_zerg_supply(self): \"\"\" The client incorrectly rounds zerg supply down", "send to closest if worker is doing nothing elif worker.is_idle", "in self._units_previous_map: await self.on_unit_created(unit) for unit in self.units.structure: if unit.tag", "in the given location.\"\"\" building_type = type(building) assert building_type in", "for every resource resource_groups = [[resource] for resource in self.state.resources]", ".ids.ability_id import AbilityId from .ids.unit_typeid import UnitTypeId from .ids.upgrade_id import", "building: UnitTypeId, near: Union[Unit, Point2, Point3], max_distance: int = 20,", "= self._game_data.units[item_id.value] cost = self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost: enough_supply = self.can_feed(item_id)", "Point3, Unit)) pos = pos.position.to2.rounded return self.state.creep[pos] == 1 def", "start of the game for the starting base building.\"\"\" async", "self.supply_army: int = state.common.food_army self.supply_workers: int = state.common.food_workers # Doesn't", "to gas ratio is bigger than `resource_ratio`, this function prefer", "8 } # get all target tags a worker can", "on_building_construction_started(self, unit: Unit): \"\"\" Override this in your bot class.", "sc2.data import Alert if self.alert(Alert.AddOnComplete): print(\"Addon Complete\") Alert codes: AlertError", "mine at that base # get workers that work at", "(e.g. an enemy unit), it will misplace the expansion. \"\"\"", "get all workers that target the gas extraction site #", "and all_minerals_near_base: target_mineral = min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else:", "item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool = True ) ->", "self.warp_gate_count: int = state.common.warp_gate_count self.idle_worker_count: int = state.common.idle_worker_count self.army_count: int", "== 1 def _prepare_start(self, client, player_id, game_info, game_data): \"\"\"Ran until", "int(sum(resource.position.y for resource in resources) / amount) + 0.5 possible_points", "ability_id in abilities: if only_check_energy_and_cooldown: return True cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range", "is less than target ratio if self.vespene and self.minerals /", "center_x, offset[1] + center_y)) for offset in offsets) # Filter", "r, p in zip(res, possible_positions) if r == ActionResult.Success] if", "self.cached_known_enemy_units = None async def issue_events(self): \"\"\" This function will", "= self._game_data.units[building.value].creation_ability else: # AbilityId building = self._game_data.abilities[building.value] if await", "UnitTypeId from .ids.upgrade_id import UpgradeId from .pixel_map import PixelMap from", "center_y)) for offset in offsets) # Filter out points that", "class CanAffordWrapper: def __init__(self, can_afford_minerals, can_afford_vespene, have_enough_supply): self.can_afford_minerals = can_afford_minerals", "self.race == Race.Protoss: self.warp_gate_count: int = state.common.warp_gate_count self.idle_worker_count: int =", "zip(res, possible_positions) if r == ActionResult.Success] if not possible: continue", "await self.get_available_abilities([self.units.random]) \"\"\" return await self._client.query_available_abilities(units, ignore_resource_requirements) async def expand_now(", "game_info.py for more information \"\"\" if hasattr(self, \"cached_main_base_ramp\"): return self.cached_main_base_ramp", "] # distribute every worker in the pool for worker", "quite slow when there are lots of workers or multiple", "places that need more workers deficit_mining_places = [] for mining_place", "find_placement( self, building: UnitTypeId, near: Union[Unit, Point2, Point3], max_distance: int", "_prepare_step(self, state, proto_game_info): # Set attributes from new state before", "abilities_amount = Counter() for worker in self.workers: # type: Unit", "TrainError TrainUnitComplete TrainWorkerComplete TransformationComplete UnitUnderAttack UpgradeComplete VespeneExhausted WarpInComplete \"\"\" assert", "self.state.enemy_units.structure @property def main_base_ramp(self) -> \"Ramp\": \"\"\" Returns the Ramp", "<= cast_range ): return True return False def select_build_worker(self, pos:", "the already_pending function, includes protoss units warping in, and all", "bool: \"\"\" Checks if you have enough free supply to", "await self._client.actions(action) if not r: # success cost = self._game_data.calculate_ability_cost(action.ability)", "in local_minerals_tags or (unit.is_carrying_minerals and unit.order_target == mining_place.tag) ) #", "None async def issue_events(self): \"\"\" This function will be automatically", "dict() self._previous_upgrades: Set[UpgradeId] = set() self.units: Units = Units([]) def", "-> \"Ramp\": \"\"\" Returns the Ramp instance of the closest", "distance: distance = d closest = el return closest async", "grid point. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos =", "in self.workers for o in w.orders]) amount += sum([egg.orders[0].ability ==", "# The bot ID will stay the same each game", "if action.unit.orders: # action: UnitCommand # current_action: UnitOrder current_action =", "+ 0.5 center_y = int(sum(resource.position.y for resource in resources) /", "position. Remember, buildings usually use 2x2, 3x3 or 5x5 of", "an SCV is constructing a building, already_pending would count this", "message: str): \"\"\" Send a chat message. \"\"\" assert isinstance(message,", "in {2, 5} is: # ParaSite map has 5 upper", "Filter out points that are too near possible_points = (", "space to point and all(point.distance_to(resource) > (7 if resource in", "p.distance_to_point2(near)) return None def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]:", "self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self, state, proto_game_info): # Set attributes", "we group resources by RESOURCE_SPREAD_THRESHOLD = 8.5 geysers = self.state.vespene_geyser", "return False def select_build_worker(self, pos: Union[Unit, Point2, Point3], force: bool", "actions.append(worker.gather(target_mineral)) # more workers to distribute than free mining spots", "for dy in range(-distance, distance + 1, placement_step)] ) ]", "The map Acolyte has 4 upper points at the wrong", "all other places if not possible_mining_places: possible_mining_places = deficit_mining_places #", "action_result(self): if not self.can_afford_vespene: return ActionResult.NotEnoughVespene elif not self.can_afford_minerals: return", "= 3 - self.player_id return Race(self._game_info.player_races[self.enemy_id]) @property def time(self) ->", "prefer gas else: possible_mining_places = [place for place in deficit_mining_places", "preferred type is not available any more, get all other", "values self.cached_known_enemy_structures = None self.cached_known_enemy_units = None async def issue_events(self):", ") else: # get tags of minerals around expansion local_minerals_tags", "if force else None async def can_place(self, building: Union[AbilityData, AbilityId,", "None self.larva_count: int = None self.cached_known_enemy_structures = None self.cached_known_enemy_units =", "# Check if any pair of resource of these groups", "resource in resources) / amount) + 0.5 possible_points = (Point2((offset[0]", "Returns True if you can place something at a position.", "int: \"\"\" Returns terrain height at a position. Caution: terrain", "-> bool: \"\"\" Returns True if you have vision on", "given location.\"\"\" building_type = type(building) assert building_type in {AbilityData, AbilityId,", "it from the list deficit_mining_places.remove(current_place) # if current place is", "self.state.game_loop / 22.4 # / (1/1.4) * (1/16) @property def", "get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int: \"\"\" Returns terrain", ") if workers: for worker in workers.sorted_by_distance_to(pos).prefer_idle: if ( not", "function, includes protoss units warping in, and all units in", "unit: Unit): \"\"\" Override this in your bot class. Note", "is a gas extraction site, # go to the mineral", "def enemy_race(self) -> Race: assert len(self._game_info.player_races) == 2, \"enemy_race not", "correction self.supply_left -= correction async def get_available_abilities( self, units: Union[List[Unit],", "and need to send them to the closest patch if", "Unit]) -> bool: \"\"\" Returns True if there is creep", "at the wrong ramp (which is closest to the start", "the closest main-ramp to start location. Look in game_info.py for", "= player_id self.race: Race = Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict = dict()", "mineral field that is near and has the most minerals", "AbilityId: building = self._game_data.abilities[building.value] r = await self._client.query_building_placement(building, [position]) return", "player.\"\"\" owned = {} for el in self.expansion_locations: def is_near_to_expansion(t):", "of workers or multiple bases. \"\"\" if not self.state.mineral_field or", "for _ in range(-difference)] # prepare all minerals near a", "or self.workers ) if workers: for worker in workers.sorted_by_distance_to(pos).prefer_idle: if", "= None self.supply_left: Union[float, int] = None self.idle_worker_count: int =", "the single groups and add the merged group resource_groups.remove(group_a) resource_groups.remove(group_b)", "worker.orders or len(worker.orders) == 1 and worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER}", "free supply to build the unit \"\"\" required = self._game_data.units[unit_type.value]._proto.food_required", "the bot when the game data is available. \"\"\" async", "await self._client.query_pathing(startp, el) if d is None: continue if d", "next((x for x in self.townhalls if is_near_to_expansion(x)), None) if th:", "TrainUnitComplete TrainWorkerComplete TransformationComplete UnitUnderAttack UpgradeComplete VespeneExhausted WarpInComplete \"\"\" assert isinstance(alert_code,", "= upgrade_type.name[-1] creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id for structure in self.units.filter(lambda unit:", "the next possible expansion via 'self.get_next_expansion()'. If the target expansion", "place.vespene_contents] # else prefer gas else: possible_mining_places = [place for", "t = self.time return f\"{int(t // 60):02}:{int(t % 60):02}\" @property", "Set attributes from new state before on_step.\"\"\" self.state: GameState =", "places and worker is not idle # so dont move", "if not r: # success cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -=", "self.can_afford_vespene: return ActionResult.NotEnoughVespene elif not self.can_afford_minerals: return ActionResult.NotEnoughMinerals elif not", "this function prefer filling geysers first, if it is lower,", "MergeComplete MineralsExhausted MorphComplete MothershipComplete MULEExpired NuclearLaunchDetected NukeComplete NydusWormDetected ResearchComplete TrainError", "for dx in range(-distance, distance + 1, placement_step)] + [(dx,", "== Race.Zerg: self.larva_count: int = state.common.larva_count # Workaround Zerg supply", "[[resource] for resource in self.state.resources] # Loop the merging process", "enemy_race(self) -> Race: assert len(self._game_info.player_races) == 2, \"enemy_race not available\"", "already in progress, or if a worker is en route", "have_enough_supply def __bool__(self): return self.can_afford_minerals and self.can_afford_vespene and self.have_enough_supply @property", "def known_enemy_structures(self) -> Units: \"\"\"List of known enemy units, structures", "any resource of another group # Distance we group resources", "mining place current_place = min(deficit_mining_places, key=lambda place: place.distance_to(worker)) # remove", "in a group is closer than 6 to any resource", "to any resource of another group # Distance we group", "1), repeat=2) if math.hypot(x, y) <= 8 ] # Dict", "from it local_workers = self.workers.filter( lambda unit: unit.order_target == mining_place.tag", "# coordinates because bases have size 5. center_x = int(sum(resource.position.x", "self.state.upgrades: return 1 level = None if \"LEVEL\" in upgrade_type.name:", "minerals to gas ratio is bigger than `resource_ratio`, this function", "at the main ramp. # The map Acolyte has 4", "distribution function. For example long distance mining control and moving", "in production, and all structures, and all morphs \"\"\" abilities_amount", "self.minerals: int = None self.vespene: int = None self.supply_army: Union[float,", "from .data import ActionResult, Alert, Race, Result, Target, race_gas, race_townhalls,", "= cached_abilities_of_unit else: abilities = (await self.get_available_abilities([unit]))[0] if ability_id in", "cooldown, energy cost, and whether the ability has been researched.", "3 - self.player_id return Race(self._game_info.player_races[self.enemy_id]) @property def time(self) -> Union[int,", "from .unit import Unit from .units import Units logger =", "= Units([]) def _prepare_first_step(self): \"\"\"First step extra preparations. Must not", "unit.tag not in self._units_previous_map: await self.on_building_construction_started(unit) async def _issue_building_complete_event(self, unit):", "progress, or if a worker is en route to build", "building = self._game_data.units[building.value].creation_ability elif building_type == AbilityId: building = self._game_data.abilities[building.value]", "): # Remove the single groups and add the merged", "[ (x, y) for x, y in itertools.product(range(-offset_range, offset_range +", "self.race == Race.Zerg: self.larva_count: int = state.common.larva_count # Workaround Zerg", "th = next((x for x in self.townhalls if is_near_to_expansion(x)), None)", "Race.Random start_townhall_type = { Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY,", "select_build_worker(self, pos: Union[Unit, Point2, Point3], force: bool = False) ->", ") -> \"CanAffordWrapper\": \"\"\"Tests if the player has enough resources", "+ 1, placement_step)] + [(-distance, dy) for dy in range(-distance,", "not worker.orders or len(worker.orders) == 1 and worker.orders[0].ability.id in {AbilityId.MOVE,", "then build queues of other units (such as Carriers (Interceptors)", "main.py and triggers the following functions: - on_unit_created - on_unit_destroyed", "time(self) -> Union[int, float]: \"\"\" Returns time in seconds, assumes", "Caution: terrain height is different from a unit's z-coordinate. \"\"\"", "for unit in self.units: # type: Unit for order in", "through a grid point. \"\"\" assert isinstance(pos, (Point2, Point3, Unit))", "can place something at a position. Remember, buildings usually use", "patch if len(worker_pool) > len(deficit_mining_places): all_minerals_near_base = [ mineral for", "cast an ability.\"\"\" enough_supply = True if isinstance(item_id, UnitTypeId): unit", "PixelMap from .position import Point2, Point3 from .unit import Unit", "0 return order.progress return 0 @property_cache_once_per_frame def _abilities_all_units(self) -> Counter:", "Point3 or Unit\" pos = pos.position.to2.rounded return self._game_info.terrain_height[pos] # returns", "<= self.vespene, enough_supply) async def can_cast( self, unit: Unit, ability_id:", "are not being handled. WARNING: This is quite slow when", "automatically run from main.py and triggers the following functions: -", "not self.can_afford_vespene: return ActionResult.NotEnoughVespene elif not self.can_afford_minerals: return ActionResult.NotEnoughMinerals elif", "for events self._units_previous_map: Dict = {unit.tag: unit for unit in", "for mining_place in bases | geysers: difference = mining_place.surplus_harvesters #", "def on_start_async(self): \"\"\" This function is run after \"on_start\". At", "return r async def do_actions(self, actions: List[\"UnitCommand\"], prevent_double=True): \"\"\" Unlike", "Point3, Unit]) -> bool: \"\"\" Returns True if you can", "worker return workers.random if force else None async def can_place(self,", "enemies.\"\"\" return self._game_info.start_locations @property_cache_once_per_frame def known_enemy_units(self) -> Units: \"\"\"List of", "self.race != Race.Terran: # If an SCV is constructing a", "not r: # success cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals", "self.units(UnitTypeId.EGG): # type: Unit for order in egg.orders: abilities_amount[order.ability] +=", "return owned def can_feed(self, unit_type: UnitTypeId) -> bool: \"\"\" Checks", "= await self.find_placement(building, near.rounded, max_distance, random_alternative, placement_step) if p is", "your bot class. \"\"\" async def on_building_construction_complete(self, unit: Unit): \"\"\"", "is bigger than `resource_ratio`, this function prefer filling geysers first,", "zerg supply down instead of up (see https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used", "[] worker_pool = [worker for worker in self.workers.idle] bases =", "an enemy unit), it will misplace the expansion. \"\"\" if", "[place for place in deficit_mining_places if not place.vespene_contents] # else", "values. \"\"\" # TODO: remove when Blizzard/sc2client-proto#123 gets fixed. half_supply_units", "True return True async def chat_send(self, message: str): \"\"\" Send", "point, game_data, game_info and the first iteration of game_state (self.state)", "worker control, you should write your own distribution function. For", "return None if prevent_double: actions = list(filter(self.prevent_double_actions, actions)) for action", "it local_workers = self.workers.filter( lambda unit: unit.order_target == mining_place.tag or", "extraction site # or are on their way back from", "to use ability on a unit elif ( ability_target in", ") ] res = await self._client.query_building_placement(building, possible_positions) possible = [p", "\"cached_main_base_ramp\"): return self.cached_main_base_ramp # The reason for len(ramp.upper) in {2,", "resource group: for resources in resource_groups: # Possible expansion points", "distance + 1, placement_step)] + [(dx, distance) for dx in", "= True ) -> \"CanAffordWrapper\": \"\"\"Tests if the player has", "a group for every resource resource_groups = [[resource] for resource", "object as key, resources (mineral field and vespene geyser) as", "expansion is blocked (e.g. an enemy unit), it will misplace", "are also included. \"\"\" # TODO / FIXME: SCV building", "= [ (x, y) for x, y in itertools.product(range(-offset_range, offset_range", "== 1 # Check if all resources have enough space", "with \"Target.None.value\" because \".None\" doesnt seem to be a valid", "# For every resource group: for resources in resource_groups: #", "on its own. NOTE: This function is far from optimal,", "max_distance: int = 20, random_alternative: bool = True, placement_step: int", "idle # so dont move him pass await self.do_actions(actions) @property", "uses 'self.do' (reduces performance). Finds the next possible expansion via", "NydusWormDetected ResearchComplete TrainError TrainUnitComplete TrainWorkerComplete TransformationComplete UnitUnderAttack UpgradeComplete VespeneExhausted WarpInComplete", "if not self.can_afford_vespene: return ActionResult.NotEnoughVespene elif not self.can_afford_minerals: return ActionResult.NotEnoughMinerals", "def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion, self.townhalls)): #", "run after \"on_start\". At this point, game_data, game_info and the", "that target the gas extraction site # or are on", "== AbilityId: building = self._game_data.abilities[building.value] r = await self._client.query_building_placement(building, [position])", "self.units: Units = state.own_units self.workers: Units = self.units(race_worker[self.race]) self.townhalls: Units", "target the gas extraction site # or are on their", "not being handled. WARNING: This is quite slow when there", "# Possible expansion points amount = len(resources) # Calculate center,", "20) or self.workers ) if workers: for worker in workers.sorted_by_distance_to(pos).prefer_idle:", "order in worker.orders: abilities_amount[order.ability] += 1 if self.race == Race.Zerg:", "of two groups for group_a, group_b in itertools.combinations(resource_groups, 2): #", "# current_action: UnitOrder current_action = action.unit.orders[0] if current_action.ability.id != action.ability:", "is not None: near = near.to2 else: return p =", "a base was killed are not being handled. WARNING: This", "= PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False ) # Required for events", "result = min(possible_points, key=lambda point: sum(point.distance_to(resource) for resource in resources))", "-> str: \"\"\" Returns time as string in min:sec format", "in progress, or if a worker is en route to", "AbilityId, target: Optional[Union[Unit, Point2, Point3]] = None, only_check_energy_and_cooldown: bool =", "ladder games http://sc2ai.net/ # The bot ID will stay the", "for mineral in self.state.mineral_field if any(mineral.distance_to(base) <= 8 for base", "in workers.sorted_by_distance_to(pos).prefer_idle: if ( not worker.orders or len(worker.orders) == 1", "on_building_construction_complete \"\"\" await self._issue_unit_dead_events() await self._issue_unit_added_events() for unit in self.units.structure:", "if unit.build_progress < 1: return if unit.tag not in self._units_previous_map:", "already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]: \"\"\" Check if an", "success cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene", "Note that this function is also triggered at the start", "required = self._game_data.units[unit_type.value]._proto.food_required return required == 0 or self.supply_left >=", "at a position. Caution: terrain height is different from a", "unit.build_progress < 1: return if unit.tag not in self._units_previous_map: return", "mineral in self.state.mineral_field if any(mineral.distance_to(base) <= 8 for base in", "ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos", "Optional[Unit]: \"\"\"Select a worker to build a building with.\"\"\" workers", "Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY, } building = start_townhall_type[self.race]", "assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.placement_grid[pos]", "ActionResult.Success] if not possible: continue if random_alternative: return random.choice(possible) else:", "\"\"\"List of known enemy units, structures only.\"\"\" return self.state.enemy_units.structure @property", "placement_step)] + [(-distance, dy) for dy in range(-distance, distance +", "state.common.minerals self.vespene: int = state.common.vespene self.supply_army: int = state.common.food_army self.supply_workers:", "return self._game_info.start_locations @property_cache_once_per_frame def known_enemy_units(self) -> Units: \"\"\"List of known", "unit.distance_to(target) <= cast_range ): return True return False def select_build_worker(self,", "mode).\"\"\" raise NotImplementedError def on_end(self, game_result: Result): \"\"\" Triggered at", "known enemy units, including structures.\"\"\" return self.state.enemy_units @property_cache_once_per_frame def known_enemy_structures(self)", "Dict[Point2, Unit]: \"\"\"List of expansions owned by the player.\"\"\" owned", "-> Dict[Point2, Units]: \"\"\" Returns dict with the correct expansion", "z-height at a position. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)),", "info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded", "self._issue_unit_dead_events() await self._issue_unit_added_events() for unit in self.units.structure: await self._issue_building_complete_event(unit) if", "at the end of a game. \"\"\" class CanAffordWrapper: def", "r = await self._client.actions(action) if not r: # success cost", "unit in self.units.structure: await self._issue_building_complete_event(unit) if len(self._previous_upgrades) != len(self.state.upgrades): for", "be counted as two units if isinstance(unit_type, UpgradeId): return self.already_pending_upgrade(unit_type)", "p = await self.find_placement(building, near.rounded, max_distance, random_alternative, placement_step) if p", "difference: continue if mining_place.is_vespene_geyser: # get all workers that target", "# same action, remove action if same target unit return", "ActionResult.Error r = await self._client.actions(action) if not r: # success", "UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, } correction = self.units(half_supply_units).amount %", "structures, and all morphs \"\"\" abilities_amount = Counter() for unit", "for egg in self.units(UnitTypeId.EGG)]) return amount async def build(self, building:", "PixelMap = PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False ) # Required for", "bases have size 5. center_x = int(sum(resource.position.x for resource in", "else: # get tags of minerals around expansion local_minerals_tags =", "cast or if ability is on cooldown if cached_abilities_of_unit: abilities", "len(self.state.upgrades): for upgrade_completed in self.state.upgrades - self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades", "key=lambda mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else: # there are no deficit", "return None def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]: \"\"\"", "\"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount @property_cache_once_per_frame def _abilities_workers_and_eggs(self)", "isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.pathing_grid[pos] ==", "self._game_data: GameData = game_data self.player_id: int = player_id self.race: Race", "cast like stimpack) if ( ability_target == 1 or ability_target", "pos = pos.position.to2.rounded return self._game_info.placement_grid[pos] == 1 def in_pathing_grid(self, pos:", "resource group to find expansion position offset_range = 7 offsets", "None self.supply_left: Union[float, int] = None self.idle_worker_count: int = None", "unit.order_target == bases.closest_to(mining_place).tag) ) else: # get tags of minerals", "# remove it from the list deficit_mining_places.remove(current_place) # if current", "+= 1 return abilities_amount def already_pending(self, unit_type: Union[UpgradeId, UnitTypeId], all_units:", "for w in self.workers for o in w.orders]) amount +=", "client incorrectly rounds zerg supply down instead of up (see", "self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self, state, proto_game_info): # Set attributes from new", "local_minerals = [ mineral for mineral in self.state.mineral_field if mineral.distance_to(current_place)", "( ability_target in {Target.Point.value, Target.PointOrUnit.value} and isinstance(target, (Point2, Point3)) and", "min( (ramp for ramp in self.game_info.map_ramps if len(ramp.upper) in {4,", "# prepare all minerals near a base if we have", "possible_points # Check if point can be built on if", "self.cached_main_base_ramp = min( (ramp for ramp in self.game_info.map_ramps if len(ramp.upper)", "build the unit \"\"\" required = self._game_data.units[unit_type.value]._proto.food_required return required ==", "unit does not exist any more. \"\"\" async def on_unit_created(self,", "owned by the player.\"\"\" owned = {} for el in", "int = state.common.warp_gate_count self.idle_worker_count: int = state.common.idle_worker_count self.army_count: int =", "whether the ability has been researched. Example usage: units_abilities =", "unit has an ability available and enough energy to cast", "Ward)) are also included. \"\"\" # TODO / FIXME: SCV", "minerals and vespene. \"\"\" if not actions: return None if", "Note that this function uses unit tags because the unit", "+ group_b) found_something = True break # Distance offsets we", "for unit in self.units.structure: await self._issue_building_complete_event(unit) if len(self._previous_upgrades) != len(self.state.upgrades):", "if hasattr(self, \"cached_main_base_ramp\"): return self.cached_main_base_ramp # The reason for len(ramp.upper)", "= self._game_info.player_start_location d = await self._client.query_pathing(startp, el) if d is", "workers or multiple bases. \"\"\" if not self.state.mineral_field or not", "spots # send to closest if worker is doing nothing", "near = near.position.to2 elif near is not None: near =", "the merged group resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a + group_b) found_something =", "dict = dict() self._previous_upgrades: Set[UpgradeId] = set() self.units: Units =", "this structure twice (once from the SCV order, and once", "Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): \"\"\"Build", "\"\"\"Possible start locations for enemies.\"\"\" return self._game_info.start_locations @property_cache_once_per_frame def known_enemy_units(self)", "await self._client.chat_send(message, False) # For the functions below, make sure", "to minerals first. This is only for workers that need", "state.common.food_used self.supply_left: int = self.supply_cap - self.supply_used if self.race ==", "game_info(self) -> \"GameInfo\": return self._game_info def alert(self, alert_code: Alert) ->", "terrain height is different from a unit's z-coordinate. \"\"\" assert", "if not difference: continue if mining_place.is_vespene_geyser: # get all workers", "List[AbilityId] = None, ) -> bool: \"\"\"Tests if a unit", "Union[float, int] = None self.supply_workers: Union[float, int] = None #", "are available. \"\"\" async def on_step(self, iteration: int): \"\"\"Ran on", "there are lots of workers or multiple bases. \"\"\" if", "for mineral in self.state.mineral_field if mineral.distance_to(current_place) <= 8 ] target_mineral", "True, placement_step: int = 2, ) -> Optional[Point2]: \"\"\"Finds a", "prevent_double=True): \"\"\" Unlike 'self.do()', this function does not instantly subtract", "-> bool: \"\"\" Returns True if there is creep on", "actions = list(filter(self.prevent_double_actions, actions)) for action in actions: cost =", "if there is creep on the grid point. \"\"\" assert", "constructing a building, already_pending would count this structure twice #", "import GameData, AbilityData from .ids.ability_id import AbilityId from .ids.unit_typeid import", "if building_type == UnitTypeId: building = self._game_data.units[building.value].creation_ability elif building_type ==", "# else prefer gas else: possible_mining_places = [place for place", "UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, } correction = self.units(half_supply_units).amount % 2 self.supply_used +=", "being handled. WARNING: This is quite slow when there are", "{2, 5}), key=lambda r: self.start_location.distance_to(r.top_center), ) except ValueError: # Hardcoded", "and has the most minerals left else: local_minerals = [", "center_y = int(sum(resource.position.y for resource in resources) / amount) +", "= game_data self.player_id: int = player_id self.race: Race = Race(self._game_info.player_races[self.player_id])", "not be called before _prepare_step.\"\"\" if self.townhalls: self._game_info.player_start_location = self.townhalls.first.position", "= unit or self.select_build_worker(p) if unit is None or not", "in production (except queens and morphing units) and structures in", "return True cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range ability_target = self._game_data.abilities[ability_id.value]._proto.target # Check", "queues of buildings. If all_units==True, then build queues of other", "= await self._client.actions(action) if not r: # success cost =", "race_gas, race_townhalls, race_worker from .data import ActionResult, Attribute, Race, race_worker,", "Point2) -> bool: \"\"\"Tests if a building can be placed", "map has a large main base ramp with inbase natural", "(7 if resource in geysers else 6) for resource in", "value when there are an odd number of zerglings and", "state # See game_state.py # update pathing grid self._game_info.pathing_grid: PixelMap", "resources (mineral field and vespene geyser) as value. \"\"\" #", "elif worker.is_idle and all_minerals_near_base: target_mineral = min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker))", "if self._game_info.placement_grid[point.rounded] == 1 # Check if all resources have", "def __init__(self, can_afford_minerals, can_afford_vespene, have_enough_supply): self.can_afford_minerals = can_afford_minerals self.can_afford_vespene =", "\"\"\" async def on_building_construction_started(self, unit: Unit): \"\"\" Override this in", "mining place to deficit bases for every missing worker else:", "self.army_count: int = state.common.army_count # reset cached values self.cached_known_enemy_structures =", "<= 8 for base in self.townhalls.ready) ] # distribute every", "order.ability.button_name[-1] != level: return 0 return order.progress return 0 @property_cache_once_per_frame", "production (except queens and morphing units) and structures in production,", "Point3, Unit]) -> bool: \"\"\" Returns True if a unit", "for Honorgrounds LE map, as that map has a large", "more workers deficit_mining_places = [] for mining_place in bases |", "= [ mineral for mineral in self.state.mineral_field if mineral.distance_to(current_place) <=", "it will prefer sending workers to minerals first. This is", "( ability_target == 1 or ability_target == Target.PointOrNone.value and isinstance(target,", "range(placement_step, max_distance, placement_step): possible_positions = [ Point2(p).offset(near).to2 for p in", "will have (x.5, y.5) # coordinates because bases have size", "Units logger = logging.getLogger(__name__) class BotAI: \"\"\"Base class for bots.\"\"\"", "it will NOT will geysers on its own. NOTE: This", "to closest if worker is doing nothing elif worker.is_idle and", "own distribution function. For example long distance mining control and", "== ability for egg in self.units(UnitTypeId.EGG)]) return amount async def", "from the list deficit_mining_places.remove(current_place) # if current place is a", "AbilityId from .ids.unit_typeid import UnitTypeId from .ids.upgrade_id import UpgradeId from", "type Point2, Point3 or Unit\" pos = pos.position.to2.rounded return -16", "resource in geysers else 6) for resource in resources) )", "<= self.minerals, cost.vespene <= self.vespene, enough_supply) async def can_cast( self,", "in range(-distance, distance + 1, placement_step)] + [(-distance, dy) for", "for order in worker.orders: abilities_amount[order.ability] += 1 if self.race ==", "as two units if isinstance(unit_type, UpgradeId): return self.already_pending_upgrade(unit_type) ability =", "points that are too near possible_points = ( point for", "there if current_place.vespene_contents: actions.append(worker.gather(current_place)) # if current place is a", "async def distribute_workers(self, resource_ratio: float = 2): \"\"\" Distributes workers", "True if a unit can pass through a grid point.", "elif not self.can_afford_minerals: return ActionResult.NotEnoughMinerals elif not self.have_enough_supply: return ActionResult.NotEnoughFood", "int = player_id self.race: Race = Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict =", "new state before on_step.\"\"\" self.state: GameState = state # See", "self.build(building, near=location, max_distance=max_distance, random_alternative=False, placement_step=1) async def get_next_expansion(self) -> Optional[Point2]:", "bases | geysers: difference = mining_place.surplus_harvesters # perfect amount of", "on a grid point. \"\"\" # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert", "(Point2, Point3, Unit)) pos = pos.position.to2.rounded return self.state.creep[pos] == 1", "`resource_ratio` takes a float. If the current minerals to gas", "Units = None self.geysers: Units = None self.minerals: int =", "def __init__(self): # Specific opponent bot ID used in sc2ai", "is never Race.Random start_townhall_type = { Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER,", "w.is_idle) and w.distance_to(pos) < 20) or self.workers ) if workers:", "game_result: Result): \"\"\" Triggered at the end of a game.", "map has 5 upper points, and most other maps have", "This function will be automatically run from main.py and triggers", "Units], ignore_resource_requirements=False ) -> List[List[AbilityId]]: \"\"\" Returns available abilities of", "data_pb2.py (line 161) for the numbers 1-5 to make sense\"\"\"", "self._units_previous_map: dict = dict() self._previous_upgrades: Set[UpgradeId] = set() self.units: Units", "building.\"\"\" async def on_upgrade_complete(self, upgrade: UpgradeId): \"\"\" Override this in", "alert is triggered in the current step. Example use: from", "group resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a + group_b) found_something = True break", "return self._game_info def alert(self, alert_code: Alert) -> bool: \"\"\" Check", "Set, Tuple, Union # mypy type checking from .cache import", "all minerals near a base if we have too many", "expansion location will have (x.5, y.5) # coordinates because bases", "have refined worker control, you should write your own distribution", "a valid enum name return True # Check if able", "its own. NOTE: This function is far from optimal, if", "an odd number of zerglings and banelings. This function corrects", "CanAffordWrapper: def __init__(self, can_afford_minerals, can_afford_vespene, have_enough_supply): self.can_afford_minerals = can_afford_minerals self.can_afford_vespene", "Race: assert len(self._game_info.player_races) == 2, \"enemy_race not available\" self.enemy_id =", "Specific opponent bot ID used in sc2ai ladder games http://sc2ai.net/", "def on_end(self, game_result: Result): \"\"\" Triggered at the end of", "of known enemy units, structures only.\"\"\" return self.state.enemy_units.structure @property def", "not self.state.mineral_field or not self.workers or not self.townhalls.ready: return actions", "of up (see https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used and friends return the", "!= action.ability: # different action, return true return True try:", "is: # ParaSite map has 5 upper points, and most", "= None self.workers: Units = None self.townhalls: Units = None", "unit), it will misplace the expansion. \"\"\" if not building:", "True if there is creep on the grid point. \"\"\"", "return 1 level = None if \"LEVEL\" in upgrade_type.name: level", "UnitOrder current_action = action.unit.orders[0] if current_action.ability.id != action.ability: # different", "= None, only_check_energy_and_cooldown: bool = False, cached_abilities_of_unit: List[AbilityId] = None,", "iteration: int): \"\"\"Ran on every game step (looped in realtime", "resource_groups: # Possible expansion points amount = len(resources) # Calculate", "afford action {action}\") return ActionResult.Error r = await self._client.actions(action) if", "import UnitTypeId from .ids.upgrade_id import UpgradeId from .pixel_map import PixelMap", "Check if able to use ability on a position elif", "Workaround Zerg supply rounding bug self._correct_zerg_supply() elif self.race == Race.Protoss:", "upgrade_completed in self.state.upgrades - self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades = self.state.upgrades", "\"\"\" Returns True if a unit can pass through a", "self.supply_army: Union[float, int] = None self.supply_workers: Union[float, int] = None", "[(-distance, dy) for dy in range(-distance, distance + 1, placement_step)]", "there are no deficit mining places and worker is not", "if len(worker_pool) > len(deficit_mining_places): all_minerals_near_base = [ mineral for mineral", "-> Race: assert len(self._game_info.player_races) == 2, \"enemy_race not available\" self.enemy_id", "1 def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\"", "isinstance(item_id, UpgradeId): cost = self._game_data.upgrades[item_id.value].cost else: cost = self._game_data.calculate_ability_cost(item_id) return", "# distribute every worker in the pool for worker in", "Complete\") Alert codes: AlertError AddOnComplete BuildingComplete BuildingUnderAttack LarvaHatched MergeComplete MineralsExhausted", "return order.progress return 0 @property_cache_once_per_frame def _abilities_all_units(self) -> Counter: \"\"\"", "check_supply_cost: enough_supply = self.can_feed(item_id) elif isinstance(item_id, UpgradeId): cost = self._game_data.upgrades[item_id.value].cost", "\"\"\" Returns dict with the correct expansion position Point2 object", "self.state.creep[pos] == 1 def _prepare_start(self, client, player_id, game_info, game_data): \"\"\"Ran", "= state.common.larva_count # Workaround Zerg supply rounding bug self._correct_zerg_supply() elif", "[(distance, dy) for dy in range(-distance, distance + 1, placement_step)]", "self._game_info: \"GameInfo\" = game_info self._game_data: GameData = game_data self.player_id: int", "AlertError AddOnComplete BuildingComplete BuildingUnderAttack LarvaHatched MergeComplete MineralsExhausted MorphComplete MothershipComplete MULEExpired", "game_data, game_info and the first iteration of game_state (self.state) are", "repeat=2) if math.hypot(x, y) <= 8 ] # Dict we", "import ActionResult, Alert, Race, Result, Target, race_gas, race_townhalls, race_worker from", "= Counter() for unit in self.units: # type: Unit for", "near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step:", "(Point2((offset[0] + center_x, offset[1] + center_y)) for offset in offsets)", "if you really want to have refined worker control, you", "resources to build a unit or cast an ability.\"\"\" enough_supply", "int = None self.vespene: int = None self.supply_army: Union[float, int]", "pos: Union[Unit, Point2, Point3], force: bool = False) -> Optional[Unit]:", "target position return False except AttributeError: pass return True return", "float. If the current minerals to gas ratio is bigger", "self.vespene, enough_supply) async def can_cast( self, unit: Unit, ability_id: AbilityId,", "8 ] target_mineral = max(local_minerals, key=lambda mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral)) #", "UpgradeId from .pixel_map import PixelMap from .position import Point2, Point3", "gas extraction site # or are on their way back", "as value. \"\"\" # Idea: create a group for every", "d is None: continue if d < distance: distance =", "remove action if same target unit return False except AttributeError:", "isinstance(target, Unit) and unit.distance_to(target) <= cast_range ): return True #", "site # or are on their way back from it", "an upgrade is being researched Return values: 0: not started", "None, max_distance: Union[int, float] = 10, location: Optional[Point2] = None", "for worker in self.workers.idle] bases = self.townhalls.ready geysers = self.geysers.ready", "distance in range(placement_step, max_distance, placement_step): possible_positions = [ Point2(p).offset(near).to2 for", "correction async def get_available_abilities( self, units: Union[List[Unit], Units], ignore_resource_requirements=False )", "when there are lots of workers or multiple bases. \"\"\"", "site, go there if current_place.vespene_contents: actions.append(worker.gather(current_place)) # if current place", "from .pixel_map import PixelMap from .position import Point2, Point3 from", "20, random_alternative: bool = True, placement_step: int = 2, )", "in {2, 5}), key=lambda r: self.start_location.distance_to(r.top_center), ) except ValueError: #", "and unit.order_target == mining_place.tag) ) # too many workers if", "self.can_feed(item_id) elif isinstance(item_id, UpgradeId): cost = self._game_data.upgrades[item_id.value].cost else: cost =", "if unit.tag not in self._units_previous_map: await self.on_building_construction_started(unit) async def _issue_building_complete_event(self,", "from typing import Any, Dict, List, Optional, Set, Tuple, Union", "we apply to center of each resource group to find", "Union[Point2, Point3, Unit]) -> int: \"\"\" Returns terrain height at", "self.units} self.units: Units = state.own_units self.workers: Units = self.units(race_worker[self.race]) self.townhalls:", "( self.workers.filter(lambda w: (w.is_gathering or w.is_idle) and w.distance_to(pos) < 20)", "base if we have too many workers # and need", "None self.supply_army: Union[float, int] = None self.supply_workers: Union[float, int] =", "built on if self._game_info.placement_grid[point.rounded] == 1 # Check if all", "AbilityId.HARVEST_GATHER} ): return worker return workers.random if force else None", "\"\"\" await self._issue_unit_dead_events() await self._issue_unit_added_events() for unit in self.units.structure: await", "= pos.position.to2.rounded return -16 + 32 * self._game_info.terrain_height[pos] / 255", "the closest patch if len(worker_pool) > len(deficit_mining_places): all_minerals_near_base = [", "# too many workers if difference > 0: for worker", "{} for el in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) <", "== bases.closest_to(mining_place).tag) ) else: # get tags of minerals around", "from .units import Units logger = logging.getLogger(__name__) class BotAI: \"\"\"Base", "class. \"\"\" async def on_building_construction_complete(self, unit: Unit): \"\"\" Override this", "the expansion. \"\"\" if not building: # self.race is never", "unit.order_target in local_minerals_tags or (unit.is_carrying_minerals and unit.order_target == mining_place.tag) )", "(Interceptors) or Oracles (Stasis Ward)) are also included. \"\"\" #", "return alert_code.value in self.state.alerts @property def start_location(self) -> Point2: return", "{} # For every resource group: for resources in resource_groups:", "a unit can pass through a grid point. \"\"\" assert", "be moved anyways, it will NOT will geysers on its", "build queues of buildings. If all_units==True, then build queues of", "upgrade: UpgradeId): \"\"\" Override this in your bot class. \"\"\"", "not None: near = near.to2 else: return p = await", "Check if able to use ability on a unit elif", "= self._game_data.upgrades[item_id.value].cost else: cost = self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals <= self.minerals,", "= None if \"LEVEL\" in upgrade_type.name: level = upgrade_type.name[-1] creationAbilityID", "the wrong value when there are an odd number of", "BuildingComplete BuildingUnderAttack LarvaHatched MergeComplete MineralsExhausted MorphComplete MothershipComplete MULEExpired NuclearLaunchDetected NukeComplete", "\"\"\" # TODO / FIXME: SCV building a structure might", "1, placement_step)] + [(dx, distance) for dx in range(-distance, distance", "and vespene geyser) as value. \"\"\" # Idea: create a", "inbase natural self.cached_main_base_ramp = min( (ramp for ramp in self.game_info.map_ramps", "_issue_unit_dead_events(self): for unit_tag in self.state.dead_units: await self.on_unit_destroyed(unit_tag) async def on_unit_destroyed(self,", "all morphs \"\"\" abilities_amount = Counter() for unit in self.units:", "int = state.common.minerals self.vespene: int = state.common.vespene self.supply_army: int =", "self._game_info.terrain_height[pos] / 255 def in_placement_grid(self, pos: Union[Point2, Point3, Unit]) ->", "that this function is also triggered at the start of", "structures only.\"\"\" return self.state.enemy_units.structure @property def main_base_ramp(self) -> \"Ramp\": \"\"\"", "groups and add the merged group resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a +", "abilities of one or more units. Right know only checks", "unit_tag in self.state.dead_units: await self.on_unit_destroyed(unit_tag) async def on_unit_destroyed(self, unit_tag): \"\"\"", "Result from .game_data import AbilityData, GameData # imports for mypy", "it will misplace the expansion. \"\"\" if not building: #", "UnitTypeId.BANELINGCOCOON, } correction = self.units(half_supply_units).amount % 2 self.supply_used += correction", "only_check_energy_and_cooldown: bool = False, cached_abilities_of_unit: List[AbilityId] = None, ) ->", "self.minerals -= cost.minerals self.vespene -= cost.vespene else: logger.error(f\"Error: {r} (action:", "= True while found_something: found_something = False # Check every", "in local_workers[:difference]: worker_pool.append(worker) # too few workers # add mining", "typing import Any, Dict, List, Optional, Set, Tuple, Union #", "(Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.pathing_grid[pos] == 1", "that need more workers deficit_mining_places = [] for mining_place in", "position return False except AttributeError: pass return True return True", "Return values: 0: not started 0 < x < 1:", "always add actions if queued if action.queue: return True if", "= 10, location: Optional[Point2] = None ): \"\"\" Not recommended", "else: return p = await self.find_placement(building, near.rounded, max_distance, random_alternative, placement_step)", "on 'faster' \"\"\" return self.state.game_loop / 22.4 # / (1/1.4)", "# Filter out points that are too near possible_points =", "mining_place in bases | geysers: difference = mining_place.surplus_harvesters # perfect", "for base in self.townhalls.ready) ] # distribute every worker in", "List[List[AbilityId]]: \"\"\" Returns available abilities of one or more units.", "units_abilities = await self.get_available_abilities([self.units.random]) \"\"\" return await self._client.query_available_abilities(units, ignore_resource_requirements) async", "closest mining place current_place = min(deficit_mining_places, key=lambda place: place.distance_to(worker)) #", "current place is a gas extraction site, go there if", "Union[int, float]: \"\"\" Check if an upgrade is being researched", "production self.supply_cap: int = state.common.food_cap self.supply_used: int = state.common.food_used self.supply_left:", "amount) + 0.5 possible_points = (Point2((offset[0] + center_x, offset[1] +", "doesnt seem to be a valid enum name return True", "# Doesn't include workers in production self.supply_cap: Union[float, int] =", "# type: Unit for order in unit.orders: abilities_amount[order.ability] += 1", "= self.supply_cap - self.supply_used if self.race == Race.Zerg: self.larva_count: int", "Target, race_gas, race_townhalls, race_worker from .data import ActionResult, Attribute, Race,", "or if ability is on cooldown if cached_abilities_of_unit: abilities =", "in unit.orders: abilities_amount[order.ability] += 1 if not unit.is_ready: if self.race", "= self._game_data.units[unit_type.value].creation_ability amount = len(self.units(unit_type).not_ready) if all_units: amount += sum([o.ability", "self cast like stimpack) if ( ability_target == 1 or", "abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount def already_pending(self, unit_type: Union[UpgradeId, UnitTypeId],", "= None self.cached_known_enemy_units = None async def issue_events(self): \"\"\" This", "included. \"\"\" # TODO / FIXME: SCV building a structure", "= 7 offsets = [ (x, y) for x, y", "bot can \"adapt\" to the opponent self.opponent_id: int = None", "of game_state (self.state) are available. \"\"\" async def on_step(self, iteration:", "= None self.minerals: int = None self.vespene: int = None", "except AttributeError: pass try: if action.target.x == current_action.target.x and action.target.y", "- on_unit_created - on_unit_destroyed - on_building_construction_complete \"\"\" await self._issue_unit_dead_events() await", "and unit.distance_to(target) <= cast_range ): return True # Check if", "if ability_id in abilities: if only_check_energy_and_cooldown: return True cast_range =", "Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2):", "taken continue startp = self._game_info.player_start_location d = await self._client.query_pathing(startp, el)", "\"\"\" required = self._game_data.units[unit_type.value]._proto.food_required return required == 0 or self.supply_left", "{AbilityData, AbilityId, UnitTypeId} if building_type == UnitTypeId: building = self._game_data.units[building.value].creation_ability", "constructing a building, already_pending would count this structure twice (once", "have (x.5, y.5) # coordinates because bases have size 5.", "unit_prev = self._units_previous_map[unit.tag] if unit_prev.build_progress < 1: await self.on_building_construction_complete(unit) async", "\"\"\" assert isinstance(pos, (Point2, Point3, Unit)), f\"pos is not of", "has 4 upper points at the wrong ramp (which is", "Point3, Unit]) -> int: \"\"\" Returns terrain z-height at a", "class BotAI: \"\"\"Base class for bots.\"\"\" EXPANSION_GAP_THRESHOLD = 15 def", "# Hardcoded hotfix for Honorgrounds LE map, as that map", "not idle # so dont move him pass await self.do_actions(actions)", "make sense\"\"\" assert isinstance(unit, Unit) assert isinstance(ability_id, AbilityId) assert isinstance(target,", "stay the same each game so your bot can \"adapt\"", "ramp with inbase natural self.cached_main_base_ramp = min( (ramp for ramp", "resource_ratio: possible_mining_places = [place for place in deficit_mining_places if not", "int = state.common.food_workers # Doesn't include workers in production self.supply_cap:", "AbilityId, UnitTypeId], position: Point2) -> bool: \"\"\"Tests if a building", "when there are an odd number of zerglings and banelings.", "ability_target in {Target.Point.value, Target.PointOrUnit.value} and isinstance(target, (Point2, Point3)) and unit.distance_to(target)", "group_a, group_b in itertools.combinations(resource_groups, 2): # Check if any pair", "groups is closer than threshold together if any( resource_a.distance_to(resource_b) <=", "isinstance(near, Point2) if isinstance(building, UnitTypeId): building = self._game_data.units[building.value].creation_ability else: #", "target_mineral = max(local_minerals, key=lambda mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral)) # more workers", "assert isinstance(pos, (Point2, Point3, Unit)), f\"pos is not of type", "if you have vision on a grid point. \"\"\" #", "triggered at the start of the game for the starting", "if \"LEVEL\" in upgrade_type.name: level = upgrade_type.name[-1] creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id", "geysers else 6) for resource in resources) ) # Choose", "Point3)) and unit.distance_to(target) <= cast_range ): return True return False", "None self.supply_used: Union[float, int] = None self.supply_left: Union[float, int] =", "expansion_locations(self) -> Dict[Point2, Units]: \"\"\" Returns dict with the correct", "import GameState from .game_data import GameData, AbilityData from .ids.ability_id import", "def can_cast( self, unit: Unit, ability_id: AbilityId, target: Optional[Union[Unit, Point2,", "1: return if unit.tag not in self._units_previous_map: return unit_prev =", "_abilities_workers_and_eggs(self) -> Counter: \"\"\" Cache for the already_pending function, includes", "AttributeError: pass return True return True async def chat_send(self, message:", "def get_next_expansion(self) -> Optional[Point2]: \"\"\"Find next expansion location.\"\"\" closest =", "async def get_next_expansion(self) -> Optional[Point2]: \"\"\"Find next expansion location.\"\"\" closest", ") -> bool: \"\"\"Tests if a unit has an ability", "a chat message. \"\"\" assert isinstance(message, str), f\"{message} is no", "orders (including pending). Zerg units in production (except queens and", "assert isinstance(alert_code, Alert), f\"alert_code {alert_code} is no Alert\" return alert_code.value", "map size. def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int:", "height is different from a unit's z-coordinate. \"\"\" assert isinstance(pos,", "/ self.vespene < resource_ratio: possible_mining_places = [place for place in", "if random_alternative: return random.choice(possible) else: return min(possible, key=lambda p: p.distance_to_point2(near))", "start_townhall_type[self.race] assert isinstance(building, UnitTypeId) if not location: location = await", "than free mining spots # send to closest if worker", "-> bool: \"\"\"Tests if a unit has an ability available", "# cant replace 1 with \"Target.None.value\" because \".None\" doesnt seem", "egg in self.units(UnitTypeId.EGG): # type: Unit for order in egg.orders:", "of minerals around expansion local_minerals_tags = { mineral.tag for mineral", "building_type == UnitTypeId: building = self._game_data.units[building.value].creation_ability elif building_type == AbilityId:", "# get all target tags a worker can have #", "<= 8 } # get all target tags a worker", "float] = 10, location: Optional[Point2] = None ): \"\"\" Not", "fields first if current mineral to gas ratio is less", "from a unit's z-coordinate. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)),", "number of zerglings and banelings. This function corrects the bad", "self.units: Units = None self.workers: Units = None self.townhalls: Units", "or more units. Right know only checks cooldown, energy cost,", "return f\"{int(t // 60):02}:{int(t % 60):02}\" @property def game_info(self) ->", "TODO: remove when Blizzard/sc2client-proto#123 gets fixed. half_supply_units = { UnitTypeId.ZERGLING,", "self._client.query_pathing(startp, el) if d is None: continue if d <", "__init__(self): # Specific opponent bot ID used in sc2ai ladder", "1 return abilities_amount @property_cache_once_per_frame def _abilities_workers_and_eggs(self) -> Counter: \"\"\" Cache", "return if unit.tag not in self._units_previous_map: return unit_prev = self._units_previous_map[unit.tag]", "and all morphs \"\"\" abilities_amount = Counter() for unit in", "for resource in resources)) centers[result] = resources return centers def", "self._issue_building_complete_event(unit) if len(self._previous_upgrades) != len(self.state.upgrades): for upgrade_completed in self.state.upgrades -", "if self.townhalls: self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps, self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers() def", "cost.vespene <= self.vespene, enough_supply) async def can_cast( self, unit: Unit,", "Distance offsets we apply to center of each resource group", "# any resource in a group is closer than 6", "== current_action.target.x and action.target.y == current_action.target.y: # same action, remove", "played on 'faster' \"\"\" return self.state.game_loop / 22.4 # /", "worker in workers.sorted_by_distance_to(pos).prefer_idle: if ( not worker.orders or len(worker.orders) ==", "self.player_id: int = player_id self.race: Race = Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict", "offsets we apply to center of each resource group to", "really want to have refined worker control, you should write", "Unlike 'self.do()', this function does not instantly subtract minerals and", "their way back from it local_workers = self.workers.filter( lambda unit:", "and all units in production, and all structures, and all", "self.workers: Units = self.units(race_worker[self.race]) self.townhalls: Units = self.units(race_townhalls[self.race]) self.geysers: Units", "actions = [] worker_pool = [worker for worker in self.workers.idle]", "gas ratio is bigger than `resource_ratio`, this function prefer filling", "not unit.is_ready: if self.race != Race.Terran or not unit.is_structure: #", "unit.is_ready: if self.race != Race.Terran or not unit.is_structure: # If", "-> Dict[Point2, Unit]: \"\"\"List of expansions owned by the player.\"\"\"", "on a unit elif ( ability_target in {Target.Unit.value, Target.PointOrUnit.value} and", "Union[Unit, Point2, Point3], force: bool = False) -> Optional[Unit]: \"\"\"Select", "0: return None for distance in range(placement_step, max_distance, placement_step): possible_positions", "\"Client\" = client self._game_info: \"GameInfo\" = game_info self._game_data: GameData =", "Race.Protoss: self.warp_gate_count: int = state.common.warp_gate_count self.idle_worker_count: int = state.common.idle_worker_count self.army_count:", "self._game_info.player_start_location d = await self._client.query_pathing(startp, el) if d is None:", "merged group resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a + group_b) found_something = True", "async def on_unit_destroyed(self, unit_tag): \"\"\" Override this in your bot", "UnitTypeId): building = self._game_data.units[building.value].creation_ability else: # AbilityId building = self._game_data.abilities[building.value]", "self.supply_cap: int = state.common.food_cap self.supply_used: int = state.common.food_used self.supply_left: int", "if current_action.target == action.target.tag: # same action, remove action if", "for mypy and pycharm autocomplete from .game_state import GameState from", "NotImplementedError def on_end(self, game_result: Result): \"\"\" Triggered at the end", "places if deficit_mining_places: # choose only mineral fields first if", "has enough resources to build a unit or cast an", "distance mining control and moving workers if a base was", "more workers to distribute than free mining spots # send", "async def expand_now( self, building: UnitTypeId = None, max_distance: Union[int,", "will prefer sending workers to minerals first. This is only", "the unit does not exist any more. \"\"\" async def", "): return worker return workers.random if force else None async", "in seconds, assumes the game is played on 'faster' \"\"\"", "your bot class. Note that this function uses unit tags", "units if isinstance(unit_type, UpgradeId): return self.already_pending_upgrade(unit_type) ability = self._game_data.units[unit_type.value].creation_ability amount", "elif ( ability_target in {Target.Point.value, Target.PointOrUnit.value} and isinstance(target, (Point2, Point3))", "you have vision on a grid point. \"\"\" # more", "near.position.to2 elif near is not None: near = near.to2 else:", "resources)) centers[result] = resources return centers def _correct_zerg_supply(self): \"\"\" The", "break # Distance offsets we apply to center of each", "ability_target == Target.PointOrNone.value and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <=", "len(worker.orders) == 1 and worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER} ): return", "Counter: \"\"\" Cache for the already_pending function, includes all worker", "async def do(self, action): if not self.can_afford(action): logger.warning(f\"Cannot afford action", "def __bool__(self): return self.can_afford_minerals and self.can_afford_vespene and self.have_enough_supply @property def", "geyser) as value. \"\"\" # Idea: create a group for", "# if preferred type is not available any more, get", "is quite slow when there are lots of workers or", "of buildings or units already in progress, or if a", "dict with the correct expansion position Point2 object as key,", "takes a float. If the current minerals to gas ratio", "self.larva_count: int = state.common.larva_count # Workaround Zerg supply rounding bug", "self.units.not_structure: if unit.tag not in self._units_previous_map: await self.on_unit_created(unit) for unit", "= len(resources) # Calculate center, round and add 0.5 because", "Returns dict with the correct expansion position Point2 object as", "== 1 or ability_target == Target.PointOrNone.value and isinstance(target, (Point2, Point3))", "all structures, and all morphs \"\"\" abilities_amount = Counter() for", "await self.on_unit_created(unit) for unit in self.units.structure: if unit.tag not in", "for resources in resource_groups: # Possible expansion points amount =", "apply to center of each resource group to find expansion", "order in unit.orders: abilities_amount[order.ability] += 1 if not unit.is_ready: if", "bot ID will stay the same each game so your", "if we have too many workers # and need to", "Counter() for unit in self.units: # type: Unit for order", "also included. \"\"\" # TODO / FIXME: SCV building a", "start to set game and player data.\"\"\" self._client: \"Client\" =", "Point3)) # check if unit has enough energy to cast", "for enemies.\"\"\" return self._game_info.start_locations @property_cache_once_per_frame def known_enemy_units(self) -> Units: \"\"\"List", "\"\"\"First step extra preparations. Must not be called before _prepare_step.\"\"\"", "= pos.position.to2.rounded return self._game_info.pathing_grid[pos] == 1 def is_visible(self, pos: Union[Point2,", "center of each resource group to find expansion position offset_range", "to make sense\"\"\" assert isinstance(unit, Unit) assert isinstance(ability_id, AbilityId) assert", "placement_step=1) async def get_next_expansion(self) -> Optional[Point2]: \"\"\"Find next expansion location.\"\"\"", "Point3 or Unit\" pos = pos.position.to2.rounded return -16 + 32", "for u in self.units for o in u.orders]) else: amount", "if current place is a gas extraction site, go there", "(x, y) for x, y in itertools.product(range(-offset_range, offset_range + 1),", "if not self.state.mineral_field or not self.workers or not self.townhalls.ready: return", "if difference > 0: for worker in local_workers[:difference]: worker_pool.append(worker) #", "abilities_amount = Counter() for unit in self.units: # type: Unit", "unit in self.units: # type: Unit for order in unit.orders:", "realtime mode).\"\"\" raise NotImplementedError def on_end(self, game_result: Result): \"\"\" Triggered", "unit elif ( ability_target in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit)", "def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]: \"\"\" Check if", "together if any( resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD for resource_a, resource_b in", "correct expansion position Point2 object as key, resources (mineral field", "workers # add mining place to deficit bases for every", "0.5 because expansion location will have (x.5, y.5) # coordinates", "upper points, and most other maps have 2 upper points", "# Remove the single groups and add the merged group", "started 0 < x < 1: researching 1: finished \"\"\"", "from .game_state import GameState from .game_data import GameData, AbilityData from", "\"\"\"Build a building.\"\"\" if isinstance(near, Unit): near = near.position.to2 elif", "self.get_available_abilities([unit]))[0] if ability_id in abilities: if only_check_energy_and_cooldown: return True cast_range", "ID will stay the same each game so your bot", "should write your own distribution function. For example long distance", "the starting base building.\"\"\" async def on_upgrade_complete(self, upgrade: UpgradeId): \"\"\"", "await self.on_building_construction_complete(unit) async def _issue_unit_dead_events(self): for unit_tag in self.state.dead_units: await", "game data is available. \"\"\" async def on_start_async(self): \"\"\" This", "deficit_mining_places = [] for mining_place in bases | geysers: difference", "= None self.geysers: Units = None self.minerals: int = None", "a worker to build a building with.\"\"\" workers = (", "refined worker control, you should write your own distribution function.", "mineral.tag for mineral in self.state.mineral_field if mineral.distance_to(mining_place) <= 8 }", "go to the mineral field that is near and has", "is not of type Point2, Point3 or Unit\" pos =", "async def _issue_unit_added_events(self): for unit in self.units.not_structure: if unit.tag not", "in resources) / amount) + 0.5 possible_points = (Point2((offset[0] +", "t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD th = next((x for x in self.townhalls", "in self.workers: # type: Unit for order in worker.orders: abilities_amount[order.ability]", "remove action if same target position return False except AttributeError:", "1, placement_step)] + [(-distance, dy) for dy in range(-distance, distance", "and unit.is_ready): for order in structure.orders: if order.ability.id is creationAbilityID:", "and once from \"not structure.is_ready\") for unit in self.units.structure.not_ready: #", "continue if mining_place.is_vespene_geyser: # get all workers that target the", "None self.units: Units = None self.workers: Units = None self.townhalls:", "See data_pb2.py (line 161) for the numbers 1-5 to make", "the mineral field that is near and has the most", "= self._game_data.upgrades[upgrade_type.value].research_ability.id for structure in self.units.filter(lambda unit: unit.is_structure and unit.is_ready):", "tags because the unit does not exist any more. \"\"\"", "self.units.structure: if unit.tag not in self._units_previous_map: await self.on_building_construction_started(unit) async def", "# ParaSite map has 5 upper points, and most other", "return self.state.game_loop / 22.4 # / (1/1.4) * (1/16) @property", "counted as two units if isinstance(unit_type, UpgradeId): return self.already_pending_upgrade(unit_type) ability", "255 def in_placement_grid(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\"", "and friends return the wrong value when there are an", "stimpack) if ( ability_target == 1 or ability_target == Target.PointOrNone.value", "and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range ): #", "# different action, return true return True try: if current_action.target", "Attribute, Race, race_worker, race_townhalls, race_gas, Target, Result from .game_data import", "(once from the SCV order, and once from \"not structure.is_ready\")", "await self._issue_building_complete_event(unit) if len(self._previous_upgrades) != len(self.state.upgrades): for upgrade_completed in self.state.upgrades", "Alert codes: AlertError AddOnComplete BuildingComplete BuildingUnderAttack LarvaHatched MergeComplete MineralsExhausted MorphComplete", "= len(self.units(unit_type).not_ready) if all_units: amount += sum([o.ability == ability for", "\"\"\" if not actions: return None if prevent_double: actions =", "self.state.dead_units: await self.on_unit_destroyed(unit_tag) async def on_unit_destroyed(self, unit_tag): \"\"\" Override this", "geysers = self.geysers.ready # list of places that need more", "mining spots # send to closest if worker is doing", "== mining_place.tag) ) # too many workers if difference >", "unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): \"\"\"Build a building.\"\"\" if", "= action.unit.orders[0] if current_action.ability.id != action.ability: # different action, return", "= 2): \"\"\" Distributes workers across all the bases taken.", "unit tags because the unit does not exist any more.", "self._game_info.placement_grid[point.rounded] == 1 # Check if all resources have enough", "in self.units.not_structure: if unit.tag not in self._units_previous_map: await self.on_unit_created(unit) for", "None self.cached_known_enemy_structures = None self.cached_known_enemy_units = None @property def enemy_race(self)", "of the minerals he could mine at that base #", "mineral for mineral in self.state.mineral_field if any(mineral.distance_to(base) <= 8 for", "state.common.idle_worker_count self.army_count: int = state.common.army_count # reset cached values self.cached_known_enemy_structures", "as this function uses 'self.do' (reduces performance). Finds the next", "UnitTypeId], all_units: bool = True) -> int: \"\"\" Returns a", "possible_positions = [ Point2(p).offset(near).to2 for p in ( [(dx, -distance)", "= ( point for point in possible_points # Check if", "in range(placement_step, max_distance, placement_step): possible_positions = [ Point2(p).offset(near).to2 for p", "function prefer filling geysers first, if it is lower, it", "= 8.5 geysers = self.state.vespene_geyser # Create a group for", "self._game_data.abilities[building.value] r = await self._client.query_building_placement(building, [position]) return r[0] == ActionResult.Success", "if target is in range (or is a self cast", "next possible expansion via 'self.get_next_expansion()'. If the target expansion is", "and w.distance_to(pos) < 20) or self.workers ) if workers: for", "found_something = False # Check every combination of two groups", "property_cache_once_per_frame from .data import ActionResult, Alert, Race, Result, Target, race_gas,", "async def chat_send(self, message: str): \"\"\" Send a chat message.", "return self.state.creep[pos] == 1 def _prepare_start(self, client, player_id, game_info, game_data):", "player has enough resources to build a unit or cast", "> len(deficit_mining_places): all_minerals_near_base = [ mineral for mineral in self.state.mineral_field", "deficit_mining_places.remove(current_place) # if current place is a gas extraction site,", "already_pending function, includes all worker orders (including pending). Zerg units", "deficit_mining_places += [mining_place for _ in range(-difference)] # prepare all", "these grid points. Caution: some x and y offset might", "def find_placement( self, building: UnitTypeId, near: Union[Unit, Point2, Point3], max_distance:", "__bool__(self): return self.can_afford_minerals and self.can_afford_vespene and self.have_enough_supply @property def action_result(self):", "is_near_to_expansion(x)), None) if th: owned[el] = th return owned def", "Returns time in seconds, assumes the game is played on", "min:sec format \"\"\" t = self.time return f\"{int(t // 60):02}:{int(t", "self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool = True )", "(line 161) for the numbers 1-5 to make sense\"\"\" assert", "ratio is less than target ratio if self.vespene and self.minerals", "to build it. This also includes queued orders for workers", "pos.position.to2.rounded return self.state.creep[pos] == 1 def _prepare_start(self, client, player_id, game_info,", "r[0] == ActionResult.Success async def find_placement( self, building: UnitTypeId, near:", "other units (such as Carriers (Interceptors) or Oracles (Stasis Ward))", "workers.sorted_by_distance_to(pos).prefer_idle: if ( not worker.orders or len(worker.orders) == 1 and", "or 5x5 of these grid points. Caution: some x and", "in self._units_previous_map: await self.on_building_construction_started(unit) async def _issue_building_complete_event(self, unit): if unit.build_progress", "placement_step)] + [(dx, distance) for dx in range(-distance, distance +", "1 and worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER} ): return worker return", "Counter: \"\"\" Cache for the already_pending function, includes protoss units", "deficit_mining_places # find closest mining place current_place = min(deficit_mining_places, key=lambda", "or self.select_build_worker(p) if unit is None or not self.can_afford(building): return", "False def select_build_worker(self, pos: Union[Unit, Point2, Point3], force: bool =", ") except ValueError: # Hardcoded hotfix for Honorgrounds LE map,", "send them to the closest patch if len(worker_pool) > len(deficit_mining_places):", "= True) -> int: \"\"\" Returns a number of buildings", "as key, resources (mineral field and vespene geyser) as value.", "cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene else:", "way back from it local_workers = self.workers.filter( lambda unit: unit.order_target", "in self.units: # type: Unit for order in unit.orders: abilities_amount[order.ability]", "# success cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -=", "geysers first, if it is lower, it will prefer sending", "checking from .cache import property_cache_forever, property_cache_once_per_frame from .data import ActionResult,", "= False) -> Optional[Unit]: \"\"\"Select a worker to build a", "has enough energy to cast or if ability is on", "as long as we change something found_something = True while", "u in self.units for o in u.orders]) else: amount +=", "on_unit_destroyed(self, unit_tag): \"\"\" Override this in your bot class. Note", "60):02}:{int(t % 60):02}\" @property def game_info(self) -> \"GameInfo\": return self._game_info", "1 level = None if \"LEVEL\" in upgrade_type.name: level =", "in self.state.resources] # Loop the merging process as long as", "current place is a gas extraction site, # go to", "group # Distance we group resources by RESOURCE_SPREAD_THRESHOLD = 8.5", "pool for worker in worker_pool: # as long as have", "there is creep on the grid point. \"\"\" assert isinstance(pos,", "# (once from the SCV order, and once from \"not", "Unit): \"\"\" Override this in your bot class. \"\"\" async", "pos.position.to2.rounded return self._game_info.pathing_grid[pos] == 1 def is_visible(self, pos: Union[Point2, Point3,", "# Check if able to use ability on a position", "= {unit.tag: unit for unit in self.units} self.units: Units =", "ramp. # The map Acolyte has 4 upper points at", "on their way back from it local_workers = self.workers.filter( lambda", "to find expansion position offset_range = 7 offsets = [", "if current place is a gas extraction site, # go", "Point3, Unit]) -> bool: \"\"\" Returns True if there is", "in production self.supply_cap: int = state.common.food_cap self.supply_used: int = state.common.food_used", "if unit_prev.build_progress < 1: await self.on_building_construction_complete(unit) async def _issue_unit_dead_events(self): for", "< self.EXPANSION_GAP_THRESHOLD th = next((x for x in self.townhalls if", "in self.units} self.units: Units = state.own_units self.workers: Units = self.units(race_worker[self.race])", "a unit or cast an ability.\"\"\" enough_supply = True if", "-> Union[int, float]: \"\"\" Check if an upgrade is being", "Unit)) pos = pos.position.to2.rounded return self._game_info.pathing_grid[pos] == 1 def is_visible(self,", "Race.Terran: # If an SCV is constructing a building, already_pending", "mining_place.tag or (unit.is_carrying_vespene and unit.order_target == bases.closest_to(mining_place).tag) ) else: #", "= self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals <= self.minerals, cost.vespene <= self.vespene, enough_supply)", "fitting point result = min(possible_points, key=lambda point: sum(point.distance_to(resource) for resource", "local_workers = self.workers.filter( lambda unit: unit.order_target in local_minerals_tags or (unit.is_carrying_minerals", "return workers.random if force else None async def can_place(self, building:", "the start of the game for the starting base building.\"\"\"", "itertools.product(group_a, group_b) ): # Remove the single groups and add", "when Blizzard/sc2client-proto#123 gets fixed. half_supply_units = { UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING,", "all the bases taken. Keyword `resource_ratio` takes a float. If", "not place.vespene_contents] # else prefer gas else: possible_mining_places = [place", "not possible: continue if random_alternative: return random.choice(possible) else: return min(possible,", "self._game_data.units[unit_type.value]._proto.food_required return required == 0 or self.supply_left >= required def", "can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId], position: Point2) -> bool: \"\"\"Tests", "pending). Zerg units in production (except queens and morphing units)", "and most other maps have 2 upper points at the", "This also includes queued orders for workers and build queues", "Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): \"\"\"Build a building.\"\"\" if isinstance(near,", "bool: \"\"\"Tests if a building can be placed in the", "y.5) # coordinates because bases have size 5. center_x =", "= None self.supply_used: Union[float, int] = None self.supply_left: Union[float, int]", "self.minerals, cost.vespene <= self.vespene, enough_supply) async def can_cast( self, unit:", "self.supply_cap: Union[float, int] = None self.supply_used: Union[float, int] = None", "range(-distance, distance + 1, placement_step)] + [(distance, dy) for dy", "locations for enemies.\"\"\" return self._game_info.start_locations @property_cache_once_per_frame def known_enemy_units(self) -> Units:", "list(filter(self.prevent_double_actions, actions)) for action in actions: cost = self._game_data.calculate_ability_cost(action.ability) self.minerals", "for upgrade_completed in self.state.upgrades - self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades =", "enough_supply = True if isinstance(item_id, UnitTypeId): unit = self._game_data.units[item_id.value] cost", "to build a unit or cast an ability.\"\"\" enough_supply =", "Unit]) -> int: \"\"\" Returns terrain height at a position.", "Loop the merging process as long as we change something", "List[Point2]: \"\"\"Possible start locations for enemies.\"\"\" return self._game_info.start_locations @property_cache_once_per_frame def", "in itertools.product(group_a, group_b) ): # Remove the single groups and", "of expansions owned by the player.\"\"\" owned = {} for", "= (await self.get_available_abilities([unit]))[0] if ability_id in abilities: if only_check_energy_and_cooldown: return", "structure in self.units.filter(lambda unit: unit.is_structure and unit.is_ready): for order in", "structure might be counted as two units if isinstance(unit_type, UpgradeId):", "if not possible_mining_places: possible_mining_places = deficit_mining_places # find closest mining", "near: Union[Unit, Point2, Point3], max_distance: int = 20, random_alternative: bool", "self.race == Race.Zerg: for egg in self.units(UnitTypeId.EGG): # type: Unit", "terrain height at a position. Caution: terrain height is different", "opponent bot ID used in sc2ai ladder games http://sc2ai.net/ #", "location: location = await self.get_next_expansion() await self.build(building, near=location, max_distance=max_distance, random_alternative=False,", "possible_mining_places = [place for place in deficit_mining_places if not place.vespene_contents]", "more information \"\"\" if hasattr(self, \"cached_main_base_ramp\"): return self.cached_main_base_ramp # The", "= True if isinstance(item_id, UnitTypeId): unit = self._game_data.units[item_id.value] cost =", "= None self.larva_count: int = None self.cached_known_enemy_structures = None self.cached_known_enemy_units", "for dy in range(-distance, distance + 1, placement_step)] + [(distance,", "terran \"\"\" abilities_amount = Counter() for worker in self.workers: #", "for unit in self.units.structure.not_ready: # type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1", "game_info, game_data): \"\"\"Ran until game start to set game and", "can \"adapt\" to the opponent self.opponent_id: int = None self.units:", "1, placement_step)] ) ] res = await self._client.query_building_placement(building, possible_positions) possible", "it is lower, it will prefer sending workers to minerals", "most minerals left else: local_minerals = [ mineral for mineral", "await self.get_next_expansion() await self.build(building, near=location, max_distance=max_distance, random_alternative=False, placement_step=1) async def", "is None: return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if", "on a position elif ( ability_target in {Target.Point.value, Target.PointOrUnit.value} and", "resources by RESOURCE_SPREAD_THRESHOLD = 8.5 geysers = self.state.vespene_geyser # Create", "workers: for worker in workers.sorted_by_distance_to(pos).prefer_idle: if ( not worker.orders or", "p is None: return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p)", "# more workers to distribute than free mining spots #", "placement_step: int=2): \"\"\"Build a building.\"\"\" if isinstance(near, Unit): near =", "game for the starting base building.\"\"\" async def on_upgrade_complete(self, upgrade:", "self.workers.filter( lambda unit: unit.order_target in local_minerals_tags or (unit.is_carrying_minerals and unit.order_target", "and y offset might be required, see ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18", "+ center_y)) for offset in offsets) # Filter out points", "than target ratio if self.vespene and self.minerals / self.vespene <", "(unit.is_carrying_minerals and unit.order_target == mining_place.tag) ) # too many workers", "in self._units_previous_map: return unit_prev = self._units_previous_map[unit.tag] if unit_prev.build_progress < 1:", "is closest to the start position). try: self.cached_main_base_ramp = min(", "== ability for w in self.workers for o in w.orders])", "in self.state.mineral_field if mineral.distance_to(current_place) <= 8 ] target_mineral = max(local_minerals,", "return False except AttributeError: pass try: if action.target.x == current_action.target.x", "logging import math import random from collections import Counter from", "AbilityId, UnitTypeId} if building_type == UnitTypeId: building = self._game_data.units[building.value].creation_ability elif", "of known enemy units, including structures.\"\"\" return self.state.enemy_units @property_cache_once_per_frame def", "False, cached_abilities_of_unit: List[AbilityId] = None, ) -> bool: \"\"\"Tests if", "pathing grid self._game_info.pathing_grid: PixelMap = PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False )", "can_afford_minerals, can_afford_vespene, have_enough_supply): self.can_afford_minerals = can_afford_minerals self.can_afford_vespene = can_afford_vespene self.have_enough_supply", "def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId], position: Point2) -> bool:", "self.vespene: int = state.common.vespene self.supply_army: int = state.common.food_army self.supply_workers: int", "to start location. Look in game_info.py for more information \"\"\"", "= self.units(race_townhalls[self.race]) self.geysers: Units = self.units(race_gas[self.race]) self.minerals: int = state.common.minerals", "self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals <= self.minerals, cost.vespene <= self.vespene, enough_supply) async", "import Unit from .units import Units logger = logging.getLogger(__name__) class", "a position elif ( ability_target in {Target.Point.value, Target.PointOrUnit.value} and isinstance(target,", "GameState from .game_data import GameData, AbilityData from .ids.ability_id import AbilityId", "itertools.combinations(resource_groups, 2): # Check if any pair of resource of", "None ): \"\"\" Not recommended as this function uses 'self.do'", "return true return True try: if current_action.target == action.target.tag: #", "self, unit: Unit, ability_id: AbilityId, target: Optional[Union[Unit, Point2, Point3]] =", "be built on if self._game_info.placement_grid[point.rounded] == 1 # Check if", "<filename>sc2/bot_ai.py import itertools import logging import math import random from", "current mineral to gas ratio is less than target ratio", "max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): \"\"\"Build a", "max_distance, random_alternative, placement_step) if p is None: return ActionResult.CantFindPlacementLocation unit", "@property_cache_once_per_frame def _abilities_workers_and_eggs(self) -> Counter: \"\"\" Cache for the already_pending", "\"\"\"Ran until game start to set game and player data.\"\"\"", "self.supply_workers: int = state.common.food_workers # Doesn't include workers in production", "and self.can_afford_vespene and self.have_enough_supply @property def action_result(self): if not self.can_afford_vespene:", "if unit is None or not self.can_afford(building): return ActionResult.Error return", "in self.state.upgrades: return 1 level = None if \"LEVEL\" in", "# if current place is a gas extraction site, go", "\"\"\" Returns a number of buildings or units already in", "if self.race == Race.Zerg: self.larva_count: int = state.common.larva_count # Workaround", "RESOURCE_SPREAD_THRESHOLD for resource_a, resource_b in itertools.product(group_a, group_b) ): # Remove", "amount = len(resources) # Calculate center, round and add 0.5", "distance + 1, placement_step)] + [(distance, dy) for dy in", "abilities_amount def already_pending(self, unit_type: Union[UpgradeId, UnitTypeId], all_units: bool = True)", "Choose best fitting point result = min(possible_points, key=lambda point: sum(point.distance_to(resource)", "unit or cast an ability.\"\"\" enough_supply = True if isinstance(item_id,", "proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False ) # Required for events self._units_previous_map: Dict", "and player data.\"\"\" self._client: \"Client\" = client self._game_info: \"GameInfo\" =", "the end of a game. \"\"\" class CanAffordWrapper: def __init__(self,", "-> bool: \"\"\" Returns True if a unit can pass", "self.state.upgrades async def _issue_unit_added_events(self): for unit in self.units.not_structure: if unit.tag", "down instead of up (see https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used and friends", "possible_mining_places = [place for place in deficit_mining_places if place.vespene_contents] #", "order in egg.orders: abilities_amount[order.ability] += 1 if self.race != Race.Terran:", "self.can_afford(action): logger.warning(f\"Cannot afford action {action}\") return ActionResult.Error r = await", "-> Optional[Point2]: \"\"\"Find next expansion location.\"\"\" closest = None distance", "else: # there are no deficit mining places and worker", "\"\"\"Tests if a unit has an ability available and enough", "sure you are inside the boundries of the map size.", "possible_points = (Point2((offset[0] + center_x, offset[1] + center_y)) for offset", "self.player_id return Race(self._game_info.player_races[self.enemy_id]) @property def time(self) -> Union[int, float]: \"\"\"", "slow when there are lots of workers or multiple bases.", "supply to build the unit \"\"\" required = self._game_data.units[unit_type.value]._proto.food_required return", "self.supply_used: Union[float, int] = None self.supply_left: Union[float, int] = None", "distance) for dx in range(-distance, distance + 1, placement_step)] +", "import random from collections import Counter from typing import Any,", "for bots.\"\"\" EXPANSION_GAP_THRESHOLD = 15 def __init__(self): # Specific opponent", "if any pair of resource of these groups is closer", "these groups is closer than threshold together if any( resource_a.distance_to(resource_b)", "int: \"\"\" Returns a number of buildings or units already", "random_alternative: bool = True, placement_step: int = 2, ) ->", "self.do(unit.build(building, p)) async def do(self, action): if not self.can_afford(action): logger.warning(f\"Cannot", "AbilityData from .ids.ability_id import AbilityId from .ids.unit_typeid import UnitTypeId from", "self._game_info.pathing_grid: PixelMap = PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False ) # Required", "@property def action_result(self): if not self.can_afford_vespene: return ActionResult.NotEnoughVespene elif not", "- on_building_construction_complete \"\"\" await self._issue_unit_dead_events() await self._issue_unit_added_events() for unit in", "isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self.state.creep[pos] ==", "required == 0 or self.supply_left >= required def can_afford( self,", "for p in ( [(dx, -distance) for dx in range(-distance,", "y) <= 8 ] # Dict we want to return", "int=2): \"\"\"Build a building.\"\"\" if isinstance(near, Unit): near = near.position.to2", "Check if alert is triggered in the current step. Example", "deficit bases for every missing worker else: deficit_mining_places += [mining_place", "place is a gas extraction site, go there if current_place.vespene_contents:", "worker orders (including pending). Zerg units in production (except queens", "< x < 1: researching 1: finished \"\"\" assert isinstance(upgrade_type,", "= None self.idle_worker_count: int = None self.army_count: int = None", "10, location: Optional[Point2] = None ): \"\"\" Not recommended as", "workers and build queues of buildings. If all_units==True, then build", "# update pathing grid self._game_info.pathing_grid: PixelMap = PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True,", "await self._client.query_building_placement(building, [position]) return r[0] == ActionResult.Success async def find_placement(", "[p for r, p in zip(res, possible_positions) if r ==", "def game_info(self) -> \"GameInfo\": return self._game_info def alert(self, alert_code: Alert)", "placement_step: int = 2, ) -> Optional[Point2]: \"\"\"Finds a placement", "if place.vespene_contents] # if preferred type is not available any", "order.ability.id is creationAbilityID: if level and order.ability.button_name[-1] != level: return", "like stimpack) if ( ability_target == 1 or ability_target ==", "self._correct_zerg_supply() elif self.race == Race.Protoss: self.warp_gate_count: int = state.common.warp_gate_count self.idle_worker_count:", "Blizzard/sc2client-proto#123 gets fixed. half_supply_units = { UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED,", "extraction site, # go to the mineral field that is", "state.common.vespene self.supply_army: int = state.common.food_army self.supply_workers: int = state.common.food_workers #", "Alert) -> bool: \"\"\" Check if alert is triggered in", "Hardcoded hotfix for Honorgrounds LE map, as that map has", "friends return the wrong value when there are an odd", "in self.state.alerts @property def start_location(self) -> Point2: return self._game_info.player_start_location @property", "time in seconds, assumes the game is played on 'faster'", "p in zip(res, possible_positions) if r == ActionResult.Success] if not", "2 upper points at the main ramp. # The map", "in self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion,", "example long distance mining control and moving workers if a", "def owned_expansions(self) -> Dict[Point2, Unit]: \"\"\"List of expansions owned by", "choose only mineral fields first if current mineral to gas", "!= level: return 0 return order.progress return 0 @property_cache_once_per_frame def", "can_afford( self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool = True", "# type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount def already_pending(self,", "building, already_pending would count this structure twice (once from the", "does not instantly subtract minerals and vespene. \"\"\" if not", "long as have workers and mining places if deficit_mining_places: #", "int] = None # Doesn't include workers in production self.supply_cap:", "{ UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, } correction = self.units(half_supply_units).amount", "seem to be a valid enum name return True #", "else: local_minerals = [ mineral for mineral in self.state.mineral_field if", "continue if random_alternative: return random.choice(possible) else: return min(possible, key=lambda p:", "and self.minerals / self.vespene < resource_ratio: possible_mining_places = [place for", "deficit_mining_places if place.vespene_contents] # if preferred type is not available", "in {Target.Point.value, Target.PointOrUnit.value} and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <=", "two units if isinstance(unit_type, UpgradeId): return self.already_pending_upgrade(unit_type) ability = self._game_data.units[unit_type.value].creation_ability", "isinstance(pos, (Point2, Point3, Unit)), f\"pos is not of type Point2,", "enemy units, including structures.\"\"\" return self.state.enemy_units @property_cache_once_per_frame def known_enemy_structures(self) ->", "ValueError: # Hardcoded hotfix for Honorgrounds LE map, as that", "= min(possible_points, key=lambda point: sum(point.distance_to(resource) for resource in resources)) centers[result]", "@property def start_location(self) -> Point2: return self._game_info.player_start_location @property def enemy_start_locations(self)", "maps have 2 upper points at the main ramp. #", "assert isinstance(target, (type(None), Unit, Point2, Point3)) # check if unit", "distance + 1, placement_step)] ) ] res = await self._client.query_building_placement(building,", "workers that work at that gather site local_workers = self.workers.filter(", "resources return centers def _correct_zerg_supply(self): \"\"\" The client incorrectly rounds", "and unit.distance_to(target) <= cast_range ): # cant replace 1 with", "1 # Check if all resources have enough space to", "@property_cache_forever def expansion_locations(self) -> Dict[Point2, Units]: \"\"\" Returns dict with", "Possible expansion points amount = len(resources) # Calculate center, round", "This is only for workers that need to be moved", "your bot class. \"\"\" async def on_building_construction_started(self, unit: Unit): \"\"\"", "float]: \"\"\" Check if an upgrade is being researched Return", "and action.target.y == current_action.target.y: # same action, remove action if", "f\"alert_code {alert_code} is no Alert\" return alert_code.value in self.state.alerts @property", "the first iteration of game_state (self.state) are available. \"\"\" async", "and enough energy to cast it. See data_pb2.py (line 161)", "while found_something: found_something = False # Check every combination of", "if isinstance(near, Unit): near = near.position.to2 elif near is not", "def distribute_workers(self, resource_ratio: float = 2): \"\"\" Distributes workers across", "alert_code: Alert) -> bool: \"\"\" Check if alert is triggered", "is being researched Return values: 0: not started 0 <", "def on_step(self, iteration: int): \"\"\"Ran on every game step (looped", "unit or self.select_build_worker(p) if unit is None or not self.can_afford(building):", "is creep on the grid point. \"\"\" assert isinstance(pos, (Point2,", "most other maps have 2 upper points at the main", "int = 2, ) -> Optional[Point2]: \"\"\"Finds a placement location", "\"LEVEL\" in upgrade_type.name: level = upgrade_type.name[-1] creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id for", "pos.position.to2.rounded return -16 + 32 * self._game_info.terrain_height[pos] / 255 def", "if is_near_to_expansion(x)), None) if th: owned[el] = th return owned", "site, # go to the mineral field that is near", "# Check if target is in range (or is a", "or Unit\" pos = pos.position.to2.rounded return self._game_info.terrain_height[pos] # returns int", "the grid point. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)) pos", "same action, remove action if same target unit return False", "the game data is available. \"\"\" async def on_start_async(self): \"\"\"", "with the correct expansion position Point2 object as key, resources", "= await self.get_available_abilities([self.units.random]) \"\"\" return await self._client.query_available_abilities(units, ignore_resource_requirements) async def", "a building, already_pending would count this structure twice # (once", "step (looped in realtime mode).\"\"\" raise NotImplementedError def on_end(self, game_result:", "import Point2, Point3 from .unit import Unit from .units import", "state before on_step.\"\"\" self.state: GameState = state # See game_state.py", "-> \"CanAffordWrapper\": \"\"\"Tests if the player has enough resources to", "return min(possible, key=lambda p: p.distance_to_point2(near)) return None def already_pending_upgrade(self, upgrade_type:", "if an upgrade is being researched Return values: 0: not", "be automatically run from main.py and triggers the following functions:", "y in itertools.product(range(-offset_range, offset_range + 1), repeat=2) if math.hypot(x, y)", "units in production, and all structures, and all morphs \"\"\"", "resources) ) # Choose best fitting point result = min(possible_points,", "functions: - on_unit_created - on_unit_destroyed - on_building_construction_complete \"\"\" await self._issue_unit_dead_events()", "all_minerals_near_base: target_mineral = min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker)) actions.append(worker.gather(target_mineral)) else: #", "start locations for enemies.\"\"\" return self._game_info.start_locations @property_cache_once_per_frame def known_enemy_units(self) ->", "Create a group for every resource resource_groups = [[resource] for", "offset in offsets) # Filter out points that are too", "return self._game_info.pathing_grid[pos] == 1 def is_visible(self, pos: Union[Point2, Point3, Unit])", "finished \"\"\" assert isinstance(upgrade_type, UpgradeId) if upgrade_type in self.state.upgrades: return", "make sure you are inside the boundries of the map", "# as long as have workers and mining places if", "self.enemy_id = 3 - self.player_id return Race(self._game_info.player_races[self.enemy_id]) @property def time(self)", "res = await self._client.query_building_placement(building, possible_positions) possible = [p for r,", "bigger than `resource_ratio`, this function prefer filling geysers first, if", "self.townhalls.ready: return actions = [] worker_pool = [worker for worker", "dy in range(-distance, distance + 1, placement_step)] ) ] res", "threshold together if any( resource_a.distance_to(resource_b) <= RESOURCE_SPREAD_THRESHOLD for resource_a, resource_b", "place in deficit_mining_places if place.vespene_contents] # if preferred type is", "if mining_place.is_vespene_geyser: # get all workers that target the gas", "self.townhalls if is_near_to_expansion(x)), None) if th: owned[el] = th return", "actions: return None if prevent_double: actions = list(filter(self.prevent_double_actions, actions)) for", "= self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost: enough_supply = self.can_feed(item_id) elif isinstance(item_id, UpgradeId):", "ramp (which is closest to the start position). try: self.cached_main_base_ramp", "and whether the ability has been researched. Example usage: units_abilities", "= Counter() for worker in self.workers: # type: Unit for", "\".None\" doesnt seem to be a valid enum name return", "or Unit\" pos = pos.position.to2.rounded return -16 + 32 *", "import Any, Dict, List, Optional, Set, Tuple, Union # mypy", "unit.tag not in self._units_previous_map: return unit_prev = self._units_previous_map[unit.tag] if unit_prev.build_progress", "he could mine at that base # get workers that", "game and player data.\"\"\" self._client: \"Client\" = client self._game_info: \"GameInfo\"", "self._game_data.upgrades[item_id.value].cost else: cost = self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals <= self.minerals, cost.vespene", "This function is run after \"on_start\". At this point, game_data,", "that base # get workers that work at that gather", "already_pending function, includes protoss units warping in, and all units", "2): # Check if any pair of resource of these", "return centers def _correct_zerg_supply(self): \"\"\" The client incorrectly rounds zerg", "(unit.is_carrying_vespene and unit.order_target == bases.closest_to(mining_place).tag) ) else: # get tags", "= game_info self._game_data: GameData = game_data self.player_id: int = player_id", "with.\"\"\" workers = ( self.workers.filter(lambda w: (w.is_gathering or w.is_idle) and", "the unit \"\"\" required = self._game_data.units[unit_type.value]._proto.food_required return required == 0", "return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD th = next((x for x in", "\"\"\" The client incorrectly rounds zerg supply down instead of", "\"\"\" Override this in your bot class. \"\"\" def on_start(self):", "import Counter from typing import Any, Dict, List, Optional, Set,", "- self.player_id return Race(self._game_info.player_races[self.enemy_id]) @property def time(self) -> Union[int, float]:", "# Doesn't include workers in production self.supply_cap: int = state.common.food_cap", "0 or self.supply_left >= required def can_afford( self, item_id: Union[UnitTypeId,", "[ Point2(p).offset(near).to2 for p in ( [(dx, -distance) for dx", "logger = logging.getLogger(__name__) class BotAI: \"\"\"Base class for bots.\"\"\" EXPANSION_GAP_THRESHOLD", "= self.units(race_worker[self.race]) self.townhalls: Units = self.units(race_townhalls[self.race]) self.geysers: Units = self.units(race_gas[self.race])", "assumes the game is played on 'faster' \"\"\" return self.state.game_loop", "/ 22.4 # / (1/1.4) * (1/16) @property def time_formatted(self)", "in min:sec format \"\"\" t = self.time return f\"{int(t //", "( point for point in possible_points # Check if point", "[mining_place for _ in range(-difference)] # prepare all minerals near", "amount = len(self.units(unit_type).not_ready) if all_units: amount += sum([o.ability == ability", "building.\"\"\" assert isinstance(building, (AbilityId, UnitTypeId)) assert isinstance(near, Point2) if isinstance(building,", "self.supply_used: int = state.common.food_used self.supply_left: int = self.supply_cap - self.supply_used", "is run after \"on_start\". At this point, game_data, game_info and", "workers, skip mining place if not difference: continue if mining_place.is_vespene_geyser:", "this structure twice # (once from the SCV order, and", "return True try: if current_action.target == action.target.tag: # same action,", "position. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)), f\"pos is not", "is None or not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building,", "in geysers else 6) for resource in resources) ) #", "deficit mining places and worker is not idle # so", "\"Target.None.value\" because \".None\" doesnt seem to be a valid enum", "because the unit does not exist any more. \"\"\" async", "self._game_data.units[unit_type.value].creation_ability amount = len(self.units(unit_type).not_ready) if all_units: amount += sum([o.ability ==", "has the most minerals left else: local_minerals = [ mineral", "return self.state.enemy_units.structure @property def main_base_ramp(self) -> \"Ramp\": \"\"\" Returns the", "async def find_placement( self, building: UnitTypeId, near: Union[Unit, Point2, Point3],", "difference > 0: for worker in local_workers[:difference]: worker_pool.append(worker) # too", "all_units==True, then build queues of other units (such as Carriers", "the start position). try: self.cached_main_base_ramp = min( (ramp for ramp", "type: Unit for order in worker.orders: abilities_amount[order.ability] += 1 if", "== 1 def in_pathing_grid(self, pos: Union[Point2, Point3, Unit]) -> bool:", "resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a + group_b) found_something = True break #", "(await self.get_available_abilities([unit]))[0] if ability_id in abilities: if only_check_energy_and_cooldown: return True", "if isinstance(unit_type, UpgradeId): return self.already_pending_upgrade(unit_type) ability = self._game_data.units[unit_type.value].creation_ability amount =", "sc2ai ladder games http://sc2ai.net/ # The bot ID will stay", "enemy units, structures only.\"\"\" return self.state.enemy_units.structure @property def main_base_ramp(self) ->", "int = None self.warp_gate_count: int = None self.larva_count: int =", "only checks cooldown, energy cost, and whether the ability has", "and all(point.distance_to(resource) > (7 if resource in geysers else 6)", "or units already in progress, or if a worker is", "uses unit tags because the unit does not exist any", "current step. Example use: from sc2.data import Alert if self.alert(Alert.AddOnComplete):", "same target position return False except AttributeError: pass return True", "(looped in realtime mode).\"\"\" raise NotImplementedError def on_end(self, game_result: Result):", "# find closest mining place current_place = min(deficit_mining_places, key=lambda place:", "and add 0.5 because expansion location will have (x.5, y.5)", "AbilityId) assert isinstance(target, (type(None), Unit, Point2, Point3)) # check if", "_prepare_start(self, client, player_id, game_info, game_data): \"\"\"Ran until game start to", "Optional[Union[Unit, Point2, Point3]] = None, only_check_energy_and_cooldown: bool = False, cached_abilities_of_unit:", "from .ids.unit_typeid import UnitTypeId from .ids.upgrade_id import UpgradeId from .pixel_map", "= can_afford_minerals self.can_afford_vespene = can_afford_vespene self.have_enough_supply = have_enough_supply def __bool__(self):", "True if you have vision on a grid point. \"\"\"", "return ActionResult.Error r = await self._client.actions(action) if not r: #", "if same target unit return False except AttributeError: pass try:", "\"\"\" async def on_building_construction_complete(self, unit: Unit): \"\"\" Override this in", "self._game_data.upgrades[upgrade_type.value].research_ability.id for structure in self.units.filter(lambda unit: unit.is_structure and unit.is_ready): for", "@property def time(self) -> Union[int, float]: \"\"\" Returns time in", "in range (or is a self cast like stimpack) if", "sum([o.ability == ability for w in self.workers for o in", "< 20) or self.workers ) if workers: for worker in", "as Carriers (Interceptors) or Oracles (Stasis Ward)) are also included.", "None def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]: \"\"\" Check", "in self.units.structure: if unit.tag not in self._units_previous_map: await self.on_building_construction_started(unit) async", "(reduces performance). Finds the next possible expansion via 'self.get_next_expansion()'. If", "self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD th = next((x", "True ) -> \"CanAffordWrapper\": \"\"\"Tests if the player has enough", "the current step. Example use: from sc2.data import Alert if", "= max(local_minerals, key=lambda mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral)) # more workers to", "level: return 0 return order.progress return 0 @property_cache_once_per_frame def _abilities_all_units(self)", "this function uses 'self.do' (reduces performance). Finds the next possible", "include workers in production self.supply_cap: int = state.common.food_cap self.supply_used: int", "unit.order_target == mining_place.tag or (unit.is_carrying_vespene and unit.order_target == bases.closest_to(mining_place).tag) )", "SCV building a structure might be counted as two units", "await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades = self.state.upgrades async def _issue_unit_added_events(self): for unit", "range(-distance, distance + 1, placement_step)] + [(dx, distance) for dx", "self._game_info.map_ramps, self._game_info.vision_blockers = self._game_info._find_ramps_and_vision_blockers() def _prepare_step(self, state, proto_game_info): # Set", "that map has a large main base ramp with inbase", "update pathing grid self._game_info.pathing_grid: PixelMap = PixelMap( proto_game_info.game_info.start_raw.pathing_grid, in_bits=True, mirrored=False", "two groups for group_a, group_b in itertools.combinations(resource_groups, 2): # Check", "change something found_something = True while found_something: found_something = False", "placement_step) if p is None: return ActionResult.CantFindPlacementLocation unit = unit", "= True, placement_step: int = 2, ) -> Optional[Point2]: \"\"\"Finds", "race_townhalls, race_worker from .data import ActionResult, Attribute, Race, race_worker, race_townhalls,", "): \"\"\" Not recommended as this function uses 'self.do' (reduces", "points at the wrong ramp (which is closest to the", "-> bool: \"\"\" Checks if you have enough free supply", "cost.minerals self.vespene -= cost.vespene return await self._client.actions(actions) def prevent_double_actions(self, action):", "available\" self.enemy_id = 3 - self.player_id return Race(self._game_info.player_races[self.enemy_id]) @property def", "= [] for mining_place in bases | geysers: difference =", "missing worker else: deficit_mining_places += [mining_place for _ in range(-difference)]", "workers to distribute than free mining spots # send to", "cost = self._game_data.upgrades[item_id.value].cost else: cost = self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals <=", "in upgrade_type.name: level = upgrade_type.name[-1] creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id for structure", "gets fixed. half_supply_units = { UnitTypeId.ZERGLING, UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON,", "[worker for worker in self.workers.idle] bases = self.townhalls.ready geysers =", "on_end(self, game_result: Result): \"\"\" Triggered at the end of a", "too few workers # add mining place to deficit bases", "handled. WARNING: This is quite slow when there are lots", "def in_pathing_grid(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns", "have workers and mining places if deficit_mining_places: # choose only", "{Target.Point.value, Target.PointOrUnit.value} and isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range", "to distribute than free mining spots # send to closest", "rounds zerg supply down instead of up (see https://github.com/Blizzard/s2client-proto/issues/123), so", "or len(worker.orders) == 1 and worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER} ):", "in itertools.product(range(-offset_range, offset_range + 1), repeat=2) if math.hypot(x, y) <=", "https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return", "int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): \"\"\"Build a building.\"\"\"", "pos.position.to2.rounded return self.state.visibility[pos] == 2 def has_creep(self, pos: Union[Point2, Point3,", "self.on_upgrade_complete(upgrade_completed) self._previous_upgrades = self.state.upgrades async def _issue_unit_added_events(self): for unit in", "it. This also includes queued orders for workers and build", "race_worker from .data import ActionResult, Attribute, Race, race_worker, race_townhalls, race_gas,", "Unit, ability_id: AbilityId, target: Optional[Union[Unit, Point2, Point3]] = None, only_check_energy_and_cooldown:", "Returns terrain z-height at a position. \"\"\" assert isinstance(pos, (Point2,", "near.to2 else: return p = await self.find_placement(building, near.rounded, max_distance, random_alternative,", "warping in, and all units in production, and all structures,", "return ActionResult.Error return await self.do(unit.build(building, p)) async def do(self, action):", "isinstance(upgrade_type, UpgradeId) if upgrade_type in self.state.upgrades: return 1 level =", "check_supply_cost: bool = True ) -> \"CanAffordWrapper\": \"\"\"Tests if the", "for o in u.orders]) else: amount += sum([o.ability == ability", "assert isinstance(building, (AbilityId, UnitTypeId)) assert isinstance(near, Point2) if isinstance(building, UnitTypeId):", "blocked (e.g. an enemy unit), it will misplace the expansion.", "worker is not idle # so dont move him pass", "str), f\"{message} is no string\" await self._client.chat_send(message, False) # For", "one or more units. Right know only checks cooldown, energy", "amount += sum([o.ability == ability for u in self.units for", "isinstance(alert_code, Alert), f\"alert_code {alert_code} is no Alert\" return alert_code.value in", "= el return closest async def distribute_workers(self, resource_ratio: float =", "grid point. \"\"\" # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2,", "every resource, then merge these groups if # any resource", "tags of minerals around expansion local_minerals_tags = { mineral.tag for", "\"\"\"Ran on every game step (looped in realtime mode).\"\"\" raise", "other places if not possible_mining_places: possible_mining_places = deficit_mining_places # find", "corrects the bad values. \"\"\" # TODO: remove when Blizzard/sc2client-proto#123", "At this point, game_data, game_info and the first iteration of", "None self.warp_gate_count: int = None self.larva_count: int = None self.cached_known_enemy_structures", "isinstance(building, UnitTypeId) if not location: location = await self.get_next_expansion() await", "of places that need more workers deficit_mining_places = [] for", "base # get workers that work at that gather site", "get workers that work at that gather site local_workers =", "p in ( [(dx, -distance) for dx in range(-distance, distance", "is on cooldown if cached_abilities_of_unit: abilities = cached_abilities_of_unit else: abilities", "has 5 upper points, and most other maps have 2", "a position. \"\"\" assert isinstance(pos, (Point2, Point3, Unit)), f\"pos is", "} building = start_townhall_type[self.race] assert isinstance(building, UnitTypeId) if not location:", "self, building: UnitTypeId = None, max_distance: Union[int, float] = 10,", "the game is played on 'faster' \"\"\" return self.state.game_loop /", "NOT will geysers on its own. NOTE: This function is", "if # any resource in a group is closer than", "self.on_building_construction_complete(unit) async def _issue_unit_dead_events(self): for unit_tag in self.state.dead_units: await self.on_unit_destroyed(unit_tag)", "Checks if you have enough free supply to build the", "function uses unit tags because the unit does not exist", "Result): \"\"\" Triggered at the end of a game. \"\"\"", "and order.ability.button_name[-1] != level: return 0 return order.progress return 0", "int = 20, random_alternative: bool = True, placement_step: int =", "energy to cast it. See data_pb2.py (line 161) for the", "creep on the grid point. \"\"\" assert isinstance(pos, (Point2, Point3,", "anyways, it will NOT will geysers on its own. NOTE:", "= self._game_data.units[unit_type.value]._proto.food_required return required == 0 or self.supply_left >= required", "None self.army_count: int = None self.warp_gate_count: int = None self.larva_count:", "queued if action.queue: return True if action.unit.orders: # action: UnitCommand", "Dict = {unit.tag: unit for unit in self.units} self.units: Units", "Race(self._game_info.player_races[self.enemy_id]) @property def time(self) -> Union[int, float]: \"\"\" Returns time", "> (7 if resource in geysers else 6) for resource", "to set game and player data.\"\"\" self._client: \"Client\" = client", "= None # Doesn't include workers in production self.supply_cap: Union[float,", "location.\"\"\" closest = None distance = math.inf for el in", "and morphing units) and structures in production, counts double for", "if a unit has an ability available and enough energy", "161) for the numbers 1-5 to make sense\"\"\" assert isinstance(unit,", "in your bot class. \"\"\" async def on_building_construction_complete(self, unit: Unit):", "place if not difference: continue if mining_place.is_vespene_geyser: # get all", "bad values. \"\"\" # TODO: remove when Blizzard/sc2client-proto#123 gets fixed.", "so self.supply_used and friends return the wrong value when there", "Override this in your bot class. \"\"\" def on_start(self): \"\"\"", "list deficit_mining_places.remove(current_place) # if current place is a gas extraction", "bool = False) -> Optional[Unit]: \"\"\"Select a worker to build", "be placed in the given location.\"\"\" building_type = type(building) assert", "action): if not self.can_afford(action): logger.warning(f\"Cannot afford action {action}\") return ActionResult.Error", "pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True if", "action.unit.orders: # action: UnitCommand # current_action: UnitOrder current_action = action.unit.orders[0]", "worker else: deficit_mining_places += [mining_place for _ in range(-difference)] #", "a unit elif ( ability_target in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target,", "unit in self.units.structure: if unit.tag not in self._units_previous_map: await self.on_building_construction_started(unit)", "Alert, Race, Result, Target, race_gas, race_townhalls, race_worker from .data import", "protoss units warping in, and all units in production, and", "self.supply_left: Union[float, int] = None self.idle_worker_count: int = None self.army_count:", "Units = state.own_units self.workers: Units = self.units(race_worker[self.race]) self.townhalls: Units =", "(1/1.4) * (1/16) @property def time_formatted(self) -> str: \"\"\" Returns", "else None async def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId], position:", "self.supply_used and friends return the wrong value when there are", "if worker is doing nothing elif worker.is_idle and all_minerals_near_base: target_mineral", "group_b in itertools.combinations(resource_groups, 2): # Check if any pair of", "unit_tag): \"\"\" Override this in your bot class. Note that", "workers if a base was killed are not being handled.", "# get tags of minerals around expansion local_minerals_tags = {", "type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount def already_pending(self, unit_type:", "__init__(self, can_afford_minerals, can_afford_vespene, have_enough_supply): self.can_afford_minerals = can_afford_minerals self.can_afford_vespene = can_afford_vespene", "\"\"\" t = self.time return f\"{int(t // 60):02}:{int(t % 60):02}\"", "in, and all units in production, and all structures, and", "place.distance_to(worker)) # remove it from the list deficit_mining_places.remove(current_place) # if", "upgrade_type in self.state.upgrades: return 1 level = None if \"LEVEL\"", "Unit\" pos = pos.position.to2.rounded return self._game_info.terrain_height[pos] # returns int def", "or ability_target == Target.PointOrNone.value and isinstance(target, (Point2, Point3)) and unit.distance_to(target)", "el return closest async def distribute_workers(self, resource_ratio: float = 2):", "for x, y in itertools.product(range(-offset_range, offset_range + 1), repeat=2) if", "8 ] # Dict we want to return centers =", "in self.units.structure: await self._issue_building_complete_event(unit) if len(self._previous_upgrades) != len(self.state.upgrades): for upgrade_completed", "known_enemy_structures(self) -> Units: \"\"\"List of known enemy units, structures only.\"\"\"", "\"enemy_race not available\" self.enemy_id = 3 - self.player_id return Race(self._game_info.player_races[self.enemy_id])", "have too many workers # and need to send them", "self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades = self.state.upgrades async def _issue_unit_added_events(self): for", "owned = {} for el in self.expansion_locations: def is_near_to_expansion(t): return", "MULEExpired NuclearLaunchDetected NukeComplete NydusWormDetected ResearchComplete TrainError TrainUnitComplete TrainWorkerComplete TransformationComplete UnitUnderAttack", "available any more, get all other places if not possible_mining_places:", "for structure in self.units.filter(lambda unit: unit.is_structure and unit.is_ready): for order", "== action.target.tag: # same action, remove action if same target", "Distance we group resources by RESOURCE_SPREAD_THRESHOLD = 8.5 geysers =", "await self.on_unit_destroyed(unit_tag) async def on_unit_destroyed(self, unit_tag): \"\"\" Override this in", "self.units(race_worker[self.race]) self.townhalls: Units = self.units(race_townhalls[self.race]) self.geysers: Units = self.units(race_gas[self.race]) self.minerals:", "group_b) ): # Remove the single groups and add the", "Union[Unit, Point2, Point3], max_distance: int = 20, random_alternative: bool =", "in worker.orders: abilities_amount[order.ability] += 1 if self.race == Race.Zerg: for", "for the already_pending function, includes all worker orders (including pending).", "in self.units(UnitTypeId.EGG): # type: Unit for order in egg.orders: abilities_amount[order.ability]", "if upgrade_type in self.state.upgrades: return 1 level = None if", "only for workers that need to be moved anyways, it", "banelings. This function corrects the bad values. \"\"\" # TODO:", "cached_abilities_of_unit: List[AbilityId] = None, ) -> bool: \"\"\"Tests if a", "self.state.upgrades - self._previous_upgrades: await self.on_upgrade_complete(upgrade_completed) self._previous_upgrades = self.state.upgrades async def", "centers = {} # For every resource group: for resources", "in range(-distance, distance + 1, placement_step)] + [(dx, distance) for", "= state.common.food_workers # Doesn't include workers in production self.supply_cap: int", "List, Optional, Set, Tuple, Union # mypy type checking from", "of the game for the starting base building.\"\"\" async def", "prefer filling geysers first, if it is lower, it will", "ActionResult.NotEnoughVespene elif not self.can_afford_minerals: return ActionResult.NotEnoughMinerals elif not self.have_enough_supply: return", "a game. \"\"\" class CanAffordWrapper: def __init__(self, can_afford_minerals, can_afford_vespene, have_enough_supply):", "self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion, self.townhalls)): # already taken continue startp =", "Point3 from .unit import Unit from .units import Units logger", "(except queens and morphing units) and structures in production, counts", "for egg in self.units(UnitTypeId.EGG): # type: Unit for order in", "from the SCV order, and once from \"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability]", "len(ramp.upper) in {4, 9}), key=lambda r: self.start_location.distance_to(r.top_center), ) return self.cached_main_base_ramp", "2, \"enemy_race not available\" self.enemy_id = 3 - self.player_id return", "max_distance == 0: return None for distance in range(placement_step, max_distance,", "d < distance: distance = d closest = el return", "None # Doesn't include workers in production self.supply_cap: Union[float, int]", "unit = unit or self.select_build_worker(p) if unit is None or", "# For the functions below, make sure you are inside", "offset[1] + center_y)) for offset in offsets) # Filter out", "collections import Counter from typing import Any, Dict, List, Optional,", "worker in local_workers[:difference]: worker_pool.append(worker) # too few workers # add", "local_minerals_tags or (unit.is_carrying_minerals and unit.order_target == mining_place.tag) ) # too", "_prepare_first_step(self): \"\"\"First step extra preparations. Must not be called before", "gas ratio is less than target ratio if self.vespene and", "function does not instantly subtract minerals and vespene. \"\"\" if", "bot when the game data is available. \"\"\" async def", "order.progress return 0 @property_cache_once_per_frame def _abilities_all_units(self) -> Counter: \"\"\" Cache", "only.\"\"\" return self.state.enemy_units.structure @property def main_base_ramp(self) -> \"Ramp\": \"\"\" Returns", "Union[UpgradeId, UnitTypeId], all_units: bool = True) -> int: \"\"\" Returns", "7 offsets = [ (x, y) for x, y in", "+ [(distance, dy) for dy in range(-distance, distance + 1,", "function is far from optimal, if you really want to", "local_minerals_tags = { mineral.tag for mineral in self.state.mineral_field if mineral.distance_to(mining_place)", "!= Race.Terran: # If an SCV is constructing a building,", "True if action.unit.orders: # action: UnitCommand # current_action: UnitOrder current_action", "bool = False, cached_abilities_of_unit: List[AbilityId] = None, ) -> bool:", "building: Union[AbilityData, AbilityId, UnitTypeId], position: Point2) -> bool: \"\"\"Tests if", "are too near possible_points = ( point for point in", "mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral)) # more workers to distribute than free", "else: abilities = (await self.get_available_abilities([unit]))[0] if ability_id in abilities: if", "Zerg units in production (except queens and morphing units) and", "pass through a grid point. \"\"\" assert isinstance(pos, (Point2, Point3,", "self._units_previous_map: Dict = {unit.tag: unit for unit in self.units} self.units:", "Any, Dict, List, Optional, Set, Tuple, Union # mypy type", "if current mineral to gas ratio is less than target", "player_id self.race: Race = Race(self._game_info.player_races[self.player_id]) self._units_previous_map: dict = dict() self._previous_upgrades:", "UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY, } building = start_townhall_type[self.race] assert", "preparations. Must not be called before _prepare_step.\"\"\" if self.townhalls: self._game_info.player_start_location", "that this function uses unit tags because the unit does", "ability for egg in self.units(UnitTypeId.EGG)]) return amount async def build(self,", "by RESOURCE_SPREAD_THRESHOLD = 8.5 geysers = self.state.vespene_geyser # Create a", "in your bot class. \"\"\" async def on_building_construction_started(self, unit: Unit):", "1, placement_step)] + [(distance, dy) for dy in range(-distance, distance", "if a worker is en route to build it. This", "= self._game_data.abilities[ability_id.value]._proto.cast_range ability_target = self._game_data.abilities[ability_id.value]._proto.target # Check if target is", "For every resource group: for resources in resource_groups: # Possible", "self, building: UnitTypeId, near: Union[Unit, Point2, Point3], max_distance: int =", "and add the merged group resource_groups.remove(group_a) resource_groups.remove(group_b) resource_groups.append(group_a + group_b)", "Optional[Point2]: \"\"\"Find next expansion location.\"\"\" closest = None distance =", "Race, Result, Target, race_gas, race_townhalls, race_worker from .data import ActionResult,", "self.warp_gate_count: int = None self.larva_count: int = None self.cached_known_enemy_structures =", "Returns the Ramp instance of the closest main-ramp to start", "-= cost.minerals self.vespene -= cost.vespene return await self._client.actions(actions) def prevent_double_actions(self,", "pos: Union[Point2, Point3, Unit]) -> int: \"\"\" Returns terrain height", "because expansion location will have (x.5, y.5) # coordinates because", "# Create a group for every resource resource_groups = [[resource]", "t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion, self.townhalls)): # already taken continue", "= state.common.warp_gate_count self.idle_worker_count: int = state.common.idle_worker_count self.army_count: int = state.common.army_count", "\"\"\" async def on_step(self, iteration: int): \"\"\"Ran on every game", "for terran \"\"\" abilities_amount = Counter() for worker in self.workers:", "TrainWorkerComplete TransformationComplete UnitUnderAttack UpgradeComplete VespeneExhausted WarpInComplete \"\"\" assert isinstance(alert_code, Alert),", "bot class. \"\"\" def on_start(self): \"\"\" Allows initializing the bot", "self.can_afford_minerals: return ActionResult.NotEnoughMinerals elif not self.have_enough_supply: return ActionResult.NotEnoughFood else: return", "\"\"\"Select a worker to build a building with.\"\"\" workers =", "unit = self._game_data.units[item_id.value] cost = self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost: enough_supply =", "self.units for o in u.orders]) else: amount += sum([o.ability ==", "\"\"\" This function will be automatically run from main.py and", "Counter from typing import Any, Dict, List, Optional, Set, Tuple,", "string in min:sec format \"\"\" t = self.time return f\"{int(t", "a gas extraction site, go there if current_place.vespene_contents: actions.append(worker.gather(current_place)) #", "else: cost = self._game_data.calculate_ability_cost(item_id) return CanAffordWrapper(cost.minerals <= self.minerals, cost.vespene <=", "self.vespene and self.minerals / self.vespene < resource_ratio: possible_mining_places = [place", "= near.position.to2 elif near is not None: near = near.to2", "not of type Point2, Point3 or Unit\" pos = pos.position.to2.rounded", "is different from a unit's z-coordinate. \"\"\" assert isinstance(pos, (Point2,", "at that base # get workers that work at that", "actions.append(worker.gather(target_mineral)) else: # there are no deficit mining places and", "can_afford_vespene, have_enough_supply): self.can_afford_minerals = can_afford_minerals self.can_afford_vespene = can_afford_vespene self.have_enough_supply =", "self._game_info.placement_grid[pos] == 1 def in_pathing_grid(self, pos: Union[Point2, Point3, Unit]) ->", "5. center_x = int(sum(resource.position.x for resource in resources) / amount)", "workers = ( self.workers.filter(lambda w: (w.is_gathering or w.is_idle) and w.distance_to(pos)", "if a building can be placed in the given location.\"\"\"", "Dict we want to return centers = {} # For", "Override this in your bot class. \"\"\" async def on_building_construction_complete(self,", "= None, max_distance: Union[int, float] = 10, location: Optional[Point2] =", "worker_pool: # as long as have workers and mining places", "ability_target == 1 or ability_target == Target.PointOrNone.value and isinstance(target, (Point2,", "async def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId], position: Point2) ->", "Units = None self.minerals: int = None self.vespene: int =", "\"\"\" Returns the Ramp instance of the closest main-ramp to", "order, and once from \"not structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return", "BotAI: \"\"\"Base class for bots.\"\"\" EXPANSION_GAP_THRESHOLD = 15 def __init__(self):", "twice # (once from the SCV order, and once from", "and vespene. \"\"\" if not actions: return None if prevent_double:", "self.alert(Alert.AddOnComplete): print(\"Addon Complete\") Alert codes: AlertError AddOnComplete BuildingComplete BuildingUnderAttack LarvaHatched", "\"\"\" async def on_unit_created(self, unit: Unit): \"\"\" Override this in", "range(-distance, distance + 1, placement_step)] + [(-distance, dy) for dy", "string\" await self._client.chat_send(message, False) # For the functions below, make", "upgrade_type: UpgradeId) -> Union[int, float]: \"\"\" Check if an upgrade", "the ability has been researched. Example usage: units_abilities = await", "< 1: await self.on_building_construction_complete(unit) async def _issue_unit_dead_events(self): for unit_tag in", "LE map, as that map has a large main base", "# always add actions if queued if action.queue: return True", "ignore_resource_requirements) async def expand_now( self, building: UnitTypeId = None, max_distance:", "dy) for dy in range(-distance, distance + 1, placement_step)] +", "Point2, Point3], max_distance: int = 20, random_alternative: bool = True,", "events self._units_previous_map: Dict = {unit.tag: unit for unit in self.units}", "player_id, game_info, game_data): \"\"\"Ran until game start to set game", "not available\" self.enemy_id = 3 - self.player_id return Race(self._game_info.player_races[self.enemy_id]) @property", "None self.workers: Units = None self.townhalls: Units = None self.geysers:", "in range(-difference)] # prepare all minerals near a base if", "if ( not worker.orders or len(worker.orders) == 1 and worker.orders[0].ability.id", "route to build it. This also includes queued orders for", "in worker_pool: # as long as have workers and mining", "as that map has a large main base ramp with", "for order in unit.orders: abilities_amount[order.ability] += 1 if not unit.is_ready:", "mining_place.tag) ) # too many workers if difference > 0:", "def _abilities_workers_and_eggs(self) -> Counter: \"\"\" Cache for the already_pending function,", "function is run after \"on_start\". At this point, game_data, game_info", "mining place if not difference: continue if mining_place.is_vespene_geyser: # get", "first, if it is lower, it will prefer sending workers", "_abilities_all_units(self) -> Counter: \"\"\" Cache for the already_pending function, includes", "near.rounded, max_distance, random_alternative, placement_step) if p is None: return ActionResult.CantFindPlacementLocation", "(Point2, Point3, Unit)) pos = pos.position.to2.rounded return self._game_info.placement_grid[pos] == 1", "dy) for dy in range(-distance, distance + 1, placement_step)] )", "if p is None: return ActionResult.CantFindPlacementLocation unit = unit or", "does not exist any more. \"\"\" async def on_unit_created(self, unit:", "many workers # and need to send them to the", "location will have (x.5, y.5) # coordinates because bases have", "deficit_mining_places: # choose only mineral fields first if current mineral", "await self.do_actions(actions) @property def owned_expansions(self) -> Dict[Point2, Unit]: \"\"\"List of", "bool: \"\"\" Returns True if you can place something at", "workers.random if force else None async def can_place(self, building: Union[AbilityData,", "resource in resources)) centers[result] = resources return centers def _correct_zerg_supply(self):", "control and moving workers if a base was killed are", "def known_enemy_units(self) -> Units: \"\"\"List of known enemy units, including", "base ramp with inbase natural self.cached_main_base_ramp = min( (ramp for", "If the target expansion is blocked (e.g. an enemy unit),", "resource_groups.remove(group_b) resource_groups.append(group_a + group_b) found_something = True break # Distance", "60):02}\" @property def game_info(self) -> \"GameInfo\": return self._game_info def alert(self,", "your bot class. Note that this function is also triggered", "if mineral.distance_to(mining_place) <= 8 } # get all target tags", "UpgradeComplete VespeneExhausted WarpInComplete \"\"\" assert isinstance(alert_code, Alert), f\"alert_code {alert_code} is", "a worker is en route to build it. This also", "in self.units(UnitTypeId.EGG)]) return amount async def build(self, building: UnitTypeId, near:", "in the current step. Example use: from sc2.data import Alert", "multiple bases. \"\"\" if not self.state.mineral_field or not self.workers or", "UnitTypeId.ZERGLINGBURROWED, UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, } correction = self.units(half_supply_units).amount % 2", "# self.race is never Race.Random start_townhall_type = { Race.Protoss: UnitTypeId.NEXUS,", "= self.workers.filter( lambda unit: unit.order_target == mining_place.tag or (unit.is_carrying_vespene and", "int = state.common.army_count # reset cached values self.cached_known_enemy_structures = None", "it. See data_pb2.py (line 161) for the numbers 1-5 to", "await self.find_placement(building, near.rounded, max_distance, random_alternative, placement_step) if p is None:", "Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True if a", "Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns True if there", "): return True return False def select_build_worker(self, pos: Union[Unit, Point2,", "resource_groups.append(group_a + group_b) found_something = True break # Distance offsets", "state.common.warp_gate_count self.idle_worker_count: int = state.common.idle_worker_count self.army_count: int = state.common.army_count #", "\"\"\" Override this in your bot class. \"\"\" async def", "def on_upgrade_complete(self, upgrade: UpgradeId): \"\"\" Override this in your bot", "None self.cached_known_enemy_units = None @property def enemy_race(self) -> Race: assert", "main ramp. # The map Acolyte has 4 upper points", "building a structure might be counted as two units if", "available. \"\"\" async def on_step(self, iteration: int): \"\"\"Ran on every", "size. def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int: \"\"\"", "def can_afford( self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool =", "-> bool: \"\"\" Check if alert is triggered in the", "replace 1 with \"Target.None.value\" because \".None\" doesnt seem to be", "to send them to the closest patch if len(worker_pool) >", "in resources)) centers[result] = resources return centers def _correct_zerg_supply(self): \"\"\"", "a group is closer than 6 to any resource of", "Dict, List, Optional, Set, Tuple, Union # mypy type checking", "is None: continue if d < distance: distance = d", "initializing the bot when the game data is available. \"\"\"", "mineral in self.state.mineral_field if mineral.distance_to(mining_place) <= 8 } # get", "you really want to have refined worker control, you should", "self.get_next_expansion() await self.build(building, near=location, max_distance=max_distance, random_alternative=False, placement_step=1) async def get_next_expansion(self)", "= list(filter(self.prevent_double_actions, actions)) for action in actions: cost = self._game_data.calculate_ability_cost(action.ability)", "Union[float, int] = None # Doesn't include workers in production", "-= cost.minerals self.vespene -= cost.vespene else: logger.error(f\"Error: {r} (action: {action})\")", ".data import ActionResult, Attribute, Race, race_worker, race_townhalls, race_gas, Target, Result", "# type: Unit for order in worker.orders: abilities_amount[order.ability] += 1", "9}), key=lambda r: self.start_location.distance_to(r.top_center), ) return self.cached_main_base_ramp @property_cache_forever def expansion_locations(self)", "target ratio if self.vespene and self.minerals / self.vespene < resource_ratio:", "bot ID used in sc2ai ladder games http://sc2ai.net/ # The", "None) if th: owned[el] = th return owned def can_feed(self,", "await self.build(building, near=location, max_distance=max_distance, random_alternative=False, placement_step=1) async def get_next_expansion(self) ->", "mirrored=False ) # Required for events self._units_previous_map: Dict = {unit.tag:", "an ability.\"\"\" enough_supply = True if isinstance(item_id, UnitTypeId): unit =", "groups if # any resource in a group is closer", "assert len(self._game_info.player_races) == 2, \"enemy_race not available\" self.enemy_id = 3", "mining control and moving workers if a base was killed", "class. Note that this function is also triggered at the", "possible expansion via 'self.get_next_expansion()'. If the target expansion is blocked", "time_formatted(self) -> str: \"\"\" Returns time as string in min:sec", "% 2 self.supply_used += correction self.supply_army += correction self.supply_left -=", "return 0 @property_cache_once_per_frame def _abilities_all_units(self) -> Counter: \"\"\" Cache for", "{2, 5} is: # ParaSite map has 5 upper points,", "unit: Unit, ability_id: AbilityId, target: Optional[Union[Unit, Point2, Point3]] = None,", "chat message. \"\"\" assert isinstance(message, str), f\"{message} is no string\"", "= [worker for worker in self.workers.idle] bases = self.townhalls.ready geysers", "(Stasis Ward)) are also included. \"\"\" # TODO / FIXME:", "\"\"\" Cache for the already_pending function, includes all worker orders", "for place in deficit_mining_places if not place.vespene_contents] # else prefer", "(mineral field and vespene geyser) as value. \"\"\" # Idea:", "including structures.\"\"\" return self.state.enemy_units @property_cache_once_per_frame def known_enemy_structures(self) -> Units: \"\"\"List", "location for building.\"\"\" assert isinstance(building, (AbilityId, UnitTypeId)) assert isinstance(near, Point2)", "self.supply_left >= required def can_afford( self, item_id: Union[UnitTypeId, UpgradeId, AbilityId],", "Unit for order in worker.orders: abilities_amount[order.ability] += 1 if self.race", "len(resources) # Calculate center, round and add 0.5 because expansion", "enough_supply = self.can_feed(item_id) elif isinstance(item_id, UpgradeId): cost = self._game_data.upgrades[item_id.value].cost else:", "+ 1), repeat=2) if math.hypot(x, y) <= 8 ] #", "elif ( ability_target in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit) and", "a building.\"\"\" if isinstance(near, Unit): near = near.position.to2 elif near", "not location: location = await self.get_next_expansion() await self.build(building, near=location, max_distance=max_distance,", "For example long distance mining control and moving workers if", "None for distance in range(placement_step, max_distance, placement_step): possible_positions = [", "List[\"UnitCommand\"], prevent_double=True): \"\"\" Unlike 'self.do()', this function does not instantly", "cost.vespene return await self._client.actions(actions) def prevent_double_actions(self, action): # always add", "\"\"\" def on_start(self): \"\"\" Allows initializing the bot when the", "== 2, \"enemy_race not available\" self.enemy_id = 3 - self.player_id", "\"Ramp\": \"\"\" Returns the Ramp instance of the closest main-ramp", "SCV is constructing a building, already_pending would count this structure", "instead of up (see https://github.com/Blizzard/s2client-proto/issues/123), so self.supply_used and friends return", "coordinates because bases have size 5. center_x = int(sum(resource.position.x for", "will misplace the expansion. \"\"\" if not building: # self.race", "return closest async def distribute_workers(self, resource_ratio: float = 2): \"\"\"", "range(-difference)] # prepare all minerals near a base if we", "minerals first. This is only for workers that need to", "and the first iteration of game_state (self.state) are available. \"\"\"", "\"\"\" assert isinstance(upgrade_type, UpgradeId) if upgrade_type in self.state.upgrades: return 1", "== current_action.target.y: # same action, remove action if same target", "6 to any resource of another group # Distance we", "try: if action.target.x == current_action.target.x and action.target.y == current_action.target.y: #", "or units_abilities = await self.get_available_abilities([self.units.random]) \"\"\" return await self._client.query_available_abilities(units, ignore_resource_requirements)", "from .ids.upgrade_id import UpgradeId from .pixel_map import PixelMap from .position", "type is not available any more, get all other places", "'faster' \"\"\" return self.state.game_loop / 22.4 # / (1/1.4) *", "units (such as Carriers (Interceptors) or Oracles (Stasis Ward)) are", "upper points at the main ramp. # The map Acolyte", "-16 + 32 * self._game_info.terrain_height[pos] / 255 def in_placement_grid(self, pos:", "or w.is_idle) and w.distance_to(pos) < 20) or self.workers ) if", "too many workers if difference > 0: for worker in", "Units: \"\"\"List of known enemy units, including structures.\"\"\" return self.state.enemy_units", "so your bot can \"adapt\" to the opponent self.opponent_id: int", "= None self.supply_workers: Union[float, int] = None # Doesn't include", "mypy and pycharm autocomplete from .game_state import GameState from .game_data", "isinstance(building, UnitTypeId): building = self._game_data.units[building.value].creation_ability else: # AbilityId building =", "# type: Unit for order in egg.orders: abilities_amount[order.ability] += 1", "def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\" Returns", "= state.common.food_army self.supply_workers: int = state.common.food_workers # Doesn't include workers", "this point, game_data, game_info and the first iteration of game_state", "position Point2 object as key, resources (mineral field and vespene", "== UnitTypeId: building = self._game_data.units[building.value].creation_ability elif building_type == AbilityId: building", "2x2, 3x3 or 5x5 of these grid points. Caution: some", "bases.closest_to(mining_place).tag) ) else: # get tags of minerals around expansion", "\"\"\" Returns True if you have vision on a grid", "each game so your bot can \"adapt\" to the opponent", "isinstance(item_id, UnitTypeId): unit = self._game_data.units[item_id.value] cost = self._game_data.calculate_ability_cost(unit.creation_ability) if check_supply_cost:", "== 0: return None for distance in range(placement_step, max_distance, placement_step):", "-> int: \"\"\" Returns a number of buildings or units", "th: owned[el] = th return owned def can_feed(self, unit_type: UnitTypeId)", "bot class. Note that this function uses unit tags because", "\"\"\" This function is run after \"on_start\". At this point,", "await self._client.actions(actions) def prevent_double_actions(self, action): # always add actions if", "\"GameInfo\": return self._game_info def alert(self, alert_code: Alert) -> bool: \"\"\"", "<= 8 ] target_mineral = max(local_minerals, key=lambda mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral))", "'self.do()', this function does not instantly subtract minerals and vespene.", "have 2 upper points at the main ramp. # The", "self.on_building_construction_started(unit) async def _issue_building_complete_event(self, unit): if unit.build_progress < 1: return", "place.vespene_contents] # if preferred type is not available any more,", "resource_ratio: float = 2): \"\"\" Distributes workers across all the", "Dict[Point2, Units]: \"\"\" Returns dict with the correct expansion position", "def _issue_unit_added_events(self): for unit in self.units.not_structure: if unit.tag not in", "possible_points = ( point for point in possible_points # Check", "r: # success cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene", "= state.common.vespene self.supply_army: int = state.common.food_army self.supply_workers: int = state.common.food_workers", "building.\"\"\" if isinstance(near, Unit): near = near.position.to2 elif near is", "bot class. \"\"\" async def on_building_construction_started(self, unit: Unit): \"\"\" Override", "\"\"\" Returns True if there is creep on the grid", "None self.idle_worker_count: int = None self.army_count: int = None self.warp_gate_count:", "return True return True async def chat_send(self, message: str): \"\"\"", "-> Point2: return self._game_info.player_start_location @property def enemy_start_locations(self) -> List[Point2]: \"\"\"Possible", "incorrectly rounds zerg supply down instead of up (see https://github.com/Blizzard/s2client-proto/issues/123),", "be required, see ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\" assert isinstance(pos, (Point2,", "only mineral fields first if current mineral to gas ratio", "subtract minerals and vespene. \"\"\" if not actions: return None", "you are inside the boundries of the map size. def", "_issue_unit_added_events(self): for unit in self.units.not_structure: if unit.tag not in self._units_previous_map:", "return self.cached_main_base_ramp # The reason for len(ramp.upper) in {2, 5}", "performance). Finds the next possible expansion via 'self.get_next_expansion()'. If the", "\"\"\" Returns time in seconds, assumes the game is played", "= [[resource] for resource in self.state.resources] # Loop the merging", "any(mineral.distance_to(base) <= 8 for base in self.townhalls.ready) ] # distribute", "'self.do' (reduces performance). Finds the next possible expansion via 'self.get_next_expansion()'.", "building with.\"\"\" workers = ( self.workers.filter(lambda w: (w.is_gathering or w.is_idle)", "the game for the starting base building.\"\"\" async def on_upgrade_complete(self,", "on_step(self, iteration: int): \"\"\"Ran on every game step (looped in", "was killed are not being handled. WARNING: This is quite", "self.expansion_locations: def is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion, self.townhalls)):", "enemy unit), it will misplace the expansion. \"\"\" if not", "th return owned def can_feed(self, unit_type: UnitTypeId) -> bool: \"\"\"", "amount += sum([egg.orders[0].ability == ability for egg in self.units(UnitTypeId.EGG)]) return", "base building.\"\"\" async def on_upgrade_complete(self, upgrade: UpgradeId): \"\"\" Override this", "the target expansion is blocked (e.g. an enemy unit), it", "state.common.larva_count # Workaround Zerg supply rounding bug self._correct_zerg_supply() elif self.race", "True return False def select_build_worker(self, pos: Union[Unit, Point2, Point3], force:", "at a position. Remember, buildings usually use 2x2, 3x3 or", "= 15 def __init__(self): # Specific opponent bot ID used", "max_distance: Union[int, float] = 10, location: Optional[Point2] = None ):", "= None self.townhalls: Units = None self.geysers: Units = None", "and structures in production, counts double for terran \"\"\" abilities_amount", "game is played on 'faster' \"\"\" return self.state.game_loop / 22.4", "natural self.cached_main_base_ramp = min( (ramp for ramp in self.game_info.map_ramps if", "def already_pending(self, unit_type: Union[UpgradeId, UnitTypeId], all_units: bool = True) ->", "def on_building_construction_complete(self, unit: Unit): \"\"\" Override this in your bot", "-> Optional[Unit]: \"\"\"Select a worker to build a building with.\"\"\"", "need to be moved anyways, it will NOT will geysers", "async def on_building_construction_complete(self, unit: Unit): \"\"\" Override this in your", "place current_place = min(deficit_mining_places, key=lambda place: place.distance_to(worker)) # remove it", "UnitUnderAttack UpgradeComplete VespeneExhausted WarpInComplete \"\"\" assert isinstance(alert_code, Alert), f\"alert_code {alert_code}", "cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range ability_target = self._game_data.abilities[ability_id.value]._proto.target # Check if target", "+= 1 if not unit.is_ready: if self.race != Race.Terran or", "of these groups is closer than threshold together if any(", "is a self cast like stimpack) if ( ability_target ==", "out points that are too near possible_points = ( point", "\"\"\" Returns terrain z-height at a position. \"\"\" assert isinstance(pos,", "await self.on_building_construction_started(unit) async def _issue_building_complete_event(self, unit): if unit.build_progress < 1:", "type: Unit for order in egg.orders: abilities_amount[order.ability] += 1 if", "Look in game_info.py for more information \"\"\" if hasattr(self, \"cached_main_base_ramp\"):", "key, resources (mineral field and vespene geyser) as value. \"\"\"", "units_abilities = await self.get_available_abilities(self.units) or units_abilities = await self.get_available_abilities([self.units.random]) \"\"\"", "current_action.ability.id != action.ability: # different action, return true return True", "\"not structure.is_ready\") for unit in self.units.structure.not_ready: # type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability]", "state.common.food_workers # Doesn't include workers in production self.supply_cap: int =", "all worker orders (including pending). Zerg units in production (except", "\"\"\" async def on_start_async(self): \"\"\" This function is run after", "if you can place something at a position. Remember, buildings", "not in self._units_previous_map: return unit_prev = self._units_previous_map[unit.tag] if unit_prev.build_progress <", "Unit from .units import Units logger = logging.getLogger(__name__) class BotAI:", "self.units: # type: Unit for order in unit.orders: abilities_amount[order.ability] +=", "Unit)) pos = pos.position.to2.rounded return self.state.visibility[pos] == 2 def has_creep(self,", "all_units: amount += sum([o.ability == ability for u in self.units", "return True # Check if able to use ability on", "can_afford_minerals self.can_afford_vespene = can_afford_vespene self.have_enough_supply = have_enough_supply def __bool__(self): return", "async def issue_events(self): \"\"\" This function will be automatically run", "for action in actions: cost = self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals", "name return True # Check if able to use ability", "is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion, self.townhalls)): # already", "math.hypot(x, y) <= 8 ] # Dict we want to", "return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD if any(map(is_near_to_expansion, self.townhalls)): # already taken", "pass return True return True async def chat_send(self, message: str):", "return self.state.enemy_units @property_cache_once_per_frame def known_enemy_structures(self) -> Units: \"\"\"List of known", "mineral in self.state.mineral_field if mineral.distance_to(current_place) <= 8 ] target_mineral =", "Point3, Unit)) pos = pos.position.to2.rounded return self.state.visibility[pos] == 2 def", "for worker in worker_pool: # as long as have workers", "Cache for the already_pending function, includes all worker orders (including", "self._previous_upgrades: Set[UpgradeId] = set() self.units: Units = Units([]) def _prepare_first_step(self):", "need to send them to the closest patch if len(worker_pool)", "None: near = near.to2 else: return p = await self.find_placement(building,", "vespene. \"\"\" if not actions: return None if prevent_double: actions", "32 * self._game_info.terrain_height[pos] / 255 def in_placement_grid(self, pos: Union[Point2, Point3,", "mining_place.is_vespene_geyser: # get all workers that target the gas extraction", "field that is near and has the most minerals left", "self.game_info.map_ramps if len(ramp.upper) in {2, 5}), key=lambda r: self.start_location.distance_to(r.top_center), )", "self.supply_army += correction self.supply_left -= correction async def get_available_abilities( self,", "location = await self.get_next_expansion() await self.build(building, near=location, max_distance=max_distance, random_alternative=False, placement_step=1)", "base in self.townhalls.ready) ] # distribute every worker in the", "autocomplete from .game_state import GameState from .game_data import GameData, AbilityData", "UpgradeId): \"\"\" Override this in your bot class. \"\"\" def", "self._client.actions(actions) def prevent_double_actions(self, action): # always add actions if queued", "# or are on their way back from it local_workers", "is no Alert\" return alert_code.value in self.state.alerts @property def start_location(self)", "self.start_location.distance_to(r.top_center), ) return self.cached_main_base_ramp @property_cache_forever def expansion_locations(self) -> Dict[Point2, Units]:", "self.get_available_abilities([self.units.random]) \"\"\" return await self._client.query_available_abilities(units, ignore_resource_requirements) async def expand_now( self,", "dx in range(-distance, distance + 1, placement_step)] + [(-distance, dy)", "from new state before on_step.\"\"\" self.state: GameState = state #", "None self.minerals: int = None self.vespene: int = None self.supply_army:", "level = upgrade_type.name[-1] creationAbilityID = self._game_data.upgrades[upgrade_type.value].research_ability.id for structure in self.units.filter(lambda", "self.units: Units = Units([]) def _prepare_first_step(self): \"\"\"First step extra preparations.", "Alert), f\"alert_code {alert_code} is no Alert\" return alert_code.value in self.state.alerts", "mineral to gas ratio is less than target ratio if", "resource resource_groups = [[resource] for resource in self.state.resources] # Loop", "For the functions below, make sure you are inside the", "of the map size. def get_terrain_height(self, pos: Union[Point2, Point3, Unit])", "can pass through a grid point. \"\"\" assert isinstance(pos, (Point2,", "(Point2, Point3, Unit)), f\"pos is not of type Point2, Point3", "): return True # Check if able to use ability", "of buildings. If all_units==True, then build queues of other units", "x, y in itertools.product(range(-offset_range, offset_range + 1), repeat=2) if math.hypot(x,", "prefer sending workers to minerals first. This is only for", "for ramp in self.game_info.map_ramps if len(ramp.upper) in {2, 5}), key=lambda", "# If an SCV is constructing a building, already_pending would", "a gas extraction site, # go to the mineral field", ") # too many workers if difference > 0: for", "False) # For the functions below, make sure you are", "else: possible_mining_places = [place for place in deficit_mining_places if place.vespene_contents]", "next expansion location.\"\"\" closest = None distance = math.inf for", "not self.can_afford_minerals: return ActionResult.NotEnoughMinerals elif not self.have_enough_supply: return ActionResult.NotEnoughFood else:", "tags of the minerals he could mine at that base", "\"\"\" Unlike 'self.do()', this function does not instantly subtract minerals", ") -> List[List[AbilityId]]: \"\"\" Returns available abilities of one or", "assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self.state.visibility[pos]", "[ mineral for mineral in self.state.mineral_field if any(mineral.distance_to(base) <= 8", "(including pending). Zerg units in production (except queens and morphing", "{action})\") return r async def do_actions(self, actions: List[\"UnitCommand\"], prevent_double=True): \"\"\"", "morphing units) and structures in production, counts double for terran", "max(local_minerals, key=lambda mineral: mineral.mineral_contents) actions.append(worker.gather(target_mineral)) # more workers to distribute", "x < 1: researching 1: finished \"\"\" assert isinstance(upgrade_type, UpgradeId)", "if order.ability.id is creationAbilityID: if level and order.ability.button_name[-1] != level:", "int = None self.supply_army: Union[float, int] = None self.supply_workers: Union[float,", "True) -> int: \"\"\" Returns a number of buildings or", "to the closest patch if len(worker_pool) > len(deficit_mining_places): all_minerals_near_base =", "def issue_events(self): \"\"\" This function will be automatically run from", "on every game step (looped in realtime mode).\"\"\" raise NotImplementedError", "from .game_data import AbilityData, GameData # imports for mypy and", "target: Optional[Union[Unit, Point2, Point3]] = None, only_check_energy_and_cooldown: bool = False,", "\"\"\"Find next expansion location.\"\"\" closest = None distance = math.inf", "before on_step.\"\"\" self.state: GameState = state # See game_state.py #", "of resource of these groups is closer than threshold together", "amount async def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance:", "for mineral in self.state.mineral_field if mineral.distance_to(mining_place) <= 8 } #", "def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit:", "that are too near possible_points = ( point for point", "Point2(p).offset(near).to2 for p in ( [(dx, -distance) for dx in", "self.cached_main_base_ramp @property_cache_forever def expansion_locations(self) -> Dict[Point2, Units]: \"\"\" Returns dict", "size 5. center_x = int(sum(resource.position.x for resource in resources) /", "\"\"\" return await self._client.query_available_abilities(units, ignore_resource_requirements) async def expand_now( self, building:", "NOTE: This function is far from optimal, if you really", "is_near_to_expansion(t): return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD th = next((x for x", "building = self._game_data.abilities[building.value] if await self.can_place(building, near): return near if", "UnitTypeId.BANELING, UnitTypeId.BANELINGBURROWED, UnitTypeId.BANELINGCOCOON, } correction = self.units(half_supply_units).amount % 2 self.supply_used", "if ability is on cooldown if cached_abilities_of_unit: abilities = cached_abilities_of_unit", "1: finished \"\"\" assert isinstance(upgrade_type, UpgradeId) if upgrade_type in self.state.upgrades:", "True if you can place something at a position. Remember,", "get all target tags a worker can have # tags", "enough energy to cast or if ability is on cooldown", "by the player.\"\"\" owned = {} for el in self.expansion_locations:", "UpgradeId) -> Union[int, float]: \"\"\" Check if an upgrade is", "key=lambda point: sum(point.distance_to(resource) for resource in resources)) centers[result] = resources", "ability on a unit elif ( ability_target in {Target.Unit.value, Target.PointOrUnit.value}", "if action.queue: return True if action.unit.orders: # action: UnitCommand #", "from .ids.ability_id import AbilityId from .ids.unit_typeid import UnitTypeId from .ids.upgrade_id", "of one or more units. Right know only checks cooldown,", "target expansion is blocked (e.g. an enemy unit), it will", "elif near is not None: near = near.to2 else: return", "have # tags of the minerals he could mine at", "(action: {action})\") return r async def do_actions(self, actions: List[\"UnitCommand\"], prevent_double=True):", "Point2, Point3)) # check if unit has enough energy to", "None, ) -> bool: \"\"\"Tests if a unit has an", "boundries of the map size. def get_terrain_height(self, pos: Union[Point2, Point3,", "bot class. Note that this function is also triggered at", "there are an odd number of zerglings and banelings. This", "async def can_cast( self, unit: Unit, ability_id: AbilityId, target: Optional[Union[Unit,", "self._units_previous_map: return unit_prev = self._units_previous_map[unit.tag] if unit_prev.build_progress < 1: await", "buildings usually use 2x2, 3x3 or 5x5 of these grid", "location. Look in game_info.py for more information \"\"\" if hasattr(self,", "units) and structures in production, counts double for terran \"\"\"", "worker in the pool for worker in worker_pool: # as", "int = None self.units: Units = None self.workers: Units =", "y offset might be required, see ramp code: https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 \"\"\"", "any resource in a group is closer than 6 to", "action {action}\") return ActionResult.Error r = await self._client.actions(action) if not", "the same each game so your bot can \"adapt\" to", "except ValueError: # Hardcoded hotfix for Honorgrounds LE map, as", "Units = self.units(race_gas[self.race]) self.minerals: int = state.common.minerals self.vespene: int =", "Returns terrain height at a position. Caution: terrain height is", "self, units: Union[List[Unit], Units], ignore_resource_requirements=False ) -> List[List[AbilityId]]: \"\"\" Returns", "self.select_build_worker(p) if unit is None or not self.can_afford(building): return ActionResult.Error", "offset_range = 7 offsets = [ (x, y) for x,", "= [place for place in deficit_mining_places if place.vespene_contents] # if", "or not unit.is_structure: # If an SCV is constructing a", "= None, ) -> bool: \"\"\"Tests if a unit has", "if d is None: continue if d < distance: distance", "possible = [p for r, p in zip(res, possible_positions) if", "self.workers: # type: Unit for order in worker.orders: abilities_amount[order.ability] +=", "to build the unit \"\"\" required = self._game_data.units[unit_type.value]._proto.food_required return required", ".cache import property_cache_forever, property_cache_once_per_frame from .data import ActionResult, Alert, Race,", "unit.distance_to(target) <= cast_range ): # cant replace 1 with \"Target.None.value\"", "no Alert\" return alert_code.value in self.state.alerts @property def start_location(self) ->", "placement_step)] ) ] res = await self._client.query_building_placement(building, possible_positions) possible =", "structure.is_ready\") abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] += 1 return abilities_amount @property_cache_once_per_frame def _abilities_workers_and_eggs(self) ->", "Race.Zerg: self.larva_count: int = state.common.larva_count # Workaround Zerg supply rounding", "Unit, Point2, Point3)) # check if unit has enough energy", "production, and all structures, and all morphs \"\"\" abilities_amount =", "= self._game_data.abilities[building.value] r = await self._client.query_building_placement(building, [position]) return r[0] ==", "cast_range ): return True # Check if able to use", "or not self.townhalls.ready: return actions = [] worker_pool = [worker", "if math.hypot(x, y) <= 8 ] # Dict we want", "self.state.visibility[pos] == 2 def has_creep(self, pos: Union[Point2, Point3, Unit]) ->", "write your own distribution function. For example long distance mining", "structure.is_ready\") for unit in self.units.structure.not_ready: # type: Unit abilities_amount[self._game_data.units[unit.type_id.value].creation_ability] +=", "_correct_zerg_supply(self): \"\"\" The client incorrectly rounds zerg supply down instead", "def on_building_construction_started(self, unit: Unit): \"\"\" Override this in your bot", "(Point2, Point3)) and unit.distance_to(target) <= cast_range ): return True return", "correction = self.units(half_supply_units).amount % 2 self.supply_used += correction self.supply_army +=", "1: await self.on_building_construction_complete(unit) async def _issue_unit_dead_events(self): for unit_tag in self.state.dead_units:", "self.supply_workers: Union[float, int] = None # Doesn't include workers in", "other maps have 2 upper points at the main ramp.", "self.opponent_id: int = None self.units: Units = None self.workers: Units", "= self.townhalls.ready geysers = self.geysers.ready # list of places that", "for resource in resources) / amount) + 0.5 center_y =", "group for every resource, then merge these groups if #", "None, only_check_energy_and_cooldown: bool = False, cached_abilities_of_unit: List[AbilityId] = None, )", "position: Point2) -> bool: \"\"\"Tests if a building can be", "< 1: researching 1: finished \"\"\" assert isinstance(upgrade_type, UpgradeId) if", "w in self.workers for o in w.orders]) amount += sum([egg.orders[0].ability", "= False, cached_abilities_of_unit: List[AbilityId] = None, ) -> bool: \"\"\"Tests", "for unit_tag in self.state.dead_units: await self.on_unit_destroyed(unit_tag) async def on_unit_destroyed(self, unit_tag):", "need more workers deficit_mining_places = [] for mining_place in bases", "unit.is_structure and unit.is_ready): for order in structure.orders: if order.ability.id is", "= { mineral.tag for mineral in self.state.mineral_field if mineral.distance_to(mining_place) <=", "bool: \"\"\" Returns True if a unit can pass through", "0 < x < 1: researching 1: finished \"\"\" assert", "the current minerals to gas ratio is bigger than `resource_ratio`,", "= type(building) assert building_type in {AbilityData, AbilityId, UnitTypeId} if building_type", "= self._game_data.calculate_ability_cost(action.ability) self.minerals -= cost.minerals self.vespene -= cost.vespene return await", "expansion location.\"\"\" closest = None distance = math.inf for el", "order in structure.orders: if order.ability.id is creationAbilityID: if level and", "current_action = action.unit.orders[0] if current_action.ability.id != action.ability: # different action,", "# Check if all resources have enough space to point", "= self._game_data.units[building.value].creation_ability elif building_type == AbilityId: building = self._game_data.abilities[building.value] r", "expansion local_minerals_tags = { mineral.tag for mineral in self.state.mineral_field if", "1 def in_pathing_grid(self, pos: Union[Point2, Point3, Unit]) -> bool: \"\"\"", "is closer than 6 to any resource of another group", "the SCV order, and once from \"not structure.is_ready\") for unit", "= client self._game_info: \"GameInfo\" = game_info self._game_data: GameData = game_data", "for resource in resources) ) # Choose best fitting point", "resources in resource_groups: # Possible expansion points amount = len(resources)", "for o in w.orders]) amount += sum([egg.orders[0].ability == ability for", "- self.supply_used if self.race == Race.Zerg: self.larva_count: int = state.common.larva_count", "creationAbilityID: if level and order.ability.button_name[-1] != level: return 0 return", "to have refined worker control, you should write your own", "closest = el return closest async def distribute_workers(self, resource_ratio: float", "possible_positions) if r == ActionResult.Success] if not possible: continue if", "closest to the start position). try: self.cached_main_base_ramp = min( (ramp", "= None self.supply_army: Union[float, int] = None self.supply_workers: Union[float, int]", "in resource_groups: # Possible expansion points amount = len(resources) #", "isinstance(target, (Point2, Point3)) and unit.distance_to(target) <= cast_range ): # cant", "been researched. Example usage: units_abilities = await self.get_available_abilities(self.units) or units_abilities", "TODO / FIXME: SCV building a structure might be counted", "workers to minerals first. This is only for workers that", "process as long as we change something found_something = True", "self.idle_worker_count: int = None self.army_count: int = None self.warp_gate_count: int", "geysers on its own. NOTE: This function is far from", "1 if self.race != Race.Terran: # If an SCV is", "Unit) assert isinstance(ability_id, AbilityId) assert isinstance(target, (type(None), Unit, Point2, Point3))", "amount of workers, skip mining place if not difference: continue", "enum name return True # Check if able to use", "this function does not instantly subtract minerals and vespene. \"\"\"", "# AbilityId building = self._game_data.abilities[building.value] if await self.can_place(building, near): return", "function. For example long distance mining control and moving workers" ]
[ "class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH = \"requirements_mismatch\" @dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata): scope =", "= metadata( \"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet, ) return JVMLockfileMetadataV1(requirements) @classmethod def", "import FrozenOrderedSet _jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH = \"requirements_mismatch\"", "annotations from dataclasses import dataclass from enum import Enum from", "= LockfileScope.JVM @staticmethod def new( requirements: Iterable[ArtifactRequirement], ) -> JVMLockfileMetadata:", "used in the current execution context.\"\"\" raise NotImplementedError(\"call `is_valid_for` on", "error_suffix: str, ) -> JVMLockfileMetadataV1: metadata = _get_metadata(json_dict, lockfile_description, error_suffix)", "non-strict subset of the metadata requirements. \"\"\" failure_reasons: set[InvalidJVMLockfileReason] =", "self, requirements: Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation: \"\"\"Returns Truthy", "return cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile, lockfile_path, resolve_name ), )", "JVMLockfileMetadataV1: metadata = _get_metadata(json_dict, lockfile_description, error_suffix) requirements = metadata( \"generated_with_requirements\",", "subclasses only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version that permits", "\"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def from_lockfile( cls, lockfile: bytes, lockfile_path:", "calling sites a predictable method to call to construct a", "import ArtifactRequirement from pants.util.ordered_set import FrozenOrderedSet _jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM) class", "\"\"\"Lockfile version that permits specifying a requirements as a set", "for i in requirements)) @classmethod def _from_json_dict( cls: type[JVMLockfileMetadataV1], json_dict:", "from typing import Any, Iterable, cast from pants.core.util_rules.lockfile_metadata import (", "_reading_ older, deprecated metadata versions. \"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def", "def _from_json_dict( cls: type[JVMLockfileMetadataV1], json_dict: dict[Any, Any], lockfile_description: str, error_suffix:", "is defined as the request requirements being a non-strict subset", "REQUIREMENTS_MISMATCH = \"requirements_mismatch\" @dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata): scope = LockfileScope.JVM @staticmethod", "= cast(JVMLockfileMetadataV1, instance) return { \"generated_with_requirements\": ( sorted(instance.requirements) if instance.requirements", "under the Apache License, Version 2.0 (see LICENSE). from __future__", "than a digest. Validity is tested by the set of", "JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version that permits specifying a requirements as a", "set rather than a digest. Validity is tested by the", "Iterable[ArtifactRequirement], ) -> JVMLockfileMetadata: \"\"\"Call the most recent version of", "class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version that permits specifying a requirements as", "scope = LockfileScope.JVM @staticmethod def new( requirements: Iterable[ArtifactRequirement], ) ->", "@classmethod def _from_json_dict( cls: type[JVMLockfileMetadataV1], json_dict: dict[Any, Any], lockfile_description: str,", "older, deprecated metadata versions. \"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def from_lockfile(", "dataclasses import dataclass from enum import Enum from typing import", "import dataclass from enum import Enum from typing import Any,", "-> dict[Any, Any]: instance = cast(JVMLockfileMetadataV1, instance) return { \"generated_with_requirements\":", "strings being the same in the user requirements as those", "self, requirements: Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation: \"\"\"Returns a", "cls, requirements: Iterable[ArtifactRequirement] ) -> JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str() for i", "requirements strings being the same in the user requirements as", "-> LockfileMetadataValidation: \"\"\"Returns Truthy if this `JVMLockfileMetadata` can be used", "| None, ) -> LockfileMetadataValidation: \"\"\"Returns a truthy object if", "additional_header_attrs(cls, instance: LockfileMetadata) -> dict[Any, Any]: instance = cast(JVMLockfileMetadataV1, instance)", "static method should be used in place of the `LockfileMetadata`", "new `LockfileMetadata` for writing, while still allowing us to support", "lockfile_description: str, error_suffix: str, ) -> JVMLockfileMetadataV1: metadata = _get_metadata(json_dict,", "License, Version 2.0 (see LICENSE). from __future__ import annotations from", "None = None, resolve_name: str | None = None )", "FrozenOrderedSet[str], FrozenOrderedSet, ) return JVMLockfileMetadataV1(requirements) @classmethod def additional_header_attrs(cls, instance: LockfileMetadata)", "Iterable, cast from pants.core.util_rules.lockfile_metadata import ( LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata,", "lockfile_path, resolve_name ), ) def is_valid_for( self, requirements: Iterable[ArtifactRequirement] |", "__future__ import annotations from dataclasses import dataclass from enum import", "of the metadata requirements. \"\"\" failure_reasons: set[InvalidJVMLockfileReason] = set() if", "specifying a requirements as a set rather than a digest.", "enum import Enum from typing import Any, Iterable, cast from", ") } def is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None, )", "Validity is tested by the set of requirements strings being", "in the user requirements as those in the stored requirements.", "JVMLockfileMetadataV1(requirements) @classmethod def additional_header_attrs(cls, instance: LockfileMetadata) -> dict[Any, Any]: instance", "digest. Validity is tested by the set of requirements strings", "execution context.\"\"\" raise NotImplementedError(\"call `is_valid_for` on subclasses only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True)", "of requirements strings being the same in the user requirements", "project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License,", "Licensed under the Apache License, Version 2.0 (see LICENSE). from", "metadata requirements. \"\"\" failure_reasons: set[InvalidJVMLockfileReason] = set() if not self.requirements.issuperset(i.to_metadata_str()", "be used in the current execution context.\"\"\" raise NotImplementedError(\"call `is_valid_for`", "is tested by the set of requirements strings being the", "str, ) -> JVMLockfileMetadataV1: metadata = _get_metadata(json_dict, lockfile_description, error_suffix) requirements", "# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed", "the Apache License, Version 2.0 (see LICENSE). from __future__ import", ") def is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None, ) ->", "can be used in the current execution context.\"\"\" raise NotImplementedError(\"call", "@dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata): scope = LockfileScope.JVM @staticmethod def new( requirements:", "LockfileScope.JVM @staticmethod def new( requirements: Iterable[ArtifactRequirement], ) -> JVMLockfileMetadata: \"\"\"Call", "set[InvalidJVMLockfileReason] = set() if not self.requirements.issuperset(i.to_metadata_str() for i in requirements", "version that permits specifying a requirements as a set rather", "@classmethod def from_artifact_requirements( cls, requirements: Iterable[ArtifactRequirement] ) -> JVMLockfileMetadataV1: return", "cls: type[JVMLockfileMetadataV1], json_dict: dict[Any, Any], lockfile_description: str, error_suffix: str, )", "LockfileMetadata) -> dict[Any, Any]: instance = cast(JVMLockfileMetadataV1, instance) return {", "requirements: FrozenOrderedSet[str] @classmethod def from_artifact_requirements( cls, requirements: Iterable[ArtifactRequirement] ) ->", ") -> LockfileMetadataValidation: \"\"\"Returns Truthy if this `JVMLockfileMetadata` can be", "`LockfileMetadata` constructor. This gives calling sites a predictable method to", "type[JVMLockfileMetadataV1], json_dict: dict[Any, Any], lockfile_description: str, error_suffix: str, ) ->", "requirements. For this version, \"match\" is defined as the request", "None ) } def is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None,", "not self.requirements.issuperset(i.to_metadata_str() for i in requirements or []): failure_reasons.add(InvalidJVMLockfileReason.REQUIREMENTS_MISMATCH) return", "on subclasses only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version that", "by the set of requirements strings being the same in", "metadata = _get_metadata(json_dict, lockfile_description, error_suffix) requirements = metadata( \"generated_with_requirements\", FrozenOrderedSet[str],", "requirements being a non-strict subset of the metadata requirements. \"\"\"", "from __future__ import annotations from dataclasses import dataclass from enum", "rather than a digest. Validity is tested by the set", "method should be used in place of the `LockfileMetadata` constructor.", "raise NotImplementedError(\"call `is_valid_for` on subclasses only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata):", "`JVMLockfileMetadata` can be used in the current execution context.\"\"\" raise", "CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see", "being the same in the user requirements as those in", "failure_reasons: set[InvalidJVMLockfileReason] = set() if not self.requirements.issuperset(i.to_metadata_str() for i in", "JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def from_lockfile( cls, lockfile: bytes, lockfile_path: str |", "_get_metadata, lockfile_metadata_registrar, ) from pants.jvm.resolve.common import ArtifactRequirement from pants.util.ordered_set import", "requirements. \"\"\" requirements: FrozenOrderedSet[str] @classmethod def from_artifact_requirements( cls, requirements: Iterable[ArtifactRequirement]", "instance.requirements is not None else None ) } def is_valid_for(", "FrozenOrderedSet, ) return JVMLockfileMetadataV1(requirements) @classmethod def additional_header_attrs(cls, instance: LockfileMetadata) ->", "-> JVMLockfileMetadata: \"\"\"Call the most recent version of the `LockfileMetadata`", "in the stored requirements. \"\"\" requirements: FrozenOrderedSet[str] @classmethod def from_artifact_requirements(", "current execution context.\"\"\" raise NotImplementedError(\"call `is_valid_for` on subclasses only\") @_jvm_lockfile_metadata(1)", "only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version that permits specifying", "in place of the `LockfileMetadata` constructor. This gives calling sites", "same in the user requirements as those in the stored", "the stored requirements. \"\"\" requirements: FrozenOrderedSet[str] @classmethod def from_artifact_requirements( cls,", "None, resolve_name: str | None = None ) -> JVMLockfileMetadataV1:", "used in place of the `LockfileMetadata` constructor. This gives calling", "in the current execution context.\"\"\" raise NotImplementedError(\"call `is_valid_for` on subclasses", "being a non-strict subset of the metadata requirements. \"\"\" failure_reasons:", "recent version of the `LockfileMetadata` class to construct a concrete", "lockfile, lockfile_path, resolve_name ), ) def is_valid_for( self, requirements: Iterable[ArtifactRequirement]", "cast from pants.core.util_rules.lockfile_metadata import ( LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata, lockfile_metadata_registrar,", "to construct a concrete instance. This static method should be", "resolve_name: str | None = None ) -> JVMLockfileMetadataV1: return", "def is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation:", "def new( requirements: Iterable[ArtifactRequirement], ) -> JVMLockfileMetadata: \"\"\"Call the most", "gives calling sites a predictable method to call to construct", "-> JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str() for i in requirements)) @classmethod def", ") return JVMLockfileMetadataV1(requirements) @classmethod def additional_header_attrs(cls, instance: LockfileMetadata) -> dict[Any,", "from pants.core.util_rules.lockfile_metadata import ( LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata, lockfile_metadata_registrar, )", "a digest. Validity is tested by the set of requirements", "is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation: \"\"\"Returns", "\"requirements_mismatch\" @dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata): scope = LockfileScope.JVM @staticmethod def new(", "this `JVMLockfileMetadata` can be used in the current execution context.\"\"\"", "the request requirements match the metadata requirements. For this version,", "support _reading_ older, deprecated metadata versions. \"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod", "JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile, lockfile_path, resolve_name ), ) def is_valid_for(", "\"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet, ) return JVMLockfileMetadataV1(requirements) @classmethod def additional_header_attrs(cls, instance:", "us to support _reading_ older, deprecated metadata versions. \"\"\" return", "LICENSE). from __future__ import annotations from dataclasses import dataclass from", "requirements: Iterable[ArtifactRequirement] ) -> JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str() for i in", "def from_lockfile( cls, lockfile: bytes, lockfile_path: str | None =", "versions. \"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def from_lockfile( cls, lockfile: bytes,", "if not self.requirements.issuperset(i.to_metadata_str() for i in requirements or []): failure_reasons.add(InvalidJVMLockfileReason.REQUIREMENTS_MISMATCH)", "LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile, lockfile_path, resolve_name ), ) def is_valid_for( self,", "JVMLockfileMetadataV1: return cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile, lockfile_path, resolve_name ),", "request requirements being a non-strict subset of the metadata requirements.", "instance = cast(JVMLockfileMetadataV1, instance) return { \"generated_with_requirements\": ( sorted(instance.requirements) if", "This static method should be used in place of the", "`LockfileMetadata` for writing, while still allowing us to support _reading_", "sorted(instance.requirements) if instance.requirements is not None else None ) }", "\"\"\"Returns a truthy object if the request requirements match the", "(see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0", "def additional_header_attrs(cls, instance: LockfileMetadata) -> dict[Any, Any]: instance = cast(JVMLockfileMetadataV1,", "allowing us to support _reading_ older, deprecated metadata versions. \"\"\"", "request requirements match the metadata requirements. For this version, \"match\"", "JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str() for i in requirements)) @classmethod def _from_json_dict(", "match the metadata requirements. For this version, \"match\" is defined", "metadata versions. \"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def from_lockfile( cls, lockfile:", "None ) -> JVMLockfileMetadataV1: return cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile,", "@classmethod def additional_header_attrs(cls, instance: LockfileMetadata) -> dict[Any, Any]: instance =", "\"\"\"Returns Truthy if this `JVMLockfileMetadata` can be used in the", "Iterable[ArtifactRequirement] ) -> JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str() for i in requirements))", "the set of requirements strings being the same in the", "the `LockfileMetadata` class to construct a concrete instance. This static", "import annotations from dataclasses import dataclass from enum import Enum", "json_dict: dict[Any, Any], lockfile_description: str, error_suffix: str, ) -> JVMLockfileMetadataV1:", "import Any, Iterable, cast from pants.core.util_rules.lockfile_metadata import ( LockfileMetadata, LockfileMetadataValidation,", "str, error_suffix: str, ) -> JVMLockfileMetadataV1: metadata = _get_metadata(json_dict, lockfile_description,", ") -> JVMLockfileMetadataV1: return cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile, lockfile_path,", "permits specifying a requirements as a set rather than a", "this version, \"match\" is defined as the request requirements being", "None = None ) -> JVMLockfileMetadataV1: return cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope(", "LockfileMetadataValidation, LockfileScope, _get_metadata, lockfile_metadata_registrar, ) from pants.jvm.resolve.common import ArtifactRequirement from", "@dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version that permits specifying a requirements", "a predictable method to call to construct a new `LockfileMetadata`", "a new `LockfileMetadata` for writing, while still allowing us to", "_jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH = \"requirements_mismatch\" @dataclass(frozen=True) class", "| None = None, resolve_name: str | None = None", "cls(FrozenOrderedSet(i.to_metadata_str() for i in requirements)) @classmethod def _from_json_dict( cls: type[JVMLockfileMetadataV1],", "not None else None ) } def is_valid_for( self, requirements:", "from pants.jvm.resolve.common import ArtifactRequirement from pants.util.ordered_set import FrozenOrderedSet _jvm_lockfile_metadata =", "typing import Any, Iterable, cast from pants.core.util_rules.lockfile_metadata import ( LockfileMetadata,", "context.\"\"\" raise NotImplementedError(\"call `is_valid_for` on subclasses only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True) class", "| None = None ) -> JVMLockfileMetadataV1: return cast( JVMLockfileMetadataV1,", "defined as the request requirements being a non-strict subset of", "from enum import Enum from typing import Any, Iterable, cast", "lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH = \"requirements_mismatch\" @dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata): scope", "tested by the set of requirements strings being the same", "\"match\" is defined as the request requirements being a non-strict", "Truthy if this `JVMLockfileMetadata` can be used in the current", "bytes, lockfile_path: str | None = None, resolve_name: str |", "| None, ) -> LockfileMetadataValidation: \"\"\"Returns Truthy if this `JVMLockfileMetadata`", "= _get_metadata(json_dict, lockfile_description, error_suffix) requirements = metadata( \"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet,", "\"\"\" failure_reasons: set[InvalidJVMLockfileReason] = set() if not self.requirements.issuperset(i.to_metadata_str() for i", "pants.core.util_rules.lockfile_metadata import ( LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata, lockfile_metadata_registrar, ) from", "while still allowing us to support _reading_ older, deprecated metadata", "ArtifactRequirement from pants.util.ordered_set import FrozenOrderedSet _jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum):", "return { \"generated_with_requirements\": ( sorted(instance.requirements) if instance.requirements is not None", "str | None = None ) -> JVMLockfileMetadataV1: return cast(", "), ) def is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None, )", "subset of the metadata requirements. \"\"\" failure_reasons: set[InvalidJVMLockfileReason] = set()", "return JVMLockfileMetadataV1(requirements) @classmethod def additional_header_attrs(cls, instance: LockfileMetadata) -> dict[Any, Any]:", "writing, while still allowing us to support _reading_ older, deprecated", "cast(JVMLockfileMetadataV1, instance) return { \"generated_with_requirements\": ( sorted(instance.requirements) if instance.requirements is", "truthy object if the request requirements match the metadata requirements.", "should be used in place of the `LockfileMetadata` constructor. This", "InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH = \"requirements_mismatch\" @dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata): scope = LockfileScope.JVM", "LockfileScope, _get_metadata, lockfile_metadata_registrar, ) from pants.jvm.resolve.common import ArtifactRequirement from pants.util.ordered_set", "else None ) } def is_valid_for( self, requirements: Iterable[ArtifactRequirement] |", "contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version", "concrete instance. This static method should be used in place", "class to construct a concrete instance. This static method should", "metadata requirements. For this version, \"match\" is defined as the", "class JVMLockfileMetadata(LockfileMetadata): scope = LockfileScope.JVM @staticmethod def new( requirements: Iterable[ArtifactRequirement],", "construct a concrete instance. This static method should be used", "a requirements as a set rather than a digest. Validity", "error_suffix) requirements = metadata( \"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet, ) return JVMLockfileMetadataV1(requirements)", "constructor. This gives calling sites a predictable method to call", "new( requirements: Iterable[ArtifactRequirement], ) -> JVMLockfileMetadata: \"\"\"Call the most recent", "This gives calling sites a predictable method to call to", "Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation: \"\"\"Returns Truthy if this", "i in requirements)) @classmethod def _from_json_dict( cls: type[JVMLockfileMetadataV1], json_dict: dict[Any,", "FrozenOrderedSet _jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH = \"requirements_mismatch\" @dataclass(frozen=True)", "lockfile: bytes, lockfile_path: str | None = None, resolve_name: str", "Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache", "-> LockfileMetadataValidation: \"\"\"Returns a truthy object if the request requirements", "Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under", "# Licensed under the Apache License, Version 2.0 (see LICENSE).", "metadata( \"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet, ) return JVMLockfileMetadataV1(requirements) @classmethod def additional_header_attrs(cls,", "from_lockfile( cls, lockfile: bytes, lockfile_path: str | None = None,", "a set rather than a digest. Validity is tested by", "( LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata, lockfile_metadata_registrar, ) from pants.jvm.resolve.common import", "@classmethod def from_lockfile( cls, lockfile: bytes, lockfile_path: str | None", "2.0 (see LICENSE). from __future__ import annotations from dataclasses import", "_from_json_dict( cls: type[JVMLockfileMetadataV1], json_dict: dict[Any, Any], lockfile_description: str, error_suffix: str,", "a non-strict subset of the metadata requirements. \"\"\" failure_reasons: set[InvalidJVMLockfileReason]", "requirements: Iterable[ArtifactRequirement], ) -> JVMLockfileMetadata: \"\"\"Call the most recent version", "cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile, lockfile_path, resolve_name ), ) def", "resolve_name ), ) def is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None,", "For this version, \"match\" is defined as the request requirements", "import Enum from typing import Any, Iterable, cast from pants.core.util_rules.lockfile_metadata", "Any]: instance = cast(JVMLockfileMetadataV1, instance) return { \"generated_with_requirements\": ( sorted(instance.requirements)", "version, \"match\" is defined as the request requirements being a", "method to call to construct a new `LockfileMetadata` for writing,", "= None, resolve_name: str | None = None ) ->", "cls, lockfile: bytes, lockfile_path: str | None = None, resolve_name:", "lockfile_description, error_suffix) requirements = metadata( \"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet, ) return", "None else None ) } def is_valid_for( self, requirements: Iterable[ArtifactRequirement]", "return cls(FrozenOrderedSet(i.to_metadata_str() for i in requirements)) @classmethod def _from_json_dict( cls:", "the same in the user requirements as those in the", "those in the stored requirements. \"\"\" requirements: FrozenOrderedSet[str] @classmethod def", "\"\"\"Call the most recent version of the `LockfileMetadata` class to", "Any, Iterable, cast from pants.core.util_rules.lockfile_metadata import ( LockfileMetadata, LockfileMetadataValidation, LockfileScope,", "LockfileMetadataValidation: \"\"\"Returns Truthy if this `JVMLockfileMetadata` can be used in", "user requirements as those in the stored requirements. \"\"\" requirements:", "FrozenOrderedSet[str] @classmethod def from_artifact_requirements( cls, requirements: Iterable[ArtifactRequirement] ) -> JVMLockfileMetadataV1:", "if the request requirements match the metadata requirements. For this", ") -> JVMLockfileMetadataV1: metadata = _get_metadata(json_dict, lockfile_description, error_suffix) requirements =", "deprecated metadata versions. \"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def from_lockfile( cls,", ") -> LockfileMetadataValidation: \"\"\"Returns a truthy object if the request", "requirements. \"\"\" failure_reasons: set[InvalidJVMLockfileReason] = set() if not self.requirements.issuperset(i.to_metadata_str() for", "of the `LockfileMetadata` constructor. This gives calling sites a predictable", "Apache License, Version 2.0 (see LICENSE). from __future__ import annotations", "import ( LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata, lockfile_metadata_registrar, ) from pants.jvm.resolve.common", "self.requirements.issuperset(i.to_metadata_str() for i in requirements or []): failure_reasons.add(InvalidJVMLockfileReason.REQUIREMENTS_MISMATCH) return LockfileMetadataValidation(failure_reasons)", "requirements match the metadata requirements. For this version, \"match\" is", "None, ) -> LockfileMetadataValidation: \"\"\"Returns a truthy object if the", "= lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH = \"requirements_mismatch\" @dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata):", "construct a new `LockfileMetadata` for writing, while still allowing us", "from_artifact_requirements( cls, requirements: Iterable[ArtifactRequirement] ) -> JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str() for", "lockfile_path: str | None = None, resolve_name: str | None", "stored requirements. \"\"\" requirements: FrozenOrderedSet[str] @classmethod def from_artifact_requirements( cls, requirements:", "the current execution context.\"\"\" raise NotImplementedError(\"call `is_valid_for` on subclasses only\")", "dict[Any, Any]: instance = cast(JVMLockfileMetadataV1, instance) return { \"generated_with_requirements\": (", "pants.util.ordered_set import FrozenOrderedSet _jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH =", "\"\"\" requirements: FrozenOrderedSet[str] @classmethod def from_artifact_requirements( cls, requirements: Iterable[ArtifactRequirement] )", "sites a predictable method to call to construct a new", "-> JVMLockfileMetadataV1: return cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM, lockfile, lockfile_path, resolve_name", "set of requirements strings being the same in the user", "instance. This static method should be used in place of", "LockfileMetadataValidation: \"\"\"Returns a truthy object if the request requirements match", "`is_valid_for` on subclasses only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version", "dataclass from enum import Enum from typing import Any, Iterable,", "a concrete instance. This static method should be used in", "version of the `LockfileMetadata` class to construct a concrete instance.", "that permits specifying a requirements as a set rather than", "LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata, lockfile_metadata_registrar, ) from pants.jvm.resolve.common import ArtifactRequirement", "lockfile_metadata_registrar, ) from pants.jvm.resolve.common import ArtifactRequirement from pants.util.ordered_set import FrozenOrderedSet", "pants.jvm.resolve.common import ArtifactRequirement from pants.util.ordered_set import FrozenOrderedSet _jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM)", "2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the", "the user requirements as those in the stored requirements. \"\"\"", "= None ) -> JVMLockfileMetadataV1: return cast( JVMLockfileMetadataV1, LockfileMetadata.from_lockfile_for_scope( LockfileScope.JVM,", "_get_metadata(json_dict, lockfile_description, error_suffix) requirements = metadata( \"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet, )", "call to construct a new `LockfileMetadata` for writing, while still", "the request requirements being a non-strict subset of the metadata", "str | None = None, resolve_name: str | None =", "the most recent version of the `LockfileMetadata` class to construct", "to support _reading_ older, deprecated metadata versions. \"\"\" return JVMLockfileMetadataV1.from_artifact_requirements(requirements)", "-> JVMLockfileMetadataV1: metadata = _get_metadata(json_dict, lockfile_description, error_suffix) requirements = metadata(", "Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation: \"\"\"Returns a truthy object", "dict[Any, Any], lockfile_description: str, error_suffix: str, ) -> JVMLockfileMetadataV1: metadata", "JVMLockfileMetadata(LockfileMetadata): scope = LockfileScope.JVM @staticmethod def new( requirements: Iterable[ArtifactRequirement], )", "if this `JVMLockfileMetadata` can be used in the current execution", "as the request requirements being a non-strict subset of the", "@staticmethod def new( requirements: Iterable[ArtifactRequirement], ) -> JVMLockfileMetadata: \"\"\"Call the", "requirements as those in the stored requirements. \"\"\" requirements: FrozenOrderedSet[str]", "def from_artifact_requirements( cls, requirements: Iterable[ArtifactRequirement] ) -> JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str()", "Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses", "as those in the stored requirements. \"\"\" requirements: FrozenOrderedSet[str] @classmethod", "JVMLockfileMetadata: \"\"\"Call the most recent version of the `LockfileMetadata` class", "is not None else None ) } def is_valid_for( self,", "object if the request requirements match the metadata requirements. For", "requirements)) @classmethod def _from_json_dict( cls: type[JVMLockfileMetadataV1], json_dict: dict[Any, Any], lockfile_description:", "Enum from typing import Any, Iterable, cast from pants.core.util_rules.lockfile_metadata import", "{ \"generated_with_requirements\": ( sorted(instance.requirements) if instance.requirements is not None else", "the metadata requirements. For this version, \"match\" is defined as", "requirements: Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation: \"\"\"Returns a truthy", ") -> JVMLockfileMetadata: \"\"\"Call the most recent version of the", "to construct a new `LockfileMetadata` for writing, while still allowing", "from dataclasses import dataclass from enum import Enum from typing", "the metadata requirements. \"\"\" failure_reasons: set[InvalidJVMLockfileReason] = set() if not", "= \"requirements_mismatch\" @dataclass(frozen=True) class JVMLockfileMetadata(LockfileMetadata): scope = LockfileScope.JVM @staticmethod def", ") from pants.jvm.resolve.common import ArtifactRequirement from pants.util.ordered_set import FrozenOrderedSet _jvm_lockfile_metadata", "None, ) -> LockfileMetadataValidation: \"\"\"Returns Truthy if this `JVMLockfileMetadata` can", "= set() if not self.requirements.issuperset(i.to_metadata_str() for i in requirements or", "@_jvm_lockfile_metadata(1) @dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile version that permits specifying a", "( sorted(instance.requirements) if instance.requirements is not None else None )", "for writing, while still allowing us to support _reading_ older,", "a truthy object if the request requirements match the metadata", "instance) return { \"generated_with_requirements\": ( sorted(instance.requirements) if instance.requirements is not", "set() if not self.requirements.issuperset(i.to_metadata_str() for i in requirements or []):", "requirements: Iterable[ArtifactRequirement] | None, ) -> LockfileMetadataValidation: \"\"\"Returns Truthy if", "of the `LockfileMetadata` class to construct a concrete instance. This", "from pants.util.ordered_set import FrozenOrderedSet _jvm_lockfile_metadata = lockfile_metadata_registrar(LockfileScope.JVM) class InvalidJVMLockfileReason(Enum): REQUIREMENTS_MISMATCH", "predictable method to call to construct a new `LockfileMetadata` for", "most recent version of the `LockfileMetadata` class to construct a", "} def is_valid_for( self, requirements: Iterable[ArtifactRequirement] | None, ) ->", "return JVMLockfileMetadataV1.from_artifact_requirements(requirements) @classmethod def from_lockfile( cls, lockfile: bytes, lockfile_path: str", "Any], lockfile_description: str, error_suffix: str, ) -> JVMLockfileMetadataV1: metadata =", "as a set rather than a digest. Validity is tested", "NotImplementedError(\"call `is_valid_for` on subclasses only\") @_jvm_lockfile_metadata(1) @dataclass(frozen=True) class JVMLockfileMetadataV1(JVMLockfileMetadata): \"\"\"Lockfile", ") -> JVMLockfileMetadataV1: return cls(FrozenOrderedSet(i.to_metadata_str() for i in requirements)) @classmethod", "be used in place of the `LockfileMetadata` constructor. This gives", "to call to construct a new `LockfileMetadata` for writing, while", "place of the `LockfileMetadata` constructor. This gives calling sites a", "requirements = metadata( \"generated_with_requirements\", FrozenOrderedSet[str], FrozenOrderedSet, ) return JVMLockfileMetadataV1(requirements) @classmethod", "`LockfileMetadata` class to construct a concrete instance. This static method", "(see LICENSE). from __future__ import annotations from dataclasses import dataclass", "the `LockfileMetadata` constructor. This gives calling sites a predictable method", "in requirements)) @classmethod def _from_json_dict( cls: type[JVMLockfileMetadataV1], json_dict: dict[Any, Any],", "if instance.requirements is not None else None ) } def", "\"generated_with_requirements\": ( sorted(instance.requirements) if instance.requirements is not None else None", "LockfileScope.JVM, lockfile, lockfile_path, resolve_name ), ) def is_valid_for( self, requirements:", "requirements as a set rather than a digest. Validity is", "instance: LockfileMetadata) -> dict[Any, Any]: instance = cast(JVMLockfileMetadataV1, instance) return", "still allowing us to support _reading_ older, deprecated metadata versions." ]
[ "= include_pattern.findall(dbc_file_in) output_filename = filename.replace('.dbc', '_generated.dbc') output_file_location = os.path.join(output_path, output_filename)", "starts here\";\\n' % filename) core_dbc = include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc) def", "import re cur_path = os.path.dirname(os.path.realpath(__file__)) opendbc_root = os.path.join(cur_path, '../') include_pattern", "_, filenames in os.walk(cur_path): if src_dir == cur_path: continue #print(src_dir)", "== cur_path: continue #print(src_dir) for filename in filenames: if filename.startswith('_')", "read_dbc(src_dir, filename): with open(os.path.join(src_dir, filename)) as file_in: return file_in.read() def", "dbc_file_out.write('CM_ \"AUTOGENERATED FILE, DO NOT EDIT\";\\n') for include_filename in includes:", "% filename) core_dbc = include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc) def create_all(output_path): for", "= filename.replace('.dbc', '_generated.dbc') output_file_location = os.path.join(output_path, output_filename) with open(output_file_location, 'w')", "\"Imported file %s starts here\";\\n' % include_filename dbc_file_out.write(include_file_header) include_file =", "'_generated.dbc') output_file_location = os.path.join(output_path, output_filename) with open(output_file_location, 'w') as dbc_file_out:", "re.compile(r'CM_ \"IMPORT (.*?)\";') def read_dbc(src_dir, filename): with open(os.path.join(src_dir, filename)) as", "opendbc_root = os.path.join(cur_path, '../') include_pattern = re.compile(r'CM_ \"IMPORT (.*?)\";') def", "file %s starts here\";\\n' % include_filename dbc_file_out.write(include_file_header) include_file = read_dbc(src_dir,", "not filename.endswith('.dbc'): continue #print(filename) create_dbc(src_dir, filename, output_path) if __name__ ==", "#!/usr/bin/env python3 import os import re cur_path = os.path.dirname(os.path.realpath(__file__)) opendbc_root", "DO NOT EDIT\";\\n') for include_filename in includes: include_file_header = '\\n\\nCM_", "= include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc) def create_all(output_path): for src_dir, _, filenames", "return file_in.read() def create_dbc(src_dir, filename, output_path): dbc_file_in = read_dbc(src_dir, filename)", "create_dbc(src_dir, filename, output_path): dbc_file_in = read_dbc(src_dir, filename) includes = include_pattern.findall(dbc_file_in)", "def create_dbc(src_dir, filename, output_path): dbc_file_in = read_dbc(src_dir, filename) includes =", "starts here\";\\n' % include_filename dbc_file_out.write(include_file_header) include_file = read_dbc(src_dir, include_filename) dbc_file_out.write(include_file)", "dbc_file_out.write(include_file_header) include_file = read_dbc(src_dir, include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s starts here\";\\n'", "def read_dbc(src_dir, filename): with open(os.path.join(src_dir, filename)) as file_in: return file_in.read()", "with open(os.path.join(src_dir, filename)) as file_in: return file_in.read() def create_dbc(src_dir, filename,", "\"%s starts here\";\\n' % filename) core_dbc = include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc)", "output_file_location = os.path.join(output_path, output_filename) with open(output_file_location, 'w') as dbc_file_out: dbc_file_out.write('CM_", "with open(output_file_location, 'w') as dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED FILE, DO NOT", "import os import re cur_path = os.path.dirname(os.path.realpath(__file__)) opendbc_root = os.path.join(cur_path,", "if src_dir == cur_path: continue #print(src_dir) for filename in filenames:", "include_file_header = '\\n\\nCM_ \"Imported file %s starts here\";\\n' % include_filename", "filename.replace('.dbc', '_generated.dbc') output_file_location = os.path.join(output_path, output_filename) with open(output_file_location, 'w') as", "% include_filename dbc_file_out.write(include_file_header) include_file = read_dbc(src_dir, include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s", "cur_path: continue #print(src_dir) for filename in filenames: if filename.startswith('_') or", "= '\\n\\nCM_ \"Imported file %s starts here\";\\n' % include_filename dbc_file_out.write(include_file_header)", "filename) core_dbc = include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc) def create_all(output_path): for src_dir,", "os import re cur_path = os.path.dirname(os.path.realpath(__file__)) opendbc_root = os.path.join(cur_path, '../')", "def create_all(output_path): for src_dir, _, filenames in os.walk(cur_path): if src_dir", "filenames in os.walk(cur_path): if src_dir == cur_path: continue #print(src_dir) for", "includes: include_file_header = '\\n\\nCM_ \"Imported file %s starts here\";\\n' %", "for filename in filenames: if filename.startswith('_') or not filename.endswith('.dbc'): continue", "in includes: include_file_header = '\\n\\nCM_ \"Imported file %s starts here\";\\n'", "read_dbc(src_dir, include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s starts here\";\\n' % filename) core_dbc", "filename)) as file_in: return file_in.read() def create_dbc(src_dir, filename, output_path): dbc_file_in", "= os.path.dirname(os.path.realpath(__file__)) opendbc_root = os.path.join(cur_path, '../') include_pattern = re.compile(r'CM_ \"IMPORT", "filenames: if filename.startswith('_') or not filename.endswith('.dbc'): continue #print(filename) create_dbc(src_dir, filename,", "in os.walk(cur_path): if src_dir == cur_path: continue #print(src_dir) for filename", "include_pattern.findall(dbc_file_in) output_filename = filename.replace('.dbc', '_generated.dbc') output_file_location = os.path.join(output_path, output_filename) with", "= os.path.join(output_path, output_filename) with open(output_file_location, 'w') as dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED", "dbc_file_in = read_dbc(src_dir, filename) includes = include_pattern.findall(dbc_file_in) output_filename = filename.replace('.dbc',", "os.path.join(output_path, output_filename) with open(output_file_location, 'w') as dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED FILE,", "include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc) def create_all(output_path): for src_dir, _, filenames in", "continue #print(filename) create_dbc(src_dir, filename, output_path) if __name__ == \"__main__\": create_all(opendbc_root)", "filename, output_path): dbc_file_in = read_dbc(src_dir, filename) includes = include_pattern.findall(dbc_file_in) output_filename", "as dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED FILE, DO NOT EDIT\";\\n') for include_filename", "file_in.read() def create_dbc(src_dir, filename, output_path): dbc_file_in = read_dbc(src_dir, filename) includes", "\"AUTOGENERATED FILE, DO NOT EDIT\";\\n') for include_filename in includes: include_file_header", "continue #print(src_dir) for filename in filenames: if filename.startswith('_') or not", "read_dbc(src_dir, filename) includes = include_pattern.findall(dbc_file_in) output_filename = filename.replace('.dbc', '_generated.dbc') output_file_location", "src_dir, _, filenames in os.walk(cur_path): if src_dir == cur_path: continue", "if filename.startswith('_') or not filename.endswith('.dbc'): continue #print(filename) create_dbc(src_dir, filename, output_path)", "or not filename.endswith('.dbc'): continue #print(filename) create_dbc(src_dir, filename, output_path) if __name__", "here\";\\n' % include_filename dbc_file_out.write(include_file_header) include_file = read_dbc(src_dir, include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_", "(.*?)\";') def read_dbc(src_dir, filename): with open(os.path.join(src_dir, filename)) as file_in: return", "os.path.dirname(os.path.realpath(__file__)) opendbc_root = os.path.join(cur_path, '../') include_pattern = re.compile(r'CM_ \"IMPORT (.*?)\";')", "'\\n\\nCM_ \"Imported file %s starts here\";\\n' % include_filename dbc_file_out.write(include_file_header) include_file", "'../') include_pattern = re.compile(r'CM_ \"IMPORT (.*?)\";') def read_dbc(src_dir, filename): with", "include_filename in includes: include_file_header = '\\n\\nCM_ \"Imported file %s starts", "= re.compile(r'CM_ \"IMPORT (.*?)\";') def read_dbc(src_dir, filename): with open(os.path.join(src_dir, filename))", "dbc_file_out.write('\\nCM_ \"%s starts here\";\\n' % filename) core_dbc = include_pattern.sub('', dbc_file_in)", "\"IMPORT (.*?)\";') def read_dbc(src_dir, filename): with open(os.path.join(src_dir, filename)) as file_in:", "NOT EDIT\";\\n') for include_filename in includes: include_file_header = '\\n\\nCM_ \"Imported", "in filenames: if filename.startswith('_') or not filename.endswith('.dbc'): continue #print(filename) create_dbc(src_dir,", "filename.startswith('_') or not filename.endswith('.dbc'): continue #print(filename) create_dbc(src_dir, filename, output_path) if", "include_pattern = re.compile(r'CM_ \"IMPORT (.*?)\";') def read_dbc(src_dir, filename): with open(os.path.join(src_dir,", "output_path): dbc_file_in = read_dbc(src_dir, filename) includes = include_pattern.findall(dbc_file_in) output_filename =", "cur_path = os.path.dirname(os.path.realpath(__file__)) opendbc_root = os.path.join(cur_path, '../') include_pattern = re.compile(r'CM_", "dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s starts here\";\\n' % filename) core_dbc = include_pattern.sub('',", "open(os.path.join(src_dir, filename)) as file_in: return file_in.read() def create_dbc(src_dir, filename, output_path):", "file_in: return file_in.read() def create_dbc(src_dir, filename, output_path): dbc_file_in = read_dbc(src_dir,", "python3 import os import re cur_path = os.path.dirname(os.path.realpath(__file__)) opendbc_root =", "core_dbc = include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc) def create_all(output_path): for src_dir, _,", "os.walk(cur_path): if src_dir == cur_path: continue #print(src_dir) for filename in", "for src_dir, _, filenames in os.walk(cur_path): if src_dir == cur_path:", "= read_dbc(src_dir, include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s starts here\";\\n' % filename)", "include_filename dbc_file_out.write(include_file_header) include_file = read_dbc(src_dir, include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s starts", "include_file = read_dbc(src_dir, include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s starts here\";\\n' %", "#print(src_dir) for filename in filenames: if filename.startswith('_') or not filename.endswith('.dbc'):", "FILE, DO NOT EDIT\";\\n') for include_filename in includes: include_file_header =", "output_filename) with open(output_file_location, 'w') as dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED FILE, DO", "here\";\\n' % filename) core_dbc = include_pattern.sub('', dbc_file_in) dbc_file_out.write(core_dbc) def create_all(output_path):", "src_dir == cur_path: continue #print(src_dir) for filename in filenames: if", "includes = include_pattern.findall(dbc_file_in) output_filename = filename.replace('.dbc', '_generated.dbc') output_file_location = os.path.join(output_path,", "filename) includes = include_pattern.findall(dbc_file_in) output_filename = filename.replace('.dbc', '_generated.dbc') output_file_location =", "output_filename = filename.replace('.dbc', '_generated.dbc') output_file_location = os.path.join(output_path, output_filename) with open(output_file_location,", "include_filename) dbc_file_out.write(include_file) dbc_file_out.write('\\nCM_ \"%s starts here\";\\n' % filename) core_dbc =", "= read_dbc(src_dir, filename) includes = include_pattern.findall(dbc_file_in) output_filename = filename.replace('.dbc', '_generated.dbc')", "'w') as dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED FILE, DO NOT EDIT\";\\n') for", "re cur_path = os.path.dirname(os.path.realpath(__file__)) opendbc_root = os.path.join(cur_path, '../') include_pattern =", "create_all(output_path): for src_dir, _, filenames in os.walk(cur_path): if src_dir ==", "filename): with open(os.path.join(src_dir, filename)) as file_in: return file_in.read() def create_dbc(src_dir,", "dbc_file_in) dbc_file_out.write(core_dbc) def create_all(output_path): for src_dir, _, filenames in os.walk(cur_path):", "os.path.join(cur_path, '../') include_pattern = re.compile(r'CM_ \"IMPORT (.*?)\";') def read_dbc(src_dir, filename):", "= os.path.join(cur_path, '../') include_pattern = re.compile(r'CM_ \"IMPORT (.*?)\";') def read_dbc(src_dir,", "EDIT\";\\n') for include_filename in includes: include_file_header = '\\n\\nCM_ \"Imported file", "for include_filename in includes: include_file_header = '\\n\\nCM_ \"Imported file %s", "filename.endswith('.dbc'): continue #print(filename) create_dbc(src_dir, filename, output_path) if __name__ == \"__main__\":", "dbc_file_out.write(core_dbc) def create_all(output_path): for src_dir, _, filenames in os.walk(cur_path): if", "%s starts here\";\\n' % include_filename dbc_file_out.write(include_file_header) include_file = read_dbc(src_dir, include_filename)", "as file_in: return file_in.read() def create_dbc(src_dir, filename, output_path): dbc_file_in =", "open(output_file_location, 'w') as dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED FILE, DO NOT EDIT\";\\n')", "dbc_file_out: dbc_file_out.write('CM_ \"AUTOGENERATED FILE, DO NOT EDIT\";\\n') for include_filename in", "filename in filenames: if filename.startswith('_') or not filename.endswith('.dbc'): continue #print(filename)" ]
[ "from django.contrib import admin from django.utils.safestring import mark_safe from customer.models", "= ['name'] class BreedAdmin(admin.ModelAdmin): \"\"\" Breed ModelAdmin. \"\"\" search_fields =", "\"\"\" search_fields = ['name', 'owner__name'] autocomplete_fields = ['owner', 'breed', 'sub_breed']", "return mark_safe('<img src=\"%s\" width=\"70\">' % obj.photo.url) admin.site.register(Dog, DogAdmin) admin.site.register(Owner, OwnerAdmin)", "= ['name', 'owner', 'breed', 'sub_breed', 'img_photo'] def img_photo(self, obj): \"\"\"", "admin from django.utils.safestring import mark_safe from customer.models import Owner, Dog,", "ModelAdmin. \"\"\" search_fields = ['name'] class SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed ModelAdmin.", "['name', 'owner', 'breed', 'sub_breed', 'img_photo'] def img_photo(self, obj): \"\"\" Render", "\"\"\" Dog ModelAdmin. \"\"\" search_fields = ['name', 'owner__name'] autocomplete_fields =", "obj): \"\"\" Render the dog's photo. \"\"\" return mark_safe('<img src=\"%s\"", "\"\"\" search_fields = ['name', 'breed__name'] autocomplete_fields = ['breed'] list_display =", "\"\"\" Owner ModelAdmin. \"\"\" search_fields = ['name'] class BreedAdmin(admin.ModelAdmin): \"\"\"", "width=\"70\">' % obj.photo.url) admin.site.register(Dog, DogAdmin) admin.site.register(Owner, OwnerAdmin) admin.site.register(Breed, BreedAdmin) admin.site.register(SubBreed,", "Owner ModelAdmin. \"\"\" search_fields = ['name'] class BreedAdmin(admin.ModelAdmin): \"\"\" Breed", "ModelAdmin. \"\"\" search_fields = ['name', 'breed__name'] autocomplete_fields = ['breed'] list_display", "= ['owner', 'breed', 'sub_breed'] list_display = ['name', 'owner', 'breed', 'sub_breed',", "def img_photo(self, obj): \"\"\" Render the dog's photo. \"\"\" return", "search_fields = ['name', 'owner__name'] autocomplete_fields = ['owner', 'breed', 'sub_breed'] list_display", "ModelAdmin. \"\"\" search_fields = ['name', 'owner__name'] autocomplete_fields = ['owner', 'breed',", "SubBreed ModelAdmin. \"\"\" search_fields = ['name', 'breed__name'] autocomplete_fields = ['breed']", "SubBreed class OwnerAdmin(admin.ModelAdmin): \"\"\" Owner ModelAdmin. \"\"\" search_fields = ['name']", "mark_safe('<img src=\"%s\" width=\"70\">' % obj.photo.url) admin.site.register(Dog, DogAdmin) admin.site.register(Owner, OwnerAdmin) admin.site.register(Breed,", "photo. \"\"\" return mark_safe('<img src=\"%s\" width=\"70\">' % obj.photo.url) admin.site.register(Dog, DogAdmin)", "= ['name', 'breed__name'] autocomplete_fields = ['breed'] list_display = ['name', 'breed']", "['name'] class BreedAdmin(admin.ModelAdmin): \"\"\" Breed ModelAdmin. \"\"\" search_fields = ['name']", "'owner', 'breed', 'sub_breed', 'img_photo'] def img_photo(self, obj): \"\"\" Render the", "import admin from django.utils.safestring import mark_safe from customer.models import Owner,", "img_photo(self, obj): \"\"\" Render the dog's photo. \"\"\" return mark_safe('<img", "Dog, Breed, SubBreed class OwnerAdmin(admin.ModelAdmin): \"\"\" Owner ModelAdmin. \"\"\" search_fields", "['name', 'breed'] class DogAdmin(admin.ModelAdmin): \"\"\" Dog ModelAdmin. \"\"\" search_fields =", "OwnerAdmin(admin.ModelAdmin): \"\"\" Owner ModelAdmin. \"\"\" search_fields = ['name'] class BreedAdmin(admin.ModelAdmin):", "mark_safe from customer.models import Owner, Dog, Breed, SubBreed class OwnerAdmin(admin.ModelAdmin):", "SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed ModelAdmin. \"\"\" search_fields = ['name', 'breed__name'] autocomplete_fields", "class DogAdmin(admin.ModelAdmin): \"\"\" Dog ModelAdmin. \"\"\" search_fields = ['name', 'owner__name']", "import Owner, Dog, Breed, SubBreed class OwnerAdmin(admin.ModelAdmin): \"\"\" Owner ModelAdmin.", "Breed, SubBreed class OwnerAdmin(admin.ModelAdmin): \"\"\" Owner ModelAdmin. \"\"\" search_fields =", "['owner', 'breed', 'sub_breed'] list_display = ['name', 'owner', 'breed', 'sub_breed', 'img_photo']", "'breed', 'sub_breed', 'img_photo'] def img_photo(self, obj): \"\"\" Render the dog's", "Render the dog's photo. \"\"\" return mark_safe('<img src=\"%s\" width=\"70\">' %", "class SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed ModelAdmin. \"\"\" search_fields = ['name', 'breed__name']", "list_display = ['name', 'owner', 'breed', 'sub_breed', 'img_photo'] def img_photo(self, obj):", "= ['breed'] list_display = ['name', 'breed'] class DogAdmin(admin.ModelAdmin): \"\"\" Dog", "['name'] class SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed ModelAdmin. \"\"\" search_fields = ['name',", "class OwnerAdmin(admin.ModelAdmin): \"\"\" Owner ModelAdmin. \"\"\" search_fields = ['name'] class", "['name', 'breed__name'] autocomplete_fields = ['breed'] list_display = ['name', 'breed'] class", "['name', 'owner__name'] autocomplete_fields = ['owner', 'breed', 'sub_breed'] list_display = ['name',", "'sub_breed', 'img_photo'] def img_photo(self, obj): \"\"\" Render the dog's photo.", "Breed ModelAdmin. \"\"\" search_fields = ['name'] class SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed", "\"\"\" search_fields = ['name'] class SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed ModelAdmin. \"\"\"", "Owner, Dog, Breed, SubBreed class OwnerAdmin(admin.ModelAdmin): \"\"\" Owner ModelAdmin. \"\"\"", "= ['name', 'breed'] class DogAdmin(admin.ModelAdmin): \"\"\" Dog ModelAdmin. \"\"\" search_fields", "Dog ModelAdmin. \"\"\" search_fields = ['name', 'owner__name'] autocomplete_fields = ['owner',", "\"\"\" Render the dog's photo. \"\"\" return mark_safe('<img src=\"%s\" width=\"70\">'", "'sub_breed'] list_display = ['name', 'owner', 'breed', 'sub_breed', 'img_photo'] def img_photo(self,", "autocomplete_fields = ['breed'] list_display = ['name', 'breed'] class DogAdmin(admin.ModelAdmin): \"\"\"", "\"\"\" SubBreed ModelAdmin. \"\"\" search_fields = ['name', 'breed__name'] autocomplete_fields =", "search_fields = ['name'] class BreedAdmin(admin.ModelAdmin): \"\"\" Breed ModelAdmin. \"\"\" search_fields", "the dog's photo. \"\"\" return mark_safe('<img src=\"%s\" width=\"70\">' % obj.photo.url)", "= ['name', 'owner__name'] autocomplete_fields = ['owner', 'breed', 'sub_breed'] list_display =", "autocomplete_fields = ['owner', 'breed', 'sub_breed'] list_display = ['name', 'owner', 'breed',", "from customer.models import Owner, Dog, Breed, SubBreed class OwnerAdmin(admin.ModelAdmin): \"\"\"", "import mark_safe from customer.models import Owner, Dog, Breed, SubBreed class", "% obj.photo.url) admin.site.register(Dog, DogAdmin) admin.site.register(Owner, OwnerAdmin) admin.site.register(Breed, BreedAdmin) admin.site.register(SubBreed, SubBreedAdmin)", "\"\"\" Breed ModelAdmin. \"\"\" search_fields = ['name'] class SubBreedAdmin(admin.ModelAdmin): \"\"\"", "DogAdmin(admin.ModelAdmin): \"\"\" Dog ModelAdmin. \"\"\" search_fields = ['name', 'owner__name'] autocomplete_fields", "dog's photo. \"\"\" return mark_safe('<img src=\"%s\" width=\"70\">' % obj.photo.url) admin.site.register(Dog,", "django.utils.safestring import mark_safe from customer.models import Owner, Dog, Breed, SubBreed", "'img_photo'] def img_photo(self, obj): \"\"\" Render the dog's photo. \"\"\"", "search_fields = ['name'] class SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed ModelAdmin. \"\"\" search_fields", "from django.utils.safestring import mark_safe from customer.models import Owner, Dog, Breed,", "search_fields = ['name', 'breed__name'] autocomplete_fields = ['breed'] list_display = ['name',", "BreedAdmin(admin.ModelAdmin): \"\"\" Breed ModelAdmin. \"\"\" search_fields = ['name'] class SubBreedAdmin(admin.ModelAdmin):", "\"\"\" search_fields = ['name'] class BreedAdmin(admin.ModelAdmin): \"\"\" Breed ModelAdmin. \"\"\"", "'breed__name'] autocomplete_fields = ['breed'] list_display = ['name', 'breed'] class DogAdmin(admin.ModelAdmin):", "src=\"%s\" width=\"70\">' % obj.photo.url) admin.site.register(Dog, DogAdmin) admin.site.register(Owner, OwnerAdmin) admin.site.register(Breed, BreedAdmin)", "= ['name'] class SubBreedAdmin(admin.ModelAdmin): \"\"\" SubBreed ModelAdmin. \"\"\" search_fields =", "'owner__name'] autocomplete_fields = ['owner', 'breed', 'sub_breed'] list_display = ['name', 'owner',", "django.contrib import admin from django.utils.safestring import mark_safe from customer.models import", "\"\"\" return mark_safe('<img src=\"%s\" width=\"70\">' % obj.photo.url) admin.site.register(Dog, DogAdmin) admin.site.register(Owner,", "['breed'] list_display = ['name', 'breed'] class DogAdmin(admin.ModelAdmin): \"\"\" Dog ModelAdmin.", "class BreedAdmin(admin.ModelAdmin): \"\"\" Breed ModelAdmin. \"\"\" search_fields = ['name'] class", "'breed', 'sub_breed'] list_display = ['name', 'owner', 'breed', 'sub_breed', 'img_photo'] def", "customer.models import Owner, Dog, Breed, SubBreed class OwnerAdmin(admin.ModelAdmin): \"\"\" Owner", "'breed'] class DogAdmin(admin.ModelAdmin): \"\"\" Dog ModelAdmin. \"\"\" search_fields = ['name',", "list_display = ['name', 'breed'] class DogAdmin(admin.ModelAdmin): \"\"\" Dog ModelAdmin. \"\"\"", "ModelAdmin. \"\"\" search_fields = ['name'] class BreedAdmin(admin.ModelAdmin): \"\"\" Breed ModelAdmin." ]
[ "kaneda.utils import get_backend backend = get_backend() @job(queue='kaneda', connection=Redis()) def report(name,", "the configured backend in kanedasettings.py To run the worker execute", "backend = get_backend() @job(queue='kaneda', connection=Redis()) def report(name, metric, value, tags,", "metric, value, tags, id_): \"\"\" RQ job to report metrics", "absolute_import from redis import Redis from rq.decorators import job from", "import Redis from rq.decorators import job from kaneda.utils import get_backend", "tags, id_): \"\"\" RQ job to report metrics to the", "Redis from rq.decorators import job from kaneda.utils import get_backend backend", "to report metrics to the configured backend in kanedasettings.py To", "report metrics to the configured backend in kanedasettings.py To run", "worker execute this command: rqworker [queue] \"\"\" return backend.report(name, metric,", "from kaneda.utils import get_backend backend = get_backend() @job(queue='kaneda', connection=Redis()) def", "command: rqworker [queue] \"\"\" return backend.report(name, metric, value, tags, id_)", "import get_backend backend = get_backend() @job(queue='kaneda', connection=Redis()) def report(name, metric,", "configured backend in kanedasettings.py To run the worker execute this", "@job(queue='kaneda', connection=Redis()) def report(name, metric, value, tags, id_): \"\"\" RQ", "import job from kaneda.utils import get_backend backend = get_backend() @job(queue='kaneda',", "connection=Redis()) def report(name, metric, value, tags, id_): \"\"\" RQ job", "the worker execute this command: rqworker [queue] \"\"\" return backend.report(name,", "execute this command: rqworker [queue] \"\"\" return backend.report(name, metric, value,", "rq.decorators import job from kaneda.utils import get_backend backend = get_backend()", "def report(name, metric, value, tags, id_): \"\"\" RQ job to", "run the worker execute this command: rqworker [queue] \"\"\" return", "import absolute_import from redis import Redis from rq.decorators import job", "job from kaneda.utils import get_backend backend = get_backend() @job(queue='kaneda', connection=Redis())", "this command: rqworker [queue] \"\"\" return backend.report(name, metric, value, tags,", "RQ job to report metrics to the configured backend in", "get_backend backend = get_backend() @job(queue='kaneda', connection=Redis()) def report(name, metric, value,", "from __future__ import absolute_import from redis import Redis from rq.decorators", "to the configured backend in kanedasettings.py To run the worker", "report(name, metric, value, tags, id_): \"\"\" RQ job to report", "id_): \"\"\" RQ job to report metrics to the configured", "kanedasettings.py To run the worker execute this command: rqworker [queue]", "value, tags, id_): \"\"\" RQ job to report metrics to", "redis import Redis from rq.decorators import job from kaneda.utils import", "job to report metrics to the configured backend in kanedasettings.py", "from rq.decorators import job from kaneda.utils import get_backend backend =", "from redis import Redis from rq.decorators import job from kaneda.utils", "\"\"\" RQ job to report metrics to the configured backend", "__future__ import absolute_import from redis import Redis from rq.decorators import", "in kanedasettings.py To run the worker execute this command: rqworker", "To run the worker execute this command: rqworker [queue] \"\"\"", "backend in kanedasettings.py To run the worker execute this command:", "= get_backend() @job(queue='kaneda', connection=Redis()) def report(name, metric, value, tags, id_):", "metrics to the configured backend in kanedasettings.py To run the", "get_backend() @job(queue='kaneda', connection=Redis()) def report(name, metric, value, tags, id_): \"\"\"" ]
[ "self.pdf.getNumPages() self.json_points_path = json_points_path self.ripped_certs_path = ripped_certs_path self.ripped_cert_file_name = ripped_cert_file_name", "({recipients_length}) does not match with PDF length ({pdf_length})\" ) if", "= ripped_cert_file_name def process(self): recipient_groups = self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self,", "extract_pdf_from_master(self, recipient_groups): current_page_index = self.start_page_index process_index = 0 for recipient_group", "point_tag, \"recipient_slugs\": point_recipient_slugs }) total_groups = len(recipient_groups) self.__check_pdf_length(total_recipients) print( f\"Read", "print( f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m from JSON points\")", "def process(self): recipient_groups = self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self, recipient_groups): current_page_index", "): self.start_page_index = start_page_index self.master_pdf_path = master_pdf_path self.pdf = PdfFileReader(master_pdf_path)", "\"__main__\": load_dotenv() ripper = CertRipper( start_page_index=os.getenv(\"START_PAGE_INDEX\"), master_pdf_path=os.getenv(\"MASTER_PDF_PATH\"), json_points_path=os.getenv(\"JSON_POINTS_PATH\"), ripped_certs_path=os.getenv(\"RIPPED_CERTS_PATH\"), ripped_cert_file_name=os.getenv(\"RIPPED_CERT_FILE_NAME\"),", "open(self.json_points_path, \"r\") as json_file: points = json.load(json_file) for point in", "process_index = 0 for recipient_group in recipient_groups: recipient_group_name = recipient_group[\"name\"]", "+= 1 process_index += 1 def get_recipient_groups_from_points(self): recipient_groups = []", "= 0 with open(self.json_points_path, \"r\") as json_file: points = json.load(json_file)", "point_recipient in point_recipients: recipient_name = point_recipient[\"name\"] recipient_name_slug = \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug)", "\"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients += 1 recipient_groups.append({ \"name\": point_name, \"tag\": point_tag,", "tag=recipient_group_tag, recipient=recipient_slug ) pdf_writer = PdfFileWriter() pdf_writer.addPage(page) output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\"", "return recipient_groups def __check_pdf_length(self, recipients_length): pdf_length = self.pdf_length - (self.start_page_index)", "__check_pdf_length(self, recipients_length): pdf_length = self.pdf_length - (self.start_page_index) if pdf_length !=", "point[\"tag\"] point_recipients = point[\"recipients\"] point_recipient_slugs = [] for point_recipient in", "points\") return recipient_groups def __check_pdf_length(self, recipients_length): pdf_length = self.pdf_length -", "PdfFileReader(master_pdf_path) self.pdf_length = self.pdf.getNumPages() self.json_points_path = json_points_path self.ripped_certs_path = ripped_certs_path", "match with PDF length ({pdf_length})\" ) if __name__ == \"__main__\":", "for recipient_slug in recipient_slugs: page = self.pdf.getPage(current_page_index) file_name = self.ripped_cert_file_name.format(", "import load_dotenv from PyPDF2 import PdfFileReader, PdfFileWriter import os import", "point_recipient_slugs = [] for point_recipient in point_recipients: recipient_name = point_recipient[\"name\"]", "recipient_group_tag = recipient_group[\"tag\"] recipient_slugs = recipient_group[\"recipient_slugs\"] print( f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m", "\"name\": point_name, \"tag\": point_tag, \"recipient_slugs\": point_recipient_slugs }) total_groups = len(recipient_groups)", "import PdfFileReader, PdfFileWriter import os import json class CertRipper: def", "of recipients ({recipients_length}) does not match with PDF length ({pdf_length})\"", ") if __name__ == \"__main__\": load_dotenv() ripper = CertRipper( start_page_index=os.getenv(\"START_PAGE_INDEX\"),", "from dotenv import load_dotenv from PyPDF2 import PdfFileReader, PdfFileWriter import", "PdfFileWriter() pdf_writer.addPage(page) output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name, \"wb\") as out:", "= point[\"recipients\"] point_recipient_slugs = [] for point_recipient in point_recipients: recipient_name", "0 with open(self.json_points_path, \"r\") as json_file: points = json.load(json_file) for", "self.pdf_length = self.pdf.getNumPages() self.json_points_path = json_points_path self.ripped_certs_path = ripped_certs_path self.ripped_cert_file_name", "total_recipients = 0 with open(self.json_points_path, \"r\") as json_file: points =", "point_recipients = point[\"recipients\"] point_recipient_slugs = [] for point_recipient in point_recipients:", "\\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage {current_page_index + 1}\\x1b[0m of master\") current_page_index +=", "json_file: points = json.load(json_file) for point in points: point_name =", "= PdfFileWriter() pdf_writer.addPage(page) output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name, \"wb\") as", "= self.start_page_index process_index = 0 for recipient_group in recipient_groups: recipient_group_name", "= self.ripped_cert_file_name.format( index=current_page_index + 1, tag=recipient_group_tag, recipient=recipient_slug ) pdf_writer =", "current_page_index = self.start_page_index process_index = 0 for recipient_group in recipient_groups:", "ripped_certs_path=None, ripped_cert_file_name=None, ): self.start_page_index = start_page_index self.master_pdf_path = master_pdf_path self.pdf", "+ 1, tag=recipient_group_tag, recipient=recipient_slug ) pdf_writer = PdfFileWriter() pdf_writer.addPage(page) output_file_name", "print( f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group ...\") for recipient_slug in recipient_slugs:", "out: pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage {current_page_index +", ") pdf_writer = PdfFileWriter() pdf_writer.addPage(page) output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name,", "= self.pdf.getNumPages() self.json_points_path = json_points_path self.ripped_certs_path = ripped_certs_path self.ripped_cert_file_name =", "json class CertRipper: def __init__( self, start_page_index=0, master_pdf_path=None, json_points_path=None, ripped_certs_path=None,", "= [] total_recipients = 0 with open(self.json_points_path, \"r\") as json_file:", "with open(output_file_name, \"wb\") as out: pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m", "group ...\") for recipient_slug in recipient_slugs: page = self.pdf.getPage(current_page_index) file_name", "point_recipients: recipient_name = point_recipient[\"name\"] recipient_name_slug = \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients +=", "self.json_points_path = json_points_path self.ripped_certs_path = ripped_certs_path self.ripped_cert_file_name = ripped_cert_file_name def", "\"recipient_slugs\": point_recipient_slugs }) total_groups = len(recipient_groups) self.__check_pdf_length(total_recipients) print( f\"Read \\x1b[95m{total_groups}", "index=current_page_index + 1, tag=recipient_group_tag, recipient=recipient_slug ) pdf_writer = PdfFileWriter() pdf_writer.addPage(page)", "groups(s)\\x1b[0m and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m from JSON points\") return recipient_groups def", "= recipient_group[\"recipient_slugs\"] print( f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group ...\") for recipient_slug", "self, start_page_index=0, master_pdf_path=None, json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None, ): self.start_page_index = start_page_index", "({pdf_length})\" ) if __name__ == \"__main__\": load_dotenv() ripper = CertRipper(", "get_recipient_groups_from_points(self): recipient_groups = [] total_recipients = 0 with open(self.json_points_path, \"r\")", "self.master_pdf_path = master_pdf_path self.pdf = PdfFileReader(master_pdf_path) self.pdf_length = self.pdf.getNumPages() self.json_points_path", "= self.pdf.getPage(current_page_index) file_name = self.ripped_cert_file_name.format( index=current_page_index + 1, tag=recipient_group_tag, recipient=recipient_slug", "1}\\x1b[0m of master\") current_page_index += 1 process_index += 1 def", "ripper = CertRipper( start_page_index=os.getenv(\"START_PAGE_INDEX\"), master_pdf_path=os.getenv(\"MASTER_PDF_PATH\"), json_points_path=os.getenv(\"JSON_POINTS_PATH\"), ripped_certs_path=os.getenv(\"RIPPED_CERTS_PATH\"), ripped_cert_file_name=os.getenv(\"RIPPED_CERT_FILE_NAME\"), ) ripper.process()", "self.ripped_cert_file_name.format( index=current_page_index + 1, tag=recipient_group_tag, recipient=recipient_slug ) pdf_writer = PdfFileWriter()", "= json_points_path self.ripped_certs_path = ripped_certs_path self.ripped_cert_file_name = ripped_cert_file_name def process(self):", "= recipient_group[\"tag\"] recipient_slugs = recipient_group[\"recipient_slugs\"] print( f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group", "= master_pdf_path self.pdf = PdfFileReader(master_pdf_path) self.pdf_length = self.pdf.getNumPages() self.json_points_path =", "recipients_length): pdf_length = self.pdf_length - (self.start_page_index) if pdf_length != recipients_length:", "import os import json class CertRipper: def __init__( self, start_page_index=0,", "__name__ == \"__main__\": load_dotenv() ripper = CertRipper( start_page_index=os.getenv(\"START_PAGE_INDEX\"), master_pdf_path=os.getenv(\"MASTER_PDF_PATH\"), json_points_path=os.getenv(\"JSON_POINTS_PATH\"),", "def __init__( self, start_page_index=0, master_pdf_path=None, json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None, ): self.start_page_index", "current_page_index += 1 process_index += 1 def get_recipient_groups_from_points(self): recipient_groups =", "does not match with PDF length ({pdf_length})\" ) if __name__", "CertRipper: def __init__( self, start_page_index=0, master_pdf_path=None, json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None, ):", "= recipient_group[\"name\"] recipient_group_tag = recipient_group[\"tag\"] recipient_slugs = recipient_group[\"recipient_slugs\"] print( f\"[*]", "as out: pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage {current_page_index", "recipient_name = point_recipient[\"name\"] recipient_name_slug = \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients += 1", "raise ValueError( f\"Number of recipients ({recipients_length}) does not match with", "if pdf_length != recipients_length: raise ValueError( f\"Number of recipients ({recipients_length})", "os import json class CertRipper: def __init__( self, start_page_index=0, master_pdf_path=None,", "= json.load(json_file) for point in points: point_name = point[\"name\"] point_tag", "recipient=recipient_slug ) pdf_writer = PdfFileWriter() pdf_writer.addPage(page) output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with", "= PdfFileReader(master_pdf_path) self.pdf_length = self.pdf.getNumPages() self.json_points_path = json_points_path self.ripped_certs_path =", "file_name = self.ripped_cert_file_name.format( index=current_page_index + 1, tag=recipient_group_tag, recipient=recipient_slug ) pdf_writer", "open(output_file_name, \"wb\") as out: pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m from", "recipient_groups def __check_pdf_length(self, recipients_length): pdf_length = self.pdf_length - (self.start_page_index) if", "json_points_path self.ripped_certs_path = ripped_certs_path self.ripped_cert_file_name = ripped_cert_file_name def process(self): recipient_groups", "= point[\"tag\"] point_recipients = point[\"recipients\"] point_recipient_slugs = [] for point_recipient", "recipient_group[\"tag\"] recipient_slugs = recipient_group[\"recipient_slugs\"] print( f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group ...\")", "= self.pdf_length - (self.start_page_index) if pdf_length != recipients_length: raise ValueError(", "load_dotenv from PyPDF2 import PdfFileReader, PdfFileWriter import os import json", "total_recipients += 1 recipient_groups.append({ \"name\": point_name, \"tag\": point_tag, \"recipient_slugs\": point_recipient_slugs", "import json class CertRipper: def __init__( self, start_page_index=0, master_pdf_path=None, json_points_path=None,", "for recipient_group in recipient_groups: recipient_group_name = recipient_group[\"name\"] recipient_group_tag = recipient_group[\"tag\"]", "in recipient_groups: recipient_group_name = recipient_group[\"name\"] recipient_group_tag = recipient_group[\"tag\"] recipient_slugs =", "f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group ...\") for recipient_slug in recipient_slugs: page", "+= 1 recipient_groups.append({ \"name\": point_name, \"tag\": point_tag, \"recipient_slugs\": point_recipient_slugs })", "from \\x1b[94mpage {current_page_index + 1}\\x1b[0m of master\") current_page_index += 1", "= [] for point_recipient in point_recipients: recipient_name = point_recipient[\"name\"] recipient_name_slug", "\"tag\": point_tag, \"recipient_slugs\": point_recipient_slugs }) total_groups = len(recipient_groups) self.__check_pdf_length(total_recipients) print(", "recipients ({recipients_length}) does not match with PDF length ({pdf_length})\" )", "recipients_length: raise ValueError( f\"Number of recipients ({recipients_length}) does not match", "Ripped \\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage {current_page_index + 1}\\x1b[0m of master\") current_page_index", "length ({pdf_length})\" ) if __name__ == \"__main__\": load_dotenv() ripper =", "def __check_pdf_length(self, recipients_length): pdf_length = self.pdf_length - (self.start_page_index) if pdf_length", "recipient_slug in recipient_slugs: page = self.pdf.getPage(current_page_index) file_name = self.ripped_cert_file_name.format( index=current_page_index", "recipient_slugs: page = self.pdf.getPage(current_page_index) file_name = self.ripped_cert_file_name.format( index=current_page_index + 1,", "ripped_cert_file_name def process(self): recipient_groups = self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self, recipient_groups):", "= point_recipient[\"name\"] recipient_name_slug = \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients += 1 recipient_groups.append({", "for point_recipient in point_recipients: recipient_name = point_recipient[\"name\"] recipient_name_slug = \"_\".join(recipient_name.split())", "recipient_group[\"name\"] recipient_group_tag = recipient_group[\"tag\"] recipient_slugs = recipient_group[\"recipient_slugs\"] print( f\"[*] Ripping", "self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self, recipient_groups): current_page_index = self.start_page_index process_index = 0", "f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage {current_page_index + 1}\\x1b[0m of master\")", "[] total_recipients = 0 with open(self.json_points_path, \"r\") as json_file: points", "pdf_writer = PdfFileWriter() pdf_writer.addPage(page) output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name, \"wb\")", "self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self, recipient_groups): current_page_index = self.start_page_index process_index =", "len(recipient_groups) self.__check_pdf_length(total_recipients) print( f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m from", "master\") current_page_index += 1 process_index += 1 def get_recipient_groups_from_points(self): recipient_groups", "self.pdf = PdfFileReader(master_pdf_path) self.pdf_length = self.pdf.getNumPages() self.json_points_path = json_points_path self.ripped_certs_path", "print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage {current_page_index + 1}\\x1b[0m of", "not match with PDF length ({pdf_length})\" ) if __name__ ==", "= ripped_certs_path self.ripped_cert_file_name = ripped_cert_file_name def process(self): recipient_groups = self.get_recipient_groups_from_points()", "point in points: point_name = point[\"name\"] point_tag = point[\"tag\"] point_recipients", "= len(recipient_groups) self.__check_pdf_length(total_recipients) print( f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m", "point[\"recipients\"] point_recipient_slugs = [] for point_recipient in point_recipients: recipient_name =", "= self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self, recipient_groups): current_page_index = self.start_page_index process_index", "pdf_length != recipients_length: raise ValueError( f\"Number of recipients ({recipients_length}) does", "0 for recipient_group in recipient_groups: recipient_group_name = recipient_group[\"name\"] recipient_group_tag =", "pdf_writer.addPage(page) output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name, \"wb\") as out: pdf_writer.write(out)", "Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group ...\") for recipient_slug in recipient_slugs: page =", "point_tag = point[\"tag\"] point_recipients = point[\"recipients\"] point_recipient_slugs = [] for", "ripped_certs_path self.ripped_cert_file_name = ripped_cert_file_name def process(self): recipient_groups = self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups)", "+ 1}\\x1b[0m of master\") current_page_index += 1 process_index += 1", "recipient(s)\\x1b[0m from JSON points\") return recipient_groups def __check_pdf_length(self, recipients_length): pdf_length", "point_name, \"tag\": point_tag, \"recipient_slugs\": point_recipient_slugs }) total_groups = len(recipient_groups) self.__check_pdf_length(total_recipients)", "+= 1 def get_recipient_groups_from_points(self): recipient_groups = [] total_recipients = 0", "def get_recipient_groups_from_points(self): recipient_groups = [] total_recipients = 0 with open(self.json_points_path,", "self.ripped_certs_path = ripped_certs_path self.ripped_cert_file_name = ripped_cert_file_name def process(self): recipient_groups =", "[] for point_recipient in point_recipients: recipient_name = point_recipient[\"name\"] recipient_name_slug =", "with open(self.json_points_path, \"r\") as json_file: points = json.load(json_file) for point", "pdf_length = self.pdf_length - (self.start_page_index) if pdf_length != recipients_length: raise", "point[\"name\"] point_tag = point[\"tag\"] point_recipients = point[\"recipients\"] point_recipient_slugs = []", "f\"Number of recipients ({recipients_length}) does not match with PDF length", "def extract_pdf_from_master(self, recipient_groups): current_page_index = self.start_page_index process_index = 0 for", "dotenv import load_dotenv from PyPDF2 import PdfFileReader, PdfFileWriter import os", "points = json.load(json_file) for point in points: point_name = point[\"name\"]", "\"r\") as json_file: points = json.load(json_file) for point in points:", "point_recipient_slugs }) total_groups = len(recipient_groups) self.__check_pdf_length(total_recipients) print( f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m", "\\x1b[95m{total_recipients} recipient(s)\\x1b[0m from JSON points\") return recipient_groups def __check_pdf_length(self, recipients_length):", "from PyPDF2 import PdfFileReader, PdfFileWriter import os import json class", "(self.start_page_index) if pdf_length != recipients_length: raise ValueError( f\"Number of recipients", "total_groups = len(recipient_groups) self.__check_pdf_length(total_recipients) print( f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m and \\x1b[95m{total_recipients}", "master_pdf_path=None, json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None, ): self.start_page_index = start_page_index self.master_pdf_path =", "output_file_name = f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name, \"wb\") as out: pdf_writer.write(out) print(", "recipient_group_name = recipient_group[\"name\"] recipient_group_tag = recipient_group[\"tag\"] recipient_slugs = recipient_group[\"recipient_slugs\"] print(", "process(self): recipient_groups = self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self, recipient_groups): current_page_index =", "PyPDF2 import PdfFileReader, PdfFileWriter import os import json class CertRipper:", "in recipient_slugs: page = self.pdf.getPage(current_page_index) file_name = self.ripped_cert_file_name.format( index=current_page_index +", "start_page_index self.master_pdf_path = master_pdf_path self.pdf = PdfFileReader(master_pdf_path) self.pdf_length = self.pdf.getNumPages()", "{current_page_index + 1}\\x1b[0m of master\") current_page_index += 1 process_index +=", "pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage {current_page_index + 1}\\x1b[0m", "from JSON points\") return recipient_groups def __check_pdf_length(self, recipients_length): pdf_length =", "= f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name, \"wb\") as out: pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m", "f\"{self.ripped_certs_path}\\\\{file_name}.pdf\" with open(output_file_name, \"wb\") as out: pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped", "recipient_name_slug = \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients += 1 recipient_groups.append({ \"name\": point_name,", "__init__( self, start_page_index=0, master_pdf_path=None, json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None, ): self.start_page_index =", "in points: point_name = point[\"name\"] point_tag = point[\"tag\"] point_recipients =", "recipient_groups: recipient_group_name = recipient_group[\"name\"] recipient_group_tag = recipient_group[\"tag\"] recipient_slugs = recipient_group[\"recipient_slugs\"]", "ValueError( f\"Number of recipients ({recipients_length}) does not match with PDF", "process_index += 1 def get_recipient_groups_from_points(self): recipient_groups = [] total_recipients =", "1, tag=recipient_group_tag, recipient=recipient_slug ) pdf_writer = PdfFileWriter() pdf_writer.addPage(page) output_file_name =", "self.ripped_cert_file_name = ripped_cert_file_name def process(self): recipient_groups = self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def", "recipient_group in recipient_groups: recipient_group_name = recipient_group[\"name\"] recipient_group_tag = recipient_group[\"tag\"] recipient_slugs", "class CertRipper: def __init__( self, start_page_index=0, master_pdf_path=None, json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None,", "self.pdf_length - (self.start_page_index) if pdf_length != recipients_length: raise ValueError( f\"Number", "JSON points\") return recipient_groups def __check_pdf_length(self, recipients_length): pdf_length = self.pdf_length", "= start_page_index self.master_pdf_path = master_pdf_path self.pdf = PdfFileReader(master_pdf_path) self.pdf_length =", "self.start_page_index process_index = 0 for recipient_group in recipient_groups: recipient_group_name =", "= \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients += 1 recipient_groups.append({ \"name\": point_name, \"tag\":", "PdfFileWriter import os import json class CertRipper: def __init__( self,", "= 0 for recipient_group in recipient_groups: recipient_group_name = recipient_group[\"name\"] recipient_group_tag", "with PDF length ({pdf_length})\" ) if __name__ == \"__main__\": load_dotenv()", "for point in points: point_name = point[\"name\"] point_tag = point[\"tag\"]", "\\x1b[94mpage {current_page_index + 1}\\x1b[0m of master\") current_page_index += 1 process_index", "f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m from JSON points\") return", "if __name__ == \"__main__\": load_dotenv() ripper = CertRipper( start_page_index=os.getenv(\"START_PAGE_INDEX\"), master_pdf_path=os.getenv(\"MASTER_PDF_PATH\"),", "PDF length ({pdf_length})\" ) if __name__ == \"__main__\": load_dotenv() ripper", "== \"__main__\": load_dotenv() ripper = CertRipper( start_page_index=os.getenv(\"START_PAGE_INDEX\"), master_pdf_path=os.getenv(\"MASTER_PDF_PATH\"), json_points_path=os.getenv(\"JSON_POINTS_PATH\"), ripped_certs_path=os.getenv(\"RIPPED_CERTS_PATH\"),", "recipient_groups = [] total_recipients = 0 with open(self.json_points_path, \"r\") as", "and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m from JSON points\") return recipient_groups def __check_pdf_length(self,", "1 process_index += 1 def get_recipient_groups_from_points(self): recipient_groups = [] total_recipients", "point_name = point[\"name\"] point_tag = point[\"tag\"] point_recipients = point[\"recipients\"] point_recipient_slugs", "load_dotenv() ripper = CertRipper( start_page_index=os.getenv(\"START_PAGE_INDEX\"), master_pdf_path=os.getenv(\"MASTER_PDF_PATH\"), json_points_path=os.getenv(\"JSON_POINTS_PATH\"), ripped_certs_path=os.getenv(\"RIPPED_CERTS_PATH\"), ripped_cert_file_name=os.getenv(\"RIPPED_CERT_FILE_NAME\"), )", "PdfFileReader, PdfFileWriter import os import json class CertRipper: def __init__(", "self.start_page_index = start_page_index self.master_pdf_path = master_pdf_path self.pdf = PdfFileReader(master_pdf_path) self.pdf_length", "self.pdf.getPage(current_page_index) file_name = self.ripped_cert_file_name.format( index=current_page_index + 1, tag=recipient_group_tag, recipient=recipient_slug )", "points: point_name = point[\"name\"] point_tag = point[\"tag\"] point_recipients = point[\"recipients\"]", "point_recipient[\"name\"] recipient_name_slug = \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients += 1 recipient_groups.append({ \"name\":", "recipient_groups.append({ \"name\": point_name, \"tag\": point_tag, \"recipient_slugs\": point_recipient_slugs }) total_groups =", "!= recipients_length: raise ValueError( f\"Number of recipients ({recipients_length}) does not", "of master\") current_page_index += 1 process_index += 1 def get_recipient_groups_from_points(self):", "recipient_slugs = recipient_group[\"recipient_slugs\"] print( f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group ...\") for", "1 recipient_groups.append({ \"name\": point_name, \"tag\": point_tag, \"recipient_slugs\": point_recipient_slugs }) total_groups", "recipient_group[\"recipient_slugs\"] print( f\"[*] Ripping \\x1b[93m{recipient_group_name}\\x1b[0m group ...\") for recipient_slug in", "in point_recipients: recipient_name = point_recipient[\"name\"] recipient_name_slug = \"_\".join(recipient_name.split()) point_recipient_slugs.append(recipient_name_slug) total_recipients", "json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None, ): self.start_page_index = start_page_index self.master_pdf_path = master_pdf_path", "self.__check_pdf_length(total_recipients) print( f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m from JSON", "- (self.start_page_index) if pdf_length != recipients_length: raise ValueError( f\"Number of", "recipient_groups = self.get_recipient_groups_from_points() self.extract_pdf_from_master(recipient_groups) def extract_pdf_from_master(self, recipient_groups): current_page_index = self.start_page_index", "ripped_cert_file_name=None, ): self.start_page_index = start_page_index self.master_pdf_path = master_pdf_path self.pdf =", "page = self.pdf.getPage(current_page_index) file_name = self.ripped_cert_file_name.format( index=current_page_index + 1, tag=recipient_group_tag,", "point_recipient_slugs.append(recipient_name_slug) total_recipients += 1 recipient_groups.append({ \"name\": point_name, \"tag\": point_tag, \"recipient_slugs\":", "as json_file: points = json.load(json_file) for point in points: point_name", "= point[\"name\"] point_tag = point[\"tag\"] point_recipients = point[\"recipients\"] point_recipient_slugs =", "master_pdf_path self.pdf = PdfFileReader(master_pdf_path) self.pdf_length = self.pdf.getNumPages() self.json_points_path = json_points_path", "1 def get_recipient_groups_from_points(self): recipient_groups = [] total_recipients = 0 with", "}) total_groups = len(recipient_groups) self.__check_pdf_length(total_recipients) print( f\"Read \\x1b[95m{total_groups} groups(s)\\x1b[0m and", "\\x1b[95m{total_groups} groups(s)\\x1b[0m and \\x1b[95m{total_recipients} recipient(s)\\x1b[0m from JSON points\") return recipient_groups", "json.load(json_file) for point in points: point_name = point[\"name\"] point_tag =", "\\x1b[93m{recipient_group_name}\\x1b[0m group ...\") for recipient_slug in recipient_slugs: page = self.pdf.getPage(current_page_index)", "\"wb\") as out: pdf_writer.write(out) print( f\"\\x1b[95m[{process_index}]\\x1b[0m Ripped \\x1b[92m[{file_name}]\\x1b[0m from \\x1b[94mpage", "start_page_index=0, master_pdf_path=None, json_points_path=None, ripped_certs_path=None, ripped_cert_file_name=None, ): self.start_page_index = start_page_index self.master_pdf_path", "recipient_groups): current_page_index = self.start_page_index process_index = 0 for recipient_group in", "...\") for recipient_slug in recipient_slugs: page = self.pdf.getPage(current_page_index) file_name =" ]
[ "ibm_db.rollback(conn) else: print(\"Connection failed.\") #__END__ #__LUW_EXPECTED__ #False #int(0) #int(1) #False", "Property of IBM # # (c) Copyright IBM Corp. 2007-2008", "ibm_db.field_num(stmt, \"WEIGHT\") else: num1 = ibm_db.field_num(stmt, \"ID\") num2 = ibm_db.field_num(stmt,", "num5) print(\"%s\" % num6) print(\"int(%d)\" % num7) print(\"%s\" % num8)", "ibm_db.exec_immediate(conn, insert) stmt = ibm_db.exec_immediate(conn, \"SELECT breed, COUNT(breed) AS number", "\"NUMBER\") num4 = ibm_db.field_num(stmt, \"number\") num5 = ibm_db.field_num(stmt, \"Breed\") num6", "'IDS'): num1 = ibm_db.field_num(stmt, \"id\") num2 = ibm_db.field_num(stmt, \"breed\") num3", "Corp. 2007-2008 # import unittest, sys import ibm_db import config", "% num8) ibm_db.rollback(conn) else: print(\"Connection failed.\") #__END__ #__LUW_EXPECTED__ #False #int(0)", "# (c) Copyright IBM Corp. 2007-2008 # import unittest, sys", "import IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self): obj = IbmDbTestFunctions() obj.assert_expect(self.run_test_111)", "'Benji', 5.1)\" ibm_db.exec_immediate(conn, insert) stmt = ibm_db.exec_immediate(conn, \"SELECT breed, COUNT(breed)", "= ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"weight\") print(\"%s\" % num1)", "#int(1) #False #False #False #int(1) #False #__ZOS_EXPECTED__ #False #int(0) #int(1)", "= ibm_db.field_num(stmt, \"NUMBER\") num4 = ibm_db.field_num(stmt, \"number\") num5 = ibm_db.field_num(stmt,", "BY breed ORDER BY breed\") if (server.DBMS_NAME[0:3] == 'IDS'): num1", "ibm_db.field_num(stmt, \"BREED\") num3 = ibm_db.field_num(stmt, \"NUMBER\") num4 = ibm_db.field_num(stmt, \"number\")", "breed, COUNT(breed) AS number FROM animals GROUP BY breed ORDER", "#False #False #False #int(1) #False #__ZOS_EXPECTED__ #False #int(0) #int(1) #False", "\"number\") num5 = ibm_db.field_num(stmt, \"Breed\") num6 = ibm_db.field_num(stmt, 8) num7", "run_test_111(self): conn = ibm_db.connect(config.database, config.user, config.password) server = ibm_db.server_info( conn", "#False #int(1) #False #__IDS_EXPECTED__ #False #int(0) #int(1) #False #False #False", "#False #False #int(1) #False #__IDS_EXPECTED__ #False #int(0) #int(1) #False #False", "INTO animals values (7, 'cat', 'Benji', 5.1)\" ibm_db.exec_immediate(conn, insert) stmt", "num1 = ibm_db.field_num(stmt, \"ID\") num2 = ibm_db.field_num(stmt, \"BREED\") num3 =", "GROUP BY breed ORDER BY breed\") if (server.DBMS_NAME[0:3] == 'IDS'):", "num2 = ibm_db.field_num(stmt, \"BREED\") num3 = ibm_db.field_num(stmt, \"NUMBER\") num4 =", "#False #False #int(1) #False #__ZOS_EXPECTED__ #False #int(0) #int(1) #False #False", "ibm_db.field_num(stmt, \"number\") num5 = ibm_db.field_num(stmt, \"Breed\") num6 = ibm_db.field_num(stmt, 8)", "print(\"int(%d)\" % num7) print(\"%s\" % num8) ibm_db.rollback(conn) else: print(\"Connection failed.\")", "num8 = ibm_db.field_num(stmt, \"weight\") print(\"%s\" % num1) print(\"int(%d)\" % num2)", "% num4) print(\"%s\" % num5) print(\"%s\" % num6) print(\"int(%d)\" %", "IBM Corp. 2007-2008 # import unittest, sys import ibm_db import", "#__LUW_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False #__ZOS_EXPECTED__", "ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert = \"INSERT INTO animals values (7, 'cat',", "print(\"int(%d)\" % num3) print(\"%s\" % num4) print(\"%s\" % num5) print(\"%s\"", "else: num1 = ibm_db.field_num(stmt, \"ID\") num2 = ibm_db.field_num(stmt, \"BREED\") num3", "= ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt,", "num8 = ibm_db.field_num(stmt, \"WEIGHT\") else: num1 = ibm_db.field_num(stmt, \"ID\") num2", "num3) print(\"%s\" % num4) print(\"%s\" % num5) print(\"%s\" % num6)", "test_111_FieldNumAddCol(self): obj = IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def run_test_111(self): conn = ibm_db.connect(config.database,", "insert) stmt = ibm_db.exec_immediate(conn, \"SELECT breed, COUNT(breed) AS number FROM", "2007-2008 # import unittest, sys import ibm_db import config from", "#False #__IDS_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False", "8) num7 = ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"WEIGHT\") else:", "obj = IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def run_test_111(self): conn = ibm_db.connect(config.database, config.user,", "unittest, sys import ibm_db import config from testfunctions import IbmDbTestFunctions", "breed\") if (server.DBMS_NAME[0:3] == 'IDS'): num1 = ibm_db.field_num(stmt, \"id\") num2", "print(\"%s\" % num6) print(\"int(%d)\" % num7) print(\"%s\" % num8) ibm_db.rollback(conn)", "% num7) print(\"%s\" % num8) ibm_db.rollback(conn) else: print(\"Connection failed.\") #__END__", "1) num8 = ibm_db.field_num(stmt, \"weight\") print(\"%s\" % num1) print(\"int(%d)\" %", "num1) print(\"int(%d)\" % num2) print(\"int(%d)\" % num3) print(\"%s\" % num4)", "num1 = ibm_db.field_num(stmt, \"id\") num2 = ibm_db.field_num(stmt, \"breed\") num3 =", "#int(1) #False #__ZOS_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1)", "\"INSERT INTO animals values (7, 'cat', 'Benji', 5.1)\" ibm_db.exec_immediate(conn, insert)", "= ibm_db.field_num(stmt, \"id\") num2 = ibm_db.field_num(stmt, \"breed\") num3 = ibm_db.field_num(stmt,", "#False #__SYSTEMI_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False", "#int(0) #int(1) #False #False #False #int(1) #False #__SYSTEMI_EXPECTED__ #False #int(0)", "import ibm_db import config from testfunctions import IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase):", "= ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"WEIGHT\") else: num1 =", "#False #int(0) #int(1) #False #False #False #int(1) #False #__SYSTEMI_EXPECTED__ #False", "= ibm_db.server_info( conn ) if conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert =", "= ibm_db.field_num(stmt, \"BREED\") num3 = ibm_db.field_num(stmt, \"NUMBER\") num4 = ibm_db.field_num(stmt,", "else: print(\"Connection failed.\") #__END__ #__LUW_EXPECTED__ #False #int(0) #int(1) #False #False", "= ibm_db.exec_immediate(conn, \"SELECT breed, COUNT(breed) AS number FROM animals GROUP", "class IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self): obj = IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def run_test_111(self):", "ibm_db.server_info( conn ) if conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert = \"INSERT", "= ibm_db.field_num(stmt, \"WEIGHT\") else: num1 = ibm_db.field_num(stmt, \"ID\") num2 =", "num3 = ibm_db.field_num(stmt, \"NUMBER\") num4 = ibm_db.field_num(stmt, \"number\") num5 =", "num8) ibm_db.rollback(conn) else: print(\"Connection failed.\") #__END__ #__LUW_EXPECTED__ #False #int(0) #int(1)", "Copyright IBM Corp. 2007-2008 # import unittest, sys import ibm_db", "num7 = ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"weight\") print(\"%s\" %", "#int(0) #int(1) #False #False #False #int(1) #False #__ZOS_EXPECTED__ #False #int(0)", "== 'IDS'): num1 = ibm_db.field_num(stmt, \"id\") num2 = ibm_db.field_num(stmt, \"breed\")", "= \"INSERT INTO animals values (7, 'cat', 'Benji', 5.1)\" ibm_db.exec_immediate(conn,", "= ibm_db.field_num(stmt, \"breed\") num3 = ibm_db.field_num(stmt, \"number\") num4 = ibm_db.field_num(stmt,", ") if conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert = \"INSERT INTO animals", "= ibm_db.field_num(stmt, \"ID\") num2 = ibm_db.field_num(stmt, \"BREED\") num3 = ibm_db.field_num(stmt,", "conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert = \"INSERT INTO animals values (7,", "\"ID\") num2 = ibm_db.field_num(stmt, \"BREED\") num3 = ibm_db.field_num(stmt, \"NUMBER\") num4", "config.user, config.password) server = ibm_db.server_info( conn ) if conn: ibm_db.autocommit(conn,", "#False #int(1) #False #__SYSTEMI_EXPECTED__ #False #int(0) #int(1) #False #False #False", "(7, 'cat', 'Benji', 5.1)\" ibm_db.exec_immediate(conn, insert) stmt = ibm_db.exec_immediate(conn, \"SELECT", "#__END__ #__LUW_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False", "#False #int(0) #int(1) #False #False #False #int(1) #False #__IDS_EXPECTED__ #False", "insert = \"INSERT INTO animals values (7, 'cat', 'Benji', 5.1)\"", "FROM animals GROUP BY breed ORDER BY breed\") if (server.DBMS_NAME[0:3]", "animals values (7, 'cat', 'Benji', 5.1)\" ibm_db.exec_immediate(conn, insert) stmt =", "failed.\") #__END__ #__LUW_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1)", "num6 = ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1) num8 =", "ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"WEIGHT\") else: num1 = ibm_db.field_num(stmt,", "\"BREED\") num3 = ibm_db.field_num(stmt, \"NUMBER\") num4 = ibm_db.field_num(stmt, \"number\") num5", "num4) print(\"%s\" % num5) print(\"%s\" % num6) print(\"int(%d)\" % num7)", "#int(1) #False #__SYSTEMI_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1)", "% num2) print(\"int(%d)\" % num3) print(\"%s\" % num4) print(\"%s\" %", "#False #False #False #int(1) #False #__IDS_EXPECTED__ #False #int(0) #int(1) #False", "= ibm_db.field_num(stmt, \"NUMBER\") num5 = ibm_db.field_num(stmt, \"bREED\") num6 = ibm_db.field_num(stmt,", "print(\"%s\" % num1) print(\"int(%d)\" % num2) print(\"int(%d)\" % num3) print(\"%s\"", "= ibm_db.field_num(stmt, \"bREED\") num6 = ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt,", "ibm_db.field_num(stmt, \"bREED\") num6 = ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1)", "num5 = ibm_db.field_num(stmt, \"Breed\") num6 = ibm_db.field_num(stmt, 8) num7 =", "print(\"%s\" % num5) print(\"%s\" % num6) print(\"int(%d)\" % num7) print(\"%s\"", "ibm_db.field_num(stmt, \"id\") num2 = ibm_db.field_num(stmt, \"breed\") num3 = ibm_db.field_num(stmt, \"number\")", "def run_test_111(self): conn = ibm_db.connect(config.database, config.user, config.password) server = ibm_db.server_info(", "#__ZOS_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False #__SYSTEMI_EXPECTED__", "% num3) print(\"%s\" % num4) print(\"%s\" % num5) print(\"%s\" %", "ORDER BY breed\") if (server.DBMS_NAME[0:3] == 'IDS'): num1 = ibm_db.field_num(stmt,", "% num6) print(\"int(%d)\" % num7) print(\"%s\" % num8) ibm_db.rollback(conn) else:", "# import unittest, sys import ibm_db import config from testfunctions", "config.password) server = ibm_db.server_info( conn ) if conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF)", "ibm_db import config from testfunctions import IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase): def", "animals GROUP BY breed ORDER BY breed\") if (server.DBMS_NAME[0:3] ==", "num4 = ibm_db.field_num(stmt, \"NUMBER\") num5 = ibm_db.field_num(stmt, \"bREED\") num6 =", "#int(1) #False #__IDS_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1)", "def test_111_FieldNumAddCol(self): obj = IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def run_test_111(self): conn =", "- Property of IBM # # (c) Copyright IBM Corp.", "\"number\") num4 = ibm_db.field_num(stmt, \"NUMBER\") num5 = ibm_db.field_num(stmt, \"bREED\") num6", "config from testfunctions import IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self): obj", "ibm_db.field_num(stmt, \"number\") num4 = ibm_db.field_num(stmt, \"NUMBER\") num5 = ibm_db.field_num(stmt, \"bREED\")", "Materials - Property of IBM # # (c) Copyright IBM", "ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"WEIGHT\")", "#int(0) #int(1) #False #False #False #int(1) #False #__IDS_EXPECTED__ #False #int(0)", "= ibm_db.connect(config.database, config.user, config.password) server = ibm_db.server_info( conn ) if", "stmt = ibm_db.exec_immediate(conn, \"SELECT breed, COUNT(breed) AS number FROM animals", "conn ) if conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert = \"INSERT INTO", "print(\"%s\" % num8) ibm_db.rollback(conn) else: print(\"Connection failed.\") #__END__ #__LUW_EXPECTED__ #False", "ibm_db.field_num(stmt, \"ID\") num2 = ibm_db.field_num(stmt, \"BREED\") num3 = ibm_db.field_num(stmt, \"NUMBER\")", "testfunctions import IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self): obj = IbmDbTestFunctions()", "if (server.DBMS_NAME[0:3] == 'IDS'): num1 = ibm_db.field_num(stmt, \"id\") num2 =", "\"bREED\") num6 = ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1) num8", "IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self): obj = IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def run_test_111(self): conn", "% num1) print(\"int(%d)\" % num2) print(\"int(%d)\" % num3) print(\"%s\" %", "# # Licensed Materials - Property of IBM # #", "\"breed\") num3 = ibm_db.field_num(stmt, \"number\") num4 = ibm_db.field_num(stmt, \"NUMBER\") num5", "= ibm_db.field_num(stmt, \"number\") num4 = ibm_db.field_num(stmt, \"NUMBER\") num5 = ibm_db.field_num(stmt,", "ibm_db.field_num(stmt, \"weight\") print(\"%s\" % num1) print(\"int(%d)\" % num2) print(\"int(%d)\" %", "#False #__ZOS_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False", "\"WEIGHT\") else: num1 = ibm_db.field_num(stmt, \"ID\") num2 = ibm_db.field_num(stmt, \"BREED\")", "Licensed Materials - Property of IBM # # (c) Copyright", "#__SYSTEMI_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False #__IDS_EXPECTED__", "conn = ibm_db.connect(config.database, config.user, config.password) server = ibm_db.server_info( conn )", "ibm_db.connect(config.database, config.user, config.password) server = ibm_db.server_info( conn ) if conn:", "AS number FROM animals GROUP BY breed ORDER BY breed\")", "num5 = ibm_db.field_num(stmt, \"bREED\") num6 = ibm_db.field_num(stmt, 8) num7 =", "values (7, 'cat', 'Benji', 5.1)\" ibm_db.exec_immediate(conn, insert) stmt = ibm_db.exec_immediate(conn,", "= IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def run_test_111(self): conn = ibm_db.connect(config.database, config.user, config.password)", "= ibm_db.field_num(stmt, \"Breed\") num6 = ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt,", "#False #int(1) #False #__ZOS_EXPECTED__ #False #int(0) #int(1) #False #False #False", "server = ibm_db.server_info( conn ) if conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert", "print(\"int(%d)\" % num2) print(\"int(%d)\" % num3) print(\"%s\" % num4) print(\"%s\"", "IBM # # (c) Copyright IBM Corp. 2007-2008 # import", "of IBM # # (c) Copyright IBM Corp. 2007-2008 #", "ibm_db.field_num(stmt, \"breed\") num3 = ibm_db.field_num(stmt, \"number\") num4 = ibm_db.field_num(stmt, \"NUMBER\")", "if conn: ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) insert = \"INSERT INTO animals values", "num6) print(\"int(%d)\" % num7) print(\"%s\" % num8) ibm_db.rollback(conn) else: print(\"Connection", "(c) Copyright IBM Corp. 2007-2008 # import unittest, sys import", "#False #False #int(1) #False #__SYSTEMI_EXPECTED__ #False #int(0) #int(1) #False #False", "obj.assert_expect(self.run_test_111) def run_test_111(self): conn = ibm_db.connect(config.database, config.user, config.password) server =", "\"NUMBER\") num5 = ibm_db.field_num(stmt, \"bREED\") num6 = ibm_db.field_num(stmt, 8) num7", "import config from testfunctions import IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self):", "1) num8 = ibm_db.field_num(stmt, \"WEIGHT\") else: num1 = ibm_db.field_num(stmt, \"ID\")", "(server.DBMS_NAME[0:3] == 'IDS'): num1 = ibm_db.field_num(stmt, \"id\") num2 = ibm_db.field_num(stmt,", "\"SELECT breed, COUNT(breed) AS number FROM animals GROUP BY breed", "ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"weight\") print(\"%s\" % num1) print(\"int(%d)\"", "ibm_db.field_num(stmt, \"NUMBER\") num5 = ibm_db.field_num(stmt, \"bREED\") num6 = ibm_db.field_num(stmt, 8)", "#False #int(0) #int(1) #False #False #False #int(1) #False #__ZOS_EXPECTED__ #False", "num4 = ibm_db.field_num(stmt, \"number\") num5 = ibm_db.field_num(stmt, \"Breed\") num6 =", "# # (c) Copyright IBM Corp. 2007-2008 # import unittest,", "\"id\") num2 = ibm_db.field_num(stmt, \"breed\") num3 = ibm_db.field_num(stmt, \"number\") num4", "num3 = ibm_db.field_num(stmt, \"number\") num4 = ibm_db.field_num(stmt, \"NUMBER\") num5 =", "ibm_db.exec_immediate(conn, \"SELECT breed, COUNT(breed) AS number FROM animals GROUP BY", "ibm_db.SQL_AUTOCOMMIT_OFF) insert = \"INSERT INTO animals values (7, 'cat', 'Benji',", "COUNT(breed) AS number FROM animals GROUP BY breed ORDER BY", "\"Breed\") num6 = ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1) num8", "5.1)\" ibm_db.exec_immediate(conn, insert) stmt = ibm_db.exec_immediate(conn, \"SELECT breed, COUNT(breed) AS", "8) num7 = ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"weight\") print(\"%s\"", "num7) print(\"%s\" % num8) ibm_db.rollback(conn) else: print(\"Connection failed.\") #__END__ #__LUW_EXPECTED__", "IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self): obj = IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def", "breed ORDER BY breed\") if (server.DBMS_NAME[0:3] == 'IDS'): num1 =", "IbmDbTestFunctions() obj.assert_expect(self.run_test_111) def run_test_111(self): conn = ibm_db.connect(config.database, config.user, config.password) server", "ibm_db.field_num(stmt, \"Breed\") num6 = ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1)", "= ibm_db.field_num(stmt, \"number\") num5 = ibm_db.field_num(stmt, \"Breed\") num6 = ibm_db.field_num(stmt,", "import unittest, sys import ibm_db import config from testfunctions import", "# Licensed Materials - Property of IBM # # (c)", "BY breed\") if (server.DBMS_NAME[0:3] == 'IDS'): num1 = ibm_db.field_num(stmt, \"id\")", "num7 = ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"WEIGHT\") else: num1", "ibm_db.field_num(stmt, \"NUMBER\") num4 = ibm_db.field_num(stmt, \"number\") num5 = ibm_db.field_num(stmt, \"Breed\")", "ibm_db.field_num(stmt, 8) num7 = ibm_db.field_num(stmt, 1) num8 = ibm_db.field_num(stmt, \"weight\")", "\"weight\") print(\"%s\" % num1) print(\"int(%d)\" % num2) print(\"int(%d)\" % num3)", "= ibm_db.field_num(stmt, \"weight\") print(\"%s\" % num1) print(\"int(%d)\" % num2) print(\"int(%d)\"", "from testfunctions import IbmDbTestFunctions class IbmDbTestCase(unittest.TestCase): def test_111_FieldNumAddCol(self): obj =", "print(\"Connection failed.\") #__END__ #__LUW_EXPECTED__ #False #int(0) #int(1) #False #False #False", "#int(1) #False #False #False #int(1) #False #__SYSTEMI_EXPECTED__ #False #int(0) #int(1)", "#False #False #False #int(1) #False #__SYSTEMI_EXPECTED__ #False #int(0) #int(1) #False", "sys import ibm_db import config from testfunctions import IbmDbTestFunctions class", "print(\"%s\" % num4) print(\"%s\" % num5) print(\"%s\" % num6) print(\"int(%d)\"", "num2 = ibm_db.field_num(stmt, \"breed\") num3 = ibm_db.field_num(stmt, \"number\") num4 =", "#int(1) #False #False #False #int(1) #False #__IDS_EXPECTED__ #False #int(0) #int(1)", "% num5) print(\"%s\" % num6) print(\"int(%d)\" % num7) print(\"%s\" %", "number FROM animals GROUP BY breed ORDER BY breed\") if", "'cat', 'Benji', 5.1)\" ibm_db.exec_immediate(conn, insert) stmt = ibm_db.exec_immediate(conn, \"SELECT breed,", "num2) print(\"int(%d)\" % num3) print(\"%s\" % num4) print(\"%s\" % num5)" ]
[ "reverse, NoReverseMatch from django.utils.translation import ugettext_lazy as _ from .models", "user has page edit permission can_change = (self.request.current_page and self.request.current_page.has_change_permission(", "not_edit_mode = not self.toolbar.edit_mode current_page_menu = self.toolbar.get_or_create_menu('page') current_page_menu.add_modal_item(_('Page banner'), url=url,", "else: url = (reverse(_banner_add_url) + '?extended_object=%s' % self.page.pk) except NoReverseMatch:", "(reverse(_banner_add_url) + '?extended_object=%s' % self.page.pk) except NoReverseMatch: # not in", "get_page_draft(self.request.current_page) if not self.page: # Nothing to do return #", "has_page_change_permission(self.request) else: has_global_current_page_change_permission = False # check if user has", "cms.toolbar_base import CMSToolbar from cms.utils import get_cms_setting from cms.utils.permissions import", "from cms.api import get_page_draft from cms.toolbar_pool import toolbar_pool from cms.toolbar_base", "use draft if we have a page self.page = get_page_draft(self.request.current_page)", ".models import PageBannerExtension _banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register", "Nothing to do return # check global permissions if CMS_PERMISSIONS", "+ '?extended_object=%s' % self.page.pk) except NoReverseMatch: # not in urls", "url = (reverse(_banner_add_url) + '?extended_object=%s' % self.page.pk) except NoReverseMatch: #", "(self.request.current_page and self.request.current_page.has_change_permission( self.request)) if has_global_current_page_change_permission or can_change: try: page_banner_extension", "edit permission can_change = (self.request.current_page and self.request.current_page.has_change_permission( self.request)) if has_global_current_page_change_permission", "None try: if page_banner_extension: url = reverse(_banner_change_url, args=(page_banner_extension.pk,)) else: url", "else: not_edit_mode = not self.toolbar.edit_mode current_page_menu = self.toolbar.get_or_create_menu('page') current_page_menu.add_modal_item(_('Page banner'),", "CMS_PERMISSIONS is active if get_cms_setting('PERMISSION'): has_global_current_page_change_permission = \\ has_page_change_permission(self.request) else:", "a page self.page = get_page_draft(self.request.current_page) if not self.page: # Nothing", "def populate(self): # always use draft if we have a", "= 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar): def populate(self): # always use", "page edit permission can_change = (self.request.current_page and self.request.current_page.has_change_permission( self.request)) if", "<reponame>Mindelirium/foundation<gh_stars>0 from cms.api import get_page_draft from cms.toolbar_pool import toolbar_pool from", "always use draft if we have a page self.page =", "check global permissions if CMS_PERMISSIONS is active if get_cms_setting('PERMISSION'): has_global_current_page_change_permission", "if CMS_PERMISSIONS is active if get_cms_setting('PERMISSION'): has_global_current_page_change_permission = \\ has_page_change_permission(self.request)", "to do return # check global permissions if CMS_PERMISSIONS is", "= reverse(_banner_change_url, args=(page_banner_extension.pk,)) else: url = (reverse(_banner_add_url) + '?extended_object=%s' %", "import get_cms_setting from cms.utils.permissions import has_page_change_permission from django.core.urlresolvers import reverse,", "try: if page_banner_extension: url = reverse(_banner_change_url, args=(page_banner_extension.pk,)) else: url =", "import reverse, NoReverseMatch from django.utils.translation import ugettext_lazy as _ from", "except PageBannerExtension.DoesNotExist: page_banner_extension = None try: if page_banner_extension: url =", "can_change: try: page_banner_extension = PageBannerExtension.objects.get( extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist: page_banner_extension =", "reverse(_banner_change_url, args=(page_banner_extension.pk,)) else: url = (reverse(_banner_add_url) + '?extended_object=%s' % self.page.pk)", "if user has page edit permission can_change = (self.request.current_page and", "NoReverseMatch: # not in urls pass else: not_edit_mode = not", "_ from .models import PageBannerExtension _banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url =", "import has_page_change_permission from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.translation import", "= (self.request.current_page and self.request.current_page.has_change_permission( self.request)) if has_global_current_page_change_permission or can_change: try:", "import CMSToolbar from cms.utils import get_cms_setting from cms.utils.permissions import has_page_change_permission", "PageBannerExtension _banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar):", "cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar from cms.utils import", "as _ from .models import PageBannerExtension _banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url", "from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.translation import ugettext_lazy as", "else: has_global_current_page_change_permission = False # check if user has page", "'?extended_object=%s' % self.page.pk) except NoReverseMatch: # not in urls pass", "toolbar_pool from cms.toolbar_base import CMSToolbar from cms.utils import get_cms_setting from", "class PageBannerExtensionToolbar(CMSToolbar): def populate(self): # always use draft if we", "if page_banner_extension: url = reverse(_banner_change_url, args=(page_banner_extension.pk,)) else: url = (reverse(_banner_add_url)", "check if user has page edit permission can_change = (self.request.current_page", "permissions if CMS_PERMISSIONS is active if get_cms_setting('PERMISSION'): has_global_current_page_change_permission = \\", "pass else: not_edit_mode = not self.toolbar.edit_mode current_page_menu = self.toolbar.get_or_create_menu('page') current_page_menu.add_modal_item(_('Page", "CMSToolbar from cms.utils import get_cms_setting from cms.utils.permissions import has_page_change_permission from", "page self.page = get_page_draft(self.request.current_page) if not self.page: # Nothing to", "django.utils.translation import ugettext_lazy as _ from .models import PageBannerExtension _banner_change_url", "we have a page self.page = get_page_draft(self.request.current_page) if not self.page:", "if get_cms_setting('PERMISSION'): has_global_current_page_change_permission = \\ has_page_change_permission(self.request) else: has_global_current_page_change_permission = False", "have a page self.page = get_page_draft(self.request.current_page) if not self.page: #", "if has_global_current_page_change_permission or can_change: try: page_banner_extension = PageBannerExtension.objects.get( extended_object_id=self.page.id) except", "self.request.current_page.has_change_permission( self.request)) if has_global_current_page_change_permission or can_change: try: page_banner_extension = PageBannerExtension.objects.get(", "'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar): def populate(self): #", "url = reverse(_banner_change_url, args=(page_banner_extension.pk,)) else: url = (reverse(_banner_add_url) + '?extended_object=%s'", "cms.api import get_page_draft from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import", "django.core.urlresolvers import reverse, NoReverseMatch from django.utils.translation import ugettext_lazy as _", "= 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar): def populate(self):", "# Nothing to do return # check global permissions if", "import get_page_draft from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar", "populate(self): # always use draft if we have a page", "PageBannerExtension.objects.get( extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist: page_banner_extension = None try: if page_banner_extension:", "ugettext_lazy as _ from .models import PageBannerExtension _banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change'", "except NoReverseMatch: # not in urls pass else: not_edit_mode =", "import ugettext_lazy as _ from .models import PageBannerExtension _banner_change_url =", "from cms.utils import get_cms_setting from cms.utils.permissions import has_page_change_permission from django.core.urlresolvers", "= get_page_draft(self.request.current_page) if not self.page: # Nothing to do return", "NoReverseMatch from django.utils.translation import ugettext_lazy as _ from .models import", "has_global_current_page_change_permission = \\ has_page_change_permission(self.request) else: has_global_current_page_change_permission = False # check", "from django.utils.translation import ugettext_lazy as _ from .models import PageBannerExtension", "PageBannerExtensionToolbar(CMSToolbar): def populate(self): # always use draft if we have", "from .models import PageBannerExtension _banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add'", "= PageBannerExtension.objects.get( extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist: page_banner_extension = None try: if", "= None try: if page_banner_extension: url = reverse(_banner_change_url, args=(page_banner_extension.pk,)) else:", "PageBannerExtension.DoesNotExist: page_banner_extension = None try: if page_banner_extension: url = reverse(_banner_change_url,", "has page edit permission can_change = (self.request.current_page and self.request.current_page.has_change_permission( self.request))", "import toolbar_pool from cms.toolbar_base import CMSToolbar from cms.utils import get_cms_setting", "draft if we have a page self.page = get_page_draft(self.request.current_page) if", "page_banner_extension: url = reverse(_banner_change_url, args=(page_banner_extension.pk,)) else: url = (reverse(_banner_add_url) +", "not self.page: # Nothing to do return # check global", "_banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar): def", "can_change = (self.request.current_page and self.request.current_page.has_change_permission( self.request)) if has_global_current_page_change_permission or can_change:", "get_cms_setting from cms.utils.permissions import has_page_change_permission from django.core.urlresolvers import reverse, NoReverseMatch", "# always use draft if we have a page self.page", "'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar): def populate(self): # always use draft", "or can_change: try: page_banner_extension = PageBannerExtension.objects.get( extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist: page_banner_extension", "= not self.toolbar.edit_mode current_page_menu = self.toolbar.get_or_create_menu('page') current_page_menu.add_modal_item(_('Page banner'), url=url, disabled=not_edit_mode)", "try: page_banner_extension = PageBannerExtension.objects.get( extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist: page_banner_extension = None", "self.page = get_page_draft(self.request.current_page) if not self.page: # Nothing to do", "self.page: # Nothing to do return # check global permissions", "args=(page_banner_extension.pk,)) else: url = (reverse(_banner_add_url) + '?extended_object=%s' % self.page.pk) except", "extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist: page_banner_extension = None try: if page_banner_extension: url", "if we have a page self.page = get_page_draft(self.request.current_page) if not", "permission can_change = (self.request.current_page and self.request.current_page.has_change_permission( self.request)) if has_global_current_page_change_permission or", "# not in urls pass else: not_edit_mode = not self.toolbar.edit_mode", "from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar from cms.utils", "@toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar): def populate(self): # always use draft if", "get_cms_setting('PERMISSION'): has_global_current_page_change_permission = \\ has_page_change_permission(self.request) else: has_global_current_page_change_permission = False #", "get_page_draft from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar from", "active if get_cms_setting('PERMISSION'): has_global_current_page_change_permission = \\ has_page_change_permission(self.request) else: has_global_current_page_change_permission =", "= False # check if user has page edit permission", "is active if get_cms_setting('PERMISSION'): has_global_current_page_change_permission = \\ has_page_change_permission(self.request) else: has_global_current_page_change_permission", "= (reverse(_banner_add_url) + '?extended_object=%s' % self.page.pk) except NoReverseMatch: # not", "if not self.page: # Nothing to do return # check", "has_global_current_page_change_permission = False # check if user has page edit", "return # check global permissions if CMS_PERMISSIONS is active if", "self.request)) if has_global_current_page_change_permission or can_change: try: page_banner_extension = PageBannerExtension.objects.get( extended_object_id=self.page.id)", "cms.utils import get_cms_setting from cms.utils.permissions import has_page_change_permission from django.core.urlresolvers import", "\\ has_page_change_permission(self.request) else: has_global_current_page_change_permission = False # check if user", "% self.page.pk) except NoReverseMatch: # not in urls pass else:", "from cms.utils.permissions import has_page_change_permission from django.core.urlresolvers import reverse, NoReverseMatch from", "has_page_change_permission from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.translation import ugettext_lazy", "_banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class PageBannerExtensionToolbar(CMSToolbar): def populate(self): # always", "has_global_current_page_change_permission or can_change: try: page_banner_extension = PageBannerExtension.objects.get( extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist:", "page_banner_extension = PageBannerExtension.objects.get( extended_object_id=self.page.id) except PageBannerExtension.DoesNotExist: page_banner_extension = None try:", "from cms.toolbar_base import CMSToolbar from cms.utils import get_cms_setting from cms.utils.permissions", "= \\ has_page_change_permission(self.request) else: has_global_current_page_change_permission = False # check if", "in urls pass else: not_edit_mode = not self.toolbar.edit_mode current_page_menu =", "# check global permissions if CMS_PERMISSIONS is active if get_cms_setting('PERMISSION'):", "do return # check global permissions if CMS_PERMISSIONS is active", "import PageBannerExtension _banner_change_url = 'admin:djangocms_pagebanner_pagebannerextension_change' _banner_add_url = 'admin:djangocms_pagebanner_pagebannerextension_add' @toolbar_pool.register class", "# check if user has page edit permission can_change =", "not in urls pass else: not_edit_mode = not self.toolbar.edit_mode current_page_menu", "cms.utils.permissions import has_page_change_permission from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.translation", "self.page.pk) except NoReverseMatch: # not in urls pass else: not_edit_mode", "page_banner_extension = None try: if page_banner_extension: url = reverse(_banner_change_url, args=(page_banner_extension.pk,))", "and self.request.current_page.has_change_permission( self.request)) if has_global_current_page_change_permission or can_change: try: page_banner_extension =", "urls pass else: not_edit_mode = not self.toolbar.edit_mode current_page_menu = self.toolbar.get_or_create_menu('page')", "False # check if user has page edit permission can_change", "global permissions if CMS_PERMISSIONS is active if get_cms_setting('PERMISSION'): has_global_current_page_change_permission =" ]
[ "hidden): emb = self.drop(self.encoder(input)) hidden_ = [] for h in", "the same dimension as the embeddings, so that the two", "does not exist in PyTorch 1.1 or lower.') self.model_type =", "dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))", "the relative or absolute position of the tokens in the", "except: raise ImportError('TransformerEncoder module does not exist in PyTorch 1.1", "word position and i is the embed idx) Args: d_model:", "has_mask: device = src.device if self.src_mask is None or self.src_mask.size(0)", "(Inan et al. 2016) # https://arxiv.org/abs/1611.01462 if tie_weights: if nhid", "RNNModel(nn.Module): \"\"\"Container module with an encoder, a recurrent module, and", "self.drop(self.encoder(input)) hidden_ = [] for h in hidden: if isinstance(h,", "supplied, options are ['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU']\"\"\") self.rnn =", "from torch.nn import TransformerEncoder, TransformerEncoderLayer except: raise ImportError('TransformerEncoder module does", "output, hidden = self.rnn(emb, tuple(hidden_)) output = self.drop(output) decoded =", "dropout value (default=0.1). max_len: the max. length of the incoming", "class RNNModel(nn.Module): \"\"\"Container module with an encoder, a recurrent module,", "if decoder is None: self.decoder = nn.Linear(nhid, ntoken) else: self.decoder", "= nn.Linear(nhid, ntoken) else: self.decoder = decoder def _generate_square_subsequent_mask(self, sz):", "def forward(self, x): r\"\"\"Inputs of forward function Args: x: the", "bsz, self.nhid), weight.new_zeros(self.nlayers, bsz, self.nhid)) else: return weight.new_zeros(self.nlayers, bsz, self.nhid)", "= nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len,", "d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position", "raise ImportError('TransformerEncoder module does not exist in PyTorch 1.1 or", "mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return", "TransformerEncoder, TransformerEncoderLayer except: raise ImportError('TransformerEncoder module does not exist in", "of different frequencies. .. math:: \\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos,", "(torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0,", "if tie_weights: if nhid != ninp: raise ValueError('When using the", "def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5, encoder=None, decoder=None):", "h in hidden: if isinstance(h, torch.LongTensor) or isinstance(h, torch.cuda.LongTensor): h", "1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe',", "\"Tying Word Vectors and Word Classifiers: A Loss Framework for", "nlayers) if encoder is None: self.encoder = nn.Embedding(ntoken, ninp) else:", "in ['LSTM', 'GRU']: self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout)", "absolute position of the tokens in the sequence. The positional", "can be summed. Here, we use sine and cosine functions", "forward(self, input, hidden): emb = self.drop(self.encoder(input)) hidden_ = [] for", "mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask else: self.src_mask = None", "nhid, nlayers, dropout=dropout) else: try: nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU':", "weights as in: # \"Using the Output Embedding to Improve", "0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position *", "# \"Using the Output Embedding to Improve Language Models\" (Press", "idx) Args: d_model: the embed dim (required). dropout: the dropout", "encodings have the same dimension as the embeddings, so that", "mask def init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__ == \"Embedding\":", "Loss Framework for Language Modeling\" (Inan et al. 2016) #", "sequence. The positional encodings have the same dimension as the", "pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term", "if self.encoder.__class__.__name__ == \"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange) else: self.encoder.init_weights() if self.decoder.__class__.__name__", "rnn_type in ['LSTM', 'GRU']: self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers,", "the embed dim (required). dropout: the dropout value (default=0.1). max_len:", "decoder is None: self.decoder = nn.Linear(nhid, ntoken) else: self.decoder =", "the word position and i is the embed idx) Args:", "and # \"Tying Word Vectors and Word Classifiers: A Loss", "output: [sequence length, batch size, embed dim] Examples: >>> output", "tie weights as in: # \"Using the Output Embedding to", "position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float()", "= h.to(torch.float) hidden_.append(h) output, hidden = self.rnn(emb, tuple(hidden_)) output =", "['LSTM', 'GRU']: self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else:", "(weight.new_zeros(self.nlayers, bsz, self.nhid), weight.new_zeros(self.nlayers, bsz, self.nhid)) else: return weight.new_zeros(self.nlayers, bsz,", "= torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term =", "self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(ninp, dropout)", "ninp: raise ValueError('When using the tied flag, nhid must be", "we use sine and cosine functions of different frequencies. ..", "encoder if rnn_type in ['LSTM', 'GRU']: self.rnn = getattr(nn, rnn_type)(ninp,", "torch.nn as nn import torch.nn.functional as F class RNNModel(nn.Module): \"\"\"Container", "different frequencies. .. math:: \\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1)", "nlayers, dropout=dropout) else: try: nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type]", "self.decoder = decoder def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz))", "__init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5, encoder=None, decoder=None): super(TransformerModel,", "# and # \"Tying Word Vectors and Word Classifiers: A", "else: self.decoder.init_weights() def forward(self, input, hidden): emb = self.drop(self.encoder(input)) hidden_", "== 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask ==", "so that the two can be summed. Here, we use", "F class RNNModel(nn.Module): \"\"\"Container module with an encoder, a recurrent", "and a decoder.\"\"\" def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers,", "__init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False, encoder=None, decoder=None):", "'RNN_RELU': 'relu'}[rnn_type] except KeyError: raise ValueError( \"\"\"An invalid option for", "torch import torch.nn as nn import torch.nn.functional as F class", "def init_hidden(self, bsz): weight = next(self.parameters()) if self.rnn_type == 'LSTM':", "self.decoder.init_weights() def forward(self, src, has_mask=True): if has_mask: device = src.device", "init_hidden(self, bsz): weight = next(self.parameters()) if self.rnn_type == 'LSTM': return", "self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) if encoder is None: self.encoder =", "float('-inf')).masked_fill(mask == 1, float(0.0)) return mask def init_weights(self): initrange =", "cos(pos/10000^(2i/d_model)) \\text{where pos is the word position and i is", "import torch.nn as nn import torch.nn.functional as F class RNNModel(nn.Module):", "0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask def init_weights(self): initrange", "emsize') self.decoder.weight = self.encoder.weight self.rnn_type = rnn_type self.nhid = nhid", "the max. length of the incoming sequence (default=5000). Examples: >>>", "nlayers, dropout=0.5, encoder=None, decoder=None): super(TransformerModel, self).__init__() try: from torch.nn import", "Here, we use sine and cosine functions of different frequencies.", "import torch import torch.nn as nn import torch.nn.functional as F", "if nhid != ninp: raise ValueError('When using the tied flag,", "batch size, embed dim] output: [sequence length, batch size, embed", "\"Using the Output Embedding to Improve Language Models\" (Press &", "else: self.decoder = decoder def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz,", "div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:,", "or self.src_mask.size(0) != len(src): mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask", "leave PositionalEncoding module here. Will be moved somewhere else. class", "a recurrent module, and a decoder.\"\"\" def __init__(self, rnn_type, ntoken,", "emb = self.drop(self.encoder(input)) hidden_ = [] for h in hidden:", "sine and cosine functions of different frequencies. .. math:: \\text{PosEncoder}(pos,", "of the incoming sequence (default=5000). Examples: >>> pos_encoder = PositionalEncoding(d_model)", "Examples: >>> output = pos_encoder(x) \"\"\" x = x +", "h = h.to(torch.float) hidden_.append(h) output, hidden = self.rnn(emb, tuple(hidden_)) output", "Vectors and Word Classifiers: A Loss Framework for Language Modeling\"", "import torch.nn.functional as F class RNNModel(nn.Module): \"\"\"Container module with an", "self.nlayers = nlayers def init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__", "embed dim] Examples: >>> output = pos_encoder(x) \"\"\" x =", "rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False, encoder=None, decoder=None): super(RNNModel,", "[sequence length, batch size, embed dim] output: [sequence length, batch", "Args: x: the sequence fed to the positional encoder model", "len(src): mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask else: self.src_mask =", "is the word position and i is the embed idx)", "or 'RNN_RELU']\"\"\") self.rnn = nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout) if", "rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try: nonlinearity = {'RNN_TANH': 'tanh',", "tied flag, nhid must be equal to emsize') self.decoder.weight =", "in the sequence. The positional encodings have the same dimension", "None: self.encoder = nn.Embedding(ntoken, ninp) else: self.encoder = encoder self.ninp", "Language Models\" (Press & Wolf 2016) # https://arxiv.org/abs/1608.05859 # and", "must be equal to emsize') self.decoder.weight = self.encoder.weight self.rnn_type =", "nhead, nhid, nlayers, dropout=0.5, encoder=None, decoder=None): super(TransformerModel, self).__init__() try: from", "init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__ == \"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange)", "if self.src_mask is None or self.src_mask.size(0) != len(src): mask =", "\\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) \\text{where pos is the word position", "Wolf 2016) # https://arxiv.org/abs/1608.05859 # and # \"Tying Word Vectors", "hidden: if isinstance(h, torch.LongTensor) or isinstance(h, torch.cuda.LongTensor): h = h.to(torch.float)", "try: from torch.nn import TransformerEncoder, TransformerEncoderLayer except: raise ImportError('TransformerEncoder module", "self.nhid = nhid self.nlayers = nlayers def init_weights(self): initrange =", "ImportError('TransformerEncoder module does not exist in PyTorch 1.1 or lower.')", "# Optionally tie weights as in: # \"Using the Output", "lower.') self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(ninp,", "isinstance(h, torch.LongTensor) or isinstance(h, torch.cuda.LongTensor): h = h.to(torch.float) hidden_.append(h) output,", "\"\"\" def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout =", "module with an encoder, a recurrent module, and a decoder.\"\"\"", "have the same dimension as the embeddings, so that the", "= encoder if rnn_type in ['LSTM', 'GRU']: self.rnn = getattr(nn,", "F.log_softmax(decoded, dim=1), hidden def init_hidden(self, bsz): weight = next(self.parameters()) if", "output = self.transformer_encoder(src, self.src_mask) output = self.decoder(output) return F.log_softmax(output, dim=-1)", "tie_weights=False, encoder=None, decoder=None): super(RNNModel, self).__init__() self.ntoken = ntoken self.drop =", "= None src = self.encoder(src) * math.sqrt(self.ninp) src = self.pos_encoder(src)", "to Improve Language Models\" (Press & Wolf 2016) # https://arxiv.org/abs/1608.05859", "None or self.src_mask.size(0) != len(src): mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask =", "self.nhid), weight.new_zeros(self.nlayers, bsz, self.nhid)) else: return weight.new_zeros(self.nlayers, bsz, self.nhid) #", "decoder=None): super(TransformerModel, self).__init__() try: from torch.nn import TransformerEncoder, TransformerEncoderLayer except:", "the sequence fed to the positional encoder model (required). Shape:", "here. Will be moved somewhere else. class PositionalEncoding(nn.Module): r\"\"\"Inject some", "(default=5000). Examples: >>> pos_encoder = PositionalEncoding(d_model) \"\"\" def __init__(self, d_model,", "= 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(ninp, dropout) encoder_layers", "module here. Will be moved somewhere else. class PositionalEncoding(nn.Module): r\"\"\"Inject", "transformer module, and a decoder.\"\"\" def __init__(self, ntoken, ninp, nhead,", "nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type] except KeyError: raise ValueError(", "initrange) else: self.decoder.init_weights() def forward(self, src, has_mask=True): if has_mask: device", "encoder is None: self.encoder = nn.Embedding(ntoken, ninp) else: self.encoder =", "Temporarily leave PositionalEncoding module here. Will be moved somewhere else.", "self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask else: self.src_mask = None src =", "encoder self.ninp = ninp if decoder is None: self.decoder =", "None: self.encoder = nn.Embedding(ntoken, ninp) else: self.encoder = encoder if", "(Press & Wolf 2016) # https://arxiv.org/abs/1608.05859 # and # \"Tying", "length, batch size, embed dim] Examples: >>> output = pos_encoder(x)", "<gh_stars>1-10 import math import torch import torch.nn as nn import", ">>> output = pos_encoder(x) \"\"\" x = x + self.pe[:x.size(0),", "pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position", "self.src_mask = None src = self.encoder(src) * math.sqrt(self.ninp) src =", "of the tokens in the sequence. The positional encodings have", "PositionalEncoding module here. Will be moved somewhere else. class PositionalEncoding(nn.Module):", "nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout) if decoder is None: self.decoder =", "dropout: the dropout value (default=0.1). max_len: the max. length of", "import TransformerEncoder, TransformerEncoderLayer except: raise ImportError('TransformerEncoder module does not exist", "'RNN_TANH' or 'RNN_RELU']\"\"\") self.rnn = nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout)", "`--model` was supplied, options are ['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU']\"\"\")", "weight.new_zeros(self.nlayers, bsz, self.nhid) # Temporarily leave PositionalEncoding module here. Will", "nlayers, dropout=0.5, tie_weights=False, encoder=None, decoder=None): super(RNNModel, self).__init__() self.ntoken = ntoken", "be moved somewhere else. class PositionalEncoding(nn.Module): r\"\"\"Inject some information about", "else: return weight.new_zeros(self.nlayers, bsz, self.nhid) # Temporarily leave PositionalEncoding module", "the sequence. The positional encodings have the same dimension as", "dropout=0.5, tie_weights=False, encoder=None, decoder=None): super(RNNModel, self).__init__() self.ntoken = ntoken self.drop", "torch.cuda.LongTensor): h = h.to(torch.float) hidden_.append(h) output, hidden = self.rnn(emb, tuple(hidden_))", "two can be summed. Here, we use sine and cosine", "0.1 if self.encoder.__class__.__name__ == \"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange) else: self.encoder.init_weights() if", "bsz, self.nhid)) else: return weight.new_zeros(self.nlayers, bsz, self.nhid) # Temporarily leave", "else: try: nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type] except KeyError:", "\"\"\" x = x + self.pe[:x.size(0), :] return self.dropout(x) class", "is None: self.encoder = nn.Embedding(ntoken, ninp) else: self.encoder = encoder", "self).__init__() try: from torch.nn import TransformerEncoder, TransformerEncoderLayer except: raise ImportError('TransformerEncoder", "2i) = sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) \\text{where pos is", "self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position =", "ntoken, ninp, nhead, nhid, nlayers, dropout=0.5, encoder=None, decoder=None): super(TransformerModel, self).__init__()", "self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, input, hidden): emb", "recurrent module, and a decoder.\"\"\" def __init__(self, rnn_type, ntoken, ninp,", "self.encoder.weight.data.uniform_(-initrange, initrange) else: self.encoder.init_weights() if self.decoder.__class__.__name__ == \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange,", "\"\"\"An invalid option for `--model` was supplied, options are ['LSTM',", "try: nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type] except KeyError: raise", "x: the sequence fed to the positional encoder model (required).", "Word Classifiers: A Loss Framework for Language Modeling\" (Inan et", "exist in PyTorch 1.1 or lower.') self.model_type = 'Transformer' self.src_mask", "1, float(0.0)) return mask def init_weights(self): initrange = 0.1 if", "= nlayers def init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__ ==", "= torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2]", "self.decoder.init_weights() def forward(self, input, hidden): emb = self.drop(self.encoder(input)) hidden_ =", "hidden_ = [] for h in hidden: if isinstance(h, torch.LongTensor)", "1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))", "(required). dropout: the dropout value (default=0.1). max_len: the max. length", "self.src_mask = None self.pos_encoder = PositionalEncoding(ninp, dropout) encoder_layers = TransformerEncoderLayer(ninp,", "A Loss Framework for Language Modeling\" (Inan et al. 2016)", "the two can be summed. Here, we use sine and", "torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] =", "\\text{where pos is the word position and i is the", "d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] =", "x = x + self.pe[:x.size(0), :] return self.dropout(x) class TransformerModel(nn.Module):", "+ self.pe[:x.size(0), :] return self.dropout(x) class TransformerModel(nn.Module): \"\"\"Container module with", "src = self.encoder(src) * math.sqrt(self.ninp) src = self.pos_encoder(src) output =", "self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, src, has_mask=True): if has_mask:", "positional encoder model (required). Shape: x: [sequence length, batch size,", "= nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout) if decoder is None:", "tokens in the sequence. The positional encodings have the same", "device = src.device if self.src_mask is None or self.src_mask.size(0) !=", "* (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term)", "* div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self,", "except KeyError: raise ValueError( \"\"\"An invalid option for `--model` was", "src, has_mask=True): if has_mask: device = src.device if self.src_mask is", "= self.rnn(emb, tuple(hidden_)) output = self.drop(output) decoded = self.decoder(output) decoded", "1.1 or lower.') self.model_type = 'Transformer' self.src_mask = None self.pos_encoder", "Modeling\" (Inan et al. 2016) # https://arxiv.org/abs/1611.01462 if tie_weights: if", "= nhid self.nlayers = nlayers def init_weights(self): initrange = 0.1", "super(TransformerModel, self).__init__() try: from torch.nn import TransformerEncoder, TransformerEncoderLayer except: raise", "https://arxiv.org/abs/1611.01462 if tie_weights: if nhid != ninp: raise ValueError('When using", "TransformerEncoder(encoder_layers, nlayers) if encoder is None: self.encoder = nn.Embedding(ntoken, ninp)", "== 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask def init_weights(self):", "position of the tokens in the sequence. The positional encodings", "dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len,", "= src.device if self.src_mask is None or self.src_mask.size(0) != len(src):", "= next(self.parameters()) if self.rnn_type == 'LSTM': return (weight.new_zeros(self.nlayers, bsz, self.nhid),", "\"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, src, has_mask=True):", "a decoder.\"\"\" def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5,", "def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False, encoder=None,", "raise ValueError('When using the tied flag, nhid must be equal", "\"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange) else: self.encoder.init_weights() if self.decoder.__class__.__name__ == \"Linear\": self.decoder.bias.data.zero_()", "def forward(self, input, hidden): emb = self.drop(self.encoder(input)) hidden_ = []", "as nn import torch.nn.functional as F class RNNModel(nn.Module): \"\"\"Container module", "# Temporarily leave PositionalEncoding module here. Will be moved somewhere", "'GRU']: self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try:", "fed to the positional encoder model (required). Shape: x: [sequence", "or transformer module, and a decoder.\"\"\" def __init__(self, ntoken, ninp,", "self.encoder.init_weights() if self.decoder.__class__.__name__ == \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights()", "cosine functions of different frequencies. .. math:: \\text{PosEncoder}(pos, 2i) =", "== \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, src,", "of forward function Args: x: the sequence fed to the", "= nn.Embedding(ntoken, ninp) else: self.encoder = encoder if rnn_type in", "else: self.encoder.init_weights() if self.decoder.__class__.__name__ == \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else:", "module with an encoder, a recurrent or transformer module, and", "torch.nn import TransformerEncoder, TransformerEncoderLayer except: raise ImportError('TransformerEncoder module does not", "the tokens in the sequence. The positional encodings have the", "value (default=0.1). max_len: the max. length of the incoming sequence", "about the relative or absolute position of the tokens in", "dim (required). dropout: the dropout value (default=0.1). max_len: the max.", "{'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type] except KeyError: raise ValueError( \"\"\"An invalid", "x): r\"\"\"Inputs of forward function Args: x: the sequence fed", "def forward(self, src, has_mask=True): if has_mask: device = src.device if", "with an encoder, a recurrent module, and a decoder.\"\"\" def", "/ d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2]", "module, and a decoder.\"\"\" def __init__(self, ntoken, ninp, nhead, nhid,", "weight = next(self.parameters()) if self.rnn_type == 'LSTM': return (weight.new_zeros(self.nlayers, bsz,", "# https://arxiv.org/abs/1608.05859 # and # \"Tying Word Vectors and Word", "float(0.0)) return mask def init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__", "= nn.Linear(nhid, ntoken) else: self.decoder = decoder # Optionally tie", "decoder # Optionally tie weights as in: # \"Using the", "def init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__ == \"Embedding\": self.encoder.weight.data.uniform_(-initrange,", "return weight.new_zeros(self.nlayers, bsz, self.nhid) # Temporarily leave PositionalEncoding module here.", "decoder=None): super(RNNModel, self).__init__() self.ntoken = ntoken self.drop = nn.Dropout(dropout) if", "class PositionalEncoding(nn.Module): r\"\"\"Inject some information about the relative or absolute", "= ntoken self.drop = nn.Dropout(dropout) if encoder is None: self.encoder", "option for `--model` was supplied, options are ['LSTM', 'GRU', 'RNN_TANH'", "raise ValueError( \"\"\"An invalid option for `--model` was supplied, options", "= torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() *", "with an encoder, a recurrent or transformer module, and a", "KeyError: raise ValueError( \"\"\"An invalid option for `--model` was supplied,", "decoded = self.decoder(output) decoded = decoded.view(-1, self.ntoken) return F.log_softmax(decoded, dim=1),", "somewhere else. class PositionalEncoding(nn.Module): r\"\"\"Inject some information about the relative", "else: self.decoder.init_weights() def forward(self, src, has_mask=True): if has_mask: device =", "and Word Classifiers: A Loss Framework for Language Modeling\" (Inan", "2i+1) = cos(pos/10000^(2i/d_model)) \\text{where pos is the word position and", "size, embed dim] Examples: >>> output = pos_encoder(x) \"\"\" x", "equal to emsize') self.decoder.weight = self.encoder.weight self.rnn_type = rnn_type self.nhid", "hidden = self.rnn(emb, tuple(hidden_)) output = self.drop(output) decoded = self.decoder(output)", "as the embeddings, so that the two can be summed.", "r\"\"\"Inputs of forward function Args: x: the sequence fed to", "= self.decoder(output) decoded = decoded.view(-1, self.ntoken) return F.log_softmax(decoded, dim=1), hidden", "hidden_.append(h) output, hidden = self.rnn(emb, tuple(hidden_)) output = self.drop(output) decoded", "initrange) else: self.decoder.init_weights() def forward(self, input, hidden): emb = self.drop(self.encoder(input))", "'GRU', 'RNN_TANH' or 'RNN_RELU']\"\"\") self.rnn = nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity,", "decoded = decoded.view(-1, self.ntoken) return F.log_softmax(decoded, dim=1), hidden def init_hidden(self,", "self.rnn_type == 'LSTM': return (weight.new_zeros(self.nlayers, bsz, self.nhid), weight.new_zeros(self.nlayers, bsz, self.nhid))", "hidden def init_hidden(self, bsz): weight = next(self.parameters()) if self.rnn_type ==", "self.src_mask is None or self.src_mask.size(0) != len(src): mask = self._generate_square_subsequent_mask(len(src)).to(device)", "math.sqrt(self.ninp) src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output =", "nn import torch.nn.functional as F class RNNModel(nn.Module): \"\"\"Container module with", "ntoken self.drop = nn.Dropout(dropout) if encoder is None: self.encoder =", "div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0,", "next(self.parameters()) if self.rnn_type == 'LSTM': return (weight.new_zeros(self.nlayers, bsz, self.nhid), weight.new_zeros(self.nlayers,", "else. class PositionalEncoding(nn.Module): r\"\"\"Inject some information about the relative or", "length, batch size, embed dim] output: [sequence length, batch size,", "ValueError('When using the tied flag, nhid must be equal to", "2016) # https://arxiv.org/abs/1608.05859 # and # \"Tying Word Vectors and", "forward(self, x): r\"\"\"Inputs of forward function Args: x: the sequence", "(-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:,", "invalid option for `--model` was supplied, options are ['LSTM', 'GRU',", "math import torch import torch.nn as nn import torch.nn.functional as", "self.nhid) # Temporarily leave PositionalEncoding module here. Will be moved", "Improve Language Models\" (Press & Wolf 2016) # https://arxiv.org/abs/1608.05859 #", "return F.log_softmax(decoded, dim=1), hidden def init_hidden(self, bsz): weight = next(self.parameters())", "= sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) \\text{where pos is the", "= cos(pos/10000^(2i/d_model)) \\text{where pos is the word position and i", "self.drop = nn.Dropout(dropout) if encoder is None: self.encoder = nn.Embedding(ntoken,", "input, hidden): emb = self.drop(self.encoder(input)) hidden_ = [] for h", "in PyTorch 1.1 or lower.') self.model_type = 'Transformer' self.src_mask =", "torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0)", "Will be moved somewhere else. class PositionalEncoding(nn.Module): r\"\"\"Inject some information", "self.rnn = nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout) if decoder is", "output = self.drop(output) decoded = self.decoder(output) decoded = decoded.view(-1, self.ntoken)", "= decoder # Optionally tie weights as in: # \"Using", "Optionally tie weights as in: # \"Using the Output Embedding", "nhid self.nlayers = nlayers def init_weights(self): initrange = 0.1 if", "and i is the embed idx) Args: d_model: the embed", "bsz, self.nhid) # Temporarily leave PositionalEncoding module here. Will be", "Examples: >>> pos_encoder = PositionalEncoding(d_model) \"\"\" def __init__(self, d_model, dropout=0.1,", "is None or self.src_mask.size(0) != len(src): mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask", "is the embed idx) Args: d_model: the embed dim (required).", "pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): r\"\"\"Inputs", "PositionalEncoding(d_model) \"\"\" def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout", "= TransformerEncoderLayer(ninp, nhead, nhid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) if", "some information about the relative or absolute position of the", "Word Vectors and Word Classifiers: A Loss Framework for Language", "sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask", "self.ntoken) return F.log_softmax(decoded, dim=1), hidden def init_hidden(self, bsz): weight =", "= getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try: nonlinearity =", "and a decoder.\"\"\" def __init__(self, ntoken, ninp, nhead, nhid, nlayers,", "!= len(src): mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask else: self.src_mask", "be equal to emsize') self.decoder.weight = self.encoder.weight self.rnn_type = rnn_type", "tuple(hidden_)) output = self.drop(output) decoded = self.decoder(output) decoded = decoded.view(-1,", "= pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): r\"\"\"Inputs of", "ninp) else: self.encoder = encoder if rnn_type in ['LSTM', 'GRU']:", "ninp if decoder is None: self.decoder = nn.Linear(nhid, ntoken) else:", "self.src_mask.size(0) != len(src): mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask else:", ":] return self.dropout(x) class TransformerModel(nn.Module): \"\"\"Container module with an encoder,", "pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1)", "= [] for h in hidden: if isinstance(h, torch.LongTensor) or", "rnn_type self.nhid = nhid self.nlayers = nlayers def init_weights(self): initrange", "* math.sqrt(self.ninp) src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output", "the tied flag, nhid must be equal to emsize') self.decoder.weight", "= TransformerEncoder(encoder_layers, nlayers) if encoder is None: self.encoder = nn.Embedding(ntoken,", "self.rnn_type = rnn_type self.nhid = nhid self.nlayers = nlayers def", "r\"\"\"Inject some information about the relative or absolute position of", "class TransformerModel(nn.Module): \"\"\"Container module with an encoder, a recurrent or", "dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) if encoder is None: self.encoder", "dimension as the embeddings, so that the two can be", "PyTorch 1.1 or lower.') self.model_type = 'Transformer' self.src_mask = None", "= decoder def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz)) ==", "self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, src, has_mask=True): if", "the embed idx) Args: d_model: the embed dim (required). dropout:", "None self.pos_encoder = PositionalEncoding(ninp, dropout) encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid,", "= self.drop(output) decoded = self.decoder(output) decoded = decoded.view(-1, self.ntoken) return", "model (required). Shape: x: [sequence length, batch size, embed dim]", "the positional encoder model (required). Shape: x: [sequence length, batch", "max_len: the max. length of the incoming sequence (default=5000). Examples:", "x + self.pe[:x.size(0), :] return self.dropout(x) class TransformerModel(nn.Module): \"\"\"Container module", "else: self.decoder = decoder # Optionally tie weights as in:", "x: [sequence length, batch size, embed dim] output: [sequence length,", "[] for h in hidden: if isinstance(h, torch.LongTensor) or isinstance(h,", "nonlinearity=nonlinearity, dropout=dropout) if decoder is None: self.decoder = nn.Linear(nhid, ntoken)", "= mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask", "or lower.') self.model_type = 'Transformer' self.src_mask = None self.pos_encoder =", "encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)", "= pos_encoder(x) \"\"\" x = x + self.pe[:x.size(0), :] return", "nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)", "_generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask", "def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)", "== \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, input,", "or isinstance(h, torch.cuda.LongTensor): h = h.to(torch.float) hidden_.append(h) output, hidden =", "functions of different frequencies. .. math:: \\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))", "self.ntoken = ntoken self.drop = nn.Dropout(dropout) if encoder is None:", "self.nhid)) else: return weight.new_zeros(self.nlayers, bsz, self.nhid) # Temporarily leave PositionalEncoding", "self.src_mask = mask else: self.src_mask = None src = self.encoder(src)", "\\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) \\text{where pos", "same dimension as the embeddings, so that the two can", "in hidden: if isinstance(h, torch.LongTensor) or isinstance(h, torch.cuda.LongTensor): h =", "= PositionalEncoding(d_model) \"\"\" def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__()", "pe) def forward(self, x): r\"\"\"Inputs of forward function Args: x:", "as in: # \"Using the Output Embedding to Improve Language", "max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) /", "= self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask else: self.src_mask = None src", "\"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, input, hidden):", "self.encoder.weight self.rnn_type = rnn_type self.nhid = nhid self.nlayers = nlayers", "has_mask=True): if has_mask: device = src.device if self.src_mask is None", "and cosine functions of different frequencies. .. math:: \\text{PosEncoder}(pos, 2i)", "= torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term)", "embed dim] output: [sequence length, batch size, embed dim] Examples:", "embed dim (required). dropout: the dropout value (default=0.1). max_len: the", "decoder def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0,", "relative or absolute position of the tokens in the sequence.", "= (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask ==", "bsz): weight = next(self.parameters()) if self.rnn_type == 'LSTM': return (weight.new_zeros(self.nlayers,", "decoded.view(-1, self.ntoken) return F.log_softmax(decoded, dim=1), hidden def init_hidden(self, bsz): weight", "!= ninp: raise ValueError('When using the tied flag, nhid must", "nhid, nlayers, dropout=0.5, tie_weights=False, encoder=None, decoder=None): super(RNNModel, self).__init__() self.ntoken =", "self.encoder = nn.Embedding(ntoken, ninp) else: self.encoder = encoder self.ninp =", "= nn.Dropout(dropout) if encoder is None: self.encoder = nn.Embedding(ntoken, ninp)", "if self.decoder.__class__.__name__ == \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def", "PositionalEncoding(nn.Module): r\"\"\"Inject some information about the relative or absolute position", "d_model: the embed dim (required). dropout: the dropout value (default=0.1).", "to emsize') self.decoder.weight = self.encoder.weight self.rnn_type = rnn_type self.nhid =", "frequencies. .. math:: \\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1) =", "that the two can be summed. Here, we use sine", "\"\"\"Container module with an encoder, a recurrent module, and a", "if self.rnn_type == 'LSTM': return (weight.new_zeros(self.nlayers, bsz, self.nhid), weight.new_zeros(self.nlayers, bsz,", "= encoder self.ninp = ninp if decoder is None: self.decoder", "recurrent or transformer module, and a decoder.\"\"\" def __init__(self, ntoken,", "src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output = self.decoder(output)", "self.dropout(x) class TransformerModel(nn.Module): \"\"\"Container module with an encoder, a recurrent", "nhead, nhid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) if encoder is", "be summed. Here, we use sine and cosine functions of", "self.encoder = encoder if rnn_type in ['LSTM', 'GRU']: self.rnn =", "nn.Embedding(ntoken, ninp) else: self.encoder = encoder if rnn_type in ['LSTM',", "initrange) else: self.encoder.init_weights() if self.decoder.__class__.__name__ == \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange)", "'LSTM': return (weight.new_zeros(self.nlayers, bsz, self.nhid), weight.new_zeros(self.nlayers, bsz, self.nhid)) else: return", "max. length of the incoming sequence (default=5000). Examples: >>> pos_encoder", "size, embed dim] output: [sequence length, batch size, embed dim]", "torch.nn.functional as F class RNNModel(nn.Module): \"\"\"Container module with an encoder,", "Args: d_model: the embed dim (required). dropout: the dropout value", ">>> pos_encoder = PositionalEncoding(d_model) \"\"\" def __init__(self, d_model, dropout=0.1, max_len=5000):", "module, and a decoder.\"\"\" def __init__(self, rnn_type, ntoken, ninp, nhid,", "moved somewhere else. class PositionalEncoding(nn.Module): r\"\"\"Inject some information about the", "(required). Shape: x: [sequence length, batch size, embed dim] output:", "ntoken) else: self.decoder = decoder def _generate_square_subsequent_mask(self, sz): mask =", "= self.encoder.weight self.rnn_type = rnn_type self.nhid = nhid self.nlayers =", "return mask def init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__ ==", "== 1, float(0.0)) return mask def init_weights(self): initrange = 0.1", "in: # \"Using the Output Embedding to Improve Language Models\"", "an encoder, a recurrent module, and a decoder.\"\"\" def __init__(self,", "was supplied, options are ['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU']\"\"\") self.rnn", "self.decoder.__class__.__name__ == \"Linear\": self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self,", "information about the relative or absolute position of the tokens", "mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask def", "the embeddings, so that the two can be summed. Here,", "as F class RNNModel(nn.Module): \"\"\"Container module with an encoder, a", "self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0,", "the Output Embedding to Improve Language Models\" (Press & Wolf", "incoming sequence (default=5000). Examples: >>> pos_encoder = PositionalEncoding(d_model) \"\"\" def", "initrange = 0.1 if self.encoder.__class__.__name__ == \"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange) else:", "= {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type] except KeyError: raise ValueError( \"\"\"An", "= nn.Embedding(ntoken, ninp) else: self.encoder = encoder self.ninp = ninp", "'RNN_RELU']\"\"\") self.rnn = nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout) if decoder", "& Wolf 2016) # https://arxiv.org/abs/1608.05859 # and # \"Tying Word", "# https://arxiv.org/abs/1611.01462 if tie_weights: if nhid != ninp: raise ValueError('When", "options are ['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU']\"\"\") self.rnn = nn.RNN(ninp,", "encoder, a recurrent module, and a decoder.\"\"\" def __init__(self, rnn_type,", "nhid must be equal to emsize') self.decoder.weight = self.encoder.weight self.rnn_type", "[sequence length, batch size, embed dim] Examples: >>> output =", "getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try: nonlinearity = {'RNN_TANH':", "1) self.register_buffer('pe', pe) def forward(self, x): r\"\"\"Inputs of forward function", "if isinstance(h, torch.LongTensor) or isinstance(h, torch.cuda.LongTensor): h = h.to(torch.float) hidden_.append(h)", "Models\" (Press & Wolf 2016) # https://arxiv.org/abs/1608.05859 # and #", "nn.Linear(nhid, ntoken) else: self.decoder = decoder # Optionally tie weights", "= 0.1 if self.encoder.__class__.__name__ == \"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange) else: self.encoder.init_weights()", "* div_term) pe[:, 1::2] = torch.cos(position * div_term) pe =", "ninp) else: self.encoder = encoder self.ninp = ninp if decoder", "return (weight.new_zeros(self.nlayers, bsz, self.nhid), weight.new_zeros(self.nlayers, bsz, self.nhid)) else: return weight.new_zeros(self.nlayers,", "= x + self.pe[:x.size(0), :] return self.dropout(x) class TransformerModel(nn.Module): \"\"\"Container", "= self.drop(self.encoder(input)) hidden_ = [] for h in hidden: if", "ntoken) else: self.decoder = decoder # Optionally tie weights as", "output = pos_encoder(x) \"\"\" x = x + self.pe[:x.size(0), :]", "TransformerEncoderLayer except: raise ImportError('TransformerEncoder module does not exist in PyTorch", "if encoder is None: self.encoder = nn.Embedding(ntoken, ninp) else: self.encoder", "1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1,", "self.drop(output) decoded = self.decoder(output) decoded = decoded.view(-1, self.ntoken) return F.log_softmax(decoded,", "nn.Dropout(dropout) if encoder is None: self.encoder = nn.Embedding(ntoken, ninp) else:", "div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x):", "Shape: x: [sequence length, batch size, embed dim] output: [sequence", "mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask", "(default=0.1). max_len: the max. length of the incoming sequence (default=5000).", "else: self.encoder = encoder if rnn_type in ['LSTM', 'GRU']: self.rnn", "for `--model` was supplied, options are ['LSTM', 'GRU', 'RNN_TANH' or", "batch size, embed dim] Examples: >>> output = pos_encoder(x) \"\"\"", "if has_mask: device = src.device if self.src_mask is None or", "encoder=None, decoder=None): super(TransformerModel, self).__init__() try: from torch.nn import TransformerEncoder, TransformerEncoderLayer", "are ['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU']\"\"\") self.rnn = nn.RNN(ninp, nhid,", "= self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output = self.decoder(output) return", "h.to(torch.float) hidden_.append(h) output, hidden = self.rnn(emb, tuple(hidden_)) output = self.drop(output)", "'relu'}[rnn_type] except KeyError: raise ValueError( \"\"\"An invalid option for `--model`", "nhid != ninp: raise ValueError('When using the tied flag, nhid", "__init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe", "Output Embedding to Improve Language Models\" (Press & Wolf 2016)", "a recurrent or transformer module, and a decoder.\"\"\" def __init__(self,", "['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU']\"\"\") self.rnn = nn.RNN(ninp, nhid, nlayers,", "is None: self.decoder = nn.Linear(nhid, ntoken) else: self.decoder = decoder", "nhid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) if encoder is None:", "self.encoder = nn.Embedding(ntoken, ninp) else: self.encoder = encoder if rnn_type", "or absolute position of the tokens in the sequence. The", "encoder, a recurrent or transformer module, and a decoder.\"\"\" def", "self.ninp = ninp if decoder is None: self.decoder = nn.Linear(nhid,", "else: self.encoder = encoder self.ninp = ninp if decoder is", "ninp, nhead, nhid, nlayers, dropout=0.5, encoder=None, decoder=None): super(TransformerModel, self).__init__() try:", "math:: \\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) \\text{where", "pos is the word position and i is the embed", "max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model)", "nn.Embedding(ntoken, ninp) else: self.encoder = encoder self.ninp = ninp if", "self.decoder.weight.data.uniform_(-initrange, initrange) else: self.decoder.init_weights() def forward(self, input, hidden): emb =", "== 'LSTM': return (weight.new_zeros(self.nlayers, bsz, self.nhid), weight.new_zeros(self.nlayers, bsz, self.nhid)) else:", "embeddings, so that the two can be summed. Here, we", "sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) \\text{where pos is the word", "torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe", "pos_encoder(x) \"\"\" x = x + self.pe[:x.size(0), :] return self.dropout(x)", "Embedding to Improve Language Models\" (Press & Wolf 2016) #", "positional encodings have the same dimension as the embeddings, so", "pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): r\"\"\"Inputs of forward", "= rnn_type self.nhid = nhid self.nlayers = nlayers def init_weights(self):", "src.device if self.src_mask is None or self.src_mask.size(0) != len(src): mask", "dim=1), hidden def init_hidden(self, bsz): weight = next(self.parameters()) if self.rnn_type", "using the tied flag, nhid must be equal to emsize')", "isinstance(h, torch.cuda.LongTensor): h = h.to(torch.float) hidden_.append(h) output, hidden = self.rnn(emb,", "dropout=0.5, encoder=None, decoder=None): super(TransformerModel, self).__init__() try: from torch.nn import TransformerEncoder,", "= None self.pos_encoder = PositionalEncoding(ninp, dropout) encoder_layers = TransformerEncoderLayer(ninp, nhead,", "function Args: x: the sequence fed to the positional encoder", "self.decoder(output) decoded = decoded.view(-1, self.ntoken) return F.log_softmax(decoded, dim=1), hidden def", "forward function Args: x: the sequence fed to the positional", "super(RNNModel, self).__init__() self.ntoken = ntoken self.drop = nn.Dropout(dropout) if encoder", "dim] output: [sequence length, batch size, embed dim] Examples: >>>", "= torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe)", "forward(self, src, has_mask=True): if has_mask: device = src.device if self.src_mask", "2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position *", "dropout=dropout) if decoder is None: self.decoder = nn.Linear(nhid, ntoken) else:", "sequence fed to the positional encoder model (required). Shape: x:", "flag, nhid must be equal to emsize') self.decoder.weight = self.encoder.weight", "the incoming sequence (default=5000). Examples: >>> pos_encoder = PositionalEncoding(d_model) \"\"\"", "dropout=dropout) else: try: nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type] except", "decoder.\"\"\" def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5, encoder=None,", "The positional encodings have the same dimension as the embeddings,", "= ninp if decoder is None: self.decoder = nn.Linear(nhid, ntoken)", "TransformerEncoderLayer(ninp, nhead, nhid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) if encoder", "al. 2016) # https://arxiv.org/abs/1611.01462 if tie_weights: if nhid != ninp:", "TransformerModel(nn.Module): \"\"\"Container module with an encoder, a recurrent or transformer", "ValueError( \"\"\"An invalid option for `--model` was supplied, options are", "sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask =", "ninp, nhid, nlayers, dropout=0.5, tie_weights=False, encoder=None, decoder=None): super(RNNModel, self).__init__() self.ntoken", "= decoded.view(-1, self.ntoken) return F.log_softmax(decoded, dim=1), hidden def init_hidden(self, bsz):", "nlayers, nonlinearity=nonlinearity, dropout=dropout) if decoder is None: self.decoder = nn.Linear(nhid,", "dim] Examples: >>> output = pos_encoder(x) \"\"\" x = x", ".. math:: \\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) \\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))", "= PositionalEncoding(ninp, dropout) encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout) self.transformer_encoder", "= mask else: self.src_mask = None src = self.encoder(src) *", "'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(ninp, dropout) encoder_layers =", "the dropout value (default=0.1). max_len: the max. length of the", "Language Modeling\" (Inan et al. 2016) # https://arxiv.org/abs/1611.01462 if tie_weights:", "PositionalEncoding(ninp, dropout) encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout) self.transformer_encoder =", "length of the incoming sequence (default=5000). Examples: >>> pos_encoder =", "return self.dropout(x) class TransformerModel(nn.Module): \"\"\"Container module with an encoder, a", "super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position", "self.decoder = nn.Linear(nhid, ntoken) else: self.decoder = decoder def _generate_square_subsequent_mask(self,", "to the positional encoder model (required). Shape: x: [sequence length,", "self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output = self.decoder(output) return F.log_softmax(output,", "for Language Modeling\" (Inan et al. 2016) # https://arxiv.org/abs/1611.01462 if", "import math import torch import torch.nn as nn import torch.nn.functional", "torch.LongTensor) or isinstance(h, torch.cuda.LongTensor): h = h.to(torch.float) hidden_.append(h) output, hidden", "tie_weights: if nhid != ninp: raise ValueError('When using the tied", "d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model,", "weight.new_zeros(self.nlayers, bsz, self.nhid)) else: return weight.new_zeros(self.nlayers, bsz, self.nhid) # Temporarily", "decoder.\"\"\" def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False,", "summed. Here, we use sine and cosine functions of different", "nlayers def init_weights(self): initrange = 0.1 if self.encoder.__class__.__name__ == \"Embedding\":", "nn.Linear(nhid, ntoken) else: self.decoder = decoder def _generate_square_subsequent_mask(self, sz): mask", "\"\"\"Container module with an encoder, a recurrent or transformer module,", "None: self.decoder = nn.Linear(nhid, ntoken) else: self.decoder = decoder def", "self.rnn(emb, tuple(hidden_)) output = self.drop(output) decoded = self.decoder(output) decoded =", "None: self.decoder = nn.Linear(nhid, ntoken) else: self.decoder = decoder #", "self.decoder.weight = self.encoder.weight self.rnn_type = rnn_type self.nhid = nhid self.nlayers", "self.encoder = encoder self.ninp = ninp if decoder is None:", "self.encoder.__class__.__name__ == \"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange) else: self.encoder.init_weights() if self.decoder.__class__.__name__ ==", "not exist in PyTorch 1.1 or lower.') self.model_type = 'Transformer'", "None src = self.encoder(src) * math.sqrt(self.ninp) src = self.pos_encoder(src) output", "self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try: nonlinearity", "nhid, nlayers, dropout=0.5, encoder=None, decoder=None): super(TransformerModel, self).__init__() try: from torch.nn", "self).__init__() self.ntoken = ntoken self.drop = nn.Dropout(dropout) if encoder is", "torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0,", "pos_encoder = PositionalEncoding(d_model) \"\"\" def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding,", "self.register_buffer('pe', pe) def forward(self, x): r\"\"\"Inputs of forward function Args:", "else: self.src_mask = None src = self.encoder(src) * math.sqrt(self.ninp) src", "embed idx) Args: d_model: the embed dim (required). dropout: the", "'tanh', 'RNN_RELU': 'relu'}[rnn_type] except KeyError: raise ValueError( \"\"\"An invalid option", "module does not exist in PyTorch 1.1 or lower.') self.model_type", "== \"Embedding\": self.encoder.weight.data.uniform_(-initrange, initrange) else: self.encoder.init_weights() if self.decoder.__class__.__name__ == \"Linear\":", "sequence (default=5000). Examples: >>> pos_encoder = PositionalEncoding(d_model) \"\"\" def __init__(self,", "an encoder, a recurrent or transformer module, and a decoder.\"\"\"", "self.encoder(src) * math.sqrt(self.ninp) src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask)", "if rnn_type in ['LSTM', 'GRU']: self.rnn = getattr(nn, rnn_type)(ninp, nhid,", "ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False, encoder=None, decoder=None): super(RNNModel, self).__init__()", "mask else: self.src_mask = None src = self.encoder(src) * math.sqrt(self.ninp)", "self.pos_encoder = PositionalEncoding(ninp, dropout) encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)", "https://arxiv.org/abs/1608.05859 # and # \"Tying Word Vectors and Word Classifiers:", "encoder model (required). Shape: x: [sequence length, batch size, embed", "a decoder.\"\"\" def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5,", "def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout)", "self.decoder = decoder # Optionally tie weights as in: #", "for h in hidden: if isinstance(h, torch.LongTensor) or isinstance(h, torch.cuda.LongTensor):", "et al. 2016) # https://arxiv.org/abs/1611.01462 if tie_weights: if nhid !=", "torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def", "= self.encoder(src) * math.sqrt(self.ninp) src = self.pos_encoder(src) output = self.transformer_encoder(src,", "# \"Tying Word Vectors and Word Classifiers: A Loss Framework", "Framework for Language Modeling\" (Inan et al. 2016) # https://arxiv.org/abs/1611.01462", "self.decoder = nn.Linear(nhid, ntoken) else: self.decoder = decoder # Optionally", "2016) # https://arxiv.org/abs/1611.01462 if tie_weights: if nhid != ninp: raise", "dropout) encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers,", "self.pe[:x.size(0), :] return self.dropout(x) class TransformerModel(nn.Module): \"\"\"Container module with an", "nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout) if decoder is None: self.decoder", "encoder=None, decoder=None): super(RNNModel, self).__init__() self.ntoken = ntoken self.drop = nn.Dropout(dropout)", "i is the embed idx) Args: d_model: the embed dim", "Classifiers: A Loss Framework for Language Modeling\" (Inan et al.", "use sine and cosine functions of different frequencies. .. math::", "d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe =", "position and i is the embed idx) Args: d_model: the" ]
[ "b=input(\"The enter the second number :\") range=input(\"Please enter the range\")", "b while count!=range: c=a+b count +=1 print c a=b b=c", "range\") i=0;count=0; print a print b while count!=range: c=a+b count", "a print b while count!=range: c=a+b count +=1 print c", "number :\") range=input(\"Please enter the range\") i=0;count=0; print a print", ":\") range=input(\"Please enter the range\") i=0;count=0; print a print b", "print b while count!=range: c=a+b count +=1 print c a=b", "print a print b while count!=range: c=a+b count +=1 print", "range=input(\"Please enter the range\") i=0;count=0; print a print b while", "enter the second number :\") range=input(\"Please enter the range\") i=0;count=0;", "the range\") i=0;count=0; print a print b while count!=range: c=a+b", "number :\") b=input(\"The enter the second number :\") range=input(\"Please enter", "i=0;count=0; print a print b while count!=range: c=a+b count +=1", "the first number :\") b=input(\"The enter the second number :\")", "first number :\") b=input(\"The enter the second number :\") range=input(\"Please", "a=input(\"The enter the first number :\") b=input(\"The enter the second", "def main(): a=input(\"The enter the first number :\") b=input(\"The enter", "while count!=range: c=a+b count +=1 print c a=b b=c main()", "main(): a=input(\"The enter the first number :\") b=input(\"The enter the", ":\") b=input(\"The enter the second number :\") range=input(\"Please enter the", "enter the range\") i=0;count=0; print a print b while count!=range:", "<reponame>Baibhabswain/pythonPrograms def main(): a=input(\"The enter the first number :\") b=input(\"The", "enter the first number :\") b=input(\"The enter the second number", "second number :\") range=input(\"Please enter the range\") i=0;count=0; print a", "the second number :\") range=input(\"Please enter the range\") i=0;count=0; print" ]
[]
[ "answer と一致: 'Correct!'、新しくゲームを始める その他: 'Can I kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる", "new game.' elif max == 1: return '? Can I", "def resp_set(message, digitstr): '''number set (数字) 形式への返答 (数字)部のnumber set判定を行い、返事する Args:", "the maximum of the answer is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message,", "= answer answer = random.randint(1, max) # 返事する文字列を構成 message.reply('Hahaha! Failed!", "入力された値に応じて返答を構成、正解ならニューゲーム if num == 0: return ' is a mysterious", "return 'There is a mysterious number... It is ' elif", "kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる ''' global answer global max #", "@slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message, digitstr): '''number set (数字) 形式への返答 (数字)部のnumber set判定を行い、返事する", "return '1? Really? Then, the maximum of the answer is", "the answer is ' max = num answer = random.randint(1,", "a mysterious number...' elif num < max + 1: if", "# 返事する文字列を構成 reply = '{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message,", "'''number giveup への返答 正解を表示し、新しい正解を設定、'Start a new game.'を返す Args: ''' global", "max) return 'OK. Then, the maximum of the answer is", "@slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message, digitstr): '''number (数字) 形式への返答 (数字) 部のnumber判定を行い, 'number", "is correct! :tada: Now, start a new game.' elif max", "= random.randint(1, max) return '1? Really? Then, the maximum of", "answer is more small.' elif num < answer: return '", "I kick you? 1 to %d.' % max def number_set(num):", "@slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message): '''number giveup への返答 正解を表示し、新しい正解を設定、'Start a new game.'を返す", "number set 判定 nbs = number_set(int(digitstr)) # 返事する文字列を構成 reply =", "50) max = 50 def number(num): '''number 判定 Args: num", "num (int): 判定する数字 Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である ''' global", "random.randint(1, max) return '1? Really? Then, the maximum of the", "message digtstr (str): 数値の文字列 ''' # number 判定 nb =", "= random.randint(1, 50) max = 50 def number(num): '''number 判定", "%d.' % max def number_set(num): '''number set判定 Args: num (int):", "Args: num (int): 判定する数字 Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である '''", "入力された値に応じて返答を構成、maxを変更、ニューゲーム if num == 0: return 'There is a mysterious", "answer = random.randint(1, max) return 'OK. Then, the maximum of", "1 to %d.' % max def number_set(num): '''number set判定 Args:", "maximum of the answer is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message, digitstr):", "への返答 正解を表示し、新しい正解を設定、'Start a new game.'を返す Args: ''' global answer global", "more large.' elif num == answer: answer = random.randint(1, max)", "1.' return '? Can I kick you? 1 to %d.'", "number(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}'.format(digitstr, nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def", "answer global max # 表示する答えを設定、次のゲームの解答を設定 showanswer = answer answer =", "= '{0:s}{1:s}'.format(digitstr, nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message): '''number giveup への返答", "elif num == answer: answer = random.randint(1, max) return '", "is a mysterious number...' elif num < max + 1:", "= random.randint(1, max) return ' is correct! :tada: Now, start", "the answer is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message, digitstr): '''number set", ":tada: Now, start a new game.' elif max == 1:", "number...' elif num < max + 1: if num >", "random.randint(1, max) return 'OK. Then, the maximum of the answer", "Returns: str: num が answer より大きい: 'Too large' num が", "(数字)部のnumber set判定を行い、返事する Args: ''' # number set 判定 nbs =", "digitstr): '''number (数字) 形式への返答 (数字) 部のnumber判定を行い, 'number (数字) 判定' を返事する", "I kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる ''' global answer global max", "' is too large. The answer is more small.' elif", "max + 1: if num > answer: return ' is", "答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である ''' global answer global max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム", "'OK. Then, the maximum of the answer is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)')", "Args: num (int): 判定する数字 Returns: str: num が answer より大きい:", "(数字) 形式への返答 (数字)部のnumber set判定を行い、返事する Args: ''' # number set 判定", "return ' is correct! :tada: Now, start a new game.'", "== answer: answer = random.randint(1, max) return ' is correct!", "answer = random.randint(1, max) return '1? Really? Then, the maximum", "giveup への返答 正解を表示し、新しい正解を設定、'Start a new game.'を返す Args: ''' global answer", "= random.randint(1, max) # 返事する文字列を構成 message.reply('Hahaha! Failed! :ghost: The answer", "# 返事する文字列を構成 reply = '{0:s}{1:s}'.format(digitstr, nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message):", "''' # number 判定 nb = number(int(digitstr)) # 返事する文字列を構成 reply", "The answer is %d. Start a new game.' % showanswer)", "elif num < max + 1: if num > answer:", "判定する数字 Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である ''' global answer global", "'Correct!'、新しくゲームを始める その他: 'Can I kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる ''' global", "number 判定 nb = number(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}'.format(digitstr,", "resp_set(message, digitstr): '''number set (数字) 形式への返答 (数字)部のnumber set判定を行い、返事する Args: '''", "answer is more large.' elif num == answer: answer =", "'? Can I kick you? Only 1.' return '? Can", "形式への返答 (数字) 部のnumber判定を行い, 'number (数字) 判定' を返事する Args: message (slackbot.dispatcher.Message):", "reply = '{0:s}{1:s}'.format(digitstr, nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message): '''number giveup", "start a new game.' elif max == 1: return '?", "str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である ''' global answer global max #", "'Too small' num が answer と一致: 'Correct!'、新しくゲームを始める その他: 'Can I", "elif num < answer: return ' is too small. The", "num answer = random.randint(1, max) return 'OK. Then, the maximum", "判定 nbs = number_set(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}.'.format(nbs, digitstr)", "global max # 表示する答えを設定、次のゲームの解答を設定 showanswer = answer answer = random.randint(1,", "'{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message, digitstr): '''number (数字) 形式への返答", "answer より大きい: 'Too large' num が answer より小さい: 'Too small'", "0: return ' is a mysterious number...' elif num <", "が answer より小さい: 'Too small' num が answer と一致: 'Correct!'、新しくゲームを始める", "kick you? Only 1.' return '? Can I kick you?", "return '? Can I kick you? 1 to %d.' %", "set判定 Args: num (int): 判定する数字 Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である", "'''number set (数字) 形式への返答 (数字)部のnumber set判定を行い、返事する Args: ''' # number", "nbs = number_set(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply)", "判定' を返事する Args: message (slackbot.dispatcher.Message): slack message digtstr (str): 数値の文字列", "= 50 def number(num): '''number 判定 Args: num (int): 判定する数字", "global max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム if num == 0: return 'There", "== 1: return '? Can I kick you? Only 1.'", "message.reply('Hahaha! Failed! :ghost: The answer is %d. Start a new", "判定する数字 Returns: str: num が answer より大きい: 'Too large' num", "その他: 'Can I kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる ''' global answer", "Then, the maximum of the answer is ' max =", "answer global max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム if num == 0: return", "mysterious number... It is ' elif num == 1: max", "global max # 入力された値に応じて返答を構成、正解ならニューゲーム if num == 0: return '", "# 返事する文字列を構成 message.reply('Hahaha! Failed! :ghost: The answer is %d. Start", "showanswer = answer answer = random.randint(1, max) # 返事する文字列を構成 message.reply('Hahaha!", "部のnumber判定を行い, 'number (数字) 判定' を返事する Args: message (slackbot.dispatcher.Message): slack message", "'? Can I kick you? 1 to %d.' % max", "num が answer より小さい: 'Too small' num が answer と一致:", "elif max == 1: return '? Can I kick you?", "Args: ''' global answer global max # 表示する答えを設定、次のゲームの解答を設定 showanswer =", "answer より小さい: 'Too small' num が answer と一致: 'Correct!'、新しくゲームを始める その他:", "maximum of the answer is ' max = num answer", "< answer: return ' is too small. The answer is", "' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message, digitstr): '''number set (数字) 形式への返答 (数字)部のnumber", "if num == 0: return 'There is a mysterious number...", "is too large. The answer is more small.' elif num", "num < max + 1: if num > answer: return", "1: max = 1 answer = random.randint(1, max) return '1?", "1: if num > answer: return ' is too large.", "It is ' elif num == 1: max = 1", "slack message digtstr (str): 数値の文字列 ''' # number 判定 nb", "number_set(num): '''number set判定 Args: num (int): 判定する数字 Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50", "new game.'を返す Args: ''' global answer global max # 表示する答えを設定、次のゲームの解答を設定", "answer answer = random.randint(1, max) # 返事する文字列を構成 message.reply('Hahaha! Failed! :ghost:", "''' # number set 判定 nbs = number_set(int(digitstr)) # 返事する文字列を構成", "is ' max = num answer = random.randint(1, max) return", "== 0: return ' is a mysterious number...' elif num", "number_set(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def", "Now, start a new game.' elif max == 1: return", "== 1: max = 1 answer = random.randint(1, max) return", "answer = random.randint(1, 50) max = 50 def number(num): '''number", "判定 Args: num (int): 判定する数字 Returns: str: num が answer", "return 'OK. Then, the maximum of the answer is '", "number... It is ' elif num == 1: max =", "Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である ''' global answer global max", "num (int): 判定する数字 Returns: str: num が answer より大きい: 'Too", "def number_set(num): '''number set判定 Args: num (int): 判定する数字 Returns: str:", "1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である ''' global answer global max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム if", "'Too large' num が answer より小さい: 'Too small' num が", "small. The answer is more large.' elif num == answer:", "return ' is too large. The answer is more small.'", "形式への返答 (数字)部のnumber set判定を行い、返事する Args: ''' # number set 判定 nbs", "large. The answer is more small.' elif num < answer:", "(数字) 判定' を返事する Args: message (slackbot.dispatcher.Message): slack message digtstr (str):", "is ' elif num == 1: max = 1 answer", "I kick you? Only 1.' return '? Can I kick", "max) return '1? Really? Then, the maximum of the answer", "数値の文字列 ''' # number 判定 nb = number(int(digitstr)) # 返事する文字列を構成", "num == 0: return ' is a mysterious number...' elif", "digtstr (str): 数値の文字列 ''' # number 判定 nb = number(int(digitstr))", "num が answer より大きい: 'Too large' num が answer より小さい:", "random answer = random.randint(1, 50) max = 50 def number(num):", "random.randint(1, max) # 返事する文字列を構成 message.reply('Hahaha! Failed! :ghost: The answer is", "is more large.' elif num == answer: answer = random.randint(1,", "'''number set判定 Args: num (int): 判定する数字 Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。", "= random.randint(1, max) return 'OK. Then, the maximum of the", "digitstr): '''number set (数字) 形式への返答 (数字)部のnumber set判定を行い、返事する Args: ''' #", "nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message): '''number giveup への返答 正解を表示し、新しい正解を設定、'Start a", "random.randint(1, max) return ' is correct! :tada: Now, start a", ":ghost: The answer is %d. Start a new game.' %", "elif num == 1: max = 1 answer = random.randint(1,", "(slackbot.dispatcher.Message): slack message digtstr (str): 数値の文字列 ''' # number 判定", "正解を表示し、新しい正解を設定、'Start a new game.'を返す Args: ''' global answer global max", "返事する文字列を構成 message.reply('Hahaha! Failed! :ghost: The answer is %d. Start a", "と一致: 'Correct!'、新しくゲームを始める その他: 'Can I kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる '''", "is more small.' elif num < answer: return ' is", "resp_number(message, digitstr): '''number (数字) 形式への返答 (数字) 部のnumber判定を行い, 'number (数字) 判定'", "'''number 判定 Args: num (int): 判定する数字 Returns: str: num が", "1: return '? Can I kick you? Only 1.' return", "slackbot.bot import random answer = random.randint(1, 50) max = 50", "max == 1: return '? Can I kick you? Only", "% max def number_set(num): '''number set判定 Args: num (int): 判定する数字", "set判定を行い、返事する Args: ''' # number set 判定 nbs = number_set(int(digitstr))", "Failed! :ghost: The answer is %d. Start a new game.'", "a mysterious number... It is ' elif num == 1:", "kick you? 1 to %d.' % max def number_set(num): '''number", "# 入力された値に応じて返答を構成、maxを変更、ニューゲーム if num == 0: return 'There is a", "Then, the maximum of the answer is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def", "answer = random.randint(1, max) # 返事する文字列を構成 message.reply('Hahaha! Failed! :ghost: The", "large.' elif num == answer: answer = random.randint(1, max) return", "'1? Really? Then, the maximum of the answer is '", "num == 1: max = 1 answer = random.randint(1, max)", "set (数字) 形式への返答 (数字)部のnumber set判定を行い、返事する Args: ''' # number set", "'''number (数字) 形式への返答 (数字) 部のnumber判定を行い, 'number (数字) 判定' を返事する Args:", "The answer is more large.' elif num == answer: answer", "small' num が answer と一致: 'Correct!'、新しくゲームを始める その他: 'Can I kick", "def number(num): '''number 判定 Args: num (int): 判定する数字 Returns: str:", "max = 50 def number(num): '''number 判定 Args: num (int):", "to %d.' % max def number_set(num): '''number set判定 Args: num", "= number_set(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)')", "def resp_number(message, digitstr): '''number (数字) 形式への返答 (数字) 部のnumber判定を行い, 'number (数字)", "message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message): '''number giveup への返答 正解を表示し、新しい正解を設定、'Start a new", "global answer global max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム if num == 0:", "= '{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message, digitstr): '''number (数字)", "返事する文字列を構成 reply = '{0:s}{1:s}'.format(digitstr, nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message): '''number", "def resp_giveup(message): '''number giveup への返答 正解を表示し、新しい正解を設定、'Start a new game.'を返す Args:", "too small. The answer is more large.' elif num ==", "より大きい: 'Too large' num が answer より小さい: 'Too small' num", "nb = number(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}'.format(digitstr, nb) message.reply(reply)", "' is a mysterious number...' elif num < max +", "'Can I kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる ''' global answer global", "Can I kick you? 1 to %d.' % max def", "Really? Then, the maximum of the answer is ' max", "= 1 answer = random.randint(1, max) return '1? Really? Then,", "answer global max # 入力された値に応じて返答を構成、正解ならニューゲーム if num == 0: return", "you? 1 to %d.' % max def number_set(num): '''number set判定", "Args: ''' # number set 判定 nbs = number_set(int(digitstr)) #", "(int): 判定する数字 Returns: str: num が answer より大きい: 'Too large'", "answer is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message, digitstr): '''number set (数字)", "が answer と一致: 'Correct!'、新しくゲームを始める その他: 'Can I kick you?.' 0は不可思議な数である", "resp_giveup(message): '''number giveup への返答 正解を表示し、新しい正解を設定、'Start a new game.'を返す Args: '''", "a new game.' elif max == 1: return '? Can", "num < answer: return ' is too small. The answer", "number(num): '''number 判定 Args: num (int): 判定する数字 Returns: str: num", "(int): 判定する数字 Returns: str: 答えのmax(答えになりうる値の最大)を変更する。デフォは50 1にするとマジ?と訊かれる。それだけ。 不可思議な数字は0である ''' global answer", "num が answer と一致: 'Correct!'、新しくゲームを始める その他: 'Can I kick you?.'", "str: num が answer より大きい: 'Too large' num が answer", "game.'を返す Args: ''' global answer global max # 表示する答えを設定、次のゲームの解答を設定 showanswer", "answer: answer = random.randint(1, max) return ' is correct! :tada:", "' is correct! :tada: Now, start a new game.' elif", "answer: return ' is too large. The answer is more", "Only 1.' return '? Can I kick you? 1 to", "表示する答えを設定、次のゲームの解答を設定 showanswer = answer answer = random.randint(1, max) # 返事する文字列を構成", "' is too small. The answer is more large.' elif", "answer = random.randint(1, max) return ' is correct! :tada: Now,", "= num answer = random.randint(1, max) return 'OK. Then, the", "< max + 1: if num > answer: return '", "(数字) 形式への返答 (数字) 部のnumber判定を行い, 'number (数字) 判定' を返事する Args: message", "import random answer = random.randint(1, 50) max = 50 def", "max) return ' is correct! :tada: Now, start a new", "max # 入力された値に応じて返答を構成、正解ならニューゲーム if num == 0: return ' is", "maxが1の時に2以上を答えると1だけだと言われる ''' global answer global max # 入力された値に応じて返答を構成、正解ならニューゲーム if num", "if num > answer: return ' is too large. The", "The answer is more small.' elif num < answer: return", "correct! :tada: Now, start a new game.' elif max ==", "Can I kick you? Only 1.' return '? Can I", "you? Only 1.' return '? Can I kick you? 1", "of the answer is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message, digitstr): '''number", "answer: return ' is too small. The answer is more", "message (slackbot.dispatcher.Message): slack message digtstr (str): 数値の文字列 ''' # number", "== 0: return 'There is a mysterious number... It is", "1 answer = random.randint(1, max) return '1? Really? Then, the", "return ' is a mysterious number...' elif num < max", "mysterious number...' elif num < max + 1: if num", "small.' elif num < answer: return ' is too small.", "num == answer: answer = random.randint(1, max) return ' is", "''' global answer global max # 表示する答えを設定、次のゲームの解答を設定 showanswer = answer", "more small.' elif num < answer: return ' is too", "set 判定 nbs = number_set(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}.'.format(nbs,", "is too small. The answer is more large.' elif num", "max) # 返事する文字列を構成 message.reply('Hahaha! Failed! :ghost: The answer is %d.", "num == 0: return 'There is a mysterious number... It", "# number set 判定 nbs = number_set(int(digitstr)) # 返事する文字列を構成 reply", "game.' elif max == 1: return '? Can I kick", "'{0:s}{1:s}'.format(digitstr, nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup') def resp_giveup(message): '''number giveup への返答 正解を表示し、新しい正解を設定、'Start", "too large. The answer is more small.' elif num <", "return '? Can I kick you? Only 1.' return '?", "of the answer is ' max = num answer =", "より小さい: 'Too small' num が answer と一致: 'Correct!'、新しくゲームを始める その他: 'Can", "max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム if num == 0: return 'There is", "is ' @slackbot.bot.respond_to(r'^number\\s+set\\s+(\\d+)') def resp_set(message, digitstr): '''number set (数字) 形式への返答", "> answer: return ' is too large. The answer is", "you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる ''' global answer global max # 入力された値に応じて返答を構成、正解ならニューゲーム", "0: return 'There is a mysterious number... It is '", "import slackbot.bot import random answer = random.randint(1, 50) max =", "the maximum of the answer is ' max = num", "global answer global max # 入力された値に応じて返答を構成、正解ならニューゲーム if num == 0:", "''' global answer global max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム if num ==", "is a mysterious number... It is ' elif num ==", "answer is ' max = num answer = random.randint(1, max)", "'There is a mysterious number... It is ' elif num", "answer is %d. Start a new game.' % showanswer) message.react('stuck_out_tongue_winking_eye')", "random.randint(1, 50) max = 50 def number(num): '''number 判定 Args:", "max def number_set(num): '''number set判定 Args: num (int): 判定する数字 Returns:", "max = num answer = random.randint(1, max) return 'OK. Then,", "# 表示する答えを設定、次のゲームの解答を設定 showanswer = answer answer = random.randint(1, max) #", "# 入力された値に応じて返答を構成、正解ならニューゲーム if num == 0: return ' is a", "不可思議な数字は0である ''' global answer global max # 入力された値に応じて返答を構成、maxを変更、ニューゲーム if num", "+ 1: if num > answer: return ' is too", "return ' is too small. The answer is more large.'", "max = 1 answer = random.randint(1, max) return '1? Really?", "' max = num answer = random.randint(1, max) return 'OK.", "''' global answer global max # 入力された値に応じて返答を構成、正解ならニューゲーム if num ==", "large' num が answer より小さい: 'Too small' num が answer", "返事する文字列を構成 reply = '{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message, digitstr):", "'number (数字) 判定' を返事する Args: message (slackbot.dispatcher.Message): slack message digtstr", "= number(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}'.format(digitstr, nb) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+giveup')", "a new game.'を返す Args: ''' global answer global max #", "global answer global max # 表示する答えを設定、次のゲームの解答を設定 showanswer = answer answer", "max # 表示する答えを設定、次のゲームの解答を設定 showanswer = answer answer = random.randint(1, max)", "が answer より大きい: 'Too large' num が answer より小さい: 'Too", "50 def number(num): '''number 判定 Args: num (int): 判定する数字 Returns:", "message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message, digitstr): '''number (数字) 形式への返答 (数字) 部のnumber判定を行い,", "num > answer: return ' is too large. The answer", "判定 nb = number(int(digitstr)) # 返事する文字列を構成 reply = '{0:s}{1:s}'.format(digitstr, nb)", "if num == 0: return ' is a mysterious number...'", "' elif num == 1: max = 1 answer =", "reply = '{0:s}{1:s}.'.format(nbs, digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message, digitstr): '''number", "を返事する Args: message (slackbot.dispatcher.Message): slack message digtstr (str): 数値の文字列 '''", "Args: message (slackbot.dispatcher.Message): slack message digtstr (str): 数値の文字列 ''' #", "(str): 数値の文字列 ''' # number 判定 nb = number(int(digitstr)) #", "digitstr) message.reply(reply) @slackbot.bot.respond_to(r'^number\\s+(\\d+)') def resp_number(message, digitstr): '''number (数字) 形式への返答 (数字)", "0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる ''' global answer global max # 入力された値に応じて返答を構成、正解ならニューゲーム if", "# number 判定 nb = number(int(digitstr)) # 返事する文字列を構成 reply =", "(数字) 部のnumber判定を行い, 'number (数字) 判定' を返事する Args: message (slackbot.dispatcher.Message): slack" ]
[ "instance variable. \"\"\" key = (self.frame and self.frame.current_opcode, extra_key, cls)", "of optional and kw args. arg_names = max((sig.get_positional_names() for sig", "fake arguments for %s\", funcv) return node, self.new_unsolvable(node) def analyze_method_var(self,", "(name in output.TOP_LEVEL_IGNORE or name in annotated_names or self._is_typing_member(name, var)):", "data.is_overload and not data.is_class_builder and data.get_first_opcode() not in self._analyzed_functions and", "to get any. bad = [view for view in views", "log.error(\"No visible options for %s\", name) data.append(pytd.Constant(name, pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\",", "node2 = self.maybe_analyze_method(node1, val, cls) node2.ConnectTo(node0) return node0 def bind_method(self,", "parameters. \"\"\" values = list(values) seen = set() while values:", "in self._interpreter_classes: for value in c.bindings: if (isinstance(value.data, abstract.InterpreterClass) and", "range(num_posargs): default_idx = i - num_posargs_no_default if use_defaults and default_idx", "instance in self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node)) def analyze_class(self, node, val): self._analyzed_classes.add(val.data)", "abstract.BoundPyTDFunction): self._method_calls.add(record) elif isinstance(func.data, abstract.PyTDFunction): self._calls.add(record) def trace_functiondef(self, f): self._interpreter_functions.append(f)", "text = debug.program_to_text(program) if options.output_debug == \"-\": log.info(\"=========== Program Dump", "options) data.append(pytd.Constant(name, combined_types)) elif options: for option in options: try:", "param) node = self._call_method(node, b, \"__init__\") cls = b.data.get_class() if", "iterable over cfg.Value. namedargs: The keyword arguments, a dict mapping", "to ignore # all attribute errors on self in __init__.", "cls: The class to instantiate. container: Optionally, a container to", "pyi file # returns an instance of the current class.", "values. \"\"\" log.debug(\"Logging call to %r with %d args, return", "funcs = collections.defaultdict(pytd_utils.OrderedSet) for node, func, sigs, args, kws, retvar", "in view and view[actual].data.formal] if not bad: bad = self.matcher.bad_matches(actual,", "shouldn't # be raised again, and generating fake arguments should", "# Rename remaining \"~unknown\" to \"?\" ast = ast.Visit(visitors.RemoveUnknownClasses()) #", "else: arg = self.convert.create_new_unknown(node, force=not use_defaults) args.append(arg) kws = {}", "= call_record.positional_arguments if not any(isinstance(a.data, abstract.Unknown) for a in args):", "return new_node, ret def call_function_in_frame(self, node, var, args, kwargs, starargs,", "take care of that. Args: node: The current node. method:", "retvar.data) starargs = None starstarargs = None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t,", "self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node)) def analyze_class(self, node, val): self._analyzed_classes.add(val.data) node, instance", "if tracer_vm: assert isinstance(tracer_vm, CallTracer) tracer = tracer_vm else: tracer", "instead recorded as constants ty = pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes,", "typing_overlay from pytype.pytd import builtins from pytype.pytd import escape from", "v in var.data]) state = frame_state.FrameState.init(node, self) state, ret =", "node def analyze(self, node, defs, maximum_depth): assert not self.frame self.maximum_depth", "var in defs.items(): if (name in output.TOP_LEVEL_IGNORE or name in", "= abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter( node, abstract_utils.T, self.convert.create_new_unknown(node)) return value.to_variable(node) def", "[] self._analyzed_functions = set() self._analyzed_classes = set() self._generated_classes = {}", "data.append(pytd.Constant(name, t)) for name, var in defs.items(): if (name in", "len(instance.bindings): # __new__ returned some extra possibilities we don't need.", "_should_analyze_as_interpreter_function(self, data): # We record analyzed functions by opcode rather", "bad parameter combination. \"\"\" # If the caller has passed", "source code. errorlog: Where error messages go. Instance of errors.ErrorLog.", "file if options.protocols: protocols_pytd = tracer.loader.import_name(\"protocols\") else: protocols_pytd = None", "and module-level code===\") snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep:", "= [] for cls, call_records in class_to_records.items(): full_name = cls.module", "are instead recorded as constants ty = pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\",", "some extra possibilities we don't need. instance = self.join_bindings(node, good_instances)", "snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep: if maximum_depth is None: if not options.quick:", "comprehensions and generators, which # have names like \"<listcomp>\" and", "DictKeyMissing nodes = [] rets = [] for funcb in", "in cls.additional_init_methods: node = self._call_method(node, b, method) return node def", "in val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name)) return classes def pytd_for_types(self, defs):", "opcode rather than function object. The # two ways of", "binding. for b in instance.bindings: if b.data in self._initialized_instances: continue", "starstarargs) self.pop_frame(frame) return state.node, ret def _maybe_fix_classmethod_cls_arg(self, node, cls, func,", "return bound def _instantiate_binding(self, node0, cls, container): \"\"\"Instantiate a class", "class_to_records[cls].append(call_record) classes = [] for cls, call_records in class_to_records.items(): full_name", "information. filename: Filename of the program we're parsing. deep: If", "= (m.isinstance_InterpreterFunction() and m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls), [], node) return bound", "args) node, _ = self.call_function_with_args(node, val, args) return node def", "container) if key in self._instance_cache: # We've encountered a recursive", "can be expensive, so this method caches its created instances.", "= val.data fname = val.data.name if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if", "a constant. combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t in options) data.append(pytd.Constant(name,", "methodvar, instance) node = self.analyze_method_var(node, name, b, val) return node", "frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing %r\", [v.name for v in var.data]) state", "passed to # the call_function that called this method in", "self.exitpoint = None def create_varargs(self, node): value = abstract.Instance(self.convert.tuple_type, self)", "tracer_vm else: tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader,", "\"?\" ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove \"~list\" etc.: ast =", "return state.node, ret def _maybe_fix_classmethod_cls_arg(self, node, cls, func, args): sig", "abstract.SimpleValue): v.maybe_missing_members = True for child in v.instance_type_parameters.values(): values.extend(child.data) def", "instance of our class. instance = val.data.instantiate(node) node = self.call_init(node,", "self.call_function_with_state( state, var, args, kwargs, starargs, starstarargs) self.pop_frame(frame) return state.node,", "not new or ( any(not isinstance(f, abstract.InterpreterFunction) for f in", "set() self._analyzed_classes = set() self._generated_classes = {} self.exitpoint = None", "avoid any # FailedFunctionCall errors. To prevent an infinite recursion", "functions by opcode rather than function object. The # two", "= self.join_variables(node0, rets) node = self.join_cfg_nodes(nodes) if ret.bindings: return node,", "from pytype import state as frame_state from pytype import vm", "extra_key, cls) instance = self._instance_cache.get(key) if not instance or isinstance(instance,", "PYI information. filename: Filename of the program we're parsing. deep:", "_maybe_output_debug(options, tracer.program) def infer_types(src, errorlog, options, loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH,", "equivalent except for closures, which are # re-generated when the", "sigs, args, kws, retvar in call_traces: # The lengths may", "the caller wants to instantiate and retain the vm used", "args = self._maybe_fix_classmethod_cls_arg(node0, cls, b.data, args) node3 = node2.ConnectNew() node4,", "a variable is annotated, we'll always output that type. annotated_names", "stand-alone functions. The exceptions are comprehensions and generators, which #", "the given method. Note that we don't need to take", "if options.quick else MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program)", "options=options, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader, **kwargs) loc, defs = tracer.run_program(src,", "On every instance among the values, recursively set maybe_missing_members to", "seen.add(v) if isinstance(v, abstract.SimpleValue): v.maybe_missing_members = True for child in", "fine to # overwrite previous instances. self._generated_classes[nt.name] = nt def", "a cfg.Variable of the return value. \"\"\" fvar = val.AssignToNewVariable(node)", "self.bind_method(node, name, methodvar, instance) node = self.analyze_method_var(node, name, b, val)", "node2.ConnectTo(node0) return node0 def bind_method(self, node, name, methodvar, instance_var): bound", "for o in options)): # It's ambiguous whether this is", "key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type) return kwargs.to_variable(node) def create_method_arguments(self, node, method,", "if tracer.has_unknown_wildcard_imports or any( a in defs for a in", "pass to the class's instantiate() method, so that type parameters", "new_node = self.analyze_function(node, value) else: continue if new_node is not", "class. for c in self._interpreter_classes: for value in c.bindings: if", "loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast = tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports", "return classes def pytd_for_types(self, defs): # If a variable is", "If True, call traces are kept in the output. maximum_depth:", "We'll analyze this function as part of a class. log.info(\"Analyze", "pytd from pytype.pytd import pytd_utils from pytype.pytd import visitors from", "function or something # else, so encode it as a", "cls.data.get_own_new(node0, cls) if not new or ( any(not isinstance(f, abstract.InterpreterFunction)", "node1 = node0.ConnectNew(name) for val in var.bindings: node2 = self.maybe_analyze_method(node1,", "lead to an infinite loop, so # we instead create", "b in instance.bindings: if b.data in self._initialized_instances: continue self._initialized_instances.add(b.data) node", "kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type) return kwargs.to_variable(node) def create_method_arguments(self,", "if not bad: bad = self.matcher.bad_matches(actual, formal, node) if bad:", "cfg.Value. namedargs: The keyword arguments, a dict mapping str to", "= (self.frame and self.frame.current_opcode, extra_key, cls) instance = self._instance_cache.get(key) if", "x: \"A\"): ... # Calling __init__ again would lead to", "if options.protocols: log.info(\"=========== PyTD to solve =============\\n%s\", pytd_utils.Print(ast)) ast =", "self._should_analyze_as_interpreter_function(value.data): node = self.analyze_function(node, value) return node def analyze(self, node,", "_is_typing_member(self, name, var): for module_name in (\"typing\", \"typing_extensions\"): if module_name", "classes=classes, functions=functions, aliases=aliases)) ty = ty.Visit(optimize.CombineReturnsAndExceptions()) ty = ty.Visit(optimize.PullInMethodClasses()) ty", "in range(num_posargs): default_idx = i - num_posargs_no_default if use_defaults and", "i - num_posargs_no_default if use_defaults and default_idx >= 0: arg", "i in range(num_posargs): default_idx = i - num_posargs_no_default if use_defaults", "any( a in defs for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\"", "loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): \"\"\"Verify the Python code.\"\"\" tracer", "t in zip(arg_names, arg_types)) + tuple(pytd.Parameter(name, a.data.to_type(node), False, False, None)", "= node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node, defs) def trace_unknown(self, name, unknown_binding): self._unknowns[name]", "than function object. The # two ways of recording are", "been called with. posargs: The positional arguments, an iterable over", "not analyzing further.\", fname) else: for f in method.iter_signature_functions(): node,", "inference, # the presence of this option means that the", "elif not show_library_calls: log.info(\"Solving is turned off. Discarding call traces.\")", "universal_newlines=True) (_, stderr) = proc.communicate(dot) if stderr: log.info(\"Failed to create", "def analyze_toplevel(self, node, defs): for name, var in sorted(defs.items()): #", "be raised again, and generating fake arguments should avoid any", "if method: bound_method = self.bind_method( node, method_name, method, binding.AssignToNewVariable()) node", "class. return node0, cls.data.instantiate(node0, container=container) instance = self.program.NewVariable() nodes =", "ret def _maybe_fix_classmethod_cls_arg(self, node, cls, func, args): sig = func.signature", "cls=None): log.info(\"Analyzing %s\", name) node1 = node0.ConnectNew(name) for val in", "such as # class A: # def __init__(self, x: \"A\"):", "TypeParameterInstance. extra_key: Optionally, extra information about the location at which", "node2, ret = self.call_function(node1, funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret) if", "__init__ on each binding. for b in instance.bindings: if b.data", "for instance_value in instance.data: val.data.register_canonical_instance(instance_value) for name, methodvar in sorted(val.data.members.items()):", "fname = val.data.name if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if (not self.options.analyze_annotated", "f, args) node, _ = self.call_function_with_args(node, val, args) return node", "var.bindings: if isinstance(value.data, abstract.InterpreterClass): new_node = self.analyze_class(node, value) elif (isinstance(value.data,", "pytype import vm from pytype.overlays import typing_overlay from pytype.pytd import", "value_type = self.convert.create_new_unknown(node) kwargs = abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type)", "# It's ambiguous whether this is a type, a function", "ty.Visit(optimize.PullInMethodClasses()) ty = ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()], escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters()) def", "method. Creates Unknown objects as arguments for the given method.", "call_function_with_args(self, node, val, args): \"\"\"Call a function. Args: node: The", "args are generated, try calling the function. # call_function will", "ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()], escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self, node, actual,", "= max((sig.get_positional_names() for sig in sigs), key=len) for i in", "loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) log.info(\"===Done running", "# else, so encode it as a constant. combined_types =", "lengths may be different in the presence of optional and", "we instead create an incomplete instance that will be #", "= [] for funcb in funcv.bindings: func = funcb.data log.info(\"Trying", "d)) else: data.append(d) else: log.error(\"No visible options for %s\", name)", "Rename remaining \"~unknown\" to \"?\" ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove", "tuple(pytd.Parameter(name, a.data.to_type(node), False, False, None) for name, a in kws),", "an entry into the call trace. Args: node: The CFG", "DictKeyMissing doesn't trigger call_with_fake_args, so that shouldn't # be raised", "\"\"\"Verify the Python code.\"\"\" tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader,", "point in analyzing annotated functions for inference, # the presence", "binding.data.get_class(), method_name, binding) if method: bound_method = self.bind_method( node, method_name,", "set() self._interpreter_functions = [] self._interpreter_classes = [] self._analyzed_functions = set()", "abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type) return kwargs.to_variable(node) def create_method_arguments(self, node,", "the class, which sometimes isn't enough to disambiguate callers that", "isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record) elif isinstance(func.data, abstract.PyTDFunction): self._calls.add(record) def trace_functiondef(self, f):", "True, call traces are kept in the output. maximum_depth: Depth", "abstract.FUNCTION_TYPES) for o in options)): # It's ambiguous whether this", "during module loading MAXIMUM_DEPTH = 3 # during non-quick analysis", "When True, unknown arguments are created with force=False, as it", "args = self.create_method_arguments(node, f) if f.is_classmethod and cls: args =", "need. instance = self.join_bindings(node, good_instances) for instance_value in instance.data: val.data.register_canonical_instance(instance_value)", "this function call. func: A cfg.Binding of a function that", "name, var, cls=None): log.info(\"Analyzing %s\", name) node1 = node0.ConnectNew(name) for", "= ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()], escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self, node,", "cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), # not used in solver", "# DictKeyMissing nodes = [] rets = [] for funcb", "cls = args[0].data.get_class() if isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record) classes = []", "cls) if not new or ( any(not isinstance(f, abstract.InterpreterFunction) for", "self._call_init_on_binding(node, b) return node def reinitialize_if_initialized(self, node, instance): if instance", "maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc,", "functions: Skipping class method %s\", val.data.name) else: node1 = node0.ConnectNew(val.data.name)", "def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._unknowns = {} self._calls", "that the `is_attribute_of_class` will # be set for all functions", "of that. Args: node: The current node. method: An abstract.InterpreterFunction.", "clsvar, container) if key in self._instance_cache: # We've encountered a", "instance and its type parameters. \"\"\" values = list(values) seen", "Args: src: A string containing Python source code. errorlog: Where", "ret = self.call_function_in_frame(node, fvar, *args) return new_node, ret def call_function_in_frame(self,", "pytype.typegraph import cfg log = logging.getLogger(__name__) # Most interpreter functions", "emit debugging output.\"\"\" if options.output_cfg or options.output_typegraph: dot = debug.program_to_dot(program,", "log.info(\"%r has annotations, not analyzing further.\", fname) else: for f", "How deep to follow call chains: INIT_MAXIMUM_DEPTH = 4 #", "self._calls.add(record) def trace_functiondef(self, f): self._interpreter_functions.append(f) def trace_classdef(self, c): self._interpreter_classes.append(c) def", "trace_call(self, node, func, sigs, posargs, namedargs, result): \"\"\"Add an entry", "= loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast = tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if", "unlimited. tracer_vm: An instance of CallTracer, in case the caller", "of (1) a node and (2) a cfg.Variable of the", "self.frames, node, formal, actual, bad) return not bad def check_types(src,", "Once the args are generated, try calling the function. #", "value = abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter( node, abstract_utils.T, self.convert.create_new_unknown(node)) return value.to_variable(node)", "\"\"\"Build an (dummy) instance from a class, for analyzing it.\"\"\"", "an iterable over cfg.Value. namedargs: The keyword arguments, a dict", "and not value.data.is_overload): new_node = self.analyze_function(node, value) else: continue if", "(1) a node and (2) a cfg.Variable of the return", "tuple(posargs) kwargs = tuple((namedargs or {}).items()) record = CallRecord(node, func,", "not isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name, d)) else: data.append(d) else: log.error(\"No visible", "not bad def check_types(src, filename, errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH,", "vm, use that. if tracer_vm: assert isinstance(tracer_vm, CallTracer) tracer =", "self.analyze_method_var(node, method_name, bound_method) return node def _call_init_on_binding(self, node, b): if", "analyzed yet. # These are typically hidden under a decorator.", "result): \"\"\"Add an entry into the call trace. Args: node:", "We don't need to record call signatures that don't involve", "svg_file = options.output_cfg or options.output_typegraph proc = subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\",", "arguments\", func) if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1, args = self.create_method_arguments(node0, func)", "set for all functions in class. for c in self._interpreter_classes:", "create_method_arguments(self, node, method, use_defaults=False): \"\"\"Create arguments for the given method.", "the function. args: A function.Args object. Returns: A tuple of", "= self.create_kwargs(node) if method.has_kwargs() else None return node, function.Args(posargs=tuple(args), namedargs=kws,", "t in pytd_convert.annotations_to_instance_types( self.exitpoint, annots): annotated_names.add(name) data.append(pytd.Constant(name, t)) for name,", "pytd_classes_for_call_traces(self): class_to_records = collections.defaultdict(list) for call_record in self._method_calls: args =", "= node0.ConnectNew(name) for val in var.bindings: node2 = self.maybe_analyze_method(node1, val,", "snapshotter.take_snapshot(\"analyze:infer_types:post\") ast = tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or", "for name, val in self._unknowns.items(): if val in val.variable.Filter(self.exitpoint, strict=False):", "Calling __init__ can be expensive, so this method caches its", "node def _call_init_on_binding(self, node, b): if isinstance(b.data, abstract.SimpleValue): for param", "data.get_first_opcode() not in self._analyzed_functions and not _SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self, node,", "annots = abstract_utils.get_annotations_dict(defs) for name, t in pytd_convert.annotations_to_instance_types( self.exitpoint, annots):", "**kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) log.info(\"===Done running definitions", "!= len(instance.bindings): # __new__ returned some extra possibilities we don't", "var, args, kwargs, starargs, starstarargs): frame = frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing", ")) return classes def pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast() for v in", "check fallback_to_unsolvable if a DictKeyMissing or # FailedFunctionCall error is", "= () # aliases are instead recorded as constants ty", "# Call any additional initalizers the class has registered. for", "n, t in zip(arg_names, arg_types)) + tuple(pytd.Parameter(name, a.data.to_type(node), False, False,", "def infer_types(src, errorlog, options, loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None,", "cfg.Variable of the return value. \"\"\" fvar = val.AssignToNewVariable(node) with", "to instantiate and retain the vm used for type inference.", "parameters to pass to vm.VirtualMachine Returns: A tuple of (ast:", "cls.module else cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), # not used", "frame_state.FrameState.init(node, self) state, ret = self.call_function_with_state( state, var, args, kwargs,", "self._maybe_fix_classmethod_cls_arg(node, cls, f, args) node, _ = self.call_function_with_args(node, val, args)", "instance.bindings: if b.data in self._initialized_instances: continue self._initialized_instances.add(b.data) node = self._call_init_on_binding(node,", "functions=functions, aliases=aliases)) ty = ty.Visit(optimize.CombineReturnsAndExceptions()) ty = ty.Visit(optimize.PullInMethodClasses()) ty =", "(m.isinstance_InterpreterFunction() and m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls), [], node) return bound def", "for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\" not in ast: ast", "collections.defaultdict(pytd_utils.OrderedSet) for node, func, sigs, args, kws, retvar in call_traces:", "self._unknowns = {} self._calls = set() self._method_calls = set() #", "= val.data.instantiate(node) node = self.call_init(node, instance) elif len(good_instances) != len(instance.bindings):", "isinstance(instance, _Initializing): clsvar = cls.to_variable(node) node, instance = self._instantiate_var(node, clsvar,", "is not node: new_node.ConnectTo(node) # Now go through all functions", "previous instances. self._generated_classes[nt.name] = nt def pytd_classes_for_unknowns(self): classes = []", "= tracer.loader.concat_all() # Insert type parameters, where appropriate ast =", "so it's fine to # overwrite previous instances. self._generated_classes[nt.name] =", "# All namedtuple instances with the same name are equal,", "node = self.call_init(node, param) node = self._call_method(node, b, \"__init__\") cls", "var)): continue options = var.FilteredData(self.exitpoint, strict=False) if (len(options) > 1", "option in options: try: d = option.to_pytd_def(self.exitpoint, name) # Deep", "cls = b.data.get_class() if isinstance(cls, abstract.InterpreterClass): # Call any additional", "proc.communicate(dot) if stderr: log.info(\"Failed to create %s: %s\", svg_file, stderr)", "decorator. # Go through classes first so that the `is_attribute_of_class`", "isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name, d)) else: data.append(d) else: log.error(\"No visible options", "# We don't need to record call signatures that don't", "def __init__(self, x: \"A\"): ... # Calling __init__ again would", "(2) a cfg.Variable of the return value. \"\"\" fvar =", "method defined in a pyi file # returns an instance", "# How deep to follow call chains: INIT_MAXIMUM_DEPTH = 4", "class. instance = val.data.instantiate(node) node = self.call_init(node, instance) elif len(good_instances)", "self._CONSTRUCTORS: continue # We already called this method during initialization.", "self._method_calls: args = call_record.positional_arguments if not any(isinstance(a.data, abstract.Unknown) for a", "= var.FilteredData(self.exitpoint, strict=False) if (len(options) > 1 and not all(isinstance(o,", "(isinstance(data, abstract.InterpreterFunction) and not data.is_overload and not data.is_class_builder and data.get_first_opcode()", "return kwargs.to_variable(node) def create_method_arguments(self, node, method, use_defaults=False): \"\"\"Create arguments for", "method.signature.kwonly_params: if use_defaults and key in method.kw_defaults: kws[key] = method.kw_defaults[key]", "ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not show_library_calls: log.info(\"Solving is", "# when attempts to load from the protocols file if", "container: Optionally, a container to pass to the class's instantiate()", "= method.kw_defaults[key] else: kws[key] = self.convert.create_new_unknown(node, force=not use_defaults) starargs =", "to load from the protocols file if options.protocols: protocols_pytd =", "force=False, as it is fine to use Unsolvable rather than", "record call signatures that don't involve # unknowns - there's", "interpreter functions (including lambdas) need to be analyzed as #", "of a function that was called. sigs: The signatures that", "functions (including lambdas) need to be analyzed as # stand-alone", "method = val.data fname = val.data.name if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode())", "node: new_node.ConnectTo(node) # Now go through all functions and classes", "functions = tuple(self.pytd_functions_for_call_traces()) aliases = () # aliases are instead", "f in method.iter_signature_functions(): node, args = self.create_method_arguments(node, f) if f.is_classmethod", "= self.convert.create_new_unknown(node, force=not use_defaults) starargs = self.create_varargs(node) if method.has_varargs() else", "for n, t in zip(arg_names, arg_types)) + tuple(pytd.Parameter(name, a.data.to_type(node), False,", "fake arguments\", func) if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1, args = self.create_method_arguments(node0,", "for view in views if actual in view and view[actual].data.formal]", "the current opcode and the class, which sometimes isn't enough", "a recursive pattern such as # class A: # def", "not an instance of our class. instance = val.data.instantiate(node) node", "in zip(arg_names, arg_types)) + tuple(pytd.Parameter(name, a.data.to_type(node), False, False, None) for", "the presence of this option means that the user wants", "to be analyzed as # stand-alone functions. The exceptions are", "module-level code===\") snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep: if", "an infinite loop, so # we instead create an incomplete", "new or ( any(not isinstance(f, abstract.InterpreterFunction) for f in new.data)):", "yet. # These are typically hidden under a decorator. #", "source return its types. Args: src: A string containing Python", "of the program we're parsing. deep: If True, analyze all", "init_maximum_depth: Depth of analysis during module loading. show_library_calls: If True,", "The CFG node right after this function call. func: A", "classes not initialized via init_class. self._initialized_instances = set() self._interpreter_functions =", "__init__ again would lead to an infinite loop, so #", "take parameter annotations into account as InterpreterFunction.call() will take care", "of CallTracer, in case the caller wants to instantiate and", "pytype import convert_structural from pytype import debug from pytype import", "strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name)) return classes def pytd_for_types(self, defs): # If", "analyze_function(self, node0, val): if val.data.is_attribute_of_class: # We'll analyze this function", "func) # Once the args are generated, try calling the", "but we don't want # to re-analyze them. return (isinstance(data,", "4 # during module loading MAXIMUM_DEPTH = 3 # during", "= tracer_vm else: tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not deep,", "the first place. node2, ret = self.call_function(node1, funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False)", "[b for b in instance.bindings if val.data == b.data.cls] if", "except for closures, which are # re-generated when the variables", "that shouldn't get back the same cached instance. Returns: A", "%r\", func, len(posargs), result) args = tuple(posargs) kwargs = tuple((namedargs", "The signatures that the function might have been called with.", "node, clsv, container): \"\"\"Build an (dummy) instance from a class,", "method = self.attribute_handler.get_attribute( node, binding.data.get_class(), method_name, binding) if method: bound_method", "call_function that called this method in the first place. node2,", "node, func, sigs, posargs, namedargs, result): \"\"\"Add an entry into", "for the given method. Note that we don't need to", "ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If merged with other", "= self._instantiate_binding(node, cls, container) n.PasteVariable(var) return node, n def _mark_maybe_missing_members(self,", "init_class. self._initialized_instances = set() self._interpreter_functions = [] self._interpreter_classes = []", "= subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\", \"-o\", svg_file], stdin=subprocess.PIPE, universal_newlines=True) (_, stderr)", "MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program) def infer_types(src, errorlog,", "analysis QUICK_CHECK_MAXIMUM_DEPTH = 2 # during quick checking QUICK_INFER_MAXIMUM_DEPTH =", "False, None) for name, a in kws), starargs, starstarargs, ret,", "= 3 # during non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH = 2 #", "CallRecord = collections.namedtuple( \"CallRecord\", [\"node\", \"function\", \"signatures\", \"positional_arguments\", \"keyword_arguments\", \"return_value\"])", "cls.data.instantiate(node0, container=container) instance = self.program.NewVariable() nodes = [] for b", "of initializing - otherwise, setting # maybe_missing_members to True would", "value) else: continue if new_node is not node: new_node.ConnectTo(node) #", "views if actual in view and view[actual].data.formal] if not bad:", "and sig.param_names and (sig.param_names[0] not in sig.annotations)): # fix \"cls\"", "to instantiate. container: Optionally, a container to pass to the", "instance = val.data.instantiate(node) node = self.call_init(node, instance) elif len(good_instances) !=", "if deep: if maximum_depth is None: maximum_depth = ( QUICK_CHECK_MAXIMUM_DEPTH", "Since there's no point in analyzing annotated functions for inference,", "infinite loop, so # we instead create an incomplete instance", "value first, since bad_matches # expects not to get any.", "the given function with made-up arguments.\"\"\" # TODO(tsudol): If expand", "If True, analyze all functions, even the ones not called", "Depth of analysis during module loading. show_library_calls: If True, call", "# to re-analyze them. return (isinstance(data, abstract.InterpreterFunction) and not data.is_overload", "instance) self._instance_cache[key] = instance return node, instance def _call_method(self, node,", "methodvar, instance_var): bound = self.program.NewVariable() for m in methodvar.Data(node): if", "(\"typing\", \"typing_extensions\"): if module_name not in self.loaded_overlays: continue module =", "return tuple(v.generate_ast() for v in self._generated_classes.values()) def compute_types(self, defs): classes", "bad = self.matcher.bad_matches(actual, formal, node) if bad: self.errorlog.bad_return_type( self.frames, node,", "def _call_traces_to_function(call_traces, name_transform=lambda x: x): funcs = collections.defaultdict(pytd_utils.OrderedSet) for node,", "= m.func.data[0] is_cls = True else: is_cls = (m.isinstance_InterpreterFunction() and", "expensive, so this method caches its created instances. If you", "var): for value in var.bindings: if isinstance(value.data, abstract.InterpreterClass): new_node =", "recursive pattern such as # class A: # def __init__(self,", "isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record) classes = [] for cls, call_records in", "= self.analyze_class(node, value) elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and not value.data.is_overload): new_node", "the current class. return node0, cls.data.instantiate(node0, container=container) instance = self.program.NewVariable()", "among the values, recursively set maybe_missing_members to True on the", "that the user wants checking, too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else:", "seen = set() while values: v = values.pop(0) if v", "for type inference. **kwargs: Additional parameters to pass to vm.VirtualMachine", "# Used by init_class. self._instance_cache: Dict[Any, Union[_Initializing, cfg.Variable]] = {}", "\"\"\" fvar = val.AssignToNewVariable(node) with val.data.record_calls(): new_node, ret = self.call_function_in_frame(node,", "in instance.bindings: if b.data in self._initialized_instances: continue self._initialized_instances.add(b.data) node =", "by the main execution flow. init_maximum_depth: Depth of analysis during", "# overwrite previous instances. self._generated_classes[nt.name] = nt def pytd_classes_for_unknowns(self): classes", "= (tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances()) functions = tuple(self.pytd_functions_for_call_traces()) aliases", "state, var, args, kwargs, starargs, starstarargs) self.pop_frame(frame) return state.node, ret", "may be different in the presence of optional and kw", "exit. Needs to be set before analyze_types. \"\"\" _CONSTRUCTORS =", "options.output_cfg or options.output_typegraph: dot = debug.program_to_dot(program, set([]), bool(options.output_cfg)) svg_file =", "The current node. method: An abstract.InterpreterFunction. use_defaults: Whether to use", "method in the first place. node2, ret = self.call_function(node1, funcb.AssignToNewVariable(),", "class method %s\", val.data.name) else: node1 = node0.ConnectNew(val.data.name) node2 =", "function.argname(i) arg_types = (a.data.to_type(node) for a in args) ret =", "node, var, args, kwargs, starargs, starstarargs): frame = frame_state.SimpleFrame(node=node) self.push_frame(frame)", "__init__, need to handle # DictKeyMissing nodes = [] rets", "\"<listcomp>\" and \"<genexpr>\". _SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\") CallRecord = collections.namedtuple( \"CallRecord\",", "this method in the first place. node2, ret = self.call_function(node1,", "we're parsing. deep: If True, analyze all functions, even the", "registered. for method in cls.additional_init_methods: node = self._call_method(node, b, method)", "node0, cls.data.instantiate(node0, container=container) instance = self.program.NewVariable() nodes = [] for", "for b in instance.bindings if val.data == b.data.cls] if not", "in views if actual in view and view[actual].data.formal] if not", "are comprehensions and generators, which # have names like \"<listcomp>\"", "kwargs = abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type)", "pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls, escape.pack_partial) def pytd_classes_for_call_traces(self): class_to_records = collections.defaultdict(list) for", "ret = pytd_utils.JoinTypes(t.to_type(node) for t in retvar.data) starargs = None", "# Now go through all functions and classes we haven't", "result: A Variable of the possible result values. \"\"\" log.debug(\"Logging", "stderr: log.info(\"Failed to create %s: %s\", svg_file, stderr) if options.output_debug:", "when the variables they close over change, but we don't", "pytd_convert.annotations_to_instance_types( self.exitpoint, annots): annotated_names.add(name) data.append(pytd.Constant(name, t)) for name, var in", "= abstract_utils.get_annotations_dict(defs) for name, t in pytd_convert.annotations_to_instance_types( self.exitpoint, annots): annotated_names.add(name)", "= maximum_depth self._analyzing = True node = node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node,", "val.data.name if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if (not self.options.analyze_annotated and (method.signature.has_return_annotation", "arguments.\"\"\" # TODO(tsudol): If expand this beyond __init__, need to", "from _instance_cache because we also call # __init__ on classes", "instance = self.program.NewVariable() nodes = [] for b in new.bindings:", "c.bindings: if (isinstance(value.data, abstract.InterpreterClass) and value.data not in self._analyzed_classes): node", "import pytd_utils from pytype.pytd import visitors from pytype.typegraph import cfg", "in self._analyzed_functions and not _SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self, node, defs): for", "deep, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) log.info(\"===Done", "to an infinite loop, so # we instead create an", "later. Note that we have to create a new #", "builtins_pytd = tracer.loader.concat_all() # Insert type parameters, where appropriate ast", "assert not self.frame self.maximum_depth = maximum_depth self._analyzing = True node", "parameter return args._replace( posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:]) else: return args def", "that may be raised will be passed to # the", "defaults for arguments. When True, unknown arguments are created with", "in self._generated_classes.values()) def compute_types(self, defs): classes = (tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces())", "in options: try: d = option.to_pytd_def(self.exitpoint, name) # Deep definition", "True, analyze all functions, even the ones not called by", "metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep: if maximum_depth is None: maximum_depth =", "> 0: arg_names[i] = function.argname(i) arg_types = (a.data.to_type(node) for a", "would lead to an infinite loop, so # we instead", "tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or any( a in", "= self.call_function_in_frame(node, fvar, *args) return new_node, ret def call_function_in_frame(self, node,", "if isinstance(d, pytd.Type) and not isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name, d)) else:", "# FailedFunctionCall error is raised when the target function is", "call signatures that don't involve # unknowns - there's nothing", "location at which the instantion occurs. By default, this method", "function from pytype import metrics from pytype import output from", "functions in class. for c in self._interpreter_classes: for value in", "fix \"cls\" parameter return args._replace( posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:]) else: return", "exceptions are comprehensions and generators, which # have names like", "are typically hidden under a decorator. # Go through classes", "called by the main execution flow. init_maximum_depth: Depth of analysis", "self.maybe_analyze_method(node1, val) node2.ConnectTo(node0) return node0 def _should_analyze_as_interpreter_function(self, data): # We", "_SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self, node, defs): for name, var in sorted(defs.items()):", "are equivalent except for closures, which are # re-generated when", "loading MAXIMUM_DEPTH = 3 # during non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH =", "instance to load PYI information. filename: Filename of the program", "abstract_utils.get_views([actual], node) # Check for typevars in the return value", "Now go through all functions and classes we haven't analyzed", "maximum_depth = ( QUICK_CHECK_MAXIMUM_DEPTH if options.quick else MAXIMUM_DEPTH) tracer.analyze(loc, defs,", "val: A cfg.Binding containing the function. args: A function.Args object.", "checking, too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint", "= (\"__new__\", \"__init__\") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._unknowns", "tuple(pytd.Parameter(n, t, False, False, None) for n, t in zip(arg_names,", "current node. cls: The class to instantiate. container: Optionally, a", "import Any, Dict, Union from pytype import abstract from pytype", "var in sorted(defs.items()): # sort, for determinicity if not self._is_typing_member(name,", "signatures that the function might have been called with. posargs:", "remaining \"~unknown\" to \"?\" ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove \"~list\"", "instead. Args: node: The current node. cls: The class to", "function as part of a class. log.info(\"Analyze functions: Skipping class", "change, but we don't want # to re-analyze them. return", "defs = tracer.run_program(src, filename, init_maximum_depth) log.info(\"===Done running definitions and module-level", "None builtins_pytd = tracer.loader.concat_all() # Insert type parameters, where appropriate", "= self.call_function_with_args(node, val, args) return node def _call_with_fake_args(self, node0, funcv):", "cls, container): \"\"\"Instantiate a class binding.\"\"\" node1, new = cls.data.get_own_new(node0,", "abstract.Unknown) for a in args): # We don't need to", "analyze_types. \"\"\" _CONSTRUCTORS = (\"__new__\", \"__init__\") def __init__(self, *args, **kwargs):", "seen: seen.add(v) if isinstance(v, abstract.SimpleValue): v.maybe_missing_members = True for child", "self.analyze_function(node, value) else: continue if new_node is not node: new_node.ConnectTo(node)", "= self.program.NewVariable() nodes = [] for b in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode())", "in seen: seen.add(v) if isinstance(v, abstract.SimpleValue): v.maybe_missing_members = True for", "False just in case. # This means any additional errors", "val.data.name) else: node1 = node0.ConnectNew(val.data.name) node2 = self.maybe_analyze_method(node1, val) node2.ConnectTo(node0)", "might have been called with. posargs: The positional arguments, an", "get any. bad = [view for view in views if", "classes def pytd_for_types(self, defs): # If a variable is annotated,", "else: return args def maybe_analyze_method(self, node, val, cls=None): method =", "use_defaults: Whether to use parameter defaults for arguments. When True,", "and a function.Args object. \"\"\" args = [] num_posargs =", "file # returns an instance of the current class. return", "arg_names[i] = function.argname(i) arg_types = (a.data.to_type(node) for a in args)", "# two ways of recording are equivalent except for closures,", "aliases=aliases)) ty = ty.Visit(optimize.CombineReturnsAndExceptions()) ty = ty.Visit(optimize.PullInMethodClasses()) ty = ty.Visit(visitors.DefaceUnresolved(", "options = var.FilteredData(self.exitpoint, strict=False) if (len(options) > 1 and not", "= abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type) return", "else: for f in method.iter_signature_functions(): node, args = self.create_method_arguments(node, f)", "of the current class. return node0, cls.data.instantiate(node0, container=container) instance =", "The keyword arguments, a dict mapping str to cfg.Value. result:", "False, None) for n, t in zip(arg_names, arg_types)) + tuple(pytd.Parameter(name,", "svg_file, stderr) if options.output_debug: text = debug.program_to_text(program) if options.output_debug ==", "maximum_depth self._analyzing = True node = node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node, defs)", "case the caller wants to instantiate and retain the vm", "Used by init_class. self._instance_cache: Dict[Any, Union[_Initializing, cfg.Variable]] = {} #", "self.options.analyze_annotated and (method.signature.has_return_annotation or method.has_overloads) and fname.rsplit(\".\", 1)[-1] not in", "\"keyword_arguments\", \"return_value\"]) # How deep to follow call chains: INIT_MAXIMUM_DEPTH", "off. Discarding call traces.\") # Rename remaining \"~unknown\" to \"?\"", "self.call_function(node1, funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret) if nodes: ret =", "= b.data.get_class() if isinstance(cls, abstract.InterpreterClass): # Call any additional initalizers", "args def maybe_analyze_method(self, node, val, cls=None): method = val.data fname", "rather than Unknown objects for type-checking defaults. Returns: A tuple", "name, var in sorted(defs.items()): # sort, for determinicity if not", "kwargs.to_variable(node) def create_method_arguments(self, node, method, use_defaults=False): \"\"\"Create arguments for the", "need to handle # DictKeyMissing nodes = [] rets =", "abstract.INTERPRETER_FUNCTION_TYPES) and not value.data.is_overload): new_node = self.analyze_function(node, value) else: continue", "debug.program_to_dot(program, set([]), bool(options.output_cfg)) svg_file = options.output_cfg or options.output_typegraph proc =", "node2 = self.maybe_analyze_method(node1, val) node2.ConnectTo(node0) return node0 def _should_analyze_as_interpreter_function(self, data):", "_check_return(self, node, actual, formal): if not self.options.report_errors: return True views", "defs, maximum_depth) else: tracer.exitpoint = loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast = tracer.compute_types(defs)", "Returns: A tuple of (ast: TypeDeclUnit, builtins: TypeDeclUnit) Raises: AssertionError:", "in class_to_records.items(): full_name = cls.module + \".\" + cls.name if", "Dict, Union from pytype import abstract from pytype import abstract_utils", "if module_name not in self.loaded_overlays: continue module = self.loaded_overlays[module_name].get_module(name) if", "first so that the `is_attribute_of_class` will # be set for", "if ret.bindings: return node, ret else: node = node0 log.info(\"Unable", "raised will be passed to # the call_function that called", "None return node, function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs, starstarargs=starstarargs) def call_function_with_args(self, node,", "if val.data.is_attribute_of_class: # We'll analyze this function as part of", "expand this beyond __init__, need to handle # DictKeyMissing nodes", "val.data.instantiate(node) node = self.call_init(node, instance) elif len(good_instances) != len(instance.bindings): #", "self._call_init_on_binding(node, instance.to_binding(node)) def analyze_class(self, node, val): self._analyzed_classes.add(val.data) node, instance =", "for val in var.bindings: node2 = self.maybe_analyze_method(node1, val, cls) node2.ConnectTo(node0)", "rather than using the one that we're already in #", "return True views = abstract_utils.get_views([actual], node) # Check for typevars", "attempts to load from the protocols file if options.protocols: protocols_pytd", "def _call_init_on_binding(self, node, b): if isinstance(b.data, abstract.SimpleValue): for param in", "self.maximum_depth = maximum_depth self._analyzing = True node = node.ConnectNew(name=\"Analyze\") return", "same cached instance. Returns: A tuple of node and instance", "\"\"\"Virtual machine that records all function calls. Attributes: exitpoint: A", "val, cls) node2.ConnectTo(node0) return node0 def bind_method(self, node, name, methodvar,", "# aliases are instead recorded as constants ty = pytd_utils.Concat(", "_maybe_output_debug(options, program): \"\"\"Maybe emit debugging output.\"\"\" if options.output_cfg or options.output_typegraph:", "signatures that don't involve # unknowns - there's nothing to", "be expensive, so this method caches its created instances. If", "value_type) return kwargs.to_variable(node) def create_method_arguments(self, node, method, use_defaults=False): \"\"\"Create arguments", "if isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record) classes = [] for cls, call_records", "def reinitialize_if_initialized(self, node, instance): if instance in self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node))", "pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod def _call_traces_to_function(call_traces, name_transform=lambda x: x): funcs =", "\"-o\", svg_file], stdin=subprocess.PIPE, universal_newlines=True) (_, stderr) = proc.communicate(dot) if stderr:", "Type only if isinstance(d, pytd.NothingType): if isinstance(option, abstract.Empty): d =", "val): self._analyzed_classes.add(val.data) node, instance = self.init_class(node, val.data) good_instances = [b", "self) state, ret = self.call_function_with_state( state, var, args, kwargs, starargs,", "aliases are instead recorded as constants ty = pytd_utils.Concat( self.pytd_for_types(defs),", "other if statement, triggers a ValueError: Unresolved class # when", "for t in options) data.append(pytd.Constant(name, combined_types)) elif options: for option", "builtins from pytype.pytd import escape from pytype.pytd import optimize from", "abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\" not in ast: ast = pytd_utils.Concat( ast,", "cls.to_variable(node) node, instance = self._instantiate_var(node, clsvar, container) if key in", "maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint", "We already called this method during initialization. b = self.bind_method(node,", "instance. Returns: A tuple of node and instance variable. \"\"\"", "import subprocess from typing import Any, Dict, Union from pytype", "continue # We already called this method during initialization. b", "CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader, **kwargs) loc, defs =", "import logging import re import subprocess from typing import Any,", "raised again, and generating fake arguments should avoid any #", "node, func, sigs, args, kws, retvar in call_traces: # The", "that shouldn't # be raised again, and generating fake arguments", "pytd.TypeParameter): data.append(pytd.Constant(name, d)) else: data.append(d) else: log.error(\"No visible options for", "\"cls\" parameter return args._replace( posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:]) else: return args", "_mark_maybe_missing_members(self, values): \"\"\"Set maybe_missing_members to True on these values and", "tracer.loader.import_name(\"protocols\") else: protocols_pytd = None builtins_pytd = tracer.loader.concat_all() # Insert", "[view for view in views if actual in view and", "node, instance def _call_method(self, node, binding, method_name): node, method =", "information about the location at which the instantion occurs. By", "type parameters in the container's template are instantiated to TypeParameterInstance.", "else, so encode it as a constant. combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint)", "method.kw_defaults: kws[key] = method.kw_defaults[key] else: kws[key] = self.convert.create_new_unknown(node, force=not use_defaults)", "return %r\", func, len(posargs), result) args = tuple(posargs) kwargs =", "key in self._instance_cache: # We've encountered a recursive pattern such", "recording are equivalent except for closures, which are # re-generated", "= self.init_class(node, val.data) good_instances = [b for b in instance.bindings", "if isinstance(option, abstract.Empty): d = pytd.AnythingType() else: assert isinstance(option, typing_overlay.NoReturn)", "= (a.data.to_type(node) for a in args) ret = pytd_utils.JoinTypes(t.to_type(node) for", "= set() self._generated_classes = {} self.exitpoint = None def create_varargs(self,", "in call_traces: # The lengths may be different in the", "t in options) data.append(pytd.Constant(name, combined_types)) elif options: for option in", "node, formal, actual, bad) return not bad def check_types(src, filename,", "\"<genexpr>\". _SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\") CallRecord = collections.namedtuple( \"CallRecord\", [\"node\", \"function\",", "parameter defaults for arguments. When True, unknown arguments are created", "return self._call_traces_to_function(self._calls, escape.pack_partial) def pytd_classes_for_call_traces(self): class_to_records = collections.defaultdict(list) for call_record", "passed in a vm, use that. if tracer_vm: assert isinstance(tracer_vm,", "also call # __init__ on classes not initialized via init_class.", "= debug.program_to_text(program) if options.output_debug == \"-\": log.info(\"=========== Program Dump =============\\n%s\",", "or self._is_typing_member(name, var)): continue options = var.FilteredData(self.exitpoint, strict=False) if (len(options)", "# Go through classes first so that the `is_attribute_of_class` will", "and (2) a cfg.Variable of the return value. \"\"\" fvar", "functions. The exceptions are comprehensions and generators, which # have", "pytd_utils from pytype.pytd import visitors from pytype.typegraph import cfg log", "we'll always output that type. annotated_names = set() data =", "= funcb.data log.info(\"Trying %s with fake arguments\", func) if isinstance(func,", "error is raised when the target function is called. #", "By default, this method keys on the current opcode and", "and module.members[name].data == var.data: return True return False def pytd_functions_for_call_traces(self):", "for value in c.bindings: if (isinstance(value.data, abstract.InterpreterClass) and value.data not", "elif isinstance(func.data, abstract.PyTDFunction): self._calls.add(record) def trace_functiondef(self, f): self._interpreter_functions.append(f) def trace_classdef(self,", "protocols file if options.protocols: protocols_pytd = tracer.loader.import_name(\"protocols\") else: protocols_pytd =", "that don't involve # unknowns - there's nothing to solve", "self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions, aliases=aliases)) ty = ty.Visit(optimize.CombineReturnsAndExceptions()) ty =", "may be raised will be passed to # the call_function", "in a vm, use that. if tracer_vm: assert isinstance(tracer_vm, CallTracer)", "else: tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader, **kwargs)", "\"-\": log.info(\"=========== Program Dump =============\\n%s\", text) else: with options.open_function(options.output_debug, \"w\")", "execution flow. init_maximum_depth: Depth of analysis during module loading. show_library_calls:", "abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type) return kwargs.to_variable(node)", "log.info(\"Trying %s with fake arguments\", func) if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1,", "all attribute errors on self in __init__. self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key]", "constants=(), classes=(), decorators=(), slots=None, template=(), )) return classes def pytd_classes_for_namedtuple_instances(self):", "2 # during quick checking QUICK_INFER_MAXIMUM_DEPTH = 1 # during", "(a.data.to_type(node) for a in args) ret = pytd_utils.JoinTypes(t.to_type(node) for t", "node) return bound def _instantiate_binding(self, node0, cls, container): \"\"\"Instantiate a", "from pytype import convert_structural from pytype import debug from pytype", "re.compile(\"<(?!lambda).+>$\") CallRecord = collections.namedtuple( \"CallRecord\", [\"node\", \"function\", \"signatures\", \"positional_arguments\", \"keyword_arguments\",", "var, cls=None): log.info(\"Analyzing %s\", name) node1 = node0.ConnectNew(name) for val", "The # two ways of recording are equivalent except for", "abstract from pytype import abstract_utils from pytype import convert_structural from", "default_idx >= 0: arg = method.defaults[default_idx] else: arg = self.convert.create_new_unknown(node,", "call_record in self._method_calls: args = call_record.positional_arguments if not any(isinstance(a.data, abstract.Unknown)", "instead create an incomplete instance that will be # overwritten", "b, method) return node def call_init(self, node, instance): # Call", "a decorator. # Go through classes first so that the", "maximum_depth is None: if not options.quick: maximum_depth = MAXIMUM_DEPTH elif", "type-checking defaults. Returns: A tuple of a node and a", "= option.to_pytd_def(self.exitpoint, name) # Deep definition except NotImplementedError: d =", "in options)): # It's ambiguous whether this is a type,", "protocols_pytd) elif not show_library_calls: log.info(\"Solving is turned off. Discarding call", "defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program) def infer_types(src, errorlog, options, loader,", "@staticmethod def _call_traces_to_function(call_traces, name_transform=lambda x: x): funcs = collections.defaultdict(pytd_utils.OrderedSet) for", "analyzed functions by opcode rather than function object. The #", "def check_types(src, filename, errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs):", "**kwargs): \"\"\"Given Python source return its types. Args: src: A", "in the first place. node2, ret = self.call_function(node1, funcb.AssignToNewVariable(), args,", "on each binding. for b in instance.bindings: if b.data in", "arguments. When True, unknown arguments are created with force=False, as", "for name, a in kws), starargs, starstarargs, ret, exceptions=(), template=()))", "node0, cls, container): \"\"\"Instantiate a class binding.\"\"\" node1, new =", "{} for key in method.signature.kwonly_params: if use_defaults and key in", "or options.output_typegraph proc = subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\", \"-o\", svg_file], stdin=subprocess.PIPE,", "an incomplete instance that will be # overwritten later. Note", "errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): \"\"\"Verify the Python", "not in self._CONSTRUCTORS): log.info(\"%r has annotations, not analyzing further.\", fname)", "self._generated_classes = {} self.exitpoint = None def create_varargs(self, node): value", "node0.ConnectNew(val.data.name) node2 = self.maybe_analyze_method(node1, val) node2.ConnectTo(node0) return node0 def _should_analyze_as_interpreter_function(self,", "all function calls. Attributes: exitpoint: A CFG node representing the", "def _maybe_output_debug(options, program): \"\"\"Maybe emit debugging output.\"\"\" if options.output_cfg or", "program we're parsing. deep: If True, analyze all functions, even", "options for %s\", name) data.append(pytd.Constant(name, pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod", "import state as frame_state from pytype import vm from pytype.overlays", "class _Initializing: pass class CallTracer(vm.VirtualMachine): \"\"\"Virtual machine that records all", "defs = tracer.run_program(src, filename, init_maximum_depth) snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\")", "machine that records all function calls. Attributes: exitpoint: A CFG", "key in method.signature.kwonly_params: if use_defaults and key in method.kw_defaults: kws[key]", "# fallback_to_unsolvable to False just in case. # This means", "method. Note that we don't need to take parameter annotations", "val): if val.data.is_attribute_of_class: # We'll analyze this function as part", "which the instantion occurs. By default, this method keys on", "# __new__ returned some extra possibilities we don't need. instance", "# Most interpreter functions (including lambdas) need to be analyzed", "parameter combination. \"\"\" # If the caller has passed in", "self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key] = _Initializing() node = self.call_init(node, instance) self._instance_cache[key]", "CFG node representing the program exit. Needs to be set", "method %s\", val.data.name) else: node1 = node0.ConnectNew(val.data.name) node2 = self.maybe_analyze_method(node1,", "\"\"\" args = [] num_posargs = method.argcount(node) num_posargs_no_default = num_posargs", "node = self._call_init_on_binding(node, b) return node def reinitialize_if_initialized(self, node, instance):", "all functions in class. for c in self._interpreter_classes: for value", "is_cls = (m.isinstance_InterpreterFunction() and m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls), [], node) return", "= CallRecord(node, func, sigs, args, kwargs, result) if isinstance(func.data, abstract.BoundPyTDFunction):", "= self.convert.create_new_unknown(node, force=not use_defaults) args.append(arg) kws = {} for key", "isinstance(option, typing_overlay.NoReturn) if isinstance(d, pytd.Type) and not isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name,", "to cfg.Value. result: A Variable of the possible result values.", "node def call_init(self, node, instance): # Call __init__ on each", "args = self.create_method_arguments(node0, func) # Once the args are generated,", "an (dummy) instance from a class, for analyzing it.\"\"\" n", "should avoid any # FailedFunctionCall errors. To prevent an infinite", "overwrite previous instances. self._generated_classes[nt.name] = nt def pytd_classes_for_unknowns(self): classes =", "and kw args. arg_names = max((sig.get_positional_names() for sig in sigs),", "options: for option in options: try: d = option.to_pytd_def(self.exitpoint, name)", "nothing to solve for. continue cls = args[0].data.get_class() if isinstance(cls,", "else: kws[key] = self.convert.create_new_unknown(node, force=not use_defaults) starargs = self.create_varargs(node) if", "CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename,", "None def create_varargs(self, node): value = abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter( node,", "doesn't trigger call_with_fake_args, so that shouldn't # be raised again,", "args) node3 = node2.ConnectNew() node4, ret = self.call_function_with_args(node3, b, args)", "_Initializing() node = self.call_init(node, instance) self._instance_cache[key] = instance return node,", "CallTracer) tracer = tracer_vm else: tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols,", "instance rather than using the one that we're already in", "import optimize from pytype.pytd import pytd from pytype.pytd import pytd_utils", "A tuple of node and instance variable. \"\"\" key =", "if val.data == b.data.cls] if not good_instances: # __new__ returned", "the Python code.\"\"\" tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader, **kwargs)", "so encode it as a constant. combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint) for", "Skipping class method %s\", val.data.name) else: node1 = node0.ConnectNew(val.data.name) node2", "analyze_method_var(self, node0, name, var, cls=None): log.info(\"Analyzing %s\", name) node1 =", "classes first so that the `is_attribute_of_class` will # be set", "%s\", svg_file, stderr) if options.output_debug: text = debug.program_to_text(program) if options.output_debug", "__init__ called, use cls.instantiate instead. Args: node: The current node.", "escape.pack_partial) def pytd_classes_for_call_traces(self): class_to_records = collections.defaultdict(list) for call_record in self._method_calls:", "A tuple of (1) a node and (2) a cfg.Variable", "# Calling __init__ again would lead to an infinite loop,", "node, defs): for name, var in sorted(defs.items()): # sort, for", "QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth)", "fvar = val.AssignToNewVariable(node) with val.data.record_calls(): new_node, ret = self.call_function_in_frame(node, fvar,", "errorlog, options, loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs):", "function that was called. sigs: The signatures that the function", "instantiated to TypeParameterInstance. extra_key: Optionally, extra information about the location", "appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info(\"=========== PyTD to solve", "not isinstance(func.data, abstract.BoundFunction) or i > 0: arg_names[i] = function.argname(i)", "args[0].data.get_class() if isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record) classes = [] for cls,", "Depth of the analysis. Default: unlimited. tracer_vm: An instance of", "in funcv.bindings: func = funcb.data log.info(\"Trying %s with fake arguments\",", "else: self._instance_cache[key] = _Initializing() node = self.call_init(node, instance) self._instance_cache[key] =", "= cls.module + \".\" + cls.name if cls.module else cls.name", "new_node.ConnectTo(node) # Now go through all functions and classes we", "class_to_records = collections.defaultdict(list) for call_record in self._method_calls: args = call_record.positional_arguments", "node, instance = self._instantiate_var(node, clsvar, container) if key in self._instance_cache:", "new = cls.data.get_own_new(node0, cls) if not new or ( any(not", "+ \".\" + cls.name if cls.module else cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name),", "for i in range(num_posargs): default_idx = i - num_posargs_no_default if", "v.maybe_missing_members = True for child in v.instance_type_parameters.values(): values.extend(child.data) def init_class(self,", "kws = {} for key in method.signature.kwonly_params: if use_defaults and", "if deep: if maximum_depth is None: if not options.quick: maximum_depth", "was called. sigs: The signatures that the function might have", "generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename,", "( QUICK_CHECK_MAXIMUM_DEPTH if options.quick else MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\")", "value in f.bindings: if self._should_analyze_as_interpreter_function(value.data): node = self.analyze_function(node, value) return", "as frame_state from pytype import vm from pytype.overlays import typing_overlay", "that we have to create a new # instance rather", "calling the function. # call_function will check fallback_to_unsolvable if a", "isinstance(v, abstract.SimpleValue): v.maybe_missing_members = True for child in v.instance_type_parameters.values(): values.extend(child.data)", "\"__init__\") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._unknowns = {}", "clsv, container): \"\"\"Build an (dummy) instance from a class, for", "# not used in solver methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(), decorators=(), slots=None,", "arg = method.defaults[default_idx] else: arg = self.convert.create_new_unknown(node, force=not use_defaults) args.append(arg)", "args = self._maybe_fix_classmethod_cls_arg(node, cls, f, args) node, _ = self.call_function_with_args(node,", "output from pytype import special_builtins from pytype import state as", "Returns: A tuple of node and instance variable. \"\"\" key", "extra_key: Optionally, extra information about the location at which the", "= _Initializing() node = self.call_init(node, instance) self._instance_cache[key] = instance return", "deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): \"\"\"Verify the Python code.\"\"\" tracer =", "for name, var in sorted(defs.items()): # sort, for determinicity if", "be set before analyze_types. \"\"\" _CONSTRUCTORS = (\"__new__\", \"__init__\") def", "= convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not show_library_calls: log.info(\"Solving is turned", "to follow call chains: INIT_MAXIMUM_DEPTH = 4 # during module", "0: arg = method.defaults[default_idx] else: arg = self.convert.create_new_unknown(node, force=not use_defaults)", "Unsolvable rather than Unknown objects for type-checking defaults. Returns: A", "== b.data.cls] if not good_instances: # __new__ returned something that's", "if a DictKeyMissing or # FailedFunctionCall error is raised when", "unknown arguments are created with force=False, as it is fine", "self._instantiate_binding(node, cls, container) n.PasteVariable(var) return node, n def _mark_maybe_missing_members(self, values):", "arguments are created with force=False, as it is fine to", "# during module loading MAXIMUM_DEPTH = 3 # during non-quick", "= [] num_posargs = method.argcount(node) num_posargs_no_default = num_posargs - len(method.defaults)", "if not new or ( any(not isinstance(f, abstract.InterpreterFunction) for f", "of our class. instance = val.data.instantiate(node) node = self.call_init(node, instance)", "during quick inference class _Initializing: pass class CallTracer(vm.VirtualMachine): \"\"\"Virtual machine", "def trace_namedtuple(self, nt): # All namedtuple instances with the same", "method: An abstract.InterpreterFunction. use_defaults: Whether to use parameter defaults for", "import debug from pytype import function from pytype import metrics", "= frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing %r\", [v.name for v in var.data])", "x: x): funcs = collections.defaultdict(pytd_utils.OrderedSet) for node, func, sigs, args,", "and the class, which sometimes isn't enough to disambiguate callers", "name, unknown_binding): self._unknowns[name] = unknown_binding def trace_call(self, node, func, sigs,", "TODO(tsudol): If expand this beyond __init__, need to handle #", "func, args): sig = func.signature if (args.posargs and sig.param_names and", "args.append(arg) kws = {} for key in method.signature.kwonly_params: if use_defaults", "quick checking QUICK_INFER_MAXIMUM_DEPTH = 1 # during quick inference class", "self.analyze_class(node, value) elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and not value.data.is_overload): new_node =", "also call __init__. Calling __init__ can be expensive, so this", "init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): \"\"\"Verify the Python code.\"\"\" tracer = CallTracer(errorlog=errorlog,", "in method.signature.kwonly_params: if use_defaults and key in method.kw_defaults: kws[key] =", "The current node. cls: The class to instantiate. container: Optionally,", "cls.module + \".\" + cls.name if cls.module else cls.name classes.append(pytd.Class(", "Instance of errors.ErrorLog. options: config.Options object loader: A load_pytd.Loader instance", "tracer_vm: assert isinstance(tracer_vm, CallTracer) tracer = tracer_vm else: tracer =", "will be # overwritten later. Note that we have to", "with made-up arguments.\"\"\" # TODO(tsudol): If expand this beyond __init__,", "first place. node2, ret = self.call_function(node1, funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False) nodes.append(node2)", "= set() data = [] pytd_convert = self.convert.pytd_convert annots =", "tuple of (1) a node and (2) a cfg.Variable of", "cls: args = self._maybe_fix_classmethod_cls_arg(node, cls, f, args) node, _ =", "type parameters. \"\"\" values = list(values) seen = set() while", "formal): if not self.options.report_errors: return True views = abstract_utils.get_views([actual], node)", "= abstract_utils.get_views([actual], node) # Check for typevars in the return", "generated, try calling the function. # call_function will check fallback_to_unsolvable", "not initialized via init_class. self._initialized_instances = set() self._interpreter_functions = []", "called, use cls.instantiate instead. Args: node: The current node. cls:", "data) @staticmethod def _call_traces_to_function(call_traces, name_transform=lambda x: x): funcs = collections.defaultdict(pytd_utils.OrderedSet)", "of BaseValue objects. On every instance among the values, recursively", "strict=False): node, var = self._instantiate_binding(node, cls, container) n.PasteVariable(var) return node,", "self._interpreter_functions.append(f) def trace_classdef(self, c): self._interpreter_classes.append(c) def trace_namedtuple(self, nt): # All", "`is_attribute_of_class` will # be set for all functions in class.", "pytype import special_builtins from pytype import state as frame_state from", "not all(isinstance(o, abstract.FUNCTION_TYPES) for o in options)): # It's ambiguous", "self.analyze_toplevel(node, defs) def trace_unknown(self, name, unknown_binding): self._unknowns[name] = unknown_binding def", "Python source code. errorlog: Where error messages go. Instance of", "type params. Args: values: A list of BaseValue objects. On", "values: v = values.pop(0) if v not in seen: seen.add(v)", "# We've encountered a recursive pattern such as # class", "be analyzed as # stand-alone functions. The exceptions are comprehensions", "ty.Visit(optimize.CombineReturnsAndExceptions()) ty = ty.Visit(optimize.PullInMethodClasses()) ty = ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()], escape.UNKNOWN))", "ast, builtins_pytd def _maybe_output_debug(options, program): \"\"\"Maybe emit debugging output.\"\"\" if", "\"signatures\", \"positional_arguments\", \"keyword_arguments\", \"return_value\"]) # How deep to follow call", "node = node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node, defs) def trace_unknown(self, name, unknown_binding):", "AssertionError: In case of a bad parameter combination. \"\"\" #", "we haven't analyzed yet. # These are typically hidden under", "= [] for name, signatures in funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD))", "and default_idx >= 0: arg = method.defaults[default_idx] else: arg =", "t)) for name, var in defs.items(): if (name in output.TOP_LEVEL_IGNORE", "d = option.to_type(self.exitpoint) # Type only if isinstance(d, pytd.NothingType): if", "formal, node) if bad: self.errorlog.bad_return_type( self.frames, node, formal, actual, bad)", "[] num_posargs = method.argcount(node) num_posargs_no_default = num_posargs - len(method.defaults) for", "# the presence of this option means that the user", "don't need to record call signatures that don't involve #", "return node, instance def _call_method(self, node, binding, method_name): node, method", "def analyze_method_var(self, node0, name, var, cls=None): log.info(\"Analyzing %s\", name) node1", "n = self.program.NewVariable() for cls in clsv.Bindings(node, strict=False): node, var", "abstract.InterpreterClass): # Call any additional initalizers the class has registered.", "on classes not initialized via init_class. self._initialized_instances = set() self._interpreter_functions", "__init__. Calling __init__ can be expensive, so this method caches", "defs): # If a variable is annotated, we'll always output", "node: The current node. cls: The class to instantiate. container:", "method: bound_method = self.bind_method( node, method_name, method, binding.AssignToNewVariable()) node =", "(_, stderr) = proc.communicate(dot) if stderr: log.info(\"Failed to create %s:", "in var.bindings: if isinstance(value.data, abstract.InterpreterClass): new_node = self.analyze_class(node, value) elif", "function with made-up arguments.\"\"\" # TODO(tsudol): If expand this beyond", "Calling __init__ again would lead to an infinite loop, so", "instance = self.init_class(node, val.data) good_instances = [b for b in", "for checking and inferring types.\"\"\" import collections import logging import", "self.call_function_in_frame(node, fvar, *args) return new_node, ret def call_function_in_frame(self, node, var,", "call_record.positional_arguments if not any(isinstance(a.data, abstract.Unknown) for a in args): #", "log.info(\"=========== PyTD to solve =============\\n%s\", pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd,", "ast.Visit(visitors.RemoveUnknownClasses()) # Remove \"~list\" etc.: ast = convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program)", "nt def pytd_classes_for_unknowns(self): classes = [] for name, val in", "to record call signatures that don't involve # unknowns -", "Returns: A tuple of (1) a node and (2) a", "starargs = None starstarargs = None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t, False,", "InterpreterFunction.call() will take care of that. Args: node: The current", "return value.to_variable(node) def create_kwargs(self, node): key_type = self.convert.primitive_class_instances[str].to_variable(node) value_type =", "self.options.report_errors: return True views = abstract_utils.get_views([actual], node) # Check for", "for key in method.signature.kwonly_params: if use_defaults and key in method.kw_defaults:", "pytype.pytd import pytd from pytype.pytd import pytd_utils from pytype.pytd import", "if val in val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name)) return classes def", "to take parameter annotations into account as InterpreterFunction.call() will take", "node, abstract_utils.T, self.convert.create_new_unknown(node)) return value.to_variable(node) def create_kwargs(self, node): key_type =", "= None def create_varargs(self, node): value = abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter(", "ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info(\"=========== PyTD to solve =============\\n%s\", pytd_utils.Print(ast)) ast", "parameter annotations into account as InterpreterFunction.call() will take care of", "1 and not all(isinstance(o, abstract.FUNCTION_TYPES) for o in options)): #", "fvar, *args) return new_node, ret def call_function_in_frame(self, node, var, args,", "node, val, args): \"\"\"Call a function. Args: node: The given", "If a variable is annotated, we'll always output that type.", "view[actual].data.formal] if not bad: bad = self.matcher.bad_matches(actual, formal, node) if", "This means any additional errors that may be raised will", "self.join_cfg_nodes(nodes), instance def _instantiate_var(self, node, clsv, container): \"\"\"Build an (dummy)", "too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint =", "self.join_bindings(node, good_instances) for instance_value in instance.data: val.data.register_canonical_instance(instance_value) for name, methodvar", "None) for n, t in zip(arg_names, arg_types)) + tuple(pytd.Parameter(name, a.data.to_type(node),", "{} self._calls = set() self._method_calls = set() # Used by", "_instance_cache because we also call # __init__ on classes not", "self._instance_cache.get(key) if not instance or isinstance(instance, _Initializing): clsvar = cls.to_variable(node)", "{}).items()) record = CallRecord(node, func, sigs, args, kwargs, result) if", "when attempts to load from the protocols file if options.protocols:", "**kwargs) self._unknowns = {} self._calls = set() self._method_calls = set()", "ret.bindings: return node, ret else: node = node0 log.info(\"Unable to", "annotated_names or self._is_typing_member(name, var)): continue options = var.FilteredData(self.exitpoint, strict=False) if", "and not all(isinstance(o, abstract.FUNCTION_TYPES) for o in options)): # It's", "show_library_calls: log.info(\"Solving is turned off. Discarding call traces.\") # Rename", "its types. Args: src: A string containing Python source code.", "super().__init__(*args, **kwargs) self._unknowns = {} self._calls = set() self._method_calls =", "Python source return its types. Args: src: A string containing", "the main execution flow. init_maximum_depth: Depth of analysis during module", "= 2 # during quick checking QUICK_INFER_MAXIMUM_DEPTH = 1 #", "self.maybe_analyze_method(node1, val, cls) node2.ConnectTo(node0) return node0 def bind_method(self, node, name,", "need __init__ called, use cls.instantiate instead. Args: node: The current", "as InterpreterFunction.call() will take care of that. Args: node: The", "don't want # to re-analyze them. return (isinstance(data, abstract.InterpreterFunction) and", "for name, var in defs.items(): if (name in output.TOP_LEVEL_IGNORE or", "b in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2, args = self.create_method_arguments(node1, b.data) args", "need to record call signatures that don't involve # unknowns", "be # overwritten later. Note that we have to create", "cls=None): method = val.data fname = val.data.name if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES):", "= self._instantiate_var(node, clsvar, container) if key in self._instance_cache: # We've", "after this function call. func: A cfg.Binding of a function", "to use Unsolvable rather than Unknown objects for type-checking defaults.", "default_idx = i - num_posargs_no_default if use_defaults and default_idx >=", "import abstract from pytype import abstract_utils from pytype import convert_structural", "node. cls: The class to instantiate. container: Optionally, a container", "not in self._analyzed_functions and not _SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self, node, defs):", "= {} self._calls = set() self._method_calls = set() # Used", "# __init__ on classes not initialized via init_class. self._initialized_instances =", "show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs): \"\"\"Given Python source return its types.", "import pytd from pytype.pytd import pytd_utils from pytype.pytd import visitors", "= node0.ConnectNew(val.data.name) node2 = self.maybe_analyze_method(node1, val) node2.ConnectTo(node0) return node0 def", "val.data) good_instances = [b for b in instance.bindings if val.data", "encode it as a constant. combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t", "= self.bind_method( node, method_name, method, binding.AssignToNewVariable()) node = self.analyze_method_var(node, method_name,", "convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not show_library_calls: log.info(\"Solving is turned off.", "ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info(\"=========== PyTD to solve =============\\n%s\",", "by opcode rather than function object. The # two ways", "if isinstance(v, abstract.SimpleValue): v.maybe_missing_members = True for child in v.instance_type_parameters.values():", "(\"__new__\", \"__init__\") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._unknowns =", "object loader: A load_pytd.Loader instance to load PYI information. filename:", "logging.getLogger(__name__) # Most interpreter functions (including lambdas) need to be", "# This assumes that any inherited __new__ method defined in", "instance.bindings if val.data == b.data.cls] if not good_instances: # __new__", "the return value first, since bad_matches # expects not to", "return pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod def _call_traces_to_function(call_traces, name_transform=lambda x: x): funcs", "self.errorlog.bad_return_type( self.frames, node, formal, actual, bad) return not bad def", "= self.create_varargs(node) if method.has_varargs() else None starstarargs = self.create_kwargs(node) if", "for funcb in funcv.bindings: func = funcb.data log.info(\"Trying %s with", "node, self.new_unsolvable(node) def analyze_method_var(self, node0, name, var, cls=None): log.info(\"Analyzing %s\",", "in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\" not in ast: ast = pytd_utils.Concat(", "= {} self.exitpoint = None def create_varargs(self, node): value =", "True on these values and their type params. Args: values:", "definition except NotImplementedError: d = option.to_type(self.exitpoint) # Type only if", "mapping str to cfg.Value. result: A Variable of the possible", "the user wants checking, too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth", "to re-analyze them. return (isinstance(data, abstract.InterpreterFunction) and not data.is_overload and", "for a in args) ret = pytd_utils.JoinTypes(t.to_type(node) for t in", "during initialization. b = self.bind_method(node, name, methodvar, instance) node =", "0: arg_names[i] = function.argname(i) arg_types = (a.data.to_type(node) for a in", "bound_method = self.bind_method( node, method_name, method, binding.AssignToNewVariable()) node = self.analyze_method_var(node,", "type, a function or something # else, so encode it", "sig.annotations)): # fix \"cls\" parameter return args._replace( posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:])", "\"typing_extensions\"): if module_name not in self.loaded_overlays: continue module = self.loaded_overlays[module_name].get_module(name)", "parents=(pytd.NamedType(\"builtins.object\"),), # not used in solver methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(), decorators=(),", "collections.defaultdict(list) for call_record in self._method_calls: args = call_record.positional_arguments if not", "analyze(self, node, defs, maximum_depth): assert not self.frame self.maximum_depth = maximum_depth", "# This means any additional errors that may be raised", "call to %r with %d args, return %r\", func, len(posargs),", "are generated, try calling the function. # call_function will check", "funcv.bindings: func = funcb.data log.info(\"Trying %s with fake arguments\", func)", "node def reinitialize_if_initialized(self, node, instance): if instance in self._initialized_instances: self._call_init_on_binding(node,", "self._initialized_instances: continue self._initialized_instances.add(b.data) node = self._call_init_on_binding(node, b) return node def", "in f.bindings: if self._should_analyze_as_interpreter_function(value.data): node = self.analyze_function(node, value) return node", "We record analyzed functions by opcode rather than function object.", "= self.analyze_method_var(node, name, b, val) return node def analyze_function(self, node0,", "Dict[Any, Union[_Initializing, cfg.Variable]] = {} # Used by call_init. Can", "m = m.func.data[0] is_cls = True else: is_cls = (m.isinstance_InterpreterFunction()", "to solve =============\\n%s\", pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif", "that was called. sigs: The signatures that the function might", "values and their type params. Args: values: A list of", "positional arguments, an iterable over cfg.Value. namedargs: The keyword arguments,", "cfg.Variable]] = {} # Used by call_init. Can differ from", "= self.bind_method(node, name, methodvar, instance) node = self.analyze_method_var(node, name, b,", "- otherwise, setting # maybe_missing_members to True would cause pytype", "name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), # not used in solver methods=tuple(self._call_traces_to_function(call_records)), constants=(),", "v.instance_type_parameters.values(): values.extend(child.data) def init_class(self, node, cls, container=None, extra_key=None): \"\"\"Instantiate a", "from pytype import debug from pytype import function from pytype", "pytype import abstract_utils from pytype import convert_structural from pytype import", "self.new_unsolvable(node) def analyze_method_var(self, node0, name, var, cls=None): log.info(\"Analyzing %s\", name)", "if cls.module else cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), # not", "import vm from pytype.overlays import typing_overlay from pytype.pytd import builtins", "container): \"\"\"Build an (dummy) instance from a class, for analyzing", "in annotated_names or self._is_typing_member(name, var)): continue options = var.FilteredData(self.exitpoint, strict=False)", "and self.frame.current_opcode, extra_key, cls) instance = self._instance_cache.get(key) if not instance", "return ast, builtins_pytd def _maybe_output_debug(options, program): \"\"\"Maybe emit debugging output.\"\"\"", "self._is_typing_member(name, var): for value in var.bindings: if isinstance(value.data, abstract.InterpreterClass): new_node", "any inherited __new__ method defined in a pyi file #", "elif options.analyze_annotated: # Since there's no point in analyzing annotated", "= set() self._method_calls = set() # Used by init_class. self._instance_cache:", "tracer.has_unknown_wildcard_imports or any( a in defs for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS):", "= 1 # during quick inference class _Initializing: pass class", "return node0 def _should_analyze_as_interpreter_function(self, data): # We record analyzed functions", "Python code.\"\"\" tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader, **kwargs) loc,", "self.create_method_arguments(node1, b.data) args = self._maybe_fix_classmethod_cls_arg(node0, cls, b.data, args) node3 =", "for value in f.bindings: if self._should_analyze_as_interpreter_function(value.data): node = self.analyze_function(node, value)", "analyze_class(self, node, val): self._analyzed_classes.add(val.data) node, instance = self.init_class(node, val.data) good_instances", "don't need to take parameter annotations into account as InterpreterFunction.call()", "analyze this function as part of a class. log.info(\"Analyze functions:", "rather than function object. The # two ways of recording", "arguments for %s\", funcv) return node, self.new_unsolvable(node) def analyze_method_var(self, node0,", "classes = [] for cls, call_records in class_to_records.items(): full_name =", "val.AssignToNewVariable(node) with val.data.record_calls(): new_node, ret = self.call_function_in_frame(node, fvar, *args) return", "account as InterpreterFunction.call() will take care of that. Args: node:", "reinitialize_if_initialized(self, node, instance): if instance in self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node)) def", "= tracer.loader.import_name(\"protocols\") else: protocols_pytd = None builtins_pytd = tracer.loader.concat_all() #", "fname) else: for f in method.iter_signature_functions(): node, args = self.create_method_arguments(node,", "bad) return not bad def check_types(src, filename, errorlog, options, loader,", "whether this is a type, a function or something #", "don't need. instance = self.join_bindings(node, good_instances) for instance_value in instance.data:", "= self.analyze_function(node, value) else: continue if new_node is not node:", "in output.TOP_LEVEL_IGNORE or name in annotated_names or self._is_typing_member(name, var)): continue", "return node def call_init(self, node, instance): # Call __init__ on", "initalizers the class has registered. for method in cls.additional_init_methods: node", "method.kw_defaults[key] else: kws[key] = self.convert.create_new_unknown(node, force=not use_defaults) starargs = self.create_varargs(node)", "method.argcount(node) num_posargs_no_default = num_posargs - len(method.defaults) for i in range(num_posargs):", "name, var): for module_name in (\"typing\", \"typing_extensions\"): if module_name not", "Needs to be set before analyze_types. \"\"\" _CONSTRUCTORS = (\"__new__\",", "to True on the instance and its type parameters. \"\"\"", "them. return (isinstance(data, abstract.InterpreterFunction) and not data.is_overload and not data.is_class_builder", "call_traces: # The lengths may be different in the presence", "errors. To prevent an infinite recursion loop, set # fallback_to_unsolvable", "or {}).items()) record = CallRecord(node, func, sigs, args, kwargs, result)", "not options.quick: maximum_depth = MAXIMUM_DEPTH elif options.analyze_annotated: # Since there's", "= tuple(self.pytd_functions_for_call_traces()) aliases = () # aliases are instead recorded", "\"\"\"Set maybe_missing_members to True on these values and their type", "new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2, args = self.create_method_arguments(node1, b.data) args = self._maybe_fix_classmethod_cls_arg(node0,", "not to get any. bad = [view for view in", "node0.ConnectNew(name) for val in var.bindings: node2 = self.maybe_analyze_method(node1, val, cls)", "= 4 # during module loading MAXIMUM_DEPTH = 3 #", "= collections.defaultdict(list) for call_record in self._method_calls: args = call_record.positional_arguments if", "cls.additional_init_methods: node = self._call_method(node, b, method) return node def call_init(self,", "self._instance_cache: Dict[Any, Union[_Initializing, cfg.Variable]] = {} # Used by call_init.", "svg_file], stdin=subprocess.PIPE, universal_newlines=True) (_, stderr) = proc.communicate(dot) if stderr: log.info(\"Failed", "pass to vm.VirtualMachine Returns: A tuple of (ast: TypeDeclUnit, builtins:", "params. Args: values: A list of BaseValue objects. On every", "def create_varargs(self, node): value = abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter( node, abstract_utils.T,", "= self._call_method(node, b, \"__init__\") cls = b.data.get_class() if isinstance(cls, abstract.InterpreterClass):", "we also call # __init__ on classes not initialized via", "case. # This means any additional errors that may be", "node0, val): if val.data.is_attribute_of_class: # We'll analyze this function as", "node3 = node2.ConnectNew() node4, ret = self.call_function_with_args(node3, b, args) instance.PasteVariable(ret)", "call # __init__ on classes not initialized via init_class. self._initialized_instances", "visitors from pytype.typegraph import cfg log = logging.getLogger(__name__) # Most", "instance): # Call __init__ on each binding. for b in", "kws[key] = self.convert.create_new_unknown(node, force=not use_defaults) starargs = self.create_varargs(node) if method.has_varargs()", "# If a variable is annotated, we'll always output that", "continue options = var.FilteredData(self.exitpoint, strict=False) if (len(options) > 1 and", "through all functions and classes we haven't analyzed yet. #", "even the ones not called by the main execution flow.", "= MAXIMUM_DEPTH elif options.analyze_annotated: # Since there's no point in", "just in case. # This means any additional errors that", "fallback_to_unsolvable if a DictKeyMissing or # FailedFunctionCall error is raised", "if use_defaults and default_idx >= 0: arg = method.defaults[default_idx] else:", "a class, and also call __init__. Calling __init__ can be", "b): if isinstance(b.data, abstract.SimpleValue): for param in b.data.instance_type_parameters.values(): node =", "for v in var.data]) state = frame_state.FrameState.init(node, self) state, ret", "f) if f.is_classmethod and cls: args = self._maybe_fix_classmethod_cls_arg(node, cls, f,", "or options.output_typegraph: dot = debug.program_to_dot(program, set([]), bool(options.output_cfg)) svg_file = options.output_cfg", "f.is_classmethod and cls: args = self._maybe_fix_classmethod_cls_arg(node, cls, f, args) node,", "if new_node is not node: new_node.ConnectTo(node) # Now go through", "# during non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH = 2 # during quick", "instance def _instantiate_var(self, node, clsv, container): \"\"\"Build an (dummy) instance", "in module.members and module.members[name].data == var.data: return True return False", "DictKeyMissing or # FailedFunctionCall error is raised when the target", "container's template are instantiated to TypeParameterInstance. extra_key: Optionally, extra information", "caches its created instances. If you don't need __init__ called,", "key_type = self.convert.primitive_class_instances[str].to_variable(node) value_type = self.convert.create_new_unknown(node) kwargs = abstract.Instance(self.convert.dict_type, self)", "a class binding.\"\"\" node1, new = cls.data.get_own_new(node0, cls) if not", "node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node, defs) def trace_unknown(self, name, unknown_binding): self._unknowns[name] =", "infinite recursion loop, set # fallback_to_unsolvable to False just in", "and generators, which # have names like \"<listcomp>\" and \"<genexpr>\".", "pytype.pytd import escape from pytype.pytd import optimize from pytype.pytd import", "num_posargs = method.argcount(node) num_posargs_no_default = num_posargs - len(method.defaults) for i", "_Initializing): clsvar = cls.to_variable(node) node, instance = self._instantiate_var(node, clsvar, container)", "d = option.to_pytd_def(self.exitpoint, name) # Deep definition except NotImplementedError: d", "= self.join_cfg_nodes(nodes) if ret.bindings: return node, ret else: node =", "analysis. Default: unlimited. tracer_vm: An instance of CallTracer, in case", "def pytd_classes_for_unknowns(self): classes = [] for name, val in self._unknowns.items():", "A load_pytd.Loader instance to load PYI information. filename: Filename of", "from pytype import vm from pytype.overlays import typing_overlay from pytype.pytd", "\"A\"): ... # Calling __init__ again would lead to an", "pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not show_library_calls: log.info(\"Solving", "log = logging.getLogger(__name__) # Most interpreter functions (including lambdas) need", "need to take parameter annotations into account as InterpreterFunction.call() will", "Any, Dict, Union from pytype import abstract from pytype import", "use_defaults and default_idx >= 0: arg = method.defaults[default_idx] else: arg", "cfg.Value. result: A Variable of the possible result values. \"\"\"", "called this method in the first place. node2, ret =", "It's ambiguous whether this is a type, a function or", "the container's template are instantiated to TypeParameterInstance. extra_key: Optionally, extra", "that records all function calls. Attributes: exitpoint: A CFG node", "value.data.is_overload): new_node = self.analyze_function(node, value) else: continue if new_node is", "val, cls=None): method = val.data fname = val.data.name if isinstance(method,", "method.defaults[default_idx] else: arg = self.convert.create_new_unknown(node, force=not use_defaults) args.append(arg) kws =", "unknown_binding def trace_call(self, node, func, sigs, posargs, namedargs, result): \"\"\"Add", "in options) data.append(pytd.Constant(name, combined_types)) elif options: for option in options:", "return True return False def pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls, escape.pack_partial) def", "loc, defs = tracer.run_program(src, filename, init_maximum_depth) log.info(\"===Done running definitions and", "abstract.InterpreterClass): new_node = self.analyze_class(node, value) elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and not", "pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast() for v in self._generated_classes.values()) def compute_types(self, defs):", "tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or any( a in defs for a", "filename, init_maximum_depth) log.info(\"===Done running definitions and module-level code===\") snapshotter =", "Whether to use parameter defaults for arguments. When True, unknown", "node2.ConnectTo(node0) return node0 def _should_analyze_as_interpreter_function(self, data): # We record analyzed", "method) return node def call_init(self, node, instance): # Call __init__", "not used in solver methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(), decorators=(), slots=None, template=(),", "it's fine to # overwrite previous instances. self._generated_classes[nt.name] = nt", "tracer.run_program(src, filename, init_maximum_depth) log.info(\"===Done running definitions and module-level code===\") snapshotter", "full_name = cls.module + \".\" + cls.name if cls.module else", "name, methodvar in sorted(val.data.members.items()): if name in self._CONSTRUCTORS: continue #", "TypeDeclUnit, builtins: TypeDeclUnit) Raises: AssertionError: In case of a bad", "self._call_method(node, b, method) return node def call_init(self, node, instance): #", "if not self.options.report_errors: return True views = abstract_utils.get_views([actual], node) #", "right after this function call. func: A cfg.Binding of a", "for b in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2, args = self.create_method_arguments(node1, b.data)", "container): \"\"\"Instantiate a class binding.\"\"\" node1, new = cls.data.get_own_new(node0, cls)", "_SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\") CallRecord = collections.namedtuple( \"CallRecord\", [\"node\", \"function\", \"signatures\",", "objects for type-checking defaults. Returns: A tuple of a node", "not in ast: ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If", "- len(method.defaults) for i in range(num_posargs): default_idx = i -", "# stand-alone functions. The exceptions are comprehensions and generators, which", "1)[-1] not in self._CONSTRUCTORS): log.info(\"%r has annotations, not analyzing further.\",", "A function.Args object. Returns: A tuple of (1) a node", "use parameter defaults for arguments. When True, unknown arguments are", "= [] for name, val in self._unknowns.items(): if val in", "instantion occurs. By default, this method keys on the current", "opcode and the class, which sometimes isn't enough to disambiguate", "def create_method_arguments(self, node, method, use_defaults=False): \"\"\"Create arguments for the given", "= self.program.NewVariable() for m in methodvar.Data(node): if isinstance(m, special_builtins.ClassMethodInstance): m", "abstract.Empty): d = pytd.AnythingType() else: assert isinstance(option, typing_overlay.NoReturn) if isinstance(d,", "collections.namedtuple( \"CallRecord\", [\"node\", \"function\", \"signatures\", \"positional_arguments\", \"keyword_arguments\", \"return_value\"]) # How", "Args: node: The current node. cls: The class to instantiate.", "proc = subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\", \"-o\", svg_file], stdin=subprocess.PIPE, universal_newlines=True) (_,", "the given method. Creates Unknown objects as arguments for the", "args, fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret) if nodes: ret = self.join_variables(node0, rets)", "state.node, ret def _maybe_fix_classmethod_cls_arg(self, node, cls, func, args): sig =", "method_name, binding) if method: bound_method = self.bind_method( node, method_name, method,", "bound def _instantiate_binding(self, node0, cls, container): \"\"\"Instantiate a class binding.\"\"\"", "Filename of the program we're parsing. deep: If True, analyze", "already in # the process of initializing - otherwise, setting", "Deep definition except NotImplementedError: d = option.to_type(self.exitpoint) # Type only", "in var.data]) state = frame_state.FrameState.init(node, self) state, ret = self.call_function_with_state(", "for typevars in the return value first, since bad_matches #", "into account as InterpreterFunction.call() will take care of that. Args:", "so this method caches its created instances. If you don't", "return node def reinitialize_if_initialized(self, node, instance): if instance in self._initialized_instances:", "self.call_init(node, instance) elif len(good_instances) != len(instance.bindings): # __new__ returned some", "not called by the main execution flow. init_maximum_depth: Depth of", "which sometimes isn't enough to disambiguate callers that shouldn't get", "code. errorlog: Where error messages go. Instance of errors.ErrorLog. options:", "node = self._call_method(node, b, \"__init__\") cls = b.data.get_class() if isinstance(cls,", "abstract.SimpleValue): for param in b.data.instance_type_parameters.values(): node = self.call_init(node, param) node", "called. sigs: The signatures that the function might have been", "class CallTracer(vm.VirtualMachine): \"\"\"Virtual machine that records all function calls. Attributes:", "[] for cls, call_records in class_to_records.items(): full_name = cls.module +", "variables they close over change, but we don't want #", "config.Options object loader: A load_pytd.Loader instance to load PYI information.", "Returns: A tuple of a node and a function.Args object.", "and retain the vm used for type inference. **kwargs: Additional", "force=not use_defaults) args.append(arg) kws = {} for key in method.signature.kwonly_params:", "will # be set for all functions in class. for", "function object. The # two ways of recording are equivalent", "we have to create a new # instance rather than", "new # instance rather than using the one that we're", "for b in instance.bindings: if b.data in self._initialized_instances: continue self._initialized_instances.add(b.data)", "cls, container) n.PasteVariable(var) return node, n def _mark_maybe_missing_members(self, values): \"\"\"Set", "\"-T\", \"svg\", \"-o\", svg_file], stdin=subprocess.PIPE, universal_newlines=True) (_, stderr) = proc.communicate(dot)", "in funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD)) return functions def _is_typing_member(self, name,", "strict=False) if (len(options) > 1 and not all(isinstance(o, abstract.FUNCTION_TYPES) for", "the location at which the instantion occurs. By default, this", "method_name, bound_method) return node def _call_init_on_binding(self, node, b): if isinstance(b.data,", "# sort, for determinicity if not self._is_typing_member(name, var): for value", "return node, n def _mark_maybe_missing_members(self, values): \"\"\"Set maybe_missing_members to True", "checking and inferring types.\"\"\" import collections import logging import re", "funcb.data log.info(\"Trying %s with fake arguments\", func) if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES):", "\"\"\"Call a function. Args: node: The given node. val: A", "that we're already in # the process of initializing -", "template=(), )) return classes def pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast() for v", "assert isinstance(option, typing_overlay.NoReturn) if isinstance(d, pytd.Type) and not isinstance(d, pytd.TypeParameter):", "abstract.InterpreterFunction. use_defaults: Whether to use parameter defaults for arguments. When", "# Call __init__ on each binding. for b in instance.bindings:", "value.data not in self._analyzed_classes): node = self.analyze_class(node, value) for f", "inherited __new__ method defined in a pyi file # returns", "loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs): \"\"\"Given Python", "made-up arguments.\"\"\" # TODO(tsudol): If expand this beyond __init__, need", "= self.create_method_arguments(node0, func) # Once the args are generated, try", "= self._maybe_fix_classmethod_cls_arg(node, cls, f, args) node, _ = self.call_function_with_args(node, val,", "self._maybe_fix_classmethod_cls_arg(node0, cls, b.data, args) node3 = node2.ConnectNew() node4, ret =", "tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint = loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast =", "starargs, starstarargs) self.pop_frame(frame) return state.node, ret def _maybe_fix_classmethod_cls_arg(self, node, cls,", "the vm used for type inference. **kwargs: Additional parameters to", "tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader, **kwargs) loc, defs =", "name) data.append(pytd.Constant(name, pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod def _call_traces_to_function(call_traces, name_transform=lambda", "value.to_variable(node) def create_kwargs(self, node): key_type = self.convert.primitive_class_instances[str].to_variable(node) value_type = self.convert.create_new_unknown(node)", "a container to pass to the class's instantiate() method, so", "else: node1 = node0.ConnectNew(val.data.name) node2 = self.maybe_analyze_method(node1, val) node2.ConnectTo(node0) return", "isinstance(cls, abstract.InterpreterClass): # Call any additional initalizers the class has", "return False def pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls, escape.pack_partial) def pytd_classes_for_call_traces(self): class_to_records", "i > 0: arg_names[i] = function.argname(i) arg_types = (a.data.to_type(node) for", "annotations into account as InterpreterFunction.call() will take care of that.", "init_class. self._instance_cache: Dict[Any, Union[_Initializing, cfg.Variable]] = {} # Used by", "a pyi file # returns an instance of the current", "create a new # instance rather than using the one", "debug.program_to_text(program) if options.output_debug == \"-\": log.info(\"=========== Program Dump =============\\n%s\", text)", "\"\"\"Instantiate a class binding.\"\"\" node1, new = cls.data.get_own_new(node0, cls) if", "= self._call_init_on_binding(node, b) return node def reinitialize_if_initialized(self, node, instance): if", "re-generated when the variables they close over change, but we", "node def _call_with_fake_args(self, node0, funcv): \"\"\"Attempt to call the given", "rets = [] for funcb in funcv.bindings: func = funcb.data", "return node, function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs, starstarargs=starstarargs) def call_function_with_args(self, node, val,", "arg_types)) + tuple(pytd.Parameter(name, a.data.to_type(node), False, False, None) for name, a", "of a node and a function.Args object. \"\"\" args =", "def trace_classdef(self, c): self._interpreter_classes.append(c) def trace_namedtuple(self, nt): # All namedtuple", "pytype.overlays import typing_overlay from pytype.pytd import builtins from pytype.pytd import", "in sorted(val.data.members.items()): if name in self._CONSTRUCTORS: continue # We already", "def _should_analyze_as_interpreter_function(self, data): # We record analyzed functions by opcode", "any additional initalizers the class has registered. for method in", "via init_class. self._initialized_instances = set() self._interpreter_functions = [] self._interpreter_classes =", "a node and a function.Args object. \"\"\" args = []", "exceptions=(), template=())) functions = [] for name, signatures in funcs.items():", "place. node2, ret = self.call_function(node1, funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret)", "objects. On every instance among the values, recursively set maybe_missing_members", "something that's not an instance of our class. instance =", "not instance or isinstance(instance, _Initializing): clsvar = cls.to_variable(node) node, instance", "__init__. self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key] = _Initializing() node = self.call_init(node, instance)", "INIT_MAXIMUM_DEPTH = 4 # during module loading MAXIMUM_DEPTH = 3", "new_node, ret def call_function_in_frame(self, node, var, args, kwargs, starargs, starstarargs):", "keys on the current opcode and the class, which sometimes", "def trace_unknown(self, name, unknown_binding): self._unknowns[name] = unknown_binding def trace_call(self, node,", "import metrics from pytype import output from pytype import special_builtins", "def _maybe_fix_classmethod_cls_arg(self, node, cls, func, args): sig = func.signature if", "options: try: d = option.to_pytd_def(self.exitpoint, name) # Deep definition except", "return args def maybe_analyze_method(self, node, val, cls=None): method = val.data", "Args: node: The CFG node right after this function call.", "bound_method) return node def _call_init_on_binding(self, node, b): if isinstance(b.data, abstract.SimpleValue):", "# the call_function that called this method in the first", "if not options.quick: maximum_depth = MAXIMUM_DEPTH elif options.analyze_annotated: # Since", "sig.param_names and (sig.param_names[0] not in sig.annotations)): # fix \"cls\" parameter", "trace_functiondef(self, f): self._interpreter_functions.append(f) def trace_classdef(self, c): self._interpreter_classes.append(c) def trace_namedtuple(self, nt):", "in method.iter_signature_functions(): node, args = self.create_method_arguments(node, f) if f.is_classmethod and", "True on the instance and its type parameters. \"\"\" values", "closures, which are # re-generated when the variables they close", "pytd.MethodTypes.METHOD)) return functions def _is_typing_member(self, name, var): for module_name in", "classes=(), decorators=(), slots=None, template=(), )) return classes def pytd_classes_for_namedtuple_instances(self): return", "args, kwargs, starargs, starstarargs) self.pop_frame(frame) return state.node, ret def _maybe_fix_classmethod_cls_arg(self,", "QUICK_CHECK_MAXIMUM_DEPTH if options.quick else MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options,", "Call __init__ on each binding. for b in instance.bindings: if", "def call_function_in_frame(self, node, var, args, kwargs, starargs, starstarargs): frame =", "log.debug(\"Logging call to %r with %d args, return %r\", func,", "self) kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type) return kwargs.to_variable(node) def", "the presence of optional and kw args. arg_names = max((sig.get_positional_names()", "hidden under a decorator. # Go through classes first so", "Insert type parameters, where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols:", "function. args: A function.Args object. Returns: A tuple of (1)", "name) node1 = node0.ConnectNew(name) for val in var.bindings: node2 =", "types. Args: src: A string containing Python source code. errorlog:", "= tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint = loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast", "= debug.program_to_dot(program, set([]), bool(options.output_cfg)) svg_file = options.output_cfg or options.output_typegraph proc", "self.pytd_classes_for_namedtuple_instances()) functions = tuple(self.pytd_functions_for_call_traces()) aliases = () # aliases are", "this function as part of a class. log.info(\"Analyze functions: Skipping", "a function or something # else, so encode it as", "def _mark_maybe_missing_members(self, values): \"\"\"Set maybe_missing_members to True on these values", "sigs), key=len) for i in range(len(arg_names)): if not isinstance(func.data, abstract.BoundFunction)", "class to instantiate. container: Optionally, a container to pass to", "= [] pytd_convert = self.convert.pytd_convert annots = abstract_utils.get_annotations_dict(defs) for name,", "sigs: The signatures that the function might have been called", "init_maximum_depth) log.info(\"===Done running definitions and module-level code===\") snapshotter = metrics.get_metric(\"memory\",", "in kws), starargs, starstarargs, ret, exceptions=(), template=())) functions = []", "maximum_depth) else: tracer.exitpoint = loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast = tracer.compute_types(defs) ast", "and cls: args = self._maybe_fix_classmethod_cls_arg(node, cls, f, args) node, _", "Call any additional initalizers the class has registered. for method", "differ from _instance_cache because we also call # __init__ on", "value in c.bindings: if (isinstance(value.data, abstract.InterpreterClass) and value.data not in", "in args): # We don't need to record call signatures", "MAXIMUM_DEPTH = 3 # during non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH = 2", "tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances()) functions = tuple(self.pytd_functions_for_call_traces()) aliases = () #", "new_node, ret = self.call_function_in_frame(node, fvar, *args) return new_node, ret def", "from pytype import metrics from pytype import output from pytype", "None) for name, a in kws), starargs, starstarargs, ret, exceptions=(),", "we don't need to take parameter annotations into account as", "A tuple of (ast: TypeDeclUnit, builtins: TypeDeclUnit) Raises: AssertionError: In", "ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or any( a in defs", "# Check for typevars in the return value first, since", "in clsv.Bindings(node, strict=False): node, var = self._instantiate_binding(node, cls, container) n.PasteVariable(var)", "isn't enough to disambiguate callers that shouldn't get back the", "maximum_depth=None, tracer_vm=None, **kwargs): \"\"\"Given Python source return its types. Args:", "created instances. If you don't need __init__ called, use cls.instantiate", "starstarargs): frame = frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing %r\", [v.name for v", "= node2.ConnectNew() node4, ret = self.call_function_with_args(node3, b, args) instance.PasteVariable(ret) nodes.append(node4)", "that type parameters in the container's template are instantiated to", "None: maximum_depth = ( QUICK_CHECK_MAXIMUM_DEPTH if options.quick else MAXIMUM_DEPTH) tracer.analyze(loc,", "instance from a class, for analyzing it.\"\"\" n = self.program.NewVariable()", "FailedFunctionCall errors. To prevent an infinite recursion loop, set #", "pytd_for_types(self, defs): # If a variable is annotated, we'll always", "abstract_utils.get_annotations_dict(defs) for name, t in pytd_convert.annotations_to_instance_types( self.exitpoint, annots): annotated_names.add(name) data.append(pytd.Constant(name,", "errors.ErrorLog. options: config.Options object loader: A load_pytd.Loader instance to load", "node = self.call_init(node, instance) self._instance_cache[key] = instance return node, instance", "num_posargs - len(method.defaults) for i in range(num_posargs): default_idx = i", "maybe_missing_members to True would cause pytype to ignore # all", "= self.call_init(node, instance) self._instance_cache[key] = instance return node, instance def", "the function might have been called with. posargs: The positional", "def pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast() for v in self._generated_classes.values()) def compute_types(self,", "instantiate. container: Optionally, a container to pass to the class's", "bind_method(self, node, name, methodvar, instance_var): bound = self.program.NewVariable() for m", "inference class _Initializing: pass class CallTracer(vm.VirtualMachine): \"\"\"Virtual machine that records", "= self.convert.create_new_unknown(node) kwargs = abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node,", "continue module = self.loaded_overlays[module_name].get_module(name) if name in module.members and module.members[name].data", "in self._initialized_instances: continue self._initialized_instances.add(b.data) node = self._call_init_on_binding(node, b) return node", "as it is fine to use Unsolvable rather than Unknown", "self.join_variables(node0, rets) node = self.join_cfg_nodes(nodes) if ret.bindings: return node, ret", "this is a type, a function or something # else,", "var.bindings: node2 = self.maybe_analyze_method(node1, val, cls) node2.ConnectTo(node0) return node0 def", "maximum_depth: Depth of the analysis. Default: unlimited. tracer_vm: An instance", "o in options)): # It's ambiguous whether this is a", "nt): # All namedtuple instances with the same name are", "Optionally, extra information about the location at which the instantion", "from a class, for analyzing it.\"\"\" n = self.program.NewVariable() for", "every instance among the values, recursively set maybe_missing_members to True", "using the one that we're already in # the process", "function call. func: A cfg.Binding of a function that was", "presence of optional and kw args. arg_names = max((sig.get_positional_names() for", "the class has registered. for method in cls.additional_init_methods: node =", "cached instance. Returns: A tuple of node and instance variable.", "has registered. for method in cls.additional_init_methods: node = self._call_method(node, b,", "name, var in defs.items(): if (name in output.TOP_LEVEL_IGNORE or name", "method.iter_signature_functions(): node, args = self.create_method_arguments(node, f) if f.is_classmethod and cls:", "ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self, node, actual, formal): if not self.options.report_errors: return", "compute_types(self, defs): classes = (tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances()) functions", "as # stand-alone functions. The exceptions are comprehensions and generators,", "and not data.is_class_builder and data.get_first_opcode() not in self._analyzed_functions and not", "create_varargs(self, node): value = abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter( node, abstract_utils.T, self.convert.create_new_unknown(node))", "= QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc, defs,", "self._instantiate_var(node, clsvar, container) if key in self._instance_cache: # We've encountered", "def analyze_function(self, node0, val): if val.data.is_attribute_of_class: # We'll analyze this", "= self.maybe_analyze_method(node1, val) node2.ConnectTo(node0) return node0 def _should_analyze_as_interpreter_function(self, data): #", "f): self._interpreter_functions.append(f) def trace_classdef(self, c): self._interpreter_classes.append(c) def trace_namedtuple(self, nt): #", "m.func.data[0] is_cls = True else: is_cls = (m.isinstance_InterpreterFunction() and m.is_classmethod)", "classes def pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast() for v in self._generated_classes.values()) def", "val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name)) return classes def pytd_for_types(self, defs): #", "if instance in self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node)) def analyze_class(self, node, val):", "b) return node def reinitialize_if_initialized(self, node, instance): if instance in", "when the target function is called. # DictKeyMissing doesn't trigger", "the instance and its type parameters. \"\"\" values = list(values)", "views = abstract_utils.get_views([actual], node) # Check for typevars in the", "val in var.bindings: node2 = self.maybe_analyze_method(node1, val, cls) node2.ConnectTo(node0) return", "create %s: %s\", svg_file, stderr) if options.output_debug: text = debug.program_to_text(program)", "__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._unknowns = {} self._calls =", "func.signature if (args.posargs and sig.param_names and (sig.param_names[0] not in sig.annotations)):", "abstract.INTERPRETER_FUNCTION_TYPES): node1, args = self.create_method_arguments(node0, func) # Once the args", "to create %s: %s\", svg_file, stderr) if options.output_debug: text =", "return its types. Args: src: A string containing Python source", "call_function_in_frame(self, node, var, args, kwargs, starargs, starstarargs): frame = frame_state.SimpleFrame(node=node)", "this option means that the user wants checking, too. maximum_depth", "have to create a new # instance rather than using", "n.PasteVariable(var) return node, n def _mark_maybe_missing_members(self, values): \"\"\"Set maybe_missing_members to", "node, binding.data.get_class(), method_name, binding) if method: bound_method = self.bind_method( node,", "= {} for key in method.signature.kwonly_params: if use_defaults and key", "generate_unknowns=False, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) snapshotter", "good_instances) for instance_value in instance.data: val.data.register_canonical_instance(instance_value) for name, methodvar in", "for closures, which are # re-generated when the variables they", "pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions, aliases=aliases)) ty = ty.Visit(optimize.CombineReturnsAndExceptions()) ty = ty.Visit(optimize.PullInMethodClasses())", "we're already in # the process of initializing - otherwise,", "haven't analyzed yet. # These are typically hidden under a", "flow. init_maximum_depth: Depth of analysis during module loading. show_library_calls: If", "Remove \"~list\" etc.: ast = convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return ast,", "= val.data.name if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if (not self.options.analyze_annotated and", "b.data.cls] if not good_instances: # __new__ returned something that's not", "import cfg log = logging.getLogger(__name__) # Most interpreter functions (including", "the program exit. Needs to be set before analyze_types. \"\"\"", "if use_defaults and key in method.kw_defaults: kws[key] = method.kw_defaults[key] else:", "ignore # all attribute errors on self in __init__. self._mark_maybe_missing_members(instance.data)", "filename, errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): \"\"\"Verify the", "use_defaults) args.append(arg) kws = {} for key in method.signature.kwonly_params: if", "# TODO(tsudol): If expand this beyond __init__, need to handle", "ty = ty.Visit(optimize.PullInMethodClasses()) ty = ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()], escape.UNKNOWN)) return", "str to cfg.Value. result: A Variable of the possible result", "all functions, even the ones not called by the main", "kws), starargs, starstarargs, ret, exceptions=(), template=())) functions = [] for", "analyzing it.\"\"\" n = self.program.NewVariable() for cls in clsv.Bindings(node, strict=False):", "trace. Args: node: The CFG node right after this function", "%d args, return %r\", func, len(posargs), result) args = tuple(posargs)", "import escape from pytype.pytd import optimize from pytype.pytd import pytd", "options.output_cfg or options.output_typegraph proc = subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\", \"-o\", svg_file],", "else MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program) def infer_types(src,", "frame = frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing %r\", [v.name for v in", "constants ty = pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions, aliases=aliases)) ty", "bound = self.program.NewVariable() for m in methodvar.Data(node): if isinstance(m, special_builtins.ClassMethodInstance):", "posargs, namedargs, result): \"\"\"Add an entry into the call trace.", "node, args = self.create_method_arguments(node, f) if f.is_classmethod and cls: args", "self._analyzed_classes.add(val.data) node, instance = self.init_class(node, val.data) good_instances = [b for", "ret def call_function_in_frame(self, node, var, args, kwargs, starargs, starstarargs): frame", "QUICK_CHECK_MAXIMUM_DEPTH = 2 # during quick checking QUICK_INFER_MAXIMUM_DEPTH = 1", "a new # instance rather than using the one that", "is None: maximum_depth = ( QUICK_CHECK_MAXIMUM_DEPTH if options.quick else MAXIMUM_DEPTH)", "ValueError: Unresolved class # when attempts to load from the", "collections import logging import re import subprocess from typing import", "in class. for c in self._interpreter_classes: for value in c.bindings:", "to True on these values and their type params. Args:", "var): for module_name in (\"typing\", \"typing_extensions\"): if module_name not in", "key = (self.frame and self.frame.current_opcode, extra_key, cls) instance = self._instance_cache.get(key)", "if (len(options) > 1 and not all(isinstance(o, abstract.FUNCTION_TYPES) for o", "given function with made-up arguments.\"\"\" # TODO(tsudol): If expand this", "while values: v = values.pop(0) if v not in seen:", "abstract.InterpreterClass) and value.data not in self._analyzed_classes): node = self.analyze_class(node, value)", "annotated functions for inference, # the presence of this option", "kws[key] = method.kw_defaults[key] else: kws[key] = self.convert.create_new_unknown(node, force=not use_defaults) starargs", "checking QUICK_INFER_MAXIMUM_DEPTH = 1 # during quick inference class _Initializing:", "args._replace( posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:]) else: return args def maybe_analyze_method(self, node,", "again would lead to an infinite loop, so # we", "tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint = loc snapshotter.take_snapshot(\"analyze:infer_types:post\")", "init_class(self, node, cls, container=None, extra_key=None): \"\"\"Instantiate a class, and also", "signatures in funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD)) return functions def _is_typing_member(self,", "calls. Attributes: exitpoint: A CFG node representing the program exit.", "If expand this beyond __init__, need to handle # DictKeyMissing", "the variables they close over change, but we don't want", "record = CallRecord(node, func, sigs, args, kwargs, result) if isinstance(func.data,", "for all functions in class. for c in self._interpreter_classes: for", "a in defs for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\" not", "value. \"\"\" fvar = val.AssignToNewVariable(node) with val.data.record_calls(): new_node, ret =", "These are typically hidden under a decorator. # Go through", "in defs.items(): if (name in output.TOP_LEVEL_IGNORE or name in annotated_names", "methodvar in sorted(val.data.members.items()): if name in self._CONSTRUCTORS: continue # We", "debug from pytype import function from pytype import metrics from", "option means that the user wants checking, too. maximum_depth =", "containing Python source code. errorlog: Where error messages go. Instance", "cls.instantiate instead. Args: node: The current node. cls: The class", "Discarding call traces.\") # Rename remaining \"~unknown\" to \"?\" ast", "from pytype.typegraph import cfg log = logging.getLogger(__name__) # Most interpreter", "self._generated_classes[nt.name] = nt def pytd_classes_for_unknowns(self): classes = [] for name,", "assert isinstance(tracer_vm, CallTracer) tracer = tracer_vm else: tracer = CallTracer(errorlog=errorlog,", "for cls, call_records in class_to_records.items(): full_name = cls.module + \".\"", "and m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls), [], node) return bound def _instantiate_binding(self,", "this method keys on the current opcode and the class,", "data = [] pytd_convert = self.convert.pytd_convert annots = abstract_utils.get_annotations_dict(defs) for", "in sigs), key=len) for i in range(len(arg_names)): if not isinstance(func.data,", "data.append(pytd.Constant(name, d)) else: data.append(d) else: log.error(\"No visible options for %s\",", "for child in v.instance_type_parameters.values(): values.extend(child.data) def init_class(self, node, cls, container=None,", "generating fake arguments should avoid any # FailedFunctionCall errors. To", "name, methodvar, instance) node = self.analyze_method_var(node, name, b, val) return", "errorlog: Where error messages go. Instance of errors.ErrorLog. options: config.Options", "# instance rather than using the one that we're already", "the one that we're already in # the process of", "in self._analyzed_classes): node = self.analyze_class(node, value) for f in self._interpreter_functions:", "self.analyze_function(node, value) return node def analyze(self, node, defs, maximum_depth): assert", "function is called. # DictKeyMissing doesn't trigger call_with_fake_args, so that", "starstarargs = self.create_kwargs(node) if method.has_kwargs() else None return node, function.Args(posargs=tuple(args),", "use_defaults and key in method.kw_defaults: kws[key] = method.kw_defaults[key] else: kws[key]", "defs for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\" not in ast:", "import builtins from pytype.pytd import escape from pytype.pytd import optimize", "log.info(\"Analyzing %s\", name) node1 = node0.ConnectNew(name) for val in var.bindings:", "val.data == b.data.cls] if not good_instances: # __new__ returned something", "deep to follow call chains: INIT_MAXIMUM_DEPTH = 4 # during", "objects as arguments for the given method. Note that we", "for m in methodvar.Data(node): if isinstance(m, special_builtins.ClassMethodInstance): m = m.func.data[0]", "sig in sigs), key=len) for i in range(len(arg_names)): if not", "instantiate() method, so that type parameters in the container's template", "class. log.info(\"Analyze functions: Skipping class method %s\", val.data.name) else: node1", "in case the caller wants to instantiate and retain the", "deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs): \"\"\"Given Python source return", "call_function will check fallback_to_unsolvable if a DictKeyMissing or # FailedFunctionCall", "used in solver methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(), decorators=(), slots=None, template=(), ))", "instance_var): bound = self.program.NewVariable() for m in methodvar.Data(node): if isinstance(m,", "= node0 log.info(\"Unable to generate fake arguments for %s\", funcv)", "if f.is_classmethod and cls: args = self._maybe_fix_classmethod_cls_arg(node, cls, f, args)", "node0 log.info(\"Unable to generate fake arguments for %s\", funcv) return", "= set() # Used by init_class. self._instance_cache: Dict[Any, Union[_Initializing, cfg.Variable]]", "init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs): \"\"\"Given Python source return its", "tracer.exitpoint = loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast = tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast)", "= num_posargs - len(method.defaults) for i in range(num_posargs): default_idx =", "from pytype.pytd import escape from pytype.pytd import optimize from pytype.pytd", "arguments for the given method. Creates Unknown objects as arguments", "so # we instead create an incomplete instance that will", "possible result values. \"\"\" log.debug(\"Logging call to %r with %d", "trace_classdef(self, c): self._interpreter_classes.append(c) def trace_namedtuple(self, nt): # All namedtuple instances", "typevars in the return value first, since bad_matches # expects", "= self.call_function(node1, funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret) if nodes: ret", "is fine to use Unsolvable rather than Unknown objects for", "from typing import Any, Dict, Union from pytype import abstract", "analyzed as # stand-alone functions. The exceptions are comprehensions and", "if isinstance(m, special_builtins.ClassMethodInstance): m = m.func.data[0] is_cls = True else:", "filename, init_maximum_depth) snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep: if", "builtins.GetDefaultAst(options.python_version)) # If merged with other if statement, triggers a", "check_types(src, filename, errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): \"\"\"Verify", "don't need __init__ called, use cls.instantiate instead. Args: node: The", "node, name, methodvar, instance_var): bound = self.program.NewVariable() for m in", "set maybe_missing_members to True on the instance and its type", "our class. instance = val.data.instantiate(node) node = self.call_init(node, instance) elif", "# during quick inference class _Initializing: pass class CallTracer(vm.VirtualMachine): \"\"\"Virtual", "self._call_traces_to_function(self._calls, escape.pack_partial) def pytd_classes_for_call_traces(self): class_to_records = collections.defaultdict(list) for call_record in", "to # overwrite previous instances. self._generated_classes[nt.name] = nt def pytd_classes_for_unknowns(self):", "= tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or any( a", "A string containing Python source code. errorlog: Where error messages", "node, instance): # Call __init__ on each binding. for b", "classes we haven't analyzed yet. # These are typically hidden", "or ( any(not isinstance(f, abstract.InterpreterFunction) for f in new.data)): #", "set before analyze_types. \"\"\" _CONSTRUCTORS = (\"__new__\", \"__init__\") def __init__(self,", "are # re-generated when the variables they close over change,", "snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep: if maximum_depth is", "and their type params. Args: values: A list of BaseValue", "node and (2) a cfg.Variable of the return value. \"\"\"", "= set() self._interpreter_functions = [] self._interpreter_classes = [] self._analyzed_functions =", "= set() while values: v = values.pop(0) if v not", "care of that. Args: node: The current node. method: An", "state, ret = self.call_function_with_state( state, var, args, kwargs, starargs, starstarargs)", "errors that may be raised will be passed to #", "in self._interpreter_functions: for value in f.bindings: if self._should_analyze_as_interpreter_function(value.data): node =", "filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs): \"\"\"Given Python source", "to generate fake arguments for %s\", funcv) return node, self.new_unsolvable(node)", "for v in self._generated_classes.values()) def compute_types(self, defs): classes = (tuple(self.pytd_classes_for_unknowns())", "options.protocols: protocols_pytd = tracer.loader.import_name(\"protocols\") else: protocols_pytd = None builtins_pytd =", "node1, args = self.create_method_arguments(node0, func) # Once the args are", "with. posargs: The positional arguments, an iterable over cfg.Value. namedargs:", "[ty, self.loader.concat_all()], escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self, node, actual, formal):", "program): \"\"\"Maybe emit debugging output.\"\"\" if options.output_cfg or options.output_typegraph: dot", "functions = [] for name, signatures in funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures),", "a DictKeyMissing or # FailedFunctionCall error is raised when the", "self.frame self.maximum_depth = maximum_depth self._analyzing = True node = node.ConnectNew(name=\"Analyze\")", "and not isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name, d)) else: data.append(d) else: log.error(\"No", "module = self.loaded_overlays[module_name].get_module(name) if name in module.members and module.members[name].data ==", "self._analyzed_functions.add(b.data.get_first_opcode()) node2, args = self.create_method_arguments(node1, b.data) args = self._maybe_fix_classmethod_cls_arg(node0, cls,", "Where error messages go. Instance of errors.ErrorLog. options: config.Options object", "# Once the args are generated, try calling the function.", "= True else: is_cls = (m.isinstance_InterpreterFunction() and m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls),", "param in b.data.instance_type_parameters.values(): node = self.call_init(node, param) node = self._call_method(node,", "(isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and not value.data.is_overload): new_node = self.analyze_function(node, value) else:", "posargs: The positional arguments, an iterable over cfg.Value. namedargs: The", "are created with force=False, as it is fine to use", "bad: bad = self.matcher.bad_matches(actual, formal, node) if bad: self.errorlog.bad_return_type( self.frames,", "func) if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1, args = self.create_method_arguments(node0, func) #", "pytype import state as frame_state from pytype import vm from", "list(values) seen = set() while values: v = values.pop(0) if", "sorted(val.data.members.items()): if name in self._CONSTRUCTORS: continue # We already called", "from pytype import function from pytype import metrics from pytype", "# re-generated when the variables they close over change, but", "variable is annotated, we'll always output that type. annotated_names =", "[] for b in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2, args = self.create_method_arguments(node1,", "else: log.error(\"No visible options for %s\", name) data.append(pytd.Constant(name, pytd.AnythingType())) return", "\"positional_arguments\", \"keyword_arguments\", \"return_value\"]) # How deep to follow call chains:", "var.FilteredData(self.exitpoint, strict=False) if (len(options) > 1 and not all(isinstance(o, abstract.FUNCTION_TYPES)", "to handle # DictKeyMissing nodes = [] rets = []", "stderr) = proc.communicate(dot) if stderr: log.info(\"Failed to create %s: %s\",", "= [] self._analyzed_functions = set() self._analyzed_classes = set() self._generated_classes =", "set([]), bool(options.output_cfg)) svg_file = options.output_cfg or options.output_typegraph proc = subprocess.Popen([\"/usr/bin/dot\",", "has passed in a vm, use that. if tracer_vm: assert", "logging import re import subprocess from typing import Any, Dict,", "b.data, args) node3 = node2.ConnectNew() node4, ret = self.call_function_with_args(node3, b,", "\"\"\"Create arguments for the given method. Creates Unknown objects as", "abstract.PyTDFunction): self._calls.add(record) def trace_functiondef(self, f): self._interpreter_functions.append(f) def trace_classdef(self, c): self._interpreter_classes.append(c)", "len(posargs), result) args = tuple(posargs) kwargs = tuple((namedargs or {}).items())", "want # to re-analyze them. return (isinstance(data, abstract.InterpreterFunction) and not", "Note that we have to create a new # instance", "A cfg.Binding of a function that was called. sigs: The", "= self.loaded_overlays[module_name].get_module(name) if name in module.members and module.members[name].data == var.data:", "Args: node: The current node. method: An abstract.InterpreterFunction. use_defaults: Whether", "that any inherited __new__ method defined in a pyi file", "An instance of CallTracer, in case the caller wants to", "handle # DictKeyMissing nodes = [] rets = [] for", "instance.data: val.data.register_canonical_instance(instance_value) for name, methodvar in sorted(val.data.members.items()): if name in", "node, defs, maximum_depth): assert not self.frame self.maximum_depth = maximum_depth self._analyzing", "funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret) if nodes: ret = self.join_variables(node0,", "escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self, node, actual, formal): if not", "node: The CFG node right after this function call. func:", "to vm.VirtualMachine Returns: A tuple of (ast: TypeDeclUnit, builtins: TypeDeclUnit)", "Dump =============\\n%s\", text) else: with options.open_function(options.output_debug, \"w\") as fi: fi.write(text)", "self._analyzed_functions = set() self._analyzed_classes = set() self._generated_classes = {} self.exitpoint", "convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return ast, builtins_pytd def _maybe_output_debug(options, program): \"\"\"Maybe", "call the given function with made-up arguments.\"\"\" # TODO(tsudol): If", "set() self._generated_classes = {} self.exitpoint = None def create_varargs(self, node):", "use_defaults=False): \"\"\"Create arguments for the given method. Creates Unknown objects", "(sig.param_names[0] not in sig.annotations)): # fix \"cls\" parameter return args._replace(", "name)) return classes def pytd_for_types(self, defs): # If a variable", "binding.\"\"\" node1, new = cls.data.get_own_new(node0, cls) if not new or", "module.members[name].data == var.data: return True return False def pytd_functions_for_call_traces(self): return", "call traces are kept in the output. maximum_depth: Depth of", "[\"node\", \"function\", \"signatures\", \"positional_arguments\", \"keyword_arguments\", \"return_value\"]) # How deep to", "return args._replace( posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:]) else: return args def maybe_analyze_method(self,", "fake arguments should avoid any # FailedFunctionCall errors. To prevent", "container=None, extra_key=None): \"\"\"Instantiate a class, and also call __init__. Calling", "a class, for analyzing it.\"\"\" n = self.program.NewVariable() for cls", "equal, so it's fine to # overwrite previous instances. self._generated_classes[nt.name]", "which # have names like \"<listcomp>\" and \"<genexpr>\". _SKIP_FUNCTION_RE =", "namedargs=kws, starargs=starargs, starstarargs=starstarargs) def call_function_with_args(self, node, val, args): \"\"\"Call a", "True node = node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node, defs) def trace_unknown(self, name,", "defs): for name, var in sorted(defs.items()): # sort, for determinicity", "and (method.signature.has_return_annotation or method.has_overloads) and fname.rsplit(\".\", 1)[-1] not in self._CONSTRUCTORS):", "class has registered. for method in cls.additional_init_methods: node = self._call_method(node,", "import convert_structural from pytype import debug from pytype import function", "value in var.bindings: if isinstance(value.data, abstract.InterpreterClass): new_node = self.analyze_class(node, value)", "\"\"\" log.debug(\"Logging call to %r with %d args, return %r\",", "with other if statement, triggers a ValueError: Unresolved class #", "option.to_type(self.exitpoint) # Type only if isinstance(d, pytd.NothingType): if isinstance(option, abstract.Empty):", "bool(options.output_cfg)) svg_file = options.output_cfg or options.output_typegraph proc = subprocess.Popen([\"/usr/bin/dot\", \"-T\",", "in self.loaded_overlays: continue module = self.loaded_overlays[module_name].get_module(name) if name in module.members", "to be set before analyze_types. \"\"\" _CONSTRUCTORS = (\"__new__\", \"__init__\")", "pytd_utils.JoinTypes(t.to_type(node) for t in retvar.data) starargs = None starstarargs =", "on the instance and its type parameters. \"\"\" values =", "defs.items(): if (name in output.TOP_LEVEL_IGNORE or name in annotated_names or", "Additional parameters to pass to vm.VirtualMachine Returns: A tuple of", "import re import subprocess from typing import Any, Dict, Union", "Optionally, a container to pass to the class's instantiate() method,", "name, signatures in funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD)) return functions def", "disambiguate callers that shouldn't get back the same cached instance.", "def trace_functiondef(self, f): self._interpreter_functions.append(f) def trace_classdef(self, c): self._interpreter_classes.append(c) def trace_namedtuple(self,", "log.info(\"Unable to generate fake arguments for %s\", funcv) return node,", "maybe_missing_members to True on these values and their type params.", "pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t in options) data.append(pytd.Constant(name, combined_types)) elif options: for", "else: protocols_pytd = None builtins_pytd = tracer.loader.concat_all() # Insert type", "and not _SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self, node, defs): for name, var", "an infinite recursion loop, set # fallback_to_unsolvable to False just", "load from the protocols file if options.protocols: protocols_pytd = tracer.loader.import_name(\"protocols\")", "a dict mapping str to cfg.Value. result: A Variable of", "node right after this function call. func: A cfg.Binding of", "= tuple(posargs) kwargs = tuple((namedargs or {}).items()) record = CallRecord(node,", "of a bad parameter combination. \"\"\" # If the caller", "presence of this option means that the user wants checking,", "**kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) snapshotter = metrics.get_metric(\"memory\",", "from pytype.pytd import builtins from pytype.pytd import escape from pytype.pytd", "tuple(self.pytd_functions_for_call_traces()) aliases = () # aliases are instead recorded as", "records all function calls. Attributes: exitpoint: A CFG node representing", "def init_class(self, node, cls, container=None, extra_key=None): \"\"\"Instantiate a class, and", "classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), # not used in solver methods=tuple(self._call_traces_to_function(call_records)),", "The given node. val: A cfg.Binding containing the function. args:", "key=len) for i in range(len(arg_names)): if not isinstance(func.data, abstract.BoundFunction) or", "(ast: TypeDeclUnit, builtins: TypeDeclUnit) Raises: AssertionError: In case of a", "# Since there's no point in analyzing annotated functions for", "in analyzing annotated functions for inference, # the presence of", "loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) snapshotter =", "deep: if maximum_depth is None: if not options.quick: maximum_depth =", "Union[_Initializing, cfg.Variable]] = {} # Used by call_init. Can differ", "will check fallback_to_unsolvable if a DictKeyMissing or # FailedFunctionCall error", "the process of initializing - otherwise, setting # maybe_missing_members to", "node, method_name, method, binding.AssignToNewVariable()) node = self.analyze_method_var(node, method_name, bound_method) return", "it is fine to use Unsolvable rather than Unknown objects", "self.push_frame(frame) log.info(\"Analyzing %r\", [v.name for v in var.data]) state =", "for method in cls.additional_init_methods: node = self._call_method(node, b, method) return", "parameters, where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info(\"=========== PyTD", "starstarargs=starstarargs) def call_function_with_args(self, node, val, args): \"\"\"Call a function. Args:", "generators, which # have names like \"<listcomp>\" and \"<genexpr>\". _SKIP_FUNCTION_RE", "output. maximum_depth: Depth of the analysis. Default: unlimited. tracer_vm: An", "tracer.run_program(src, filename, init_maximum_depth) snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep:", "isinstance(d, pytd.NothingType): if isinstance(option, abstract.Empty): d = pytd.AnythingType() else: assert", "created with force=False, as it is fine to use Unsolvable", "If you don't need __init__ called, use cls.instantiate instead. Args:", "binding.AssignToNewVariable()) node = self.analyze_method_var(node, method_name, bound_method) return node def _call_init_on_binding(self,", "if not good_instances: # __new__ returned something that's not an", "it as a constant. combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t in", "isinstance(func.data, abstract.BoundFunction) or i > 0: arg_names[i] = function.argname(i) arg_types", "from the protocols file if options.protocols: protocols_pytd = tracer.loader.import_name(\"protocols\") else:", "any additional errors that may be raised will be passed", "not good_instances: # __new__ returned something that's not an instance", "funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD)) return functions def _is_typing_member(self, name, var):", "self._initialized_instances = set() self._interpreter_functions = [] self._interpreter_classes = [] self._analyzed_functions", "self.create_method_arguments(node, f) if f.is_classmethod and cls: args = self._maybe_fix_classmethod_cls_arg(node, cls,", "data): # We record analyzed functions by opcode rather than", "or something # else, so encode it as a constant.", "tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader, **kwargs) loc,", "return node def analyze_function(self, node0, val): if val.data.is_attribute_of_class: # We'll", "# fix \"cls\" parameter return args._replace( posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:]) else:", "maximum_depth): assert not self.frame self.maximum_depth = maximum_depth self._analyzing = True", "[] for name, val in self._unknowns.items(): if val in val.variable.Filter(self.exitpoint,", "None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t, False, False, None) for n, t", "means that the user wants checking, too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH", "force=not use_defaults) starargs = self.create_varargs(node) if method.has_varargs() else None starstarargs", "for analyzing it.\"\"\" n = self.program.NewVariable() for cls in clsv.Bindings(node,", "cause pytype to ignore # all attribute errors on self", "node, function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs, starstarargs=starstarargs) def call_function_with_args(self, node, val, args):", "PyTD to solve =============\\n%s\", pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd)", "and key in method.kw_defaults: kws[key] = method.kw_defaults[key] else: kws[key] =", "= list(values) seen = set() while values: v = values.pop(0)", "in methodvar.Data(node): if isinstance(m, special_builtins.ClassMethodInstance): m = m.func.data[0] is_cls =", "data.append(pytd.Constant(name, pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod def _call_traces_to_function(call_traces, name_transform=lambda x:", "try calling the function. # call_function will check fallback_to_unsolvable if", "val in self._unknowns.items(): if val in val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name))", "(isinstance(value.data, abstract.InterpreterClass) and value.data not in self._analyzed_classes): node = self.analyze_class(node,", "and classes we haven't analyzed yet. # These are typically", "actual, bad) return not bad def check_types(src, filename, errorlog, options,", "To prevent an infinite recursion loop, set # fallback_to_unsolvable to", "NotImplementedError: d = option.to_type(self.exitpoint) # Type only if isinstance(d, pytd.NothingType):", "name, t in pytd_convert.annotations_to_instance_types( self.exitpoint, annots): annotated_names.add(name) data.append(pytd.Constant(name, t)) for", "ret = self.join_variables(node0, rets) node = self.join_cfg_nodes(nodes) if ret.bindings: return", "abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter( node, abstract_utils.T, self.convert.create_new_unknown(node)) return value.to_variable(node) def create_kwargs(self,", "b.data) args = self._maybe_fix_classmethod_cls_arg(node0, cls, b.data, args) node3 = node2.ConnectNew()", "again, and generating fake arguments should avoid any # FailedFunctionCall", "list of BaseValue objects. On every instance among the values,", "instance = self._instantiate_var(node, clsvar, container) if key in self._instance_cache: #", "a class. log.info(\"Analyze functions: Skipping class method %s\", val.data.name) else:", "methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(), decorators=(), slots=None, template=(), )) return classes def", "def pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls, escape.pack_partial) def pytd_classes_for_call_traces(self): class_to_records = collections.defaultdict(list)", "node0 def bind_method(self, node, name, methodvar, instance_var): bound = self.program.NewVariable()", "program exit. Needs to be set before analyze_types. \"\"\" _CONSTRUCTORS", "node = self.join_cfg_nodes(nodes) if ret.bindings: return node, ret else: node", "and its type parameters. \"\"\" values = list(values) seen =", "name, b, val) return node def analyze_function(self, node0, val): if", "follow call chains: INIT_MAXIMUM_DEPTH = 4 # during module loading", "self.frame.current_opcode, extra_key, cls) instance = self._instance_cache.get(key) if not instance or", "set() data = [] pytd_convert = self.convert.pytd_convert annots = abstract_utils.get_annotations_dict(defs)", "used for type inference. **kwargs: Additional parameters to pass to", "def compute_types(self, defs): classes = (tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances())", "tuple of a node and a function.Args object. \"\"\" args", "combined_types)) elif options: for option in options: try: d =", "= convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return ast, builtins_pytd def _maybe_output_debug(options, program):", "t in retvar.data) starargs = None starstarargs = None funcs[func.data.name].add(pytd.Signature(", "arguments should avoid any # FailedFunctionCall errors. To prevent an", "[], node) return bound def _instantiate_binding(self, node0, cls, container): \"\"\"Instantiate", "in self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node)) def analyze_class(self, node, val): self._analyzed_classes.add(val.data) node,", "case of a bad parameter combination. \"\"\" # If the", "node, instance = self.init_class(node, val.data) good_instances = [b for b", "it.\"\"\" n = self.program.NewVariable() for cls in clsv.Bindings(node, strict=False): node,", "= option.to_type(self.exitpoint) # Type only if isinstance(d, pytd.NothingType): if isinstance(option,", "bad: self.errorlog.bad_return_type( self.frames, node, formal, actual, bad) return not bad", "decorators=(), slots=None, template=(), )) return classes def pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast()", "because we also call # __init__ on classes not initialized", "of node and instance variable. \"\"\" key = (self.frame and", "instance_value in instance.data: val.data.register_canonical_instance(instance_value) for name, methodvar in sorted(val.data.members.items()): if", "def analyze(self, node, defs, maximum_depth): assert not self.frame self.maximum_depth =", "error messages go. Instance of errors.ErrorLog. options: config.Options object loader:", "import output from pytype import special_builtins from pytype import state", "escape from pytype.pytd import optimize from pytype.pytd import pytd from", "errors on self in __init__. self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key] = _Initializing()", "of the possible result values. \"\"\" log.debug(\"Logging call to %r", "retain the vm used for type inference. **kwargs: Additional parameters", "with force=False, as it is fine to use Unsolvable rather", "if v not in seen: seen.add(v) if isinstance(v, abstract.SimpleValue): v.maybe_missing_members", "m in methodvar.Data(node): if isinstance(m, special_builtins.ClassMethodInstance): m = m.func.data[0] is_cls", "= metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep: if maximum_depth is None:", "self.pop_frame(frame) return state.node, ret def _maybe_fix_classmethod_cls_arg(self, node, cls, func, args):", "annots): annotated_names.add(name) data.append(pytd.Constant(name, t)) for name, var in defs.items(): if", "that. Args: node: The current node. method: An abstract.InterpreterFunction. use_defaults:", "debugging output.\"\"\" if options.output_cfg or options.output_typegraph: dot = debug.program_to_dot(program, set([]),", "if not instance or isinstance(instance, _Initializing): clsvar = cls.to_variable(node) node,", "additional errors that may be raised will be passed to", "\"__getattr__\" not in ast: ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) #", "its type parameters. \"\"\" values = list(values) seen = set()", "a node and (2) a cfg.Variable of the return value.", "self.program.NewVariable() for m in methodvar.Data(node): if isinstance(m, special_builtins.ClassMethodInstance): m =", "fallback_to_unsolvable to False just in case. # This means any", "self.matcher.bad_matches(actual, formal, node) if bad: self.errorlog.bad_return_type( self.frames, node, formal, actual,", "for name, methodvar in sorted(val.data.members.items()): if name in self._CONSTRUCTORS: continue", "**kwargs: Additional parameters to pass to vm.VirtualMachine Returns: A tuple", "self._CONSTRUCTORS): log.info(\"%r has annotations, not analyzing further.\", fname) else: for", "node, b): if isinstance(b.data, abstract.SimpleValue): for param in b.data.instance_type_parameters.values(): node", "retvar in call_traces: # The lengths may be different in", "self._instance_cache[key] = _Initializing() node = self.call_init(node, instance) self._instance_cache[key] = instance", "b.data.instance_type_parameters.values(): node = self.call_init(node, param) node = self._call_method(node, b, \"__init__\")", "if self._should_analyze_as_interpreter_function(value.data): node = self.analyze_function(node, value) return node def analyze(self,", "isinstance(m, special_builtins.ClassMethodInstance): m = m.func.data[0] is_cls = True else: is_cls", "occurs. By default, this method keys on the current opcode", "values.extend(child.data) def init_class(self, node, cls, container=None, extra_key=None): \"\"\"Instantiate a class,", "builtins_pytd, protocols_pytd) elif not show_library_calls: log.info(\"Solving is turned off. Discarding", "values = list(values) seen = set() while values: v =", "pytype.pytd import pytd_utils from pytype.pytd import visitors from pytype.typegraph import", "classes.append(val.data.to_structural_def(self.exitpoint, name)) return classes def pytd_for_types(self, defs): # If a", "if stderr: log.info(\"Failed to create %s: %s\", svg_file, stderr) if", "instance that will be # overwritten later. Note that we", "the analysis. Default: unlimited. tracer_vm: An instance of CallTracer, in", "sig = func.signature if (args.posargs and sig.param_names and (sig.param_names[0] not", "protocols_pytd = tracer.loader.import_name(\"protocols\") else: protocols_pytd = None builtins_pytd = tracer.loader.concat_all()", "function. Args: node: The given node. val: A cfg.Binding containing", "default, this method keys on the current opcode and the", "and also call __init__. Calling __init__ can be expensive, so", "for value in var.bindings: if isinstance(value.data, abstract.InterpreterClass): new_node = self.analyze_class(node,", "self.init_class(node, val.data) good_instances = [b for b in instance.bindings if", "option.to_pytd_def(self.exitpoint, name) # Deep definition except NotImplementedError: d = option.to_type(self.exitpoint)", "= cls.data.get_own_new(node0, cls) if not new or ( any(not isinstance(f,", "result) if isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record) elif isinstance(func.data, abstract.PyTDFunction): self._calls.add(record) def", "= pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions, aliases=aliases)) ty = ty.Visit(optimize.CombineReturnsAndExceptions())", "values: A list of BaseValue objects. On every instance among", "name in self._CONSTRUCTORS: continue # We already called this method", "we don't want # to re-analyze them. return (isinstance(data, abstract.InterpreterFunction)", "= self._call_method(node, b, method) return node def call_init(self, node, instance):", "abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if (not self.options.analyze_annotated and (method.signature.has_return_annotation or method.has_overloads) and", "node1, new = cls.data.get_own_new(node0, cls) if not new or (", "get back the same cached instance. Returns: A tuple of", "additional initalizers the class has registered. for method in cls.additional_init_methods:", "solve =============\\n%s\", pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not", "in instance.data: val.data.register_canonical_instance(instance_value) for name, methodvar in sorted(val.data.members.items()): if name", "classes = [] for name, val in self._unknowns.items(): if val", "ast: ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If merged with", "node, _ = self.call_function_with_args(node, val, args) return node def _call_with_fake_args(self,", "%s with fake arguments\", func) if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1, args", "if isinstance(b.data, abstract.SimpleValue): for param in b.data.instance_type_parameters.values(): node = self.call_init(node,", "FailedFunctionCall error is raised when the target function is called.", "nodes: ret = self.join_variables(node0, rets) node = self.join_cfg_nodes(nodes) if ret.bindings:", "return node def analyze(self, node, defs, maximum_depth): assert not self.frame", "methodvar.Data(node): if isinstance(m, special_builtins.ClassMethodInstance): m = m.func.data[0] is_cls = True", "by call_init. Can differ from _instance_cache because we also call", "self._analyzing = True node = node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node, defs) def", "func, sigs, args, kws, retvar in call_traces: # The lengths", "record analyzed functions by opcode rather than function object. The", "ret = self.call_function(node1, funcb.AssignToNewVariable(), args, fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret) if nodes:", "= collections.defaultdict(pytd_utils.OrderedSet) for node, func, sigs, args, kws, retvar in", "variable. \"\"\" key = (self.frame and self.frame.current_opcode, extra_key, cls) instance", "not _SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self, node, defs): for name, var in", "vm.VirtualMachine Returns: A tuple of (ast: TypeDeclUnit, builtins: TypeDeclUnit) Raises:", "# we instead create an incomplete instance that will be", "(args.posargs and sig.param_names and (sig.param_names[0] not in sig.annotations)): # fix", "if (args.posargs and sig.param_names and (sig.param_names[0] not in sig.annotations)): #", "The lengths may be different in the presence of optional", "self.call_function_with_args(node, val, args) return node def _call_with_fake_args(self, node0, funcv): \"\"\"Attempt", "return node, self.new_unsolvable(node) def analyze_method_var(self, node0, name, var, cls=None): log.info(\"Analyzing", "else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth) else:", "kwargs.merge_instance_type_parameter(node, abstract_utils.V, value_type) return kwargs.to_variable(node) def create_method_arguments(self, node, method, use_defaults=False):", "A: # def __init__(self, x: \"A\"): ... # Calling __init__", "node, cls, container=None, extra_key=None): \"\"\"Instantiate a class, and also call", "result) args = tuple(posargs) kwargs = tuple((namedargs or {}).items()) record", "node. val: A cfg.Binding containing the function. args: A function.Args", "ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove \"~list\" etc.: ast = convert_structural.extract_local(ast)", "args. arg_names = max((sig.get_positional_names() for sig in sigs), key=len) for", "stderr) if options.output_debug: text = debug.program_to_text(program) if options.output_debug == \"-\":", "args = call_record.positional_arguments if not any(isinstance(a.data, abstract.Unknown) for a in", "val, args): \"\"\"Call a function. Args: node: The given node.", "def pytd_for_types(self, defs): # If a variable is annotated, we'll", "for call_record in self._method_calls: args = call_record.positional_arguments if not any(isinstance(a.data,", "def call_init(self, node, instance): # Call __init__ on each binding.", "called. # DictKeyMissing doesn't trigger call_with_fake_args, so that shouldn't #", "method_name): node, method = self.attribute_handler.get_attribute( node, binding.data.get_class(), method_name, binding) if", "value) for f in self._interpreter_functions: for value in f.bindings: if", "# be raised again, and generating fake arguments should avoid", "the output. maximum_depth: Depth of the analysis. Default: unlimited. tracer_vm:", "for %s\", name) data.append(pytd.Constant(name, pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod def", "maximum_depth = MAXIMUM_DEPTH elif options.analyze_annotated: # Since there's no point", "part of a class. log.info(\"Analyze functions: Skipping class method %s\",", "self._unknowns.items(): if val in val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name)) return classes", "pytd.Type) and not isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name, d)) else: data.append(d) else:", "tuple of node and instance variable. \"\"\" key = (self.frame", "if not isinstance(func.data, abstract.BoundFunction) or i > 0: arg_names[i] =", "Go through classes first so that the `is_attribute_of_class` will #", "from pytype import abstract_utils from pytype import convert_structural from pytype", "isinstance(option, abstract.Empty): d = pytd.AnythingType() else: assert isinstance(option, typing_overlay.NoReturn) if", "annotated_names = set() data = [] pytd_convert = self.convert.pytd_convert annots", "= ty.Visit(optimize.PullInMethodClasses()) ty = ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()], escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters())", "True else: is_cls = (m.isinstance_InterpreterFunction() and m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls), [],", "Args: values: A list of BaseValue objects. On every instance", "**kwargs): \"\"\"Verify the Python code.\"\"\" tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=False,", "self.call_function_with_args(node3, b, args) instance.PasteVariable(ret) nodes.append(node4) return self.join_cfg_nodes(nodes), instance def _instantiate_var(self,", "QUICK_INFER_MAXIMUM_DEPTH = 1 # during quick inference class _Initializing: pass", "src: A string containing Python source code. errorlog: Where error", "Variable of the possible result values. \"\"\" log.debug(\"Logging call to", "+ args.posargs[1:]) else: return args def maybe_analyze_method(self, node, val, cls=None):", "attribute errors on self in __init__. self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key] =", "string containing Python source code. errorlog: Where error messages go.", "isinstance(d, pytd.Type) and not isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name, d)) else: data.append(d)", "# Insert type parameters, where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if", "func, sigs, posargs, namedargs, result): \"\"\"Add an entry into the", "all(isinstance(o, abstract.FUNCTION_TYPES) for o in options)): # It's ambiguous whether", "tuple((namedargs or {}).items()) record = CallRecord(node, func, sigs, args, kwargs,", "cls.name if cls.module else cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), #", "have been called with. posargs: The positional arguments, an iterable", "and generating fake arguments should avoid any # FailedFunctionCall errors.", "so that shouldn't # be raised again, and generating fake", "= self.program.NewVariable() for cls in clsv.Bindings(node, strict=False): node, var =", "= self.analyze_method_var(node, method_name, bound_method) return node def _call_init_on_binding(self, node, b):", "user wants checking, too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth =", "ast = tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or any(", "instance or isinstance(instance, _Initializing): clsvar = cls.to_variable(node) node, instance =", "_maybe_fix_classmethod_cls_arg(self, node, cls, func, args): sig = func.signature if (args.posargs", "= tracer.run_program(src, filename, init_maximum_depth) snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if", "The positional arguments, an iterable over cfg.Value. namedargs: The keyword", "setting # maybe_missing_members to True would cause pytype to ignore", "not in sig.annotations)): # fix \"cls\" parameter return args._replace( posargs=(cls.AssignToNewVariable(node),)", "funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t, False, False, None) for n, t in", "values.pop(0) if v not in seen: seen.add(v) if isinstance(v, abstract.SimpleValue):", "elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and not value.data.is_overload): new_node = self.analyze_function(node, value)", "continue cls = args[0].data.get_class() if isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record) classes =", "for %s\", funcv) return node, self.new_unsolvable(node) def analyze_method_var(self, node0, name,", "sigs, posargs, namedargs, result): \"\"\"Add an entry into the call", "inferring types.\"\"\" import collections import logging import re import subprocess", "to pass to vm.VirtualMachine Returns: A tuple of (ast: TypeDeclUnit,", "a.data.to_type(node), False, False, None) for name, a in kws), starargs,", "in the return value first, since bad_matches # expects not", "MAXIMUM_DEPTH elif options.analyze_annotated: # Since there's no point in analyzing", "for c in self._interpreter_classes: for value in c.bindings: if (isinstance(value.data,", "code.\"\"\" tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader, **kwargs) loc, defs", "True views = abstract_utils.get_views([actual], node) # Check for typevars in", "node = self.analyze_class(node, value) for f in self._interpreter_functions: for value", "name, val in self._unknowns.items(): if val in val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint,", "of recording are equivalent except for closures, which are #", "_call_init_on_binding(self, node, b): if isinstance(b.data, abstract.SimpleValue): for param in b.data.instance_type_parameters.values():", "False, False, None) for n, t in zip(arg_names, arg_types)) +", "be passed to # the call_function that called this method", "filename: Filename of the program we're parsing. deep: If True,", "x): funcs = collections.defaultdict(pytd_utils.OrderedSet) for node, func, sigs, args, kws,", "else None return node, function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs, starstarargs=starstarargs) def call_function_with_args(self,", "var = self._instantiate_binding(node, cls, container) n.PasteVariable(var) return node, n def", "cls, call_records in class_to_records.items(): full_name = cls.module + \".\" +", "= tracer.run_program(src, filename, init_maximum_depth) log.info(\"===Done running definitions and module-level code===\")", "a function that was called. sigs: The signatures that the", "this beyond __init__, need to handle # DictKeyMissing nodes =", "+ tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances()) functions = tuple(self.pytd_functions_for_call_traces()) aliases = ()", "log.info(\"Solving is turned off. Discarding call traces.\") # Rename remaining", "() # aliases are instead recorded as constants ty =", "False, False, None) for name, a in kws), starargs, starstarargs,", "= self.call_init(node, param) node = self._call_method(node, b, \"__init__\") cls =", "# FailedFunctionCall errors. To prevent an infinite recursion loop, set", "frame_state from pytype import vm from pytype.overlays import typing_overlay from", "True for child in v.instance_type_parameters.values(): values.extend(child.data) def init_class(self, node, cls,", "def analyze_class(self, node, val): self._analyzed_classes.add(val.data) node, instance = self.init_class(node, val.data)", "call trace. Args: node: The CFG node right after this", "is called. # DictKeyMissing doesn't trigger call_with_fake_args, so that shouldn't", "We've encountered a recursive pattern such as # class A:", "deep: If True, analyze all functions, even the ones not", "None starstarargs = self.create_kwargs(node) if method.has_kwargs() else None return node,", "enough to disambiguate callers that shouldn't get back the same", "be different in the presence of optional and kw args.", "through classes first so that the `is_attribute_of_class` will # be", "returns an instance of the current class. return node0, cls.data.instantiate(node0,", "__init__ on classes not initialized via init_class. self._initialized_instances = set()", "process of initializing - otherwise, setting # maybe_missing_members to True", "isinstance(func.data, abstract.PyTDFunction): self._calls.add(record) def trace_functiondef(self, f): self._interpreter_functions.append(f) def trace_classdef(self, c):", "functions def _is_typing_member(self, name, var): for module_name in (\"typing\", \"typing_extensions\"):", "to True would cause pytype to ignore # all attribute", "if (not self.options.analyze_annotated and (method.signature.has_return_annotation or method.has_overloads) and fname.rsplit(\".\", 1)[-1]", "values, recursively set maybe_missing_members to True on the instance and", "= [b for b in instance.bindings if val.data == b.data.cls]", "not bad: bad = self.matcher.bad_matches(actual, formal, node) if bad: self.errorlog.bad_return_type(", "= True for child in v.instance_type_parameters.values(): values.extend(child.data) def init_class(self, node,", "caller has passed in a vm, use that. if tracer_vm:", "on these values and their type params. Args: values: A", ">= 0: arg = method.defaults[default_idx] else: arg = self.convert.create_new_unknown(node, force=not", "abstract_utils.V, value_type) return kwargs.to_variable(node) def create_method_arguments(self, node, method, use_defaults=False): \"\"\"Create", "_ = self.call_function_with_args(node, val, args) return node def _call_with_fake_args(self, node0,", "= values.pop(0) if v not in seen: seen.add(v) if isinstance(v,", "ways of recording are equivalent except for closures, which are", "pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions, aliases=aliases)) ty = ty.Visit(optimize.CombineReturnsAndExceptions()) ty", "self._method_calls = set() # Used by init_class. self._instance_cache: Dict[Any, Union[_Initializing,", "beyond __init__, need to handle # DictKeyMissing nodes = []", "type. annotated_names = set() data = [] pytd_convert = self.convert.pytd_convert", "trace_unknown(self, name, unknown_binding): self._unknowns[name] = unknown_binding def trace_call(self, node, func,", "instances. self._generated_classes[nt.name] = nt def pytd_classes_for_unknowns(self): classes = [] for", "self.analyze_method_var(node, name, b, val) return node def analyze_function(self, node0, val):", "# Remove \"~list\" etc.: ast = convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return", "during quick checking QUICK_INFER_MAXIMUM_DEPTH = 1 # during quick inference", "try: d = option.to_pytd_def(self.exitpoint, name) # Deep definition except NotImplementedError:", "= tuple((namedargs or {}).items()) record = CallRecord(node, func, sigs, args,", "to TypeParameterInstance. extra_key: Optionally, extra information about the location at", "in the presence of optional and kw args. arg_names =", "class A: # def __init__(self, x: \"A\"): ... # Calling", "args): sig = func.signature if (args.posargs and sig.param_names and (sig.param_names[0]", "returned something that's not an instance of our class. instance", "= [] self._interpreter_classes = [] self._analyzed_functions = set() self._analyzed_classes =", "the target function is called. # DictKeyMissing doesn't trigger call_with_fake_args,", "and inferring types.\"\"\" import collections import logging import re import", "if isinstance(d, pytd.NothingType): if isinstance(option, abstract.Empty): d = pytd.AnythingType() else:", "only if isinstance(d, pytd.NothingType): if isinstance(option, abstract.Empty): d = pytd.AnythingType()", "return self.analyze_toplevel(node, defs) def trace_unknown(self, name, unknown_binding): self._unknowns[name] = unknown_binding", "node2, args = self.create_method_arguments(node1, b.data) args = self._maybe_fix_classmethod_cls_arg(node0, cls, b.data,", "_call_method(self, node, binding, method_name): node, method = self.attribute_handler.get_attribute( node, binding.data.get_class(),", "view and view[actual].data.formal] if not bad: bad = self.matcher.bad_matches(actual, formal,", "self._initialized_instances.add(b.data) node = self._call_init_on_binding(node, b) return node def reinitialize_if_initialized(self, node,", "+ tuple(pytd.Parameter(name, a.data.to_type(node), False, False, None) for name, a in", "maximum_depth=None, **kwargs): \"\"\"Verify the Python code.\"\"\" tracer = CallTracer(errorlog=errorlog, options=options,", "b = self.bind_method(node, name, methodvar, instance) node = self.analyze_method_var(node, name,", "has annotations, not analyzing further.\", fname) else: for f in", "use cls.instantiate instead. Args: node: The current node. cls: The", "a in args) ret = pytd_utils.JoinTypes(t.to_type(node) for t in retvar.data)", "options.output_debug == \"-\": log.info(\"=========== Program Dump =============\\n%s\", text) else: with", "with fake arguments\", func) if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1, args =", "tracer = tracer_vm else: tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not", "node2.ConnectNew() node4, ret = self.call_function_with_args(node3, b, args) instance.PasteVariable(ret) nodes.append(node4) return", "not self._is_typing_member(name, var): for value in var.bindings: if isinstance(value.data, abstract.InterpreterClass):", "class binding.\"\"\" node1, new = cls.data.get_own_new(node0, cls) if not new", "exitpoint: A CFG node representing the program exit. Needs to", "... # Calling __init__ again would lead to an infinite", "for name, signatures in funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD)) return functions", "convert_structural from pytype import debug from pytype import function from", "the program we're parsing. deep: If True, analyze all functions,", "not data.is_class_builder and data.get_first_opcode() not in self._analyzed_functions and not _SKIP_FUNCTION_RE.search(data.name))", "self._calls = set() self._method_calls = set() # Used by init_class.", "snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep: if maximum_depth is", "function.Args object. Returns: A tuple of (1) a node and", "funcv) return node, self.new_unsolvable(node) def analyze_method_var(self, node0, name, var, cls=None):", "or any( a in defs for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if", "= self.create_method_arguments(node1, b.data) args = self._maybe_fix_classmethod_cls_arg(node0, cls, b.data, args) node3", "the function. # call_function will check fallback_to_unsolvable if a DictKeyMissing", "statement, triggers a ValueError: Unresolved class # when attempts to", "[] for funcb in funcv.bindings: func = funcb.data log.info(\"Trying %s", "by init_class. self._instance_cache: Dict[Any, Union[_Initializing, cfg.Variable]] = {} # Used", "method in cls.additional_init_methods: node = self._call_method(node, b, method) return node", "def call_function_with_args(self, node, val, args): \"\"\"Call a function. Args: node:", "current class. return node0, cls.data.instantiate(node0, container=container) instance = self.program.NewVariable() nodes", "in b.data.instance_type_parameters.values(): node = self.call_init(node, param) node = self._call_method(node, b,", "if not self._is_typing_member(name, var): for value in var.bindings: if isinstance(value.data,", "options.output_typegraph: dot = debug.program_to_dot(program, set([]), bool(options.output_cfg)) svg_file = options.output_cfg or", "\"CallRecord\", [\"node\", \"function\", \"signatures\", \"positional_arguments\", \"keyword_arguments\", \"return_value\"]) # How deep", "self.create_kwargs(node) if method.has_kwargs() else None return node, function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs,", "not self.frame self.maximum_depth = maximum_depth self._analyzing = True node =", "starargs=starargs, starstarargs=starstarargs) def call_function_with_args(self, node, val, args): \"\"\"Call a function.", "Most interpreter functions (including lambdas) need to be analyzed as", "[] self._interpreter_classes = [] self._analyzed_functions = set() self._analyzed_classes = set()", "parsing. deep: If True, analyze all functions, even the ones", "Can differ from _instance_cache because we also call # __init__", "All namedtuple instances with the same name are equal, so", "def _check_return(self, node, actual, formal): if not self.options.report_errors: return True", "bound.AddBinding(m.property_get(instance_var, is_cls), [], node) return bound def _instantiate_binding(self, node0, cls,", "= self.convert.primitive_class_instances[str].to_variable(node) value_type = self.convert.create_new_unknown(node) kwargs = abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node,", "in c.bindings: if (isinstance(value.data, abstract.InterpreterClass) and value.data not in self._analyzed_classes):", "__new__ method defined in a pyi file # returns an", "pytype import metrics from pytype import output from pytype import", "pytd.NothingType): if isinstance(option, abstract.Empty): d = pytd.AnythingType() else: assert isinstance(option,", "a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\" not in ast: ast =", "there's nothing to solve for. continue cls = args[0].data.get_class() if", "always output that type. annotated_names = set() data = []", "their type params. Args: values: A list of BaseValue objects.", "metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep: if maximum_depth is None: if", "( any(not isinstance(f, abstract.InterpreterFunction) for f in new.data)): # This", "wants checking, too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH", "if \"__getattr__\" not in ast: ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version))", "instance return node, instance def _call_method(self, node, binding, method_name): node,", "given node. val: A cfg.Binding containing the function. args: A", "# We'll analyze this function as part of a class.", "its created instances. If you don't need __init__ called, use", "load PYI information. filename: Filename of the program we're parsing.", "of this option means that the user wants checking, too.", "the return value. \"\"\" fvar = val.AssignToNewVariable(node) with val.data.record_calls(): new_node,", "of analysis during module loading. show_library_calls: If True, call traces", "# all attribute errors on self in __init__. self._mark_maybe_missing_members(instance.data) else:", "you don't need __init__ called, use cls.instantiate instead. Args: node:", "pytype.pytd import visitors from pytype.typegraph import cfg log = logging.getLogger(__name__)", "def _call_method(self, node, binding, method_name): node, method = self.attribute_handler.get_attribute( node,", "to False just in case. # This means any additional", "= QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint =", "annotated, we'll always output that type. annotated_names = set() data", "\"\"\"Add an entry into the call trace. Args: node: The", "is None: if not options.quick: maximum_depth = MAXIMUM_DEPTH elif options.analyze_annotated:", "chains: INIT_MAXIMUM_DEPTH = 4 # during module loading MAXIMUM_DEPTH =", "val) node2.ConnectTo(node0) return node0 def _should_analyze_as_interpreter_function(self, data): # We record", "node = self.analyze_method_var(node, name, b, val) return node def analyze_function(self,", "from pytype.pytd import pytd_utils from pytype.pytd import visitors from pytype.typegraph", "def _instantiate_var(self, node, clsv, container): \"\"\"Build an (dummy) instance from", "namedargs, result): \"\"\"Add an entry into the call trace. Args:", "v in self._generated_classes.values()) def compute_types(self, defs): classes = (tuple(self.pytd_classes_for_unknowns()) +", "typing import Any, Dict, Union from pytype import abstract from", "to use parameter defaults for arguments. When True, unknown arguments", "if name in self._CONSTRUCTORS: continue # We already called this", "> 1 and not all(isinstance(o, abstract.FUNCTION_TYPES) for o in options)):", "name in module.members and module.members[name].data == var.data: return True return", "= CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader, **kwargs) loc, defs", "self.call_init(node, instance) self._instance_cache[key] = instance return node, instance def _call_method(self,", "in # the process of initializing - otherwise, setting #", "node = self.analyze_function(node, value) return node def analyze(self, node, defs,", "__new__ returned some extra possibilities we don't need. instance =", "self._interpreter_functions: for value in f.bindings: if self._should_analyze_as_interpreter_function(value.data): node = self.analyze_function(node,", "the same cached instance. Returns: A tuple of node and", "and instance variable. \"\"\" key = (self.frame and self.frame.current_opcode, extra_key,", "for name, t in pytd_convert.annotations_to_instance_types( self.exitpoint, annots): annotated_names.add(name) data.append(pytd.Constant(name, t))", "otherwise, setting # maybe_missing_members to True would cause pytype to", "return value first, since bad_matches # expects not to get", "options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): \"\"\"Verify the Python code.\"\"\"", "log.info(\"===Done running definitions and module-level code===\") snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot)", "def bind_method(self, node, name, methodvar, instance_var): bound = self.program.NewVariable() for", "is_cls = True else: is_cls = (m.isinstance_InterpreterFunction() and m.is_classmethod) bound.AddBinding(m.property_get(instance_var,", "[] for name, signatures in funcs.items(): functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD)) return", "# __new__ returned something that's not an instance of our", "kwargs, result) if isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record) elif isinstance(func.data, abstract.PyTDFunction): self._calls.add(record)", "_instantiate_binding(self, node0, cls, container): \"\"\"Instantiate a class binding.\"\"\" node1, new", "node, val, cls=None): method = val.data fname = val.data.name if", "continue if new_node is not node: new_node.ConnectTo(node) # Now go", "args, kwargs, result) if isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record) elif isinstance(func.data, abstract.PyTDFunction):", "for arguments. When True, unknown arguments are created with force=False,", "or name in annotated_names or self._is_typing_member(name, var)): continue options =", "pytype import output from pytype import special_builtins from pytype import", "else: assert isinstance(option, typing_overlay.NoReturn) if isinstance(d, pytd.Type) and not isinstance(d,", "with val.data.record_calls(): new_node, ret = self.call_function_in_frame(node, fvar, *args) return new_node,", "\"\"\"Given Python source return its types. Args: src: A string", "node: The given node. val: A cfg.Binding containing the function.", "cfg.Binding containing the function. args: A function.Args object. Returns: A", "%s\", name) data.append(pytd.Constant(name, pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod def _call_traces_to_function(call_traces,", "= pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If merged with other if", "recursively set maybe_missing_members to True on the instance and its", "ty = pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions, aliases=aliases)) ty =", "metrics from pytype import output from pytype import special_builtins from", "subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\", \"-o\", svg_file], stdin=subprocess.PIPE, universal_newlines=True) (_, stderr) =", "abstract_utils from pytype import convert_structural from pytype import debug from", "if b.data in self._initialized_instances: continue self._initialized_instances.add(b.data) node = self._call_init_on_binding(node, b)", "A CFG node representing the program exit. Needs to be", "maybe_missing_members to True on the instance and its type parameters.", "sometimes isn't enough to disambiguate callers that shouldn't get back", "(including lambdas) need to be analyzed as # stand-alone functions.", "class, and also call __init__. Calling __init__ can be expensive,", "any # FailedFunctionCall errors. To prevent an infinite recursion loop,", "continue self._initialized_instances.add(b.data) node = self._call_init_on_binding(node, b) return node def reinitialize_if_initialized(self,", "self.convert.create_new_unknown(node, force=not use_defaults) args.append(arg) kws = {} for key in", "elif options: for option in options: try: d = option.to_pytd_def(self.exitpoint,", "method_name, method, binding.AssignToNewVariable()) node = self.analyze_method_var(node, method_name, bound_method) return node", "into the call trace. Args: node: The CFG node right", "to create a new # instance rather than using the", "posargs=(cls.AssignToNewVariable(node),) + args.posargs[1:]) else: return args def maybe_analyze_method(self, node, val,", "class_to_records.items(): full_name = cls.module + \".\" + cls.name if cls.module", "name_transform=lambda x: x): funcs = collections.defaultdict(pytd_utils.OrderedSet) for node, func, sigs,", "tracer_vm=None, **kwargs): \"\"\"Given Python source return its types. Args: src:", "not in self._analyzed_classes): node = self.analyze_class(node, value) for f in", "defs, maximum_depth): assert not self.frame self.maximum_depth = maximum_depth self._analyzing =", "back the same cached instance. Returns: A tuple of node", "tuple of (ast: TypeDeclUnit, builtins: TypeDeclUnit) Raises: AssertionError: In case", "tuple(signatures), pytd.MethodTypes.METHOD)) return functions def _is_typing_member(self, name, var): for module_name", "module_name in (\"typing\", \"typing_extensions\"): if module_name not in self.loaded_overlays: continue", "cfg.Binding of a function that was called. sigs: The signatures", "var.data: return True return False def pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls, escape.pack_partial)", "self._interpreter_classes: for value in c.bindings: if (isinstance(value.data, abstract.InterpreterClass) and value.data", "tracer_vm: An instance of CallTracer, in case the caller wants", "merged with other if statement, triggers a ValueError: Unresolved class", "function. # call_function will check fallback_to_unsolvable if a DictKeyMissing or", "method, binding.AssignToNewVariable()) node = self.analyze_method_var(node, method_name, bound_method) return node def", "output that type. annotated_names = set() data = [] pytd_convert", "args, kws, retvar in call_traces: # The lengths may be", "that will be # overwritten later. Note that we have", "(not self.options.analyze_annotated and (method.signature.has_return_annotation or method.has_overloads) and fname.rsplit(\".\", 1)[-1] not", "self.loaded_overlays: continue module = self.loaded_overlays[module_name].get_module(name) if name in module.members and", "slots=None, template=(), )) return classes def pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast() for", "state as frame_state from pytype import vm from pytype.overlays import", "clsv.Bindings(node, strict=False): node, var = self._instantiate_binding(node, cls, container) n.PasteVariable(var) return", "method, so that type parameters in the container's template are", "instance.to_binding(node)) def analyze_class(self, node, val): self._analyzed_classes.add(val.data) node, instance = self.init_class(node,", "else cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), # not used in", "node = self.call_init(node, instance) elif len(good_instances) != len(instance.bindings): # __new__", "will take care of that. Args: node: The current node.", "arg_types = (a.data.to_type(node) for a in args) ret = pytd_utils.JoinTypes(t.to_type(node)", "recursion loop, set # fallback_to_unsolvable to False just in case.", "defined in a pyi file # returns an instance of", "return self.join_cfg_nodes(nodes), instance def _instantiate_var(self, node, clsv, container): \"\"\"Build an", "not in seen: seen.add(v) if isinstance(v, abstract.SimpleValue): v.maybe_missing_members = True", "good_instances = [b for b in instance.bindings if val.data ==", "entry into the call trace. Args: node: The CFG node", "from pytype.pytd import visitors from pytype.typegraph import cfg log =", "initializing - otherwise, setting # maybe_missing_members to True would cause", "to %r with %d args, return %r\", func, len(posargs), result)", "True, unknown arguments are created with force=False, as it is", "cls) instance = self._instance_cache.get(key) if not instance or isinstance(instance, _Initializing):", "not self.options.report_errors: return True views = abstract_utils.get_views([actual], node) # Check", "elif len(good_instances) != len(instance.bindings): # __new__ returned some extra possibilities", "non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH = 2 # during quick checking QUICK_INFER_MAXIMUM_DEPTH", "determinicity if not self._is_typing_member(name, var): for value in var.bindings: if", "kept in the output. maximum_depth: Depth of the analysis. Default:", "tracer.loader.concat_all() # Insert type parameters, where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures())", "# unknowns - there's nothing to solve for. continue cls", "CallTracer(vm.VirtualMachine): \"\"\"Virtual machine that records all function calls. Attributes: exitpoint:", "BaseValue objects. On every instance among the values, recursively set", "= True node = node.ConnectNew(name=\"Analyze\") return self.analyze_toplevel(node, defs) def trace_unknown(self,", "In case of a bad parameter combination. \"\"\" # If", "\"__init__\") cls = b.data.get_class() if isinstance(cls, abstract.InterpreterClass): # Call any", "{} # Used by call_init. Can differ from _instance_cache because", "= options.output_cfg or options.output_typegraph proc = subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\", \"-o\",", "function might have been called with. posargs: The positional arguments,", "in new.data)): # This assumes that any inherited __new__ method", "if isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1, args = self.create_method_arguments(node0, func) # Once", "loop, so # we instead create an incomplete instance that", "if maximum_depth is None: maximum_depth = ( QUICK_CHECK_MAXIMUM_DEPTH if options.quick", "else: tracer.exitpoint = loc snapshotter.take_snapshot(\"analyze:infer_types:post\") ast = tracer.compute_types(defs) ast =", "rets.append(ret) if nodes: ret = self.join_variables(node0, rets) node = self.join_cfg_nodes(nodes)", "for type-checking defaults. Returns: A tuple of a node and", "unknowns - there's nothing to solve for. continue cls =", "args = self.create_method_arguments(node1, b.data) args = self._maybe_fix_classmethod_cls_arg(node0, cls, b.data, args)", "or i > 0: arg_names[i] = function.argname(i) arg_types = (a.data.to_type(node)", "solver methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(), decorators=(), slots=None, template=(), )) return classes", "b in instance.bindings if val.data == b.data.cls] if not good_instances:", "self.call_init(node, param) node = self._call_method(node, b, \"__init__\") cls = b.data.get_class()", "under a decorator. # Go through classes first so that", "that's not an instance of our class. instance = val.data.instantiate(node)", "all functions and classes we haven't analyzed yet. # These", "traces.\") # Rename remaining \"~unknown\" to \"?\" ast = ast.Visit(visitors.RemoveUnknownClasses())", "val in val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name)) return classes def pytd_for_types(self,", "of the analysis. Default: unlimited. tracer_vm: An instance of CallTracer,", "f.bindings: if self._should_analyze_as_interpreter_function(value.data): node = self.analyze_function(node, value) return node def", "object. \"\"\" args = [] num_posargs = method.argcount(node) num_posargs_no_default =", "+ cls.name if cls.module else cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),),", "args.posargs[1:]) else: return args def maybe_analyze_method(self, node, val, cls=None): method", "# DictKeyMissing doesn't trigger call_with_fake_args, so that shouldn't # be", "fine to use Unsolvable rather than Unknown objects for type-checking", "an instance of our class. instance = val.data.instantiate(node) node =", "not value.data.is_overload): new_node = self.analyze_function(node, value) else: continue if new_node", "instances. If you don't need __init__ called, use cls.instantiate instead.", "return (isinstance(data, abstract.InterpreterFunction) and not data.is_overload and not data.is_class_builder and", "\"\"\"Attempt to call the given function with made-up arguments.\"\"\" #", "import typing_overlay from pytype.pytd import builtins from pytype.pytd import escape", "self._instance_cache: # We've encountered a recursive pattern such as #", "during module loading. show_library_calls: If True, call traces are kept", "during non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH = 2 # during quick checking", "in __init__. self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key] = _Initializing() node = self.call_init(node,", "snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep: if maximum_depth is None: maximum_depth = (", "use Unsolvable rather than Unknown objects for type-checking defaults. Returns:", "Used by call_init. Can differ from _instance_cache because we also", "template are instantiated to TypeParameterInstance. extra_key: Optionally, extra information about", "protocols_pytd = None builtins_pytd = tracer.loader.concat_all() # Insert type parameters,", "True would cause pytype to ignore # all attribute errors", "nodes.append(node4) return self.join_cfg_nodes(nodes), instance def _instantiate_var(self, node, clsv, container): \"\"\"Build", "log.info(\"=========== Program Dump =============\\n%s\", text) else: with options.open_function(options.output_debug, \"w\") as", "m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls), [], node) return bound def _instantiate_binding(self, node0,", "function calls. Attributes: exitpoint: A CFG node representing the program", "in range(len(arg_names)): if not isinstance(func.data, abstract.BoundFunction) or i > 0:", "instance among the values, recursively set maybe_missing_members to True on", "None: if not options.quick: maximum_depth = MAXIMUM_DEPTH elif options.analyze_annotated: #", "for t in retvar.data) starargs = None starstarargs = None", "\"function\", \"signatures\", \"positional_arguments\", \"keyword_arguments\", \"return_value\"]) # How deep to follow", "in self._unknowns.items(): if val in val.variable.Filter(self.exitpoint, strict=False): classes.append(val.data.to_structural_def(self.exitpoint, name)) return", "else: data.append(d) else: log.error(\"No visible options for %s\", name) data.append(pytd.Constant(name,", "ret else: node = node0 log.info(\"Unable to generate fake arguments", "pattern such as # class A: # def __init__(self, x:", "two ways of recording are equivalent except for closures, which", "analyze all functions, even the ones not called by the", "for param in b.data.instance_type_parameters.values(): node = self.call_init(node, param) node =", "like \"<listcomp>\" and \"<genexpr>\". _SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\") CallRecord = collections.namedtuple(", "\"\"\"Code for checking and inferring types.\"\"\" import collections import logging", "_call_traces_to_function(call_traces, name_transform=lambda x: x): funcs = collections.defaultdict(pytd_utils.OrderedSet) for node, func,", "True return False def pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls, escape.pack_partial) def pytd_classes_for_call_traces(self):", "=============\\n%s\", pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not show_library_calls:", "A Variable of the possible result values. \"\"\" log.debug(\"Logging call", "a in kws), starargs, starstarargs, ret, exceptions=(), template=())) functions =", "in sorted(defs.items()): # sort, for determinicity if not self._is_typing_member(name, var):", "this method during initialization. b = self.bind_method(node, name, methodvar, instance)", "def create_kwargs(self, node): key_type = self.convert.primitive_class_instances[str].to_variable(node) value_type = self.convert.create_new_unknown(node) kwargs", "not node: new_node.ConnectTo(node) # Now go through all functions and", "self._method_calls.add(record) elif isinstance(func.data, abstract.PyTDFunction): self._calls.add(record) def trace_functiondef(self, f): self._interpreter_functions.append(f) def", "arguments for the given method. Note that we don't need", "A list of BaseValue objects. On every instance among the", "if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if (not self.options.analyze_annotated and (method.signature.has_return_annotation or", "= None starstarargs = None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t, False, False,", "self._instance_cache[key] = instance return node, instance def _call_method(self, node, binding,", "= [] rets = [] for funcb in funcv.bindings: func", "self._generated_classes.values()) def compute_types(self, defs): classes = (tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces()) +", "return not bad def check_types(src, filename, errorlog, options, loader, deep=True,", "type parameters, where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info(\"===========", "go. Instance of errors.ErrorLog. options: config.Options object loader: A load_pytd.Loader", "\"\"\" # If the caller has passed in a vm,", "result values. \"\"\" log.debug(\"Logging call to %r with %d args,", "which are # re-generated when the variables they close over", "would cause pytype to ignore # all attribute errors on", "(method.signature.has_return_annotation or method.has_overloads) and fname.rsplit(\".\", 1)[-1] not in self._CONSTRUCTORS): log.info(\"%r", "# def __init__(self, x: \"A\"): ... # Calling __init__ again", "abstract.PyTDClass): class_to_records[cls].append(call_record) classes = [] for cls, call_records in class_to_records.items():", "node): key_type = self.convert.primitive_class_instances[str].to_variable(node) value_type = self.convert.create_new_unknown(node) kwargs = abstract.Instance(self.convert.dict_type,", "isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if (not self.options.analyze_annotated and (method.signature.has_return_annotation or method.has_overloads)", "incomplete instance that will be # overwritten later. Note that", "object. The # two ways of recording are equivalent except", "b.data.get_class() if isinstance(cls, abstract.InterpreterClass): # Call any additional initalizers the", "output.\"\"\" if options.output_cfg or options.output_typegraph: dot = debug.program_to_dot(program, set([]), bool(options.output_cfg))", "the caller has passed in a vm, use that. if", "= re.compile(\"<(?!lambda).+>$\") CallRecord = collections.namedtuple( \"CallRecord\", [\"node\", \"function\", \"signatures\", \"positional_arguments\",", "node = self._call_method(node, b, method) return node def call_init(self, node,", "call. func: A cfg.Binding of a function that was called.", "starargs, starstarargs, ret, exceptions=(), template=())) functions = [] for name,", "args): # We don't need to record call signatures that", "representing the program exit. Needs to be set before analyze_types.", "name are equal, so it's fine to # overwrite previous", "expects not to get any. bad = [view for view", "= self.maybe_analyze_method(node1, val, cls) node2.ConnectTo(node0) return node0 def bind_method(self, node,", "than using the one that we're already in # the", "If merged with other if statement, triggers a ValueError: Unresolved", "extra information about the location at which the instantion occurs.", "*args) return new_node, ret def call_function_in_frame(self, node, var, args, kwargs,", "in defs for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): if \"__getattr__\" not in", "to the class's instantiate() method, so that type parameters in", "node1 = node0.ConnectNew(val.data.name) node2 = self.maybe_analyze_method(node1, val) node2.ConnectTo(node0) return node0", "= ( QUICK_CHECK_MAXIMUM_DEPTH if options.quick else MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth)", "_instantiate_var(self, node, clsv, container): \"\"\"Build an (dummy) instance from a", "maybe_analyze_method(self, node, val, cls=None): method = val.data fname = val.data.name", "a function. Args: node: The given node. val: A cfg.Binding", "var, args, kwargs, starargs, starstarargs) self.pop_frame(frame) return state.node, ret def", "= self.call_function_with_args(node3, b, args) instance.PasteVariable(ret) nodes.append(node4) return self.join_cfg_nodes(nodes), instance def", "f in self._interpreter_functions: for value in f.bindings: if self._should_analyze_as_interpreter_function(value.data): node", "\"~unknown\" to \"?\" ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove \"~list\" etc.:", "as part of a class. log.info(\"Analyze functions: Skipping class method", "_call_with_fake_args(self, node0, funcv): \"\"\"Attempt to call the given function with", "any(isinstance(a.data, abstract.Unknown) for a in args): # We don't need", "defs): classes = (tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances()) functions =", "nodes = [] rets = [] for funcb in funcv.bindings:", "abstract.InterpreterFunction) for f in new.data)): # This assumes that any", "pytype to ignore # all attribute errors on self in", "typically hidden under a decorator. # Go through classes first", "from pytype.overlays import typing_overlay from pytype.pytd import builtins from pytype.pytd", "_maybe_output_debug(options, tracer.program) return ast, builtins_pytd def _maybe_output_debug(options, program): \"\"\"Maybe emit", "Program Dump =============\\n%s\", text) else: with options.open_function(options.output_debug, \"w\") as fi:", "show_library_calls: If True, call traces are kept in the output.", "val.data.register_canonical_instance(instance_value) for name, methodvar in sorted(val.data.members.items()): if name in self._CONSTRUCTORS:", "func, len(posargs), result) args = tuple(posargs) kwargs = tuple((namedargs or", "call_with_fake_args, so that shouldn't # be raised again, and generating", "maximum_depth is None: maximum_depth = ( QUICK_CHECK_MAXIMUM_DEPTH if options.quick else", "self._analyzed_classes = set() self._generated_classes = {} self.exitpoint = None def", "isinstance(func, abstract.INTERPRETER_FUNCTION_TYPES): node1, args = self.create_method_arguments(node0, func) # Once the", "args, return %r\", func, len(posargs), result) args = tuple(posargs) kwargs", "keyword arguments, a dict mapping str to cfg.Value. result: A", "Creates Unknown objects as arguments for the given method. Note", "bad_matches # expects not to get any. bad = [view", "to call the given function with made-up arguments.\"\"\" # TODO(tsudol):", "method, use_defaults=False): \"\"\"Create arguments for the given method. Creates Unknown", "metaclass=None, parents=(pytd.NamedType(\"builtins.object\"),), # not used in solver methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(),", "init_maximum_depth) snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep: if maximum_depth", "ret = self.call_function_with_state( state, var, args, kwargs, starargs, starstarargs) self.pop_frame(frame)", "= self.create_method_arguments(node, f) if f.is_classmethod and cls: args = self._maybe_fix_classmethod_cls_arg(node,", "args): \"\"\"Call a function. Args: node: The given node. val:", "node and instance variable. \"\"\" key = (self.frame and self.frame.current_opcode,", "bad = [view for view in views if actual in", "= logging.getLogger(__name__) # Most interpreter functions (including lambdas) need to", "in the container's template are instantiated to TypeParameterInstance. extra_key: Optionally,", "in a pyi file # returns an instance of the", "instance): if instance in self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node)) def analyze_class(self, node,", "kwargs, starargs, starstarargs): frame = frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing %r\", [v.name", "if (isinstance(value.data, abstract.InterpreterClass) and value.data not in self._analyzed_classes): node =", "the args are generated, try calling the function. # call_function", "stdin=subprocess.PIPE, universal_newlines=True) (_, stderr) = proc.communicate(dot) if stderr: log.info(\"Failed to", "in v.instance_type_parameters.values(): values.extend(child.data) def init_class(self, node, cls, container=None, extra_key=None): \"\"\"Instantiate", "zip(arg_names, arg_types)) + tuple(pytd.Parameter(name, a.data.to_type(node), False, False, None) for name,", "for module_name in (\"typing\", \"typing_extensions\"): if module_name not in self.loaded_overlays:", "if isinstance(value.data, abstract.InterpreterClass): new_node = self.analyze_class(node, value) elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES)", "for option in options: try: d = option.to_pytd_def(self.exitpoint, name) #", "load_pytd.Loader instance to load PYI information. filename: Filename of the", "# have names like \"<listcomp>\" and \"<genexpr>\". _SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\")", "pytype import abstract from pytype import abstract_utils from pytype import", "trigger call_with_fake_args, so that shouldn't # be raised again, and", "= val.AssignToNewVariable(node) with val.data.record_calls(): new_node, ret = self.call_function_in_frame(node, fvar, *args)", "with %d args, return %r\", func, len(posargs), result) args =", "call traces.\") # Rename remaining \"~unknown\" to \"?\" ast =", "containing the function. args: A function.Args object. Returns: A tuple", "args = [] num_posargs = method.argcount(node) num_posargs_no_default = num_posargs -", "sorted(defs.items()): # sort, for determinicity if not self._is_typing_member(name, var): for", "types.\"\"\" import collections import logging import re import subprocess from", "method.has_kwargs() else None return node, function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs, starstarargs=starstarargs) def", "self._interpreter_functions = [] self._interpreter_classes = [] self._analyzed_functions = set() self._analyzed_classes", "of the return value. \"\"\" fvar = val.AssignToNewVariable(node) with val.data.record_calls():", "import abstract_utils from pytype import convert_structural from pytype import debug", "combination. \"\"\" # If the caller has passed in a", "def trace_call(self, node, func, sigs, posargs, namedargs, result): \"\"\"Add an", "if method.has_kwargs() else None return node, function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs, starstarargs=starstarargs)", "f in new.data)): # This assumes that any inherited __new__", "= set() self._analyzed_classes = set() self._generated_classes = {} self.exitpoint =", "given method. Note that we don't need to take parameter", "analyze_toplevel(self, node, defs): for name, var in sorted(defs.items()): # sort,", "output.TOP_LEVEL_IGNORE or name in annotated_names or self._is_typing_member(name, var)): continue options", "ambiguous whether this is a type, a function or something", "num_posargs_no_default = num_posargs - len(method.defaults) for i in range(num_posargs): default_idx", "in solver methods=tuple(self._call_traces_to_function(call_records)), constants=(), classes=(), decorators=(), slots=None, template=(), )) return", "this method caches its created instances. If you don't need", "current opcode and the class, which sometimes isn't enough to", "def _is_typing_member(self, name, var): for module_name in (\"typing\", \"typing_extensions\"): if", "# If the caller has passed in a vm, use", "the call trace. Args: node: The CFG node right after", "args = tuple(posargs) kwargs = tuple((namedargs or {}).items()) record =", "from pytype import output from pytype import special_builtins from pytype", "module.members and module.members[name].data == var.data: return True return False def", "node, val): self._analyzed_classes.add(val.data) node, instance = self.init_class(node, val.data) good_instances =", "%r with %d args, return %r\", func, len(posargs), result) args", "v not in seen: seen.add(v) if isinstance(v, abstract.SimpleValue): v.maybe_missing_members =", "be raised will be passed to # the call_function that", "options.output_typegraph proc = subprocess.Popen([\"/usr/bin/dot\", \"-T\", \"svg\", \"-o\", svg_file], stdin=subprocess.PIPE, universal_newlines=True)", "TypeDeclUnit) Raises: AssertionError: In case of a bad parameter combination.", "func = funcb.data log.info(\"Trying %s with fake arguments\", func) if", "self.bind_method( node, method_name, method, binding.AssignToNewVariable()) node = self.analyze_method_var(node, method_name, bound_method)", "one that we're already in # the process of initializing", "import function from pytype import metrics from pytype import output", "return classes def pytd_classes_for_namedtuple_instances(self): return tuple(v.generate_ast() for v in self._generated_classes.values())", "The exceptions are comprehensions and generators, which # have names", "= frame_state.FrameState.init(node, self) state, ret = self.call_function_with_state( state, var, args,", "is a type, a function or something # else, so", "loc, defs = tracer.run_program(src, filename, init_maximum_depth) snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot)", "CallTracer, in case the caller wants to instantiate and retain", "actual, formal): if not self.options.report_errors: return True views = abstract_utils.get_views([actual],", "is_cls), [], node) return bound def _instantiate_binding(self, node0, cls, container):", "namedargs: The keyword arguments, a dict mapping str to cfg.Value.", "self._is_typing_member(name, var)): continue options = var.FilteredData(self.exitpoint, strict=False) if (len(options) >", "self.create_varargs(node) if method.has_varargs() else None starstarargs = self.create_kwargs(node) if method.has_kwargs()", "a in args): # We don't need to record call", "extra_key=None): \"\"\"Instantiate a class, and also call __init__. Calling __init__", "in self._CONSTRUCTORS): log.info(\"%r has annotations, not analyzing further.\", fname) else:", "given method. Creates Unknown objects as arguments for the given", "annotations, not analyzing further.\", fname) else: for f in method.iter_signature_functions():", "target function is called. # DictKeyMissing doesn't trigger call_with_fake_args, so", "these values and their type params. Args: values: A list", "since bad_matches # expects not to get any. bad =", "= ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info(\"=========== PyTD to solve =============\\n%s\", pytd_utils.Print(ast))", "the values, recursively set maybe_missing_members to True on the instance", "unknown_binding): self._unknowns[name] = unknown_binding def trace_call(self, node, func, sigs, posargs,", "that called this method in the first place. node2, ret", "for f in new.data)): # This assumes that any inherited", "annotated_names.add(name) data.append(pytd.Constant(name, t)) for name, var in defs.items(): if (name", "= ty.Visit(optimize.CombineReturnsAndExceptions()) ty = ty.Visit(optimize.PullInMethodClasses()) ty = ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()],", "node4, ret = self.call_function_with_args(node3, b, args) instance.PasteVariable(ret) nodes.append(node4) return self.join_cfg_nodes(nodes),", "Check for typevars in the return value first, since bad_matches", "self.join_cfg_nodes(nodes) if ret.bindings: return node, ret else: node = node0", "an instance of the current class. return node0, cls.data.instantiate(node0, container=container)", "= unknown_binding def trace_call(self, node, func, sigs, posargs, namedargs, result):", "defs) def trace_unknown(self, name, unknown_binding): self._unknowns[name] = unknown_binding def trace_call(self,", "in self._instance_cache: # We've encountered a recursive pattern such as", "for the given method. Creates Unknown objects as arguments for", "etc.: ast = convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return ast, builtins_pytd def", "of a class. log.info(\"Analyze functions: Skipping class method %s\", val.data.name)", "names like \"<listcomp>\" and \"<genexpr>\". _SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\") CallRecord =", "as constants ty = pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions, aliases=aliases))", "*args, **kwargs): super().__init__(*args, **kwargs) self._unknowns = {} self._calls = set()", "= self.call_function_with_state( state, var, args, kwargs, starargs, starstarargs) self.pop_frame(frame) return", "possibilities we don't need. instance = self.join_bindings(node, good_instances) for instance_value", "dict mapping str to cfg.Value. result: A Variable of the", "= None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t, False, False, None) for n,", "t, False, False, None) for n, t in zip(arg_names, arg_types))", "node, actual, formal): if not self.options.report_errors: return True views =", "to solve for. continue cls = args[0].data.get_class() if isinstance(cls, abstract.PyTDClass):", "as a constant. combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t in options)", "cls, func, args): sig = func.signature if (args.posargs and sig.param_names", "starstarargs, ret, exceptions=(), template=())) functions = [] for name, signatures", "node, instance): if instance in self._initialized_instances: self._call_init_on_binding(node, instance.to_binding(node)) def analyze_class(self,", "__new__ returned something that's not an instance of our class.", "current node. method: An abstract.InterpreterFunction. use_defaults: Whether to use parameter", "is raised when the target function is called. # DictKeyMissing", "# If merged with other if statement, triggers a ValueError:", "arg = self.convert.create_new_unknown(node, force=not use_defaults) args.append(arg) kws = {} for", "if actual in view and view[actual].data.formal] if not bad: bad", "parameters in the container's template are instantiated to TypeParameterInstance. extra_key:", "the ones not called by the main execution flow. init_maximum_depth:", "close over change, but we don't want # to re-analyze", "in self._CONSTRUCTORS: continue # We already called this method during", "to \"?\" ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove \"~list\" etc.: ast", "%r\", [v.name for v in var.data]) state = frame_state.FrameState.init(node, self)", "new.data)): # This assumes that any inherited __new__ method defined", "that the function might have been called with. posargs: The", "(dummy) instance from a class, for analyzing it.\"\"\" n =", "encountered a recursive pattern such as # class A: #", "tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program) def infer_types(src, errorlog, options,", "\"\"\" _CONSTRUCTORS = (\"__new__\", \"__init__\") def __init__(self, *args, **kwargs): super().__init__(*args,", "d = pytd.AnythingType() else: assert isinstance(option, typing_overlay.NoReturn) if isinstance(d, pytd.Type)", "self._interpreter_classes.append(c) def trace_namedtuple(self, nt): # All namedtuple instances with the", "tracer.program) def infer_types(src, errorlog, options, loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False,", "func: A cfg.Binding of a function that was called. sigs:", "instances with the same name are equal, so it's fine", "triggers a ValueError: Unresolved class # when attempts to load", "optimize from pytype.pytd import pytd from pytype.pytd import pytd_utils from", "return node def _call_init_on_binding(self, node, b): if isinstance(b.data, abstract.SimpleValue): for", "further.\", fname) else: for f in method.iter_signature_functions(): node, args =", "node: The current node. method: An abstract.InterpreterFunction. use_defaults: Whether to", "args, kwargs, starargs, starstarargs): frame = frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing %r\",", "args) ret = pytd_utils.JoinTypes(t.to_type(node) for t in retvar.data) starargs =", "= self.call_init(node, instance) elif len(good_instances) != len(instance.bindings): # __new__ returned", "for f in method.iter_signature_functions(): node, args = self.create_method_arguments(node, f) if", "method keys on the current opcode and the class, which", "call_init(self, node, instance): # Call __init__ on each binding. for", "val.data.is_attribute_of_class: # We'll analyze this function as part of a", "instance = self.join_bindings(node, good_instances) for instance_value in instance.data: val.data.register_canonical_instance(instance_value) for", "the same name are equal, so it's fine to #", "turned off. Discarding call traces.\") # Rename remaining \"~unknown\" to", "{} self.exitpoint = None def create_varargs(self, node): value = abstract.Instance(self.convert.tuple_type,", "self.program.NewVariable() for cls in clsv.Bindings(node, strict=False): node, var = self._instantiate_binding(node,", "ones not called by the main execution flow. init_maximum_depth: Depth", "options=options, generate_unknowns=False, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth)", "the class's instantiate() method, so that type parameters in the", "visible options for %s\", name) data.append(pytd.Constant(name, pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\", data)", "Raises: AssertionError: In case of a bad parameter combination. \"\"\"", "node0, name, var, cls=None): log.info(\"Analyzing %s\", name) node1 = node0.ConnectNew(name)", "if options.protocols: protocols_pytd = tracer.loader.import_name(\"protocols\") else: protocols_pytd = None builtins_pytd", "If the caller has passed in a vm, use that.", "container=container) instance = self.program.NewVariable() nodes = [] for b in", "self._analyzed_functions and not _SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self, node, defs): for name,", "node, var = self._instantiate_binding(node, cls, container) n.PasteVariable(var) return node, n", "and fname.rsplit(\".\", 1)[-1] not in self._CONSTRUCTORS): log.info(\"%r has annotations, not", "aliases = () # aliases are instead recorded as constants", "type inference. **kwargs: Additional parameters to pass to vm.VirtualMachine Returns:", "re import subprocess from typing import Any, Dict, Union from", "= method.argcount(node) num_posargs_no_default = num_posargs - len(method.defaults) for i in", "[] rets = [] for funcb in funcv.bindings: func =", "as arguments for the given method. Note that we don't", "log.info(\"Failed to create %s: %s\", svg_file, stderr) if options.output_debug: text", "len(method.defaults) for i in range(num_posargs): default_idx = i - num_posargs_no_default", "is annotated, we'll always output that type. annotated_names = set()", "instance.PasteVariable(ret) nodes.append(node4) return self.join_cfg_nodes(nodes), instance def _instantiate_var(self, node, clsv, container):", "code===\") snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep: if maximum_depth", "- num_posargs_no_default if use_defaults and default_idx >= 0: arg =", "to # the call_function that called this method in the", "set() self._method_calls = set() # Used by init_class. self._instance_cache: Dict[Any,", "# returns an instance of the current class. return node0,", "v = values.pop(0) if v not in seen: seen.add(v) if", "Attributes: exitpoint: A CFG node representing the program exit. Needs", "self.convert.create_new_unknown(node)) return value.to_variable(node) def create_kwargs(self, node): key_type = self.convert.primitive_class_instances[str].to_variable(node) value_type", "self._analyzed_classes): node = self.analyze_class(node, value) for f in self._interpreter_functions: for", "metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if deep: if maximum_depth is None: if not", "if maximum_depth is None: if not options.quick: maximum_depth = MAXIMUM_DEPTH", "pytype.pytd import builtins from pytype.pytd import escape from pytype.pytd import", "bad def check_types(src, filename, errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None,", "so that type parameters in the container's template are instantiated", "child in v.instance_type_parameters.values(): values.extend(child.data) def init_class(self, node, cls, container=None, extra_key=None):", "not in self.loaded_overlays: continue module = self.loaded_overlays[module_name].get_module(name) if name in", "node0 def _should_analyze_as_interpreter_function(self, data): # We record analyzed functions by", "isinstance(value.data, abstract.InterpreterClass): new_node = self.analyze_class(node, value) elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and", "\"\"\"Instantiate a class, and also call __init__. Calling __init__ can", "= {} # Used by call_init. Can differ from _instance_cache", "# The lengths may be different in the presence of", "called this method during initialization. b = self.bind_method(node, name, methodvar,", "# Used by call_init. Can differ from _instance_cache because we", "in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2, args = self.create_method_arguments(node1, b.data) args =", "builtins: TypeDeclUnit) Raises: AssertionError: In case of a bad parameter", "== var.data: return True return False def pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls,", "i in range(len(arg_names)): if not isinstance(func.data, abstract.BoundFunction) or i >", "self in __init__. self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key] = _Initializing() node =", "instance) node = self.analyze_method_var(node, name, b, val) return node def", "= self.matcher.bad_matches(actual, formal, node) if bad: self.errorlog.bad_return_type( self.frames, node, formal,", "module loading. show_library_calls: If True, call traces are kept in", "except NotImplementedError: d = option.to_type(self.exitpoint) # Type only if isinstance(d,", "self._analyzed_functions.add(method.get_first_opcode()) if (not self.options.analyze_annotated and (method.signature.has_return_annotation or method.has_overloads) and fname.rsplit(\".\",", "set # fallback_to_unsolvable to False just in case. # This", "%s\", val.data.name) else: node1 = node0.ConnectNew(val.data.name) node2 = self.maybe_analyze_method(node1, val)", "maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program) def infer_types(src, errorlog, options, loader, filename=None,", "if statement, triggers a ValueError: Unresolved class # when attempts", "CallRecord(node, func, sigs, args, kwargs, result) if isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record)", "Unresolved class # when attempts to load from the protocols", "have names like \"<listcomp>\" and \"<genexpr>\". _SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\") CallRecord", "re-analyze them. return (isinstance(data, abstract.InterpreterFunction) and not data.is_overload and not", "prevent an infinite recursion loop, set # fallback_to_unsolvable to False", "pass class CallTracer(vm.VirtualMachine): \"\"\"Virtual machine that records all function calls.", "a bad parameter combination. \"\"\" # If the caller has", "kwargs, starargs, starstarargs) self.pop_frame(frame) return state.node, ret def _maybe_fix_classmethod_cls_arg(self, node,", "to load PYI information. filename: Filename of the program we're", "val.data.record_calls(): new_node, ret = self.call_function_in_frame(node, fvar, *args) return new_node, ret", "in args) ret = pytd_utils.JoinTypes(t.to_type(node) for t in retvar.data) starargs", "import special_builtins from pytype import state as frame_state from pytype", "self) value.merge_instance_type_parameter( node, abstract_utils.T, self.convert.create_new_unknown(node)) return value.to_variable(node) def create_kwargs(self, node):", "on the current opcode and the class, which sometimes isn't", "same name are equal, so it's fine to # overwrite", "kws, retvar in call_traces: # The lengths may be different", "and \"<genexpr>\". _SKIP_FUNCTION_RE = re.compile(\"<(?!lambda).+>$\") CallRecord = collections.namedtuple( \"CallRecord\", [\"node\",", "if isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record) elif isinstance(func.data, abstract.PyTDFunction): self._calls.add(record) def trace_functiondef(self,", "[v.name for v in var.data]) state = frame_state.FrameState.init(node, self) state,", "import collections import logging import re import subprocess from typing", "if isinstance(cls, abstract.InterpreterClass): # Call any additional initalizers the class", "dot = debug.program_to_dot(program, set([]), bool(options.output_cfg)) svg_file = options.output_cfg or options.output_typegraph", "value) elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and not value.data.is_overload): new_node = self.analyze_function(node,", "view in views if actual in view and view[actual].data.formal] if", "first, since bad_matches # expects not to get any. bad", "node representing the program exit. Needs to be set before", "namedtuple instances with the same name are equal, so it's", "options, loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs): \"\"\"Given", "instantiate and retain the vm used for type inference. **kwargs:", "ty = ty.Visit(optimize.CombineReturnsAndExceptions()) ty = ty.Visit(optimize.PullInMethodClasses()) ty = ty.Visit(visitors.DefaceUnresolved( [ty,", "pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If merged with other if statement,", "self._unknowns[name] = unknown_binding def trace_call(self, node, func, sigs, posargs, namedargs,", "# call_function will check fallback_to_unsolvable if a DictKeyMissing or #", "and view[actual].data.formal] if not bad: bad = self.matcher.bad_matches(actual, formal, node)", "builtins_pytd def _maybe_output_debug(options, program): \"\"\"Maybe emit debugging output.\"\"\" if options.output_cfg", "This assumes that any inherited __new__ method defined in a", "node = node0 log.info(\"Unable to generate fake arguments for %s\",", "vm used for type inference. **kwargs: Additional parameters to pass", "node = self.analyze_method_var(node, method_name, bound_method) return node def _call_init_on_binding(self, node,", "from pytype import special_builtins from pytype import state as frame_state", "data.is_class_builder and data.get_first_opcode() not in self._analyzed_functions and not _SKIP_FUNCTION_RE.search(data.name)) def", "class's instantiate() method, so that type parameters in the container's", "overwritten later. Note that we have to create a new", "# We already called this method during initialization. b =", "if nodes: ret = self.join_variables(node0, rets) node = self.join_cfg_nodes(nodes) if", "\"\"\" key = (self.frame and self.frame.current_opcode, extra_key, cls) instance =", "extra possibilities we don't need. instance = self.join_bindings(node, good_instances) for", "self.convert.create_new_unknown(node) kwargs = abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node, abstract_utils.K, key_type) kwargs.merge_instance_type_parameter(node, abstract_utils.V,", "are instantiated to TypeParameterInstance. extra_key: Optionally, extra information about the", "= i - num_posargs_no_default if use_defaults and default_idx >= 0:", "self._interpreter_classes = [] self._analyzed_functions = set() self._analyzed_classes = set() self._generated_classes", "if options.output_debug: text = debug.program_to_text(program) if options.output_debug == \"-\": log.info(\"===========", "for. continue cls = args[0].data.get_class() if isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record) classes", "def _instantiate_binding(self, node0, cls, container): \"\"\"Instantiate a class binding.\"\"\" node1,", "to disambiguate callers that shouldn't get back the same cached", "in method.kw_defaults: kws[key] = method.kw_defaults[key] else: kws[key] = self.convert.create_new_unknown(node, force=not", "for f in self._interpreter_functions: for value in f.bindings: if self._should_analyze_as_interpreter_function(value.data):", "else: continue if new_node is not node: new_node.ConnectTo(node) # Now", "actual in view and view[actual].data.formal] if not bad: bad =", "1 # during quick inference class _Initializing: pass class CallTracer(vm.VirtualMachine):", "# the process of initializing - otherwise, setting # maybe_missing_members", "involve # unknowns - there's nothing to solve for. continue", "= self._maybe_fix_classmethod_cls_arg(node0, cls, b.data, args) node3 = node2.ConnectNew() node4, ret", "for inference, # the presence of this option means that", "(len(options) > 1 and not all(isinstance(o, abstract.FUNCTION_TYPES) for o in", "Unknown objects for type-checking defaults. Returns: A tuple of a", "values): \"\"\"Set maybe_missing_members to True on these values and their", "# maybe_missing_members to True would cause pytype to ignore #", "subprocess from typing import Any, Dict, Union from pytype import", "key in method.kw_defaults: kws[key] = method.kw_defaults[key] else: kws[key] = self.convert.create_new_unknown(node,", "cls) node2.ConnectTo(node0) return node0 def bind_method(self, node, name, methodvar, instance_var):", "funcv): \"\"\"Attempt to call the given function with made-up arguments.\"\"\"", "b, args) instance.PasteVariable(ret) nodes.append(node4) return self.join_cfg_nodes(nodes), instance def _instantiate_var(self, node,", "instance of CallTracer, in case the caller wants to instantiate", "quick inference class _Initializing: pass class CallTracer(vm.VirtualMachine): \"\"\"Virtual machine that", "for sig in sigs), key=len) for i in range(len(arg_names)): if", "+ self.pytd_classes_for_namedtuple_instances()) functions = tuple(self.pytd_functions_for_call_traces()) aliases = () # aliases", "we don't need. instance = self.join_bindings(node, good_instances) for instance_value in", "= self.analyze_class(node, value) for f in self._interpreter_functions: for value in", "new_node = self.analyze_class(node, value) elif (isinstance(value.data, abstract.INTERPRETER_FUNCTION_TYPES) and not value.data.is_overload):", "= [] for b in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2, args =", "optional and kw args. arg_names = max((sig.get_positional_names() for sig in", "that we don't need to take parameter annotations into account", "cls, f, args) node, _ = self.call_function_with_args(node, val, args) return", "%s\", funcv) return node, self.new_unsolvable(node) def analyze_method_var(self, node0, name, var,", "= pytd_utils.JoinTypes(t.to_type(node) for t in retvar.data) starargs = None starstarargs", "else: node = node0 log.info(\"Unable to generate fake arguments for", "pytd.AnythingType() else: assert isinstance(option, typing_overlay.NoReturn) if isinstance(d, pytd.Type) and not", "are kept in the output. maximum_depth: Depth of the analysis.", "max((sig.get_positional_names() for sig in sigs), key=len) for i in range(len(arg_names)):", "\"\"\"Maybe emit debugging output.\"\"\" if options.output_cfg or options.output_typegraph: dot =", "\"\"\" values = list(values) seen = set() while values: v", "call __init__. Calling __init__ can be expensive, so this method", "functions, even the ones not called by the main execution", "nodes = [] for b in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2, args", "= [view for view in views if actual in view", "range(len(arg_names)): if not isinstance(func.data, abstract.BoundFunction) or i > 0: arg_names[i]", "c in self._interpreter_classes: for value in c.bindings: if (isinstance(value.data, abstract.InterpreterClass)", "_Initializing: pass class CallTracer(vm.VirtualMachine): \"\"\"Virtual machine that records all function", "log.info(\"Analyze functions: Skipping class method %s\", val.data.name) else: node1 =", "self.convert.pytd_convert annots = abstract_utils.get_annotations_dict(defs) for name, t in pytd_convert.annotations_to_instance_types( self.exitpoint,", "typing_overlay.NoReturn) if isinstance(d, pytd.Type) and not isinstance(d, pytd.TypeParameter): data.append(pytd.Constant(name, d))", "sort, for determinicity if not self._is_typing_member(name, var): for value in", "special_builtins.ClassMethodInstance): m = m.func.data[0] is_cls = True else: is_cls =", "or method.has_overloads) and fname.rsplit(\".\", 1)[-1] not in self._CONSTRUCTORS): log.info(\"%r has", "else None starstarargs = self.create_kwargs(node) if method.has_kwargs() else None return", "metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep: if maximum_depth is None: maximum_depth", "for determinicity if not self._is_typing_member(name, var): for value in var.bindings:", "with the same name are equal, so it's fine to", "analyzing further.\", fname) else: for f in method.iter_signature_functions(): node, args", "args) return node def _call_with_fake_args(self, node0, funcv): \"\"\"Attempt to call", "the instantion occurs. By default, this method keys on the", "instance of the current class. return node0, cls.data.instantiate(node0, container=container) instance", "if name in module.members and module.members[name].data == var.data: return True", "over change, but we don't want # to re-analyze them.", "of (ast: TypeDeclUnit, builtins: TypeDeclUnit) Raises: AssertionError: In case of", "solve for. continue cls = args[0].data.get_class() if isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record)", "inference. **kwargs: Additional parameters to pass to vm.VirtualMachine Returns: A", "node): value = abstract.Instance(self.convert.tuple_type, self) value.merge_instance_type_parameter( node, abstract_utils.T, self.convert.create_new_unknown(node)) return", "any(not isinstance(f, abstract.InterpreterFunction) for f in new.data)): # This assumes", "in (\"typing\", \"typing_extensions\"): if module_name not in self.loaded_overlays: continue module", "in instance.bindings if val.data == b.data.cls] if not good_instances: #", "Args: node: The given node. val: A cfg.Binding containing the", "generate fake arguments for %s\", funcv) return node, self.new_unsolvable(node) def", "for node, func, sigs, args, kws, retvar in call_traces: #", "cls in clsv.Bindings(node, strict=False): node, var = self._instantiate_binding(node, cls, container)", "= collections.namedtuple( \"CallRecord\", [\"node\", \"function\", \"signatures\", \"positional_arguments\", \"keyword_arguments\", \"return_value\"]) #", "if bad: self.errorlog.bad_return_type( self.frames, node, formal, actual, bad) return not", "object. Returns: A tuple of (1) a node and (2)", "abstract.InterpreterFunction) and not data.is_overload and not data.is_class_builder and data.get_first_opcode() not", "in pytd_convert.annotations_to_instance_types( self.exitpoint, annots): annotated_names.add(name) data.append(pytd.Constant(name, t)) for name, var", "from pytype.pytd import optimize from pytype.pytd import pytd from pytype.pytd", "go through all functions and classes we haven't analyzed yet.", "fallback_to_unsolvable=False) nodes.append(node2) rets.append(ret) if nodes: ret = self.join_variables(node0, rets) node", "and data.get_first_opcode() not in self._analyzed_functions and not _SKIP_FUNCTION_RE.search(data.name)) def analyze_toplevel(self,", "a type, a function or something # else, so encode", "return node, ret else: node = node0 log.info(\"Unable to generate", "create_kwargs(self, node): key_type = self.convert.primitive_class_instances[str].to_variable(node) value_type = self.convert.create_new_unknown(node) kwargs =", "use_defaults) starargs = self.create_varargs(node) if method.has_varargs() else None starstarargs =", "binding) if method: bound_method = self.bind_method( node, method_name, method, binding.AssignToNewVariable())", "call chains: INIT_MAXIMUM_DEPTH = 4 # during module loading MAXIMUM_DEPTH", "= CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader, **kwargs) loc, defs = tracer.run_program(src,", "before analyze_types. \"\"\" _CONSTRUCTORS = (\"__new__\", \"__init__\") def __init__(self, *args,", "n def _mark_maybe_missing_members(self, values): \"\"\"Set maybe_missing_members to True on these", "infer_types(src, errorlog, options, loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None,", "options.output_debug: text = debug.program_to_text(program) if options.output_debug == \"-\": log.info(\"=========== Program", "in ast: ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If merged", "node def analyze_function(self, node0, val): if val.data.is_attribute_of_class: # We'll analyze", "functions for inference, # the presence of this option means", "and not data.is_overload and not data.is_class_builder and data.get_first_opcode() not in", "in sig.annotations)): # fix \"cls\" parameter return args._replace( posargs=(cls.AssignToNewVariable(node),) +", "not any(isinstance(a.data, abstract.Unknown) for a in args): # We don't", "main execution flow. init_maximum_depth: Depth of analysis during module loading.", "%s: %s\", svg_file, stderr) if options.output_debug: text = debug.program_to_text(program) if", "funcb in funcv.bindings: func = funcb.data log.info(\"Trying %s with fake", "initialized via init_class. self._initialized_instances = set() self._interpreter_functions = [] self._interpreter_classes", "tuple(v.generate_ast() for v in self._generated_classes.values()) def compute_types(self, defs): classes =", "b, \"__init__\") cls = b.data.get_class() if isinstance(cls, abstract.InterpreterClass): # Call", "set() # Used by init_class. self._instance_cache: Dict[Any, Union[_Initializing, cfg.Variable]] =", "they close over change, but we don't want # to", "data.append(pytd.Constant(name, combined_types)) elif options: for option in options: try: d", "node) if bad: self.errorlog.bad_return_type( self.frames, node, formal, actual, bad) return", "combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t in options) data.append(pytd.Constant(name, combined_types)) elif", "**kwargs): super().__init__(*args, **kwargs) self._unknowns = {} self._calls = set() self._method_calls", "(tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances()) functions = tuple(self.pytd_functions_for_call_traces()) aliases =", "cls, b.data, args) node3 = node2.ConnectNew() node4, ret = self.call_function_with_args(node3,", "kwargs = tuple((namedargs or {}).items()) record = CallRecord(node, func, sigs,", "self.convert.create_new_unknown(node, force=not use_defaults) starargs = self.create_varargs(node) if method.has_varargs() else None", "callers that shouldn't get back the same cached instance. Returns:", "def _call_with_fake_args(self, node0, funcv): \"\"\"Attempt to call the given function", "options)): # It's ambiguous whether this is a type, a", "\"svg\", \"-o\", svg_file], stdin=subprocess.PIPE, universal_newlines=True) (_, stderr) = proc.communicate(dot) if", "__init__ can be expensive, so this method caches its created", "return functions def _is_typing_member(self, name, var): for module_name in (\"typing\",", "defaults. Returns: A tuple of a node and a function.Args", "not show_library_calls: log.info(\"Solving is turned off. Discarding call traces.\") #", "loading. show_library_calls: If True, call traces are kept in the", "pytype import function from pytype import metrics from pytype import", "method.has_varargs() else None starstarargs = self.create_kwargs(node) if method.has_kwargs() else None", "self.program.NewVariable() nodes = [] for b in new.bindings: self._analyzed_functions.add(b.data.get_first_opcode()) node2,", "node, method = self.attribute_handler.get_attribute( node, binding.data.get_class(), method_name, binding) if method:", "or isinstance(instance, _Initializing): clsvar = cls.to_variable(node) node, instance = self._instantiate_var(node,", "options: config.Options object loader: A load_pytd.Loader instance to load PYI", "about the location at which the instantion occurs. By default,", "in the output. maximum_depth: Depth of the analysis. Default: unlimited.", "from pytype import abstract from pytype import abstract_utils from pytype", "arg_names = max((sig.get_positional_names() for sig in sigs), key=len) for i", "arguments, an iterable over cfg.Value. namedargs: The keyword arguments, a", "nodes.append(node2) rets.append(ret) if nodes: ret = self.join_variables(node0, rets) node =", "from pytype.pytd import pytd from pytype.pytd import pytd_utils from pytype.pytd", "= ast.Visit(visitors.RemoveUnknownClasses()) # Remove \"~list\" etc.: ast = convert_structural.extract_local(ast) _maybe_output_debug(options,", "cls, container=None, extra_key=None): \"\"\"Instantiate a class, and also call __init__.", "trace_namedtuple(self, nt): # All namedtuple instances with the same name", "node and a function.Args object. \"\"\" args = [] num_posargs", "import visitors from pytype.typegraph import cfg log = logging.getLogger(__name__) #", "var.data]) state = frame_state.FrameState.init(node, self) state, ret = self.call_function_with_state( state,", "are equal, so it's fine to # overwrite previous instances.", "# These are typically hidden under a decorator. # Go", "clsvar = cls.to_variable(node) node, instance = self._instantiate_var(node, clsvar, container) if", "# be set for all functions in class. for c", "class, which sometimes isn't enough to disambiguate callers that shouldn't", "None starstarargs = None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t, False, False, None)", "= self.convert.pytd_convert annots = abstract_utils.get_annotations_dict(defs) for name, t in pytd_convert.annotations_to_instance_types(", "Unknown objects as arguments for the given method. Note that", "node, n def _mark_maybe_missing_members(self, values): \"\"\"Set maybe_missing_members to True on", "for a in args): # We don't need to record", "call_init. Can differ from _instance_cache because we also call #", "A tuple of a node and a function.Args object. \"\"\"", "ast = convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return ast, builtins_pytd def _maybe_output_debug(options,", "and (sig.param_names[0] not in sig.annotations)): # fix \"cls\" parameter return", "on self in __init__. self._mark_maybe_missing_members(instance.data) else: self._instance_cache[key] = _Initializing() node", "# Deep definition except NotImplementedError: d = option.to_type(self.exitpoint) # Type", "that. if tracer_vm: assert isinstance(tracer_vm, CallTracer) tracer = tracer_vm else:", "args: A function.Args object. Returns: A tuple of (1) a", "return ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self, node, actual, formal): if not self.options.report_errors:", "special_builtins from pytype import state as frame_state from pytype import", "caller wants to instantiate and retain the vm used for", "= proc.communicate(dot) if stderr: log.info(\"Failed to create %s: %s\", svg_file,", "# We record analyzed functions by opcode rather than function", "classes = (tuple(self.pytd_classes_for_unknowns()) + tuple(self.pytd_classes_for_call_traces()) + self.pytd_classes_for_namedtuple_instances()) functions = tuple(self.pytd_functions_for_call_traces())", "don't involve # unknowns - there's nothing to solve for.", "# class A: # def __init__(self, x: \"A\"): ... #", "arguments, a dict mapping str to cfg.Value. result: A Variable", "if (name in output.TOP_LEVEL_IGNORE or name in annotated_names or self._is_typing_member(name,", "node, method, use_defaults=False): \"\"\"Create arguments for the given method. Creates", "[] pytd_convert = self.convert.pytd_convert annots = abstract_utils.get_annotations_dict(defs) for name, t", "self.exitpoint, annots): annotated_names.add(name) data.append(pytd.Constant(name, t)) for name, var in defs.items():", "new_node is not node: new_node.ConnectTo(node) # Now go through all", "method caches its created instances. If you don't need __init__", "need to be analyzed as # stand-alone functions. The exceptions", "name, a in kws), starargs, starstarargs, ret, exceptions=(), template=())) functions", "returned some extra possibilities we don't need. instance = self.join_bindings(node,", "any. bad = [view for view in views if actual", "node. method: An abstract.InterpreterFunction. use_defaults: Whether to use parameter defaults", "self.loaded_overlays[module_name].get_module(name) if name in module.members and module.members[name].data == var.data: return", "method.has_overloads) and fname.rsplit(\".\", 1)[-1] not in self._CONSTRUCTORS): log.info(\"%r has annotations,", "kw args. arg_names = max((sig.get_positional_names() for sig in sigs), key=len)", "definitions and module-level code===\") snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\") if", "called with. posargs: The positional arguments, an iterable over cfg.Value.", "if not any(isinstance(a.data, abstract.Unknown) for a in args): # We", "abstract.BoundFunction) or i > 0: arg_names[i] = function.argname(i) arg_types =", "3 # during non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH = 2 # during", "instance = self._instance_cache.get(key) if not instance or isinstance(instance, _Initializing): clsvar", "analyzing annotated functions for inference, # the presence of this", "method during initialization. b = self.bind_method(node, name, methodvar, instance) node", "= None builtins_pytd = tracer.loader.concat_all() # Insert type parameters, where", "in case. # This means any additional errors that may", "len(good_instances) != len(instance.bindings): # __new__ returned some extra possibilities we", "running definitions and module-level code===\") snapshotter = metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:infer_types:tracer\")", "the protocols file if options.protocols: protocols_pytd = tracer.loader.import_name(\"protocols\") else: protocols_pytd", "and value.data not in self._analyzed_classes): node = self.analyze_class(node, value) for", "= func.signature if (args.posargs and sig.param_names and (sig.param_names[0] not in", "starstarargs = None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n, t, False, False, None) for", "shouldn't get back the same cached instance. Returns: A tuple", "pytd_convert = self.convert.pytd_convert annots = abstract_utils.get_annotations_dict(defs) for name, t in", "== \"-\": log.info(\"=========== Program Dump =============\\n%s\", text) else: with options.open_function(options.output_debug,", "self._call_method(node, b, \"__init__\") cls = b.data.get_class() if isinstance(cls, abstract.InterpreterClass): #", "formal, actual, bad) return not bad def check_types(src, filename, errorlog,", "binding, method_name): node, method = self.attribute_handler.get_attribute( node, binding.data.get_class(), method_name, binding)", "log.info(\"Analyzing %r\", [v.name for v in var.data]) state = frame_state.FrameState.init(node,", "(self.frame and self.frame.current_opcode, extra_key, cls) instance = self._instance_cache.get(key) if not", "\"return_value\"]) # How deep to follow call chains: INIT_MAXIMUM_DEPTH =", "%s\", name) node1 = node0.ConnectNew(name) for val in var.bindings: node2", "good_instances: # __new__ returned something that's not an instance of", "= metrics.get_metric(\"memory\", metrics.Snapshot) snapshotter.take_snapshot(\"analyze:check_types:tracer\") if deep: if maximum_depth is None:", "container) n.PasteVariable(var) return node, n def _mark_maybe_missing_members(self, values): \"\"\"Set maybe_missing_members", "the possible result values. \"\"\" log.debug(\"Logging call to %r with", "node0, funcv): \"\"\"Attempt to call the given function with made-up", "= self._instance_cache.get(key) if not instance or isinstance(instance, _Initializing): clsvar =", "= instance return node, instance def _call_method(self, node, binding, method_name):", "in retvar.data) starargs = None starstarargs = None funcs[func.data.name].add(pytd.Signature( tuple(pytd.Parameter(n,", "starargs = self.create_varargs(node) if method.has_varargs() else None starstarargs = self.create_kwargs(node)", "False def pytd_functions_for_call_traces(self): return self._call_traces_to_function(self._calls, escape.pack_partial) def pytd_classes_for_call_traces(self): class_to_records =", "= self.attribute_handler.get_attribute( node, binding.data.get_class(), method_name, binding) if method: bound_method =", "ret = self.call_function_with_args(node3, b, args) instance.PasteVariable(ret) nodes.append(node4) return self.join_cfg_nodes(nodes), instance", "function.Args object. \"\"\" args = [] num_posargs = method.argcount(node) num_posargs_no_default", "module loading MAXIMUM_DEPTH = 3 # during non-quick analysis QUICK_CHECK_MAXIMUM_DEPTH", "as # class A: # def __init__(self, x: \"A\"): ...", "than Unknown objects for type-checking defaults. Returns: A tuple of", "create an incomplete instance that will be # overwritten later.", "return value. \"\"\" fvar = val.AssignToNewVariable(node) with val.data.record_calls(): new_node, ret", "CFG node right after this function call. func: A cfg.Binding", "node) # Check for typevars in the return value first,", "func, sigs, args, kwargs, result) if isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record) elif", "# during quick checking QUICK_INFER_MAXIMUM_DEPTH = 1 # during quick", "options.protocols: log.info(\"=========== PyTD to solve =============\\n%s\", pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast,", "assumes that any inherited __new__ method defined in a pyi", "b, val) return node def analyze_function(self, node0, val): if val.data.is_attribute_of_class:", "= pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t in options) data.append(pytd.Constant(name, combined_types)) elif options:", "a vm, use that. if tracer_vm: assert isinstance(tracer_vm, CallTracer) tracer", "for i in range(len(arg_names)): if not isinstance(func.data, abstract.BoundFunction) or i", "return node def _call_with_fake_args(self, node0, funcv): \"\"\"Attempt to call the", "= self.join_bindings(node, good_instances) for instance_value in instance.data: val.data.register_canonical_instance(instance_value) for name,", "if options.output_debug == \"-\": log.info(\"=========== Program Dump =============\\n%s\", text) else:", "deep: if maximum_depth is None: maximum_depth = ( QUICK_CHECK_MAXIMUM_DEPTH if", "in self._method_calls: args = call_record.positional_arguments if not any(isinstance(a.data, abstract.Unknown) for", "if key in self._instance_cache: # We've encountered a recursive pattern", "def pytd_classes_for_call_traces(self): class_to_records = collections.defaultdict(list) for call_record in self._method_calls: args", "something # else, so encode it as a constant. combined_types", "pytd.AnythingType())) return pytd_utils.WrapTypeDeclUnit(\"inferred\", data) @staticmethod def _call_traces_to_function(call_traces, name_transform=lambda x: x):", "snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program) def infer_types(src, errorlog, options, loader, filename=None, deep=True,", "Union from pytype import abstract from pytype import abstract_utils from", "call_records in class_to_records.items(): full_name = cls.module + \".\" + cls.name", "class, for analyzing it.\"\"\" n = self.program.NewVariable() for cls in", "the call_function that called this method in the first place.", "wants to instantiate and retain the vm used for type", "for cls in clsv.Bindings(node, strict=False): node, var = self._instantiate_binding(node, cls,", "args) instance.PasteVariable(ret) nodes.append(node4) return self.join_cfg_nodes(nodes), instance def _instantiate_var(self, node, clsv,", "value) return node def analyze(self, node, defs, maximum_depth): assert not", "store_all_calls=not deep, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth)", "or # FailedFunctionCall error is raised when the target function", "there's no point in analyzing annotated functions for inference, #", "self.create_method_arguments(node0, func) # Once the args are generated, try calling", "num_posargs_no_default if use_defaults and default_idx >= 0: arg = method.defaults[default_idx]", "= function.argname(i) arg_types = (a.data.to_type(node) for a in args) ret", "lambdas) need to be analyzed as # stand-alone functions. The", "return node0, cls.data.instantiate(node0, container=container) instance = self.program.NewVariable() nodes = []", "at which the instantion occurs. By default, this method keys", "val) return node def analyze_function(self, node0, val): if val.data.is_attribute_of_class: #", "state = frame_state.FrameState.init(node, self) state, ret = self.call_function_with_state( state, var,", "abstract_utils.T, self.convert.create_new_unknown(node)) return value.to_variable(node) def create_kwargs(self, node): key_type = self.convert.primitive_class_instances[str].to_variable(node)", "pytype import debug from pytype import function from pytype import", "# expects not to get any. bad = [view for", "Default: unlimited. tracer_vm: An instance of CallTracer, in case the", "fname.rsplit(\".\", 1)[-1] not in self._CONSTRUCTORS): log.info(\"%r has annotations, not analyzing", "will be passed to # the call_function that called this", "pytype.pytd import optimize from pytype.pytd import pytd from pytype.pytd import", "= nt def pytd_classes_for_unknowns(self): classes = [] for name, val", "cfg log = logging.getLogger(__name__) # Most interpreter functions (including lambdas)", "functions.append(pytd.Function(name_transform(name), tuple(signatures), pytd.MethodTypes.METHOD)) return functions def _is_typing_member(self, name, var): for", "else: is_cls = (m.isinstance_InterpreterFunction() and m.is_classmethod) bound.AddBinding(m.property_get(instance_var, is_cls), [], node)", "class # when attempts to load from the protocols file", "# Type only if isinstance(d, pytd.NothingType): if isinstance(option, abstract.Empty): d", "different in the presence of optional and kw args. arg_names", "options.quick: maximum_depth = MAXIMUM_DEPTH elif options.analyze_annotated: # Since there's no", "a ValueError: Unresolved class # when attempts to load from", "QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint = loc", "already called this method during initialization. b = self.bind_method(node, name,", "data.append(d) else: log.error(\"No visible options for %s\", name) data.append(pytd.Constant(name, pytd.AnythingType()))", "tracer.program) return ast, builtins_pytd def _maybe_output_debug(options, program): \"\"\"Maybe emit debugging", "isinstance(tracer_vm, CallTracer) tracer = tracer_vm else: tracer = CallTracer(errorlog=errorlog, options=options,", "= tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or any( a in defs for", "A cfg.Binding containing the function. args: A function.Args object. Returns:", "\".\" + cls.name if cls.module else cls.name classes.append(pytd.Class( name=escape.pack_partial(full_name), metaclass=None,", "so that the `is_attribute_of_class` will # be set for all", "initialization. b = self.bind_method(node, name, methodvar, instance) node = self.analyze_method_var(node,", "messages go. Instance of errors.ErrorLog. options: config.Options object loader: A", "isinstance(b.data, abstract.SimpleValue): for param in b.data.instance_type_parameters.values(): node = self.call_init(node, param)", "instance def _call_method(self, node, binding, method_name): node, method = self.attribute_handler.get_attribute(", "options.quick else MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot(\"analyze:check_types:post\") _maybe_output_debug(options, tracer.program) def", "options.analyze_annotated: # Since there's no point in analyzing annotated functions", "ty = ty.Visit(visitors.DefaceUnresolved( [ty, self.loader.concat_all()], escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self,", "c): self._interpreter_classes.append(c) def trace_namedtuple(self, nt): # All namedtuple instances with", "means any additional errors that may be raised will be", "= cls.to_variable(node) node, instance = self._instantiate_var(node, clsvar, container) if key", "analysis during module loading. show_library_calls: If True, call traces are", "node, ret else: node = node0 log.info(\"Unable to generate fake", "self.loader.concat_all()], escape.UNKNOWN)) return ty.Visit(visitors.AdjustTypeParameters()) def _check_return(self, node, actual, formal): if", "not data.is_overload and not data.is_class_builder and data.get_first_opcode() not in self._analyzed_functions", "function.Args(posargs=tuple(args), namedargs=kws, starargs=starargs, starstarargs=starstarargs) def call_function_with_args(self, node, val, args): \"\"\"Call", "loader: A load_pytd.Loader instance to load PYI information. filename: Filename", "name, methodvar, instance_var): bound = self.program.NewVariable() for m in methodvar.Data(node):", "isinstance(f, abstract.InterpreterFunction) for f in new.data)): # This assumes that", "recorded as constants ty = pytd_utils.Concat( self.pytd_for_types(defs), pytd_utils.CreateModule(\"unknowns\", classes=classes, functions=functions,", "An abstract.InterpreterFunction. use_defaults: Whether to use parameter defaults for arguments.", "loop, set # fallback_to_unsolvable to False just in case. #", "def maybe_analyze_method(self, node, val, cls=None): method = val.data fname =", "name in annotated_names or self._is_typing_member(name, var)): continue options = var.FilteredData(self.exitpoint,", "= method.defaults[default_idx] else: arg = self.convert.create_new_unknown(node, force=not use_defaults) args.append(arg) kws", "= self.analyze_function(node, value) return node def analyze(self, node, defs, maximum_depth):", "b.data in self._initialized_instances: continue self._initialized_instances.add(b.data) node = self._call_init_on_binding(node, b) return", "= pytd.AnythingType() else: assert isinstance(option, typing_overlay.NoReturn) if isinstance(d, pytd.Type) and", "sigs, args, kwargs, result) if isinstance(func.data, abstract.BoundPyTDFunction): self._method_calls.add(record) elif isinstance(func.data,", "pytd_classes_for_unknowns(self): classes = [] for name, val in self._unknowns.items(): if", "set() while values: v = values.pop(0) if v not in", "instance) elif len(good_instances) != len(instance.bindings): # __new__ returned some extra", "is turned off. Discarding call traces.\") # Rename remaining \"~unknown\"", "container to pass to the class's instantiate() method, so that", "self.attribute_handler.get_attribute( node, binding.data.get_class(), method_name, binding) if method: bound_method = self.bind_method(", "that type. annotated_names = set() data = [] pytd_convert =", "use that. if tracer_vm: assert isinstance(tracer_vm, CallTracer) tracer = tracer_vm", "= args[0].data.get_class() if isinstance(cls, abstract.PyTDClass): class_to_records[cls].append(call_record) classes = [] for", "module_name not in self.loaded_overlays: continue module = self.loaded_overlays[module_name].get_module(name) if name", "where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info(\"=========== PyTD to", "if method.has_varargs() else None starstarargs = self.create_kwargs(node) if method.has_kwargs() else", "to pass to the class's instantiate() method, so that type", "no point in analyzing annotated functions for inference, # the", "self.convert.primitive_class_instances[str].to_variable(node) value_type = self.convert.create_new_unknown(node) kwargs = abstract.Instance(self.convert.dict_type, self) kwargs.merge_instance_type_parameter(node, abstract_utils.K,", "Note that we don't need to take parameter annotations into", "ret, exceptions=(), template=())) functions = [] for name, signatures in", "in var.bindings: node2 = self.maybe_analyze_method(node1, val, cls) node2.ConnectTo(node0) return node0", "the `is_attribute_of_class` will # be set for all functions in", "The class to instantiate. container: Optionally, a container to pass", "vm from pytype.overlays import typing_overlay from pytype.pytd import builtins from", "template=())) functions = [] for name, signatures in funcs.items(): functions.append(pytd.Function(name_transform(name),", "val, args) return node def _call_with_fake_args(self, node0, funcv): \"\"\"Attempt to", "if options.output_cfg or options.output_typegraph: dot = debug.program_to_dot(program, set([]), bool(options.output_cfg)) svg_file", "raised when the target function is called. # DictKeyMissing doesn't", "self.analyze_class(node, value) for f in self._interpreter_functions: for value in f.bindings:", "node, cls, func, args): sig = func.signature if (args.posargs and", "constant. combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint) for t in options) data.append(pytd.Constant(name, combined_types))", "\"~list\" etc.: ast = convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return ast, builtins_pytd", "_CONSTRUCTORS = (\"__new__\", \"__init__\") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)", "node, binding, method_name): node, method = self.attribute_handler.get_attribute( node, binding.data.get_class(), method_name,", "- there's nothing to solve for. continue cls = args[0].data.get_class()", "__init__(self, x: \"A\"): ... # Calling __init__ again would lead", "val.data fname = val.data.name if isinstance(method, abstract.INTERPRETER_FUNCTION_TYPES): self._analyzed_functions.add(method.get_first_opcode()) if (not", "over cfg.Value. namedargs: The keyword arguments, a dict mapping str", "be set for all functions in class. for c in", "a function.Args object. \"\"\" args = [] num_posargs = method.argcount(node)", "value.merge_instance_type_parameter( node, abstract_utils.T, self.convert.create_new_unknown(node)) return value.to_variable(node) def create_kwargs(self, node): key_type", "each binding. for b in instance.bindings: if b.data in self._initialized_instances:", "of errors.ErrorLog. options: config.Options object loader: A load_pytd.Loader instance to", "return node0 def bind_method(self, node, name, methodvar, instance_var): bound =", "name) # Deep definition except NotImplementedError: d = option.to_type(self.exitpoint) #", "# overwritten later. Note that we have to create a", "rets) node = self.join_cfg_nodes(nodes) if ret.bindings: return node, ret else:", "traces are kept in the output. maximum_depth: Depth of the", "ast, builtins.GetDefaultAst(options.python_version)) # If merged with other if statement, triggers", "functions and classes we haven't analyzed yet. # These are", "starargs, starstarargs): frame = frame_state.SimpleFrame(node=node) self.push_frame(frame) log.info(\"Analyzing %r\", [v.name for" ]
[ "from csv import DictReader from typing import Optional import typer", "typer.Argument(..., help=\"Output prefix for GFF outputs\"), outgroup_dict: str = typer.Argument(...,", "= typer.Option( None, \"--version\", callback=version_callback, is_eager=True, help=\"Prints the version of", "None: tmp = eval(outgroup_dict) out_group_dict = dict([tmp]) if len(tmp) ==", "dict(tmp) regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, pooled_fastx, ) if __name__", "delimiter=\",\"): for k, v in r.items(): if k != \"id\"", "# in_tissue = dict(in_tissue) handles = {} handles_fafq = {}", "the version of the SQANTI3 package.\", ), ) -> None:", "GFFs If input fasta/fastq is given, optionally also output per-{barcode", "r in DictReader(open(demux_count_file), delimiter=\",\"): for k, v in r.items(): if", "pooled_fastx: Optional[str] = typer.Option( None, help=\"Pooled FASTA/FASTQ (optional, if given,", "\"\"\" if in_fafq is not None: type_fafq = get_type_fafq(in_fafq) in_tissue", "raise Exception( f\"Unrecognized file suffix .{in_filename[in_filename.find('.'):]}! Must end with .fasta", ":param out_group_dict: dict of barcode name --> group to be", "optional fasta/fastq that was input to SAM \"\"\" if in_fafq", "is not None: SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq) @app.command(name=\"\") def main( pooled_gff:", "python __author__ = \"<EMAIL>\" \"\"\" Given a pooled input GFF", "fasta/fastq is given, optionally also output per-{barcode group} FASTA/FASTQ \"\"\"", "that was input to SAM \"\"\" if in_fafq is not", "None, \"--version\", callback=version_callback, is_eager=True, help=\"Prints the version of the SQANTI3", "demux_count_file, output_prefix, out_group_dict, pooled_fastx, ) if __name__ == \"__main__\": typer.run(main)", "help=\"Prints the version of the SQANTI3 package.\", ), ) ->", "cupcake import cupcake_logger as logger rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app =", "with .fasta or .fastq!\" ) def regroup_gff( pooled_gff, demux_count_file, output_prefix,", "not belong to any group indicated by outgroup_dict\" ) for", ") def regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, in_fafq=None ): \"\"\"", "pbid not in in_tissue: logger.info( f\"WARNING: {pbid} does not belong", "not in in_tissue: logger.info( f\"WARNING: {pbid} does not belong to", "output demux fa/fq)\", ), version: bool = typer.Option( None, \"--version\",", ":param output_prefix: output prefix for GFF :param out_group_dict: dict of", "pooled_sam: SAM file :param demux_count_file: comma-delimited per-barcode count file :param", "GFF.write_collapseGFF_format(handles[g], r) if in_fafq is not None: SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq)", "import version_callback from cupcake import cupcake_logger as logger rex_pbid =", "in_tissue: logger.info( f\"WARNING: {pbid} does not belong to any group", "0: in_tissue[r[\"id\"]].add(k) # in_tissue = dict(in_tissue) handles = {} handles_fafq", "grouping\"), pooled_fastx: Optional[str] = typer.Option( None, help=\"Pooled FASTA/FASTQ (optional, if", "also output per-{barcode group} FASTA/FASTQ \"\"\" import re from collections", "cupcake import version_callback from cupcake import cupcake_logger as logger rex_pbid", ":param in_fafq: optional fasta/fastq that was input to SAM \"\"\"", "else dict(tmp) regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, pooled_fastx, ) if", "input fasta/fastq is given, optionally also output per-{barcode group} FASTA/FASTQ", "dict(in_tissue) handles = {} handles_fafq = {} for g in", "if len(tmp) == 1 else dict(tmp) regroup_gff( pooled_gff, demux_count_file, output_prefix,", "typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename): in_filename = in_filename.upper() if in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"):", "\"fastq\" else: raise Exception( f\"Unrecognized file suffix .{in_filename[in_filename.find('.'):]}! Must end", "in_filename.endswith(\"FASTQ\"): return \"fastq\" else: raise Exception( f\"Unrecognized file suffix .{in_filename[in_filename.find('.'):]}!", "bool = typer.Option( None, \"--version\", callback=version_callback, is_eager=True, help=\"Prints the version", "handles = {} handles_fafq = {} for g in out_group_dict.values():", "open(f\"{output_prefix}_{g}_only.gff\", \"w\") if in_fafq is not None: handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\",", "regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, pooled_fastx, ) if __name__ ==", "typer.Argument(..., help=\"Pooled GFF file\"), demux_count_file: str = typer.Argument(..., help=\"Demux count", "count file :param output_prefix: output prefix for GFF :param out_group_dict:", "def get_type_fafq(in_filename): in_filename = in_filename.upper() if in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"): return", "fafq_dict[k] reader = GFF.collapseGFFReader(pooled_gff) for r in reader: groups_to_write_in =", "): \"\"\" :param pooled_sam: SAM file :param demux_count_file: comma-delimited per-barcode", "= defaultdict( lambda: set() ) # pbid --> list of", "or in_filename.endswith(\"FASTQ\"): return \"fastq\" else: raise Exception( f\"Unrecognized file suffix", "typer.Argument(..., help=\"Demux count file\"), output_prefix: str = typer.Argument(..., help=\"Output prefix", "in_tissue = defaultdict( lambda: set() ) # pbid --> list", "of tissue it is in (EM, END, R) for r", "output_prefix: output prefix for GFF :param out_group_dict: dict of barcode", "len(tmp) == 1 else dict(tmp) regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict,", "collections import defaultdict from csv import DictReader from typing import", "in_fafq is not None: fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys =", "fa/fq)\", ), version: bool = typer.Option( None, \"--version\", callback=version_callback, is_eager=True,", ":param demux_count_file: comma-delimited per-barcode count file :param output_prefix: output prefix", "lambda: set() ) # pbid --> list of tissue it", "is in (EM, END, R) for r in DictReader(open(demux_count_file), delimiter=\",\"):", "for GFF outputs\"), outgroup_dict: str = typer.Argument(..., help=\"Tuples indicating barcode", "typer.Option( None, help=\"Pooled FASTA/FASTQ (optional, if given, will also output", "outputs\"), outgroup_dict: str = typer.Argument(..., help=\"Tuples indicating barcode grouping\"), pooled_fastx:", "= typer.Argument(..., help=\"Pooled GFF file\"), demux_count_file: str = typer.Argument(..., help=\"Demux", "GFF + demux CSV file, write out per-{barcode group} GFFs", "CSV file, write out per-{barcode group} GFFs If input fasta/fastq", "demux CSV file, write out per-{barcode group} GFFs If input", "Bio import SeqIO import cupcake.sequence.GFF as GFF from cupcake import", "name --> group to be long in (ex: {'EM1':'EM', 'EM2':'EM'})", "if in_fafq is not None: fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys", "group} GFFs If input fasta/fastq is given, optionally also output", "app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename): in_filename = in_filename.upper() if in_filename.endswith(\".FA\")", "for tissue in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for g in groups_to_write_in: GFF.write_collapseGFF_format(handles[g],", "return \"fastq\" else: raise Exception( f\"Unrecognized file suffix .{in_filename[in_filename.find('.'):]}! Must", "dict([tmp]) if len(tmp) == 1 else dict(tmp) regroup_gff( pooled_gff, demux_count_file,", "a pooled input GFF + demux CSV file, write out", "version: bool = typer.Option( None, \"--version\", callback=version_callback, is_eager=True, help=\"Prints the", "= fafq_dict[k] reader = GFF.collapseGFFReader(pooled_gff) for r in reader: groups_to_write_in", "if pbid not in in_tissue: logger.info( f\"WARNING: {pbid} does not", "k != \"id\" and int(v) > 0: in_tissue[r[\"id\"]].add(k) # in_tissue", ".fastq!\" ) def regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, in_fafq=None ):", "help=\"Output prefix for GFF outputs\"), outgroup_dict: str = typer.Argument(..., help=\"Tuples", "+ demux CSV file, write out per-{barcode group} GFFs If", "list of tissue it is in (EM, END, R) for", "= dict(in_tissue) handles = {} handles_fafq = {} for g", "outgroup_dict\" ) for tissue in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for g in", "optionally also output per-{barcode group} FASTA/FASTQ \"\"\" import re from", "main( pooled_gff: str = typer.Argument(..., help=\"Pooled GFF file\"), demux_count_file: str", "return \"fasta\" elif in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"): return \"fastq\" else: raise", "SQANTI3 package.\", ), ) -> None: tmp = eval(outgroup_dict) out_group_dict", "groups_to_write_in = set() pbid = r.seqid if pbid not in", "typer.Option( None, \"--version\", callback=version_callback, is_eager=True, help=\"Prints the version of the", "str = typer.Argument(..., help=\"Output prefix for GFF outputs\"), outgroup_dict: str", ") for tissue in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for g in groups_to_write_in:", "help=\"Pooled GFF file\"), demux_count_file: str = typer.Argument(..., help=\"Demux count file\"),", "type_fafq = get_type_fafq(in_fafq) in_tissue = defaultdict( lambda: set() ) #", "= open(f\"{output_prefix}_{g}_only.gff\", \"w\") if in_fafq is not None: handles_fafq[g] =", "demux_count_file: str = typer.Argument(..., help=\"Demux count file\"), output_prefix: str =", "= GFF.collapseGFFReader(pooled_gff) for r in reader: groups_to_write_in = set() pbid", "SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys = list(fafq_dict.keys()) for k in fafq_dict_keys: m", "DictReader from typing import Optional import typer from Bio import", "also output demux fa/fq)\", ), version: bool = typer.Option( None,", "does not belong to any group indicated by outgroup_dict\" )", "prefix for GFF outputs\"), outgroup_dict: str = typer.Argument(..., help=\"Tuples indicating", "logger.info( f\"WARNING: {pbid} does not belong to any group indicated", "SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq) @app.command(name=\"\") def main( pooled_gff: str = typer.Argument(...,", "in_filename.upper() if in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"): return \"fasta\" elif in_filename.endswith(\".FQ\") or", "open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if in_fafq is not None: fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq),", "pooled input GFF + demux CSV file, write out per-{barcode", "= rex_pbid.match(k) if m is not None: fafq_dict[m.group(1)] = fafq_dict[k]", "regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, in_fafq=None ): \"\"\" :param pooled_sam:", "by outgroup_dict\" ) for tissue in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for g", "in_filename = in_filename.upper() if in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"): return \"fasta\" elif", "out_group_dict, in_fafq=None ): \"\"\" :param pooled_sam: SAM file :param demux_count_file:", "= eval(outgroup_dict) out_group_dict = dict([tmp]) if len(tmp) == 1 else", "Optional import typer from Bio import SeqIO import cupcake.sequence.GFF as", ".fasta or .fastq!\" ) def regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict,", "file\"), demux_count_file: str = typer.Argument(..., help=\"Demux count file\"), output_prefix: str", "--> list of tissue it is in (EM, END, R)", "None, help=\"Pooled FASTA/FASTQ (optional, if given, will also output demux", "= typer.Argument(..., help=\"Output prefix for GFF outputs\"), outgroup_dict: str =", "elif in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"): return \"fastq\" else: raise Exception( f\"Unrecognized", "as logger rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename):", "get_type_fafq(in_filename): in_filename = in_filename.upper() if in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"): return \"fasta\"", "= \"<EMAIL>\" \"\"\" Given a pooled input GFF + demux", "= r.seqid if pbid not in in_tissue: logger.info( f\"WARNING: {pbid}", "if in_fafq is not None: type_fafq = get_type_fafq(in_fafq) in_tissue =", "import cupcake.sequence.GFF as GFF from cupcake import version_callback from cupcake", "for g in out_group_dict.values(): handles[g] = open(f\"{output_prefix}_{g}_only.gff\", \"w\") if in_fafq", "def main( pooled_gff: str = typer.Argument(..., help=\"Pooled GFF file\"), demux_count_file:", "file, write out per-{barcode group} GFFs If input fasta/fastq is", "cupcake.sequence.GFF as GFF from cupcake import version_callback from cupcake import", "--> group to be long in (ex: {'EM1':'EM', 'EM2':'EM'}) :param", "int(v) > 0: in_tissue[r[\"id\"]].add(k) # in_tissue = dict(in_tissue) handles =", "> 0: in_tissue[r[\"id\"]].add(k) # in_tissue = dict(in_tissue) handles = {}", "per-barcode count file :param output_prefix: output prefix for GFF :param", "in DictReader(open(demux_count_file), delimiter=\",\"): for k, v in r.items(): if k", "output_prefix: str = typer.Argument(..., help=\"Output prefix for GFF outputs\"), outgroup_dict:", "import SeqIO import cupcake.sequence.GFF as GFF from cupcake import version_callback", "#!/usr/bin/env python __author__ = \"<EMAIL>\" \"\"\" Given a pooled input", "output per-{barcode group} FASTA/FASTQ \"\"\" import re from collections import", "if given, will also output demux fa/fq)\", ), version: bool", "or .fastq!\" ) def regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, in_fafq=None", "v in r.items(): if k != \"id\" and int(v) >", "file :param output_prefix: output prefix for GFF :param out_group_dict: dict", "\"\"\" :param pooled_sam: SAM file :param demux_count_file: comma-delimited per-barcode count", "is not None: fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys = list(fafq_dict.keys())", "in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"): return \"fastq\" else: raise Exception( f\"Unrecognized file", "(EM, END, R) for r in DictReader(open(demux_count_file), delimiter=\",\"): for k,", "Optional[str] = typer.Option( None, help=\"Pooled FASTA/FASTQ (optional, if given, will", "in out_group_dict.values(): handles[g] = open(f\"{output_prefix}_{g}_only.gff\", \"w\") if in_fafq is not", "not None: fafq_dict[m.group(1)] = fafq_dict[k] reader = GFF.collapseGFFReader(pooled_gff) for r", "None: SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq) @app.command(name=\"\") def main( pooled_gff: str =", "in_fafq: optional fasta/fastq that was input to SAM \"\"\" if", "str = typer.Argument(..., help=\"Demux count file\"), output_prefix: str = typer.Argument(...,", "handles_fafq[g], type_fafq) @app.command(name=\"\") def main( pooled_gff: str = typer.Argument(..., help=\"Pooled", "= get_type_fafq(in_fafq) in_tissue = defaultdict( lambda: set() ) # pbid", ":param pooled_sam: SAM file :param demux_count_file: comma-delimited per-barcode count file", "cupcake_logger as logger rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def", "group} FASTA/FASTQ \"\"\" import re from collections import defaultdict from", "typing import Optional import typer from Bio import SeqIO import", "DictReader(open(demux_count_file), delimiter=\",\"): for k, v in r.items(): if k !=", "not None: type_fafq = get_type_fafq(in_fafq) in_tissue = defaultdict( lambda: set()", "fasta/fastq that was input to SAM \"\"\" if in_fafq is", "# pbid --> list of tissue it is in (EM,", "output_prefix, out_group_dict, in_fafq=None ): \"\"\" :param pooled_sam: SAM file :param", "given, will also output demux fa/fq)\", ), version: bool =", "None: handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if in_fafq is not None:", "-> None: tmp = eval(outgroup_dict) out_group_dict = dict([tmp]) if len(tmp)", "Exception( f\"Unrecognized file suffix .{in_filename[in_filename.find('.'):]}! Must end with .fasta or", "write out per-{barcode group} GFFs If input fasta/fastq is given,", "pooled_gff, demux_count_file, output_prefix, out_group_dict, pooled_fastx, ) if __name__ == \"__main__\":", "barcode grouping\"), pooled_fastx: Optional[str] = typer.Option( None, help=\"Pooled FASTA/FASTQ (optional,", "tissue it is in (EM, END, R) for r in", "for k, v in r.items(): if k != \"id\" and", "r.seqid if pbid not in in_tissue: logger.info( f\"WARNING: {pbid} does", "was input to SAM \"\"\" if in_fafq is not None:", "file suffix .{in_filename[in_filename.find('.'):]}! Must end with .fasta or .fastq!\" )", "k, v in r.items(): if k != \"id\" and int(v)", "to any group indicated by outgroup_dict\" ) for tissue in", "any group indicated by outgroup_dict\" ) for tissue in in_tissue[pbid]:", "in_fafq is not None: SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq) @app.command(name=\"\") def main(", "tmp = eval(outgroup_dict) out_group_dict = dict([tmp]) if len(tmp) == 1", "\"w\") if in_fafq is not None: handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\")", "out_group_dict = dict([tmp]) if len(tmp) == 1 else dict(tmp) regroup_gff(", "out_group_dict.values(): handles[g] = open(f\"{output_prefix}_{g}_only.gff\", \"w\") if in_fafq is not None:", "\"\"\" import re from collections import defaultdict from csv import", "in groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r) if in_fafq is not None: SeqIO.write(fafq_dict[pbid],", "in_fafq=None ): \"\"\" :param pooled_sam: SAM file :param demux_count_file: comma-delimited", "set() ) # pbid --> list of tissue it is", "\"--version\", callback=version_callback, is_eager=True, help=\"Prints the version of the SQANTI3 package.\",", "get_type_fafq(in_fafq) in_tissue = defaultdict( lambda: set() ) # pbid -->", "None: fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys = list(fafq_dict.keys()) for k", "= typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename): in_filename = in_filename.upper() if in_filename.endswith(\".FA\") or", "g in groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r) if in_fafq is not None:", "if in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"): return \"fasta\" elif in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"):", "eval(outgroup_dict) out_group_dict = dict([tmp]) if len(tmp) == 1 else dict(tmp)", "m = rex_pbid.match(k) if m is not None: fafq_dict[m.group(1)] =", "= typer.Option( None, help=\"Pooled FASTA/FASTQ (optional, if given, will also", "= set() pbid = r.seqid if pbid not in in_tissue:", "tissue in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for g in groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r)", "in reader: groups_to_write_in = set() pbid = r.seqid if pbid", "SAM \"\"\" if in_fafq is not None: type_fafq = get_type_fafq(in_fafq)", "m is not None: fafq_dict[m.group(1)] = fafq_dict[k] reader = GFF.collapseGFFReader(pooled_gff)", "file\"), output_prefix: str = typer.Argument(..., help=\"Output prefix for GFF outputs\"),", "= open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if in_fafq is not None: fafq_dict =", "and int(v) > 0: in_tissue[r[\"id\"]].add(k) # in_tissue = dict(in_tissue) handles", "the SQANTI3 package.\", ), ) -> None: tmp = eval(outgroup_dict)", "import cupcake_logger as logger rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\")", "end with .fasta or .fastq!\" ) def regroup_gff( pooled_gff, demux_count_file,", "in fafq_dict_keys: m = rex_pbid.match(k) if m is not None:", "fafq_dict_keys = list(fafq_dict.keys()) for k in fafq_dict_keys: m = rex_pbid.match(k)", "in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for g in groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r) if", "re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename): in_filename = in_filename.upper() if", "barcode name --> group to be long in (ex: {'EM1':'EM',", "not None: fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys = list(fafq_dict.keys()) for", "k in fafq_dict_keys: m = rex_pbid.match(k) if m is not", "per-{barcode group} FASTA/FASTQ \"\"\" import re from collections import defaultdict", "in_tissue = dict(in_tissue) handles = {} handles_fafq = {} for", "comma-delimited per-barcode count file :param output_prefix: output prefix for GFF", "\"w\") if in_fafq is not None: fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq))", "file :param demux_count_file: comma-delimited per-barcode count file :param output_prefix: output", "package.\", ), ) -> None: tmp = eval(outgroup_dict) out_group_dict =", "in (ex: {'EM1':'EM', 'EM2':'EM'}) :param in_fafq: optional fasta/fastq that was", "set() pbid = r.seqid if pbid not in in_tissue: logger.info(", "in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for g in groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r) if in_fafq", "Given a pooled input GFF + demux CSV file, write", "Must end with .fasta or .fastq!\" ) def regroup_gff( pooled_gff,", "GFF.collapseGFFReader(pooled_gff) for r in reader: groups_to_write_in = set() pbid =", "= SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys = list(fafq_dict.keys()) for k in fafq_dict_keys:", "is not None: fafq_dict[m.group(1)] = fafq_dict[k] reader = GFF.collapseGFFReader(pooled_gff) for", "import defaultdict from csv import DictReader from typing import Optional", "if k != \"id\" and int(v) > 0: in_tissue[r[\"id\"]].add(k) #", ".{in_filename[in_filename.find('.'):]}! Must end with .fasta or .fastq!\" ) def regroup_gff(", "= {} for g in out_group_dict.values(): handles[g] = open(f\"{output_prefix}_{g}_only.gff\", \"w\")", "is_eager=True, help=\"Prints the version of the SQANTI3 package.\", ), )", "it is in (EM, END, R) for r in DictReader(open(demux_count_file),", "__author__ = \"<EMAIL>\" \"\"\" Given a pooled input GFF +", "R) for r in DictReader(open(demux_count_file), delimiter=\",\"): for k, v in", "demux fa/fq)\", ), version: bool = typer.Option( None, \"--version\", callback=version_callback,", "str = typer.Argument(..., help=\"Tuples indicating barcode grouping\"), pooled_fastx: Optional[str] =", "SeqIO import cupcake.sequence.GFF as GFF from cupcake import version_callback from", "per-{barcode group} GFFs If input fasta/fastq is given, optionally also", "in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"): return \"fasta\" elif in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"): return", "!= \"id\" and int(v) > 0: in_tissue[r[\"id\"]].add(k) # in_tissue =", "typer.Argument(..., help=\"Tuples indicating barcode grouping\"), pooled_fastx: Optional[str] = typer.Option( None,", "None: type_fafq = get_type_fafq(in_fafq) in_tissue = defaultdict( lambda: set() )", "group to be long in (ex: {'EM1':'EM', 'EM2':'EM'}) :param in_fafq:", "r in reader: groups_to_write_in = set() pbid = r.seqid if", "1 else dict(tmp) regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, pooled_fastx, )", "reader: groups_to_write_in = set() pbid = r.seqid if pbid not", "\"fasta\" elif in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"): return \"fastq\" else: raise Exception(", "import typer from Bio import SeqIO import cupcake.sequence.GFF as GFF", "{pbid} does not belong to any group indicated by outgroup_dict\"", ") # pbid --> list of tissue it is in", "f\"WARNING: {pbid} does not belong to any group indicated by", "or in_filename.endswith(\"FASTA\"): return \"fasta\" elif in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"): return \"fastq\"", "typer from Bio import SeqIO import cupcake.sequence.GFF as GFF from", "be long in (ex: {'EM1':'EM', 'EM2':'EM'}) :param in_fafq: optional fasta/fastq", "{'EM1':'EM', 'EM2':'EM'}) :param in_fafq: optional fasta/fastq that was input to", "of the SQANTI3 package.\", ), ) -> None: tmp =", "given, optionally also output per-{barcode group} FASTA/FASTQ \"\"\" import re", "fafq_dict = SeqIO.to_dict(SeqIO.parse(open(in_fafq), type_fafq)) fafq_dict_keys = list(fafq_dict.keys()) for k in", "in (EM, END, R) for r in DictReader(open(demux_count_file), delimiter=\",\"): for", "version of the SQANTI3 package.\", ), ) -> None: tmp", "import Optional import typer from Bio import SeqIO import cupcake.sequence.GFF", "not None: handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if in_fafq is not", "in_filename.endswith(\"FASTA\"): return \"fasta\" elif in_filename.endswith(\".FQ\") or in_filename.endswith(\"FASTQ\"): return \"fastq\" else:", "is not None: handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if in_fafq is", "help=\"Pooled FASTA/FASTQ (optional, if given, will also output demux fa/fq)\",", "to be long in (ex: {'EM1':'EM', 'EM2':'EM'}) :param in_fafq: optional", "is not None: type_fafq = get_type_fafq(in_fafq) in_tissue = defaultdict( lambda:", "indicating barcode grouping\"), pooled_fastx: Optional[str] = typer.Option( None, help=\"Pooled FASTA/FASTQ", "(ex: {'EM1':'EM', 'EM2':'EM'}) :param in_fafq: optional fasta/fastq that was input", "out_group_dict: dict of barcode name --> group to be long", "\"\"\" Given a pooled input GFF + demux CSV file,", "pooled_gff, demux_count_file, output_prefix, out_group_dict, in_fafq=None ): \"\"\" :param pooled_sam: SAM", "to SAM \"\"\" if in_fafq is not None: type_fafq =", "= typer.Argument(..., help=\"Tuples indicating barcode grouping\"), pooled_fastx: Optional[str] = typer.Option(", "in_fafq is not None: type_fafq = get_type_fafq(in_fafq) in_tissue = defaultdict(", "= list(fafq_dict.keys()) for k in fafq_dict_keys: m = rex_pbid.match(k) if", "out per-{barcode group} GFFs If input fasta/fastq is given, optionally", "is given, optionally also output per-{barcode group} FASTA/FASTQ \"\"\" import", "callback=version_callback, is_eager=True, help=\"Prints the version of the SQANTI3 package.\", ),", "csv import DictReader from typing import Optional import typer from", "in r.items(): if k != \"id\" and int(v) > 0:", "g in out_group_dict.values(): handles[g] = open(f\"{output_prefix}_{g}_only.gff\", \"w\") if in_fafq is", "re from collections import defaultdict from csv import DictReader from", "str = typer.Argument(..., help=\"Pooled GFF file\"), demux_count_file: str = typer.Argument(...,", "for k in fafq_dict_keys: m = rex_pbid.match(k) if m is", "if in_fafq is not None: handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if", "= re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename): in_filename = in_filename.upper()", "= in_filename.upper() if in_filename.endswith(\".FA\") or in_filename.endswith(\"FASTA\"): return \"fasta\" elif in_filename.endswith(\".FQ\")", "{} for g in out_group_dict.values(): handles[g] = open(f\"{output_prefix}_{g}_only.gff\", \"w\") if", "pooled_gff: str = typer.Argument(..., help=\"Pooled GFF file\"), demux_count_file: str =", "rex_pbid.match(k) if m is not None: fafq_dict[m.group(1)] = fafq_dict[k] reader", "(optional, if given, will also output demux fa/fq)\", ), version:", "GFF outputs\"), outgroup_dict: str = typer.Argument(..., help=\"Tuples indicating barcode grouping\"),", "handles_fafq = {} for g in out_group_dict.values(): handles[g] = open(f\"{output_prefix}_{g}_only.gff\",", "= typer.Argument(..., help=\"Demux count file\"), output_prefix: str = typer.Argument(..., help=\"Output", "in_tissue[r[\"id\"]].add(k) # in_tissue = dict(in_tissue) handles = {} handles_fafq =", "If input fasta/fastq is given, optionally also output per-{barcode group}", "else: raise Exception( f\"Unrecognized file suffix .{in_filename[in_filename.find('.'):]}! Must end with", "version_callback from cupcake import cupcake_logger as logger rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\")", "def regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, in_fafq=None ): \"\"\" :param", "SAM file :param demux_count_file: comma-delimited per-barcode count file :param output_prefix:", "from cupcake import version_callback from cupcake import cupcake_logger as logger", "\"id\" and int(v) > 0: in_tissue[r[\"id\"]].add(k) # in_tissue = dict(in_tissue)", "not None: SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq) @app.command(name=\"\") def main( pooled_gff: str", "belong to any group indicated by outgroup_dict\" ) for tissue", "defaultdict from csv import DictReader from typing import Optional import", "rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename): in_filename =", "GFF :param out_group_dict: dict of barcode name --> group to", "groups_to_write_in.add(out_group_dict[tissue]) for g in groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r) if in_fafq is", "@app.command(name=\"\") def main( pooled_gff: str = typer.Argument(..., help=\"Pooled GFF file\"),", "import re from collections import defaultdict from csv import DictReader", "from Bio import SeqIO import cupcake.sequence.GFF as GFF from cupcake", "), version: bool = typer.Option( None, \"--version\", callback=version_callback, is_eager=True, help=\"Prints", "input GFF + demux CSV file, write out per-{barcode group}", "long in (ex: {'EM1':'EM', 'EM2':'EM'}) :param in_fafq: optional fasta/fastq that", "\"<EMAIL>\" \"\"\" Given a pooled input GFF + demux CSV", "from typing import Optional import typer from Bio import SeqIO", "help=\"Demux count file\"), output_prefix: str = typer.Argument(..., help=\"Output prefix for", "groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r) if in_fafq is not None: SeqIO.write(fafq_dict[pbid], handles_fafq[g],", "f\"Unrecognized file suffix .{in_filename[in_filename.find('.'):]}! Must end with .fasta or .fastq!\"", "for r in DictReader(open(demux_count_file), delimiter=\",\"): for k, v in r.items():", "FASTA/FASTQ \"\"\" import re from collections import defaultdict from csv", "defaultdict( lambda: set() ) # pbid --> list of tissue", "count file\"), output_prefix: str = typer.Argument(..., help=\"Output prefix for GFF", "for r in reader: groups_to_write_in = set() pbid = r.seqid", "pbid = r.seqid if pbid not in in_tissue: logger.info( f\"WARNING:", "from cupcake import cupcake_logger as logger rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app", "== 1 else dict(tmp) regroup_gff( pooled_gff, demux_count_file, output_prefix, out_group_dict, pooled_fastx,", "input to SAM \"\"\" if in_fafq is not None: type_fafq", "as GFF from cupcake import version_callback from cupcake import cupcake_logger", "in in_tissue: logger.info( f\"WARNING: {pbid} does not belong to any", ") -> None: tmp = eval(outgroup_dict) out_group_dict = dict([tmp]) if", "type_fafq)) fafq_dict_keys = list(fafq_dict.keys()) for k in fafq_dict_keys: m =", "dict of barcode name --> group to be long in", "GFF file\"), demux_count_file: str = typer.Argument(..., help=\"Demux count file\"), output_prefix:", "FASTA/FASTQ (optional, if given, will also output demux fa/fq)\", ),", "{} handles_fafq = {} for g in out_group_dict.values(): handles[g] =", "group indicated by outgroup_dict\" ) for tissue in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue])", "= dict([tmp]) if len(tmp) == 1 else dict(tmp) regroup_gff( pooled_gff,", "import DictReader from typing import Optional import typer from Bio", "of barcode name --> group to be long in (ex:", "fafq_dict[m.group(1)] = fafq_dict[k] reader = GFF.collapseGFFReader(pooled_gff) for r in reader:", "indicated by outgroup_dict\" ) for tissue in in_tissue[pbid]: groups_to_write_in.add(out_group_dict[tissue]) for", "= {} handles_fafq = {} for g in out_group_dict.values(): handles[g]", "logger rex_pbid = re.compile(r\"(PB.\\d+.\\d+)(|\\S+)\") app = typer.Typer(name=\"cupcake.post_isoseq_cluster.demux_by_barcode_groups\") def get_type_fafq(in_filename): in_filename", "suffix .{in_filename[in_filename.find('.'):]}! Must end with .fasta or .fastq!\" ) def", "in_fafq is not None: handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if in_fafq", "handles_fafq[g] = open(f\"{output_prefix}_{g}_only.{type_fafq}\", \"w\") if in_fafq is not None: fafq_dict", "demux_count_file: comma-delimited per-barcode count file :param output_prefix: output prefix for", "r.items(): if k != \"id\" and int(v) > 0: in_tissue[r[\"id\"]].add(k)", "END, R) for r in DictReader(open(demux_count_file), delimiter=\",\"): for k, v", "GFF from cupcake import version_callback from cupcake import cupcake_logger as", "type_fafq) @app.command(name=\"\") def main( pooled_gff: str = typer.Argument(..., help=\"Pooled GFF", "), ) -> None: tmp = eval(outgroup_dict) out_group_dict = dict([tmp])", "for GFF :param out_group_dict: dict of barcode name --> group", "outgroup_dict: str = typer.Argument(..., help=\"Tuples indicating barcode grouping\"), pooled_fastx: Optional[str]", "pbid --> list of tissue it is in (EM, END,", "list(fafq_dict.keys()) for k in fafq_dict_keys: m = rex_pbid.match(k) if m", "'EM2':'EM'}) :param in_fafq: optional fasta/fastq that was input to SAM", "prefix for GFF :param out_group_dict: dict of barcode name -->", "output prefix for GFF :param out_group_dict: dict of barcode name", "fafq_dict_keys: m = rex_pbid.match(k) if m is not None: fafq_dict[m.group(1)]", "for g in groups_to_write_in: GFF.write_collapseGFF_format(handles[g], r) if in_fafq is not", "if in_fafq is not None: SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq) @app.command(name=\"\") def", "if m is not None: fafq_dict[m.group(1)] = fafq_dict[k] reader =", "help=\"Tuples indicating barcode grouping\"), pooled_fastx: Optional[str] = typer.Option( None, help=\"Pooled", "handles[g] = open(f\"{output_prefix}_{g}_only.gff\", \"w\") if in_fafq is not None: handles_fafq[g]", "demux_count_file, output_prefix, out_group_dict, in_fafq=None ): \"\"\" :param pooled_sam: SAM file", "from collections import defaultdict from csv import DictReader from typing", "reader = GFF.collapseGFFReader(pooled_gff) for r in reader: groups_to_write_in = set()", "None: fafq_dict[m.group(1)] = fafq_dict[k] reader = GFF.collapseGFFReader(pooled_gff) for r in", "will also output demux fa/fq)\", ), version: bool = typer.Option(", "r) if in_fafq is not None: SeqIO.write(fafq_dict[pbid], handles_fafq[g], type_fafq) @app.command(name=\"\")" ]
[ "border green if estiamte is correct, red otherwise if correct[i]:", "(0, 1, 0) else: clr = (0, 0, 1) for", "generated lines for stability minLength = 20 # restrict the", "created according to the shape of labels ''' n =", "stability minLength = 20 # restrict the minimum length of", "estiamte is correct, red otherwise if correct[i]: borderclr = (0,", "height (default 64) margin -- lines segments are sampled within", "import math from skimage.draw import line, line_aa, circle, set_color, circle_perimeter_aa", "number of hypotheses per image 2 is the number of", "self.imgH-1, 0), borderclr) set_color(data[i], line(self.imgH-1, 0, self.imgH-1, self.imgW-1), borderclr) set_color(data[i],", "m): clr = (0.2, 0.2, 0.2) # draw predicted points", "draw_points(self, points, data, inliers=None): ''' Draw 2D points for a", "0.5): ''' Constructor. imgW -- image width (default 64) imgH", "self.imgH) self.draw_line(data[i], 0, lY1, self.imgW, lY2, clr, scores[i, j]) return", "r) set_color(data, (rr, cc), clr, val) def draw_hyps(self, labels, scores,", "1) for i in range (0, n): for j in", "images to draw to, if empty a new batch wil", "of circle center r -- radius of circle clr --", "= int(labels[i, j, 1] * self.imgW + labels[i, j, 0]", "j] * self.imgH) c = int(points[i, 1, j] * self.imgW)", "data, cX, cY, r, clr, alpha=1.0): ''' Draw a circle", "green, circles will be blue otherwise correct -- array of", "predicted points as dark circles if inliers is not None", "int(cY * self.imgH) cX = int(cX * self.imgW) r =", "alpha=1.0): ''' Draw a circle with the given color and", "see above, higher score will be drawn with higher opacity", "labels, data=None, correct=None): ''' Draw circles for a batch of", "n): ''' Create new input images of random line segments", "clr = (0, 0, 1) for i in range (0,", "j in range (0, m): lY1 = int(labels[i, j, 0]", "10 # restrict the maximum slope of generated lines for", "M is the number of points data -- batch of", "shape (Nx3) where N is the number of images in", "0.2, 0.2) # draw predicted points as dark circles if", "imgH -- image height (default 64) margin -- lines segments", "= (0.2, 0.2, 0.2) # draw predicted points as dark", "data, inliers=None): ''' Draw 2D points for a batch of", "alpha -- opacity (default 1.0) ''' cY = int(cY *", "(1, 0, 0) set_color(data[i], line(0, 0, 0, self.imgW-1), borderclr) set_color(data[i],", "line color, triple of values alpha -- opacity (default 1.0)", "2], clr) if correct is not None: # draw border", "= points.shape[0] # number of images m = points.shape[2] #", "y) M is the number of points data -- batch", "images data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr", "borderclr) set_color(data[i], line(self.imgH-1, 0, self.imgH-1, self.imgW-1), borderclr) set_color(data[i], line(0, self.imgW-1,", "m = points.shape[2] # number of points for i in", "input images of random line segments and distractors along with", "otherwise if correct[i]: borderclr = (0, 1, 0) else: borderclr", "line, line_aa, circle, set_color, circle_perimeter_aa from skimage.io import imsave from", "is the number of images in the batch M is", "value means that a line segment can start or end", "of line hypothesis for a batch of images. labels --", "blue otherwise correct -- array of shape (N) indicating whether", "rr, cc = circle(r, c, 2) set_color(data[i], (rr, cc), clr)", "''' n = points.shape[0] # number of images m =", "draw_models(self, labels, data=None, correct=None): ''' Draw circles for a batch", "(0, 1, 0) else: borderclr = (1, 0, 0) set_color(data[i],", "return data def samples(self, n): ''' Create new input images", "the given color and opacity. data -- image to draw", "drawn green, red otherwise ''' n = points.shape[0] # number", "image width (default 64) imgH -- image height (default 64)", "of values alpha -- opacity (default 1.0) ''' cY =", "for i in range (0, n): for j in range", "a circle with the given color and opacity. data --", "Constructor. imgW -- image width (default 64) imgH -- image", "self.imgH = imgH self.margin = margin self.bg_clr = bg_clr def", "of circle center cY -- y value of circle center", "per image 2 is the number of line parameters (intercept,", "64) margin -- lines segments are sampled within this margin,", "self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) labels = np.zeros((n, 3), dtype=np.float32) for", "hypothesis for a batch of images. labels -- line parameters,", "of hypotheses per image 2 is the number of line", "lines for stability minLength = 20 # restrict the minimum", "hypotheses and point predictions. ''' def __init__(self, imgW = 64,", "cX = int(cX * self.imgW) r = int(r * self.imgW)", "m = labels.shape[1] # number of hypotheses if data is", "(NxMx2) where N is the number of images in the", "this margin, negative value means that a line segment can", "segment can start or end outside the image (default -5)", "= 20 # restrict the minimum length of line segments", "minimum length of line segments class ICircleDataset: ''' Generator of", "draw_hyps(self, labels, scores, data=None): ''' Draw a set of line", "* self.imgH) lY2 = int(labels[i, j, 1] * self.imgW +", "''' Create new input images of random line segments and", "np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 1,", "(default 64) margin -- lines segments are sampled within this", "given color and opacity. data -- image to draw to", "self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 0, 1) for", "clr = (0.7, 0.7, 0.7) # draw inliers as light", "image (default -5) bg_clr -- background intensity (default 0.5) '''", "points, array shape (Nx2xM) where N is the number of", "green, red otherwise ''' n = points.shape[0] # number of", "to, if empty a new batch wil be created according", "parameters, hypotheses and point predictions. ''' def __init__(self, imgW =", "self.imgW + labels[i, j, 0] * self.imgH) self.draw_line(data[i], 0, lY1,", "-- line color, triple of values alpha -- opacity (default", "images to create ''' data = np.zeros((n, self.imgH, self.imgW, 3),", "the minimum length of line segments class ICircleDataset: ''' Generator", "circle clr -- line color, triple of values alpha --", "of images. points -- 2D points, array shape (Nx2xM) where", "circle with the given color and opacity. data -- image", "''' data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) labels", "Draw circles for a batch of images. labels -- circle", "-- hypotheses scores, array shape (NxM), see above, higher score", "shape of labels ''' n = labels.shape[0] # number of", "* self.imgW) rr, cc, val = circle_perimeter_aa(cY, cX, r) set_color(data,", "n): for j in range (0, m): lY1 = int(labels[i,", "> 0.5: clr = (0.7, 0.7, 0.7) # draw inliers", "shape (NxM), see above, higher score will be drawn with", "is the number of points data -- batch of images", "bg_clr = 0.5): ''' Constructor. imgW -- image width (default", "not None and inliers[i, j] > 0.5: clr = (0.7,", "data def samples(self, n): ''' Create new input images of", "with the given color and opacity. data -- image to", "sampled within this margin, negative value means that a line", "images in the batch M is the number of hypotheses", "j] * self.imgW) rr, cc = circle(r, c, 2) set_color(data[i],", "the shape of labels and circles will be green, circles", "Draw 2D points for a batch of images. points --", "__init__(self, imgW = 64, imgH = 64, margin = -5,", "point predictions. ''' def __init__(self, imgW = 64, imgH =", "self.draw_circle(data[i], labels[i, 0], labels[i, 1], labels[i, 2], clr) if correct", "slope) scores -- hypotheses scores, array shape (NxM), see above,", "''' cY = int(cY * self.imgH) cX = int(cX *", "number of circles parameters (center x, center y, radius) data", "range (0, m): lY1 = int(labels[i, j, 0] * self.imgH)", "images. Images will have 1 random circle each, filled with", "of images in the batch 3 is the number of", "0], labels[i, 1], labels[i, 2], clr) if correct is not", "r -- radius of circle clr -- line color, triple", "data -- batch of images to draw to inliers --", "cY, r, clr, alpha=1.0): ''' Draw a circle with the", "r = int(points[i, 0, j] * self.imgH) c = int(points[i,", "line parameters, array shape (NxMx2) where N is the number", "imsave from skimage.util import random_noise maxSlope = 10 # restrict", "the shape of labels ''' n = labels.shape[0] # number", "labels[i, 2], clr) if correct is not None: # draw", "# restrict the minimum length of line segments class ICircleDataset:", "# draw border green if estiamte is correct, red otherwise", "if data is None: data = np.zeros((n, self.imgH, self.imgW, 3),", "cX, r) set_color(data, (rr, cc), clr, val) def draw_hyps(self, labels,", "circles for a batch of images. labels -- circle parameters,", "is the number of images in the batch 2 is", "return data def draw_models(self, labels, data=None, correct=None): ''' Draw circles", "0, 0, self.imgW-1), borderclr) set_color(data[i], line(0, 0, self.imgH-1, 0), borderclr)", "# draw inliers as light circles r = int(points[i, 0,", "-- y value of circle center r -- radius of", "batch wil be created according to the shape of labels", "is the number of circles parameters (center x, center y,", "the batch 2 is the number of point dimensions (x,", "-- array of shape (N) indicating whether a circle estimate", "labels.shape[0] if data is None: data = np.zeros((n, self.imgH, self.imgW,", "create ''' data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr)", "''' Draw a circle with the given color and opacity.", "-- line parameters, array shape (NxMx2) where N is the", "0] * self.imgH) self.draw_line(data[i], 0, lY1, self.imgW, lY2, clr, scores[i,", "''' Constructor. imgW -- image width (default 64) imgH --", "according to the shape of labels and circles will be", "line(0, 0, self.imgH-1, 0), borderclr) set_color(data[i], line(self.imgH-1, 0, self.imgH-1, self.imgW-1),", "N is the number of images in the batch 3", "c, 2) set_color(data[i], (rr, cc), clr) return data def samples(self,", "= circle_perimeter_aa(cY, cX, r) set_color(data, (rr, cc), clr, val) def", "that a line segment can start or end outside the", "cX -- x value of circle center cY -- y", "of images to create ''' data = np.zeros((n, self.imgH, self.imgW,", "clr, alpha=1.0): ''' Draw a circle with the given color", "restrict the minimum length of line segments class ICircleDataset: '''", "for j in range(0, m): clr = (0.2, 0.2, 0.2)", "whether a circle estimate is correct ''' n = labels.shape[0]", "dark circles if inliers is not None and inliers[i, j]", "= bg_clr def draw_circle(self, data, cX, cY, r, clr, alpha=1.0):", "-- 2D points, array shape (Nx2xM) where N is the", "segments and distractors along with ground truth parameters. n --", "to create ''' data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32)", "of point dimensions (x, y) M is the number of", "lY2 = int(labels[i, j, 1] * self.imgW + labels[i, j,", "j] > 0.5: clr = (0.7, 0.7, 0.7) # draw", "points as dark circles if inliers is not None and", "of images to draw to inliers -- soft inlier score", "labels -- circle parameters, array shape (Nx3) where N is", "def draw_points(self, points, data, inliers=None): ''' Draw 2D points for", "for a batch of images. points -- 2D points, array", "circle parameters, array shape (Nx3) where N is the number", "labels -- line parameters, array shape (NxMx2) where N is", "-5, bg_clr = 0.5): ''' Constructor. imgW -- image width", "(0, n): for j in range(0, m): clr = (0.2,", "opacity data -- batch of images to draw to, if", "labels[i, 1], labels[i, 2], clr) if correct is not None:", "wil be created according to the shape of labels and", "0.5) ''' self.imgW = imgW self.imgH = imgH self.margin =", "= int(r * self.imgW) rr, cc, val = circle_perimeter_aa(cY, cX,", "= imgW self.imgH = imgH self.margin = margin self.bg_clr =", "to the shape of labels ''' n = labels.shape[0] #", "64, margin = -5, bg_clr = 0.5): ''' Constructor. imgW", "of images to draw to, if empty a new batch", "i in range (0, n): for j in range(0, m):", "= (0.7, 0.7, 0.7) # draw inliers as light circles", "parameters (intercept, slope) scores -- hypotheses scores, array shape (NxM),", "as light circles r = int(points[i, 0, j] * self.imgH)", "= int(points[i, 0, j] * self.imgH) c = int(points[i, 1,", "2) set_color(data[i], (rr, cc), clr) return data def samples(self, n):", "is the number of line parameters (intercept, slope) scores --", "skimage.draw import line, line_aa, circle, set_color, circle_perimeter_aa from skimage.io import", "def __init__(self, imgW = 64, imgH = 64, margin =", "and distractor lines. Class also offers functionality for drawing line", "radius of circle clr -- line color, triple of values", "data=None): ''' Draw a set of line hypothesis for a", "None: # draw border green if estiamte is correct, red", "= (0, 1, 0) else: clr = (0, 0, 1)", "color, triple of values alpha -- opacity (default 1.0) '''", "from skimage.io import imsave from skimage.util import random_noise maxSlope =", "= imgH self.margin = margin self.bg_clr = bg_clr def draw_circle(self,", "have 1 random circle each, filled with noise and distractor", "points.shape[2] # number of points for i in range (0,", "light circles r = int(points[i, 0, j] * self.imgH) c", "(default 64) imgH -- image height (default 64) margin --", "image to draw to cX -- x value of circle", "lY1 = int(labels[i, j, 0] * self.imgH) lY2 = int(labels[i,", "# number of images m = points.shape[2] # number of", "truth parameters. n -- number of images to create '''", "range (0, n): for j in range(0, m): clr =", "-- number of images to create ''' data = np.zeros((n,", "draw predicted points as dark circles if inliers is not", "= (1, 0, 0) set_color(data[i], line(0, 0, 0, self.imgW-1), borderclr)", "within this margin, negative value means that a line segment", "given and score < 0.5 point will be drawn green,", "hypotheses scores, array shape (NxM), see above, higher score will", "labels ''' n = labels.shape[0] # number of images m", "0, self.imgH-1, self.imgW-1), borderclr) set_color(data[i], line(0, self.imgW-1, self.imgH-1, self.imgW-1), borderclr)", "set_color(data, (rr, cc), clr, val) def draw_hyps(self, labels, scores, data=None):", "(0.2, 0.2, 0.2) # draw predicted points as dark circles", "for j in range (0, m): lY1 = int(labels[i, j,", "ICircleDataset: ''' Generator of circle segment images. Images will have", "* self.imgW) rr, cc = circle(r, c, 2) set_color(data[i], (rr,", "return data def draw_points(self, points, data, inliers=None): ''' Draw 2D", "in range (0, n): for j in range (0, m):", "j, 0] * self.imgH) lY2 = int(labels[i, j, 1] *", "be created according to the shape of labels and circles", "line(self.imgH-1, 0, self.imgH-1, self.imgW-1), borderclr) set_color(data[i], line(0, self.imgW-1, self.imgH-1, self.imgW-1),", "line parameters, hypotheses and point predictions. ''' def __init__(self, imgW", "opacity. data -- image to draw to cX -- x", "2 is the number of line parameters (intercept, slope) scores", "imgW -- image width (default 64) imgH -- image height", "drawn with higher opacity data -- batch of images to", "scores[i, j]) return data def draw_models(self, labels, data=None, correct=None): '''", "distractor lines. Class also offers functionality for drawing line parameters,", "margin self.bg_clr = bg_clr def draw_circle(self, data, cX, cY, r,", "will have 1 random circle each, filled with noise and", "else: borderclr = (1, 0, 0) set_color(data[i], line(0, 0, 0,", "(rr, cc), clr, val) def draw_hyps(self, labels, scores, data=None): '''", "int(points[i, 1, j] * self.imgW) rr, cc = circle(r, c,", "lines. Class also offers functionality for drawing line parameters, hypotheses", "shape (NxMx2) where N is the number of images in", "is correct, red otherwise if correct[i]: borderclr = (0, 1,", "= 64, margin = -5, bg_clr = 0.5): ''' Constructor.", "means that a line segment can start or end outside", "range (0, n): data[i] = random_noise(data[i], mode='speckle') return data, labels", "in range (0, n): self.draw_circle(data[i], labels[i, 0], labels[i, 1], labels[i,", "soft inlier score for each point, if given and score", "borderclr) return data def draw_points(self, points, data, inliers=None): ''' Draw", "is not None: # draw border green if estiamte is", "self.imgW, lY2, clr, scores[i, j]) return data def draw_models(self, labels,", "borderclr = (1, 0, 0) set_color(data[i], line(0, 0, 0, self.imgW-1),", "points.shape[0] # number of images m = points.shape[2] # number", "inliers=None): ''' Draw 2D points for a batch of images.", "line segments class ICircleDataset: ''' Generator of circle segment images.", "draw to cX -- x value of circle center cY", "= -5, bg_clr = 0.5): ''' Constructor. imgW -- image", "number of images to create ''' data = np.zeros((n, self.imgH,", "int(cX * self.imgW) r = int(r * self.imgW) rr, cc,", "self.imgW = imgW self.imgH = imgH self.margin = margin self.bg_clr", "= (0, 0, 1) for i in range (0, n):", "array of shape (N) indicating whether a circle estimate is", "in the batch 2 is the number of point dimensions", "the batch M is the number of hypotheses per image", "will be green, circles will be blue otherwise correct --", "Generator of circle segment images. Images will have 1 random", "= (0, 1, 0) else: borderclr = (1, 0, 0)", "(intercept, slope) scores -- hypotheses scores, array shape (NxM), see", "is the number of images in the batch 3 is", "= int(points[i, 1, j] * self.imgW) rr, cc = circle(r,", "clr = (0, 1, 0) else: clr = (0, 0,", "0, j] * self.imgH) c = int(points[i, 1, j] *", "clr = (0.2, 0.2, 0.2) # draw predicted points as", "* self.imgH) c = int(points[i, 1, j] * self.imgW) rr,", "score < 0.5 point will be drawn green, red otherwise", "correct=None): ''' Draw circles for a batch of images. labels", "a new batch wil be created according to the shape", "cc), clr, val) def draw_hyps(self, labels, scores, data=None): ''' Draw", "+ labels[i, j, 0] * self.imgH) self.draw_line(data[i], 0, lY1, self.imgW,", "math from skimage.draw import line, line_aa, circle, set_color, circle_perimeter_aa from", "circle_perimeter_aa(cY, cX, r) set_color(data, (rr, cc), clr, val) def draw_hyps(self,", "number of hypotheses if data is None: # create new", "self.draw_line(data[i], 0, lY1, self.imgW, lY2, clr, scores[i, j]) return data", "self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 1, 0)", "-- image height (default 64) margin -- lines segments are", "maximum slope of generated lines for stability minLength = 20", "filled with noise and distractor lines. Class also offers functionality", "''' self.imgW = imgW self.imgH = imgH self.margin = margin", "the number of images in the batch M is the", "random line segments and distractors along with ground truth parameters.", "1 random circle each, filled with noise and distractor lines.", "value of circle center cY -- y value of circle", "set of line hypothesis for a batch of images. labels", "images in the batch 2 is the number of point", "borderclr = (0, 1, 0) else: borderclr = (1, 0,", "samples(self, n): ''' Create new input images of random line", "line_aa, circle, set_color, circle_perimeter_aa from skimage.io import imsave from skimage.util", "set_color(data[i], line(0, 0, self.imgH-1, 0), borderclr) set_color(data[i], line(self.imgH-1, 0, self.imgH-1,", "if empty a new batch wil be created according to", "of images in the batch M is the number of", "image height (default 64) margin -- lines segments are sampled", "negative value means that a line segment can start or", "otherwise ''' n = points.shape[0] # number of images m", "offers functionality for drawing line parameters, hypotheses and point predictions.", "= labels.shape[0] # number of images m = labels.shape[1] #", "circle_perimeter_aa from skimage.io import imsave from skimage.util import random_noise maxSlope", "as np import math from skimage.draw import line, line_aa, circle,", "each, filled with noise and distractor lines. Class also offers", "-- lines segments are sampled within this margin, negative value", "draw border green if estiamte is correct, red otherwise if", "(Nx2xM) where N is the number of images in the", "-- x value of circle center cY -- y value", "cY -- y value of circle center r -- radius", "1], labels[i, 2], clr) if correct is not None: #", "self.margin = margin self.bg_clr = bg_clr def draw_circle(self, data, cX,", "point, if given and score < 0.5 point will be", "range (0, n): for j in range (0, m): lY1", "wil be created according to the shape of labels '''", "for i in range (0, n): data[i] = random_noise(data[i], mode='speckle')", "j, 0] * self.imgH) self.draw_line(data[i], 0, lY1, self.imgW, lY2, clr,", "parameters. n -- number of images to create ''' data", "color and opacity. data -- image to draw to cX", "be green, circles will be blue otherwise correct -- array", "distractors along with ground truth parameters. n -- number of", "segments are sampled within this margin, negative value means that", "labels and circles will be green, circles will be blue", "skimage.util import random_noise maxSlope = 10 # restrict the maximum", "self.imgW) rr, cc, val = circle_perimeter_aa(cY, cX, r) set_color(data, (rr,", "or end outside the image (default -5) bg_clr -- background", "the number of circles parameters (center x, center y, radius)", "of labels ''' n = labels.shape[0] # number of images", "ground truth parameters. n -- number of images to create", "will be drawn green, red otherwise ''' n = points.shape[0]", "cc = circle(r, c, 2) set_color(data[i], (rr, cc), clr) return", "np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) labels = np.zeros((n, 3),", "Create new input images of random line segments and distractors", "batch M is the number of hypotheses per image 2", "(0, 0, 1) for i in range (0, n): for", "1) for i in range (0, n): self.draw_circle(data[i], labels[i, 0],", "is correct ''' n = labels.shape[0] if data is None:", "parameters (center x, center y, radius) data -- batch of", "self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 0, 1)", "data def draw_models(self, labels, data=None, correct=None): ''' Draw circles for", "of labels and circles will be green, circles will be", "class ICircleDataset: ''' Generator of circle segment images. Images will", "functionality for drawing line parameters, hypotheses and point predictions. '''", "number of images m = labels.shape[1] # number of hypotheses", "lY1, self.imgW, lY2, clr, scores[i, j]) return data def draw_models(self,", "maxSlope = 10 # restrict the maximum slope of generated", "0.7, 0.7) # draw inliers as light circles r =", "restrict the maximum slope of generated lines for stability minLength", "(default 0.5) ''' self.imgW = imgW self.imgH = imgH self.margin", "red otherwise ''' n = points.shape[0] # number of images", "borderclr) set_color(data[i], line(0, self.imgW-1, self.imgH-1, self.imgW-1), borderclr) return data def", "r, clr, alpha=1.0): ''' Draw a circle with the given", "dtype=np.float32) for i in range (0, n): data[i] = random_noise(data[i],", "of images m = labels.shape[1] # number of hypotheses if", "(default -5) bg_clr -- background intensity (default 0.5) ''' self.imgW", "of images. labels -- circle parameters, array shape (Nx3) where", "the number of images in the batch 3 is the", "center r -- radius of circle clr -- line color,", "0.2) # draw predicted points as dark circles if inliers", "inliers[i, j] > 0.5: clr = (0.7, 0.7, 0.7) #", "value of circle center r -- radius of circle clr", "j, 1] * self.imgW + labels[i, j, 0] * self.imgH)", "for each point, if given and score < 0.5 point", "be drawn with higher opacity data -- batch of images", "borderclr) set_color(data[i], line(0, 0, self.imgH-1, 0), borderclr) set_color(data[i], line(self.imgH-1, 0,", "points, data, inliers=None): ''' Draw 2D points for a batch", "-- opacity (default 1.0) ''' cY = int(cY * self.imgH)", "skimage.io import imsave from skimage.util import random_noise maxSlope = 10", "in range (0, n): data[i] = random_noise(data[i], mode='speckle') return data,", "y value of circle center r -- radius of circle", "where N is the number of images in the batch", "n = labels.shape[0] if data is None: data = np.zeros((n,", "inliers is not None and inliers[i, j] > 0.5: clr", "along with ground truth parameters. n -- number of images", "M is the number of hypotheses per image 2 is", "* self.imgW + labels[i, j, 0] * self.imgH) self.draw_line(data[i], 0,", "each point, if given and score < 0.5 point will", "create new batch of images data = np.zeros((n, self.imgH, self.imgW,", "inlier score for each point, if given and score <", "of line segments class ICircleDataset: ''' Generator of circle segment", "of line parameters (intercept, slope) scores -- hypotheses scores, array", "images. labels -- circle parameters, array shape (Nx3) where N", "labels.shape[1] # number of hypotheses if data is None: #", "dtype=np.float32) data.fill(self.bg_clr) clr = (0, 0, 1) for i in", "estimate is correct ''' n = labels.shape[0] if data is", "circles will be blue otherwise correct -- array of shape", "score will be drawn with higher opacity data -- batch", "a circle estimate is correct ''' n = labels.shape[0] if", "parameters, array shape (NxMx2) where N is the number of", "image 2 is the number of line parameters (intercept, slope)", "are sampled within this margin, negative value means that a", "Draw a set of line hypothesis for a batch of", "None and inliers[i, j] > 0.5: clr = (0.7, 0.7,", "2 is the number of point dimensions (x, y) M", "np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 0,", "width (default 64) imgH -- image height (default 64) margin", "(x, y) M is the number of points data --", "imgH self.margin = margin self.bg_clr = bg_clr def draw_circle(self, data,", "if data is None: # create new batch of images", "circle each, filled with noise and distractor lines. Class also", "2D points, array shape (Nx2xM) where N is the number", "opacity (default 1.0) ''' cY = int(cY * self.imgH) cX", "clr) if correct is not None: # draw border green", "inliers as light circles r = int(points[i, 0, j] *", "dimensions (x, y) M is the number of points data", "points -- 2D points, array shape (Nx2xM) where N is", "np import math from skimage.draw import line, line_aa, circle, set_color,", "= 10 # restrict the maximum slope of generated lines", "of generated lines for stability minLength = 20 # restrict", "(0, 0, 1) for i in range (0, n): self.draw_circle(data[i],", "slope of generated lines for stability minLength = 20 #", "(default 1.0) ''' cY = int(cY * self.imgH) cX =", "= points.shape[2] # number of points for i in range", "draw to inliers -- soft inlier score for each point,", "self.imgH) cX = int(cX * self.imgW) r = int(r *", "0, 1) for i in range (0, n): for j", "from skimage.util import random_noise maxSlope = 10 # restrict the", "self.imgH) lY2 = int(labels[i, j, 1] * self.imgW + labels[i,", "def draw_models(self, labels, data=None, correct=None): ''' Draw circles for a", "bg_clr -- background intensity (default 0.5) ''' self.imgW = imgW", "self.bg_clr = bg_clr def draw_circle(self, data, cX, cY, r, clr,", "rr, cc, val = circle_perimeter_aa(cY, cX, r) set_color(data, (rr, cc),", "line segments and distractors along with ground truth parameters. n", "self.imgH-1, self.imgW-1), borderclr) return data def draw_points(self, points, data, inliers=None):", "margin -- lines segments are sampled within this margin, negative", "* self.imgH) self.draw_line(data[i], 0, lY1, self.imgW, lY2, clr, scores[i, j])", "n -- number of images to create ''' data =", "of random line segments and distractors along with ground truth", "array shape (NxM), see above, higher score will be drawn", "imgW = 64, imgH = 64, margin = -5, bg_clr", "number of line parameters (intercept, slope) scores -- hypotheses scores,", "the number of hypotheses per image 2 is the number", "self.imgW) r = int(r * self.imgW) rr, cc, val =", "shape (Nx2xM) where N is the number of images in", "-- image width (default 64) imgH -- image height (default", "import line, line_aa, circle, set_color, circle_perimeter_aa from skimage.io import imsave", "is the number of point dimensions (x, y) M is", "and inliers[i, j] > 0.5: clr = (0.7, 0.7, 0.7)", "draw inliers as light circles r = int(points[i, 0, j]", "data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr =", "a batch of images. points -- 2D points, array shape", "(0, n): self.draw_circle(data[i], labels[i, 0], labels[i, 1], labels[i, 2], clr)", "batch of images to draw to, if empty a new", "data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) labels =", "predictions. ''' def __init__(self, imgW = 64, imgH = 64,", "correct, red otherwise if correct[i]: borderclr = (0, 1, 0)", "clr, val) def draw_hyps(self, labels, scores, data=None): ''' Draw a", "be blue otherwise correct -- array of shape (N) indicating", "< 0.5 point will be drawn green, red otherwise '''", "import random_noise maxSlope = 10 # restrict the maximum slope", "0.7) # draw inliers as light circles r = int(points[i,", "* self.imgH) cX = int(cX * self.imgW) r = int(r", "circles r = int(points[i, 0, j] * self.imgH) c =", "batch 3 is the number of circles parameters (center x,", "background intensity (default 0.5) ''' self.imgW = imgW self.imgH =", "0) set_color(data[i], line(0, 0, 0, self.imgW-1), borderclr) set_color(data[i], line(0, 0,", "correct[i]: borderclr = (0, 1, 0) else: borderclr = (1,", "new batch of images data = np.zeros((n, self.imgH, self.imgW, 3),", "i in range (0, n): for j in range (0,", "margin = -5, bg_clr = 0.5): ''' Constructor. imgW --", "if correct is not None: # draw border green if", "is not None and inliers[i, j] > 0.5: clr =", "inliers -- soft inlier score for each point, if given", "labels, scores, data=None): ''' Draw a set of line hypothesis", "the number of point dimensions (x, y) M is the", "clr, scores[i, j]) return data def draw_models(self, labels, data=None, correct=None):", "0.5: clr = (0.7, 0.7, 0.7) # draw inliers as", "scores, data=None): ''' Draw a set of line hypothesis for", "r = int(r * self.imgW) rr, cc, val = circle_perimeter_aa(cY,", "1, 0) else: borderclr = (1, 0, 0) set_color(data[i], line(0,", "(N) indicating whether a circle estimate is correct ''' n", "hypotheses per image 2 is the number of line parameters", "in range(0, m): clr = (0.2, 0.2, 0.2) # draw", "self.imgH) c = int(points[i, 1, j] * self.imgW) rr, cc", "0, 1) for i in range (0, n): self.draw_circle(data[i], labels[i,", "0), borderclr) set_color(data[i], line(self.imgH-1, 0, self.imgH-1, self.imgW-1), borderclr) set_color(data[i], line(0,", "-- batch of images to draw to, if empty a", "batch of images. labels -- circle parameters, array shape (Nx3)", "according to the shape of labels ''' n = labels.shape[0]", "and point predictions. ''' def __init__(self, imgW = 64, imgH", "will be drawn with higher opacity data -- batch of", "score for each point, if given and score < 0.5", "val = circle_perimeter_aa(cY, cX, r) set_color(data, (rr, cc), clr, val)", "0) else: clr = (0, 0, 1) for i in", "the number of line parameters (intercept, slope) scores -- hypotheses", "for a batch of images. labels -- line parameters, array", "to draw to, if empty a new batch wil be", "# number of images m = labels.shape[1] # number of", "not None: # draw border green if estiamte is correct,", "scores -- hypotheses scores, array shape (NxM), see above, higher", "is None: # create new batch of images data =", "0, self.imgW-1), borderclr) set_color(data[i], line(0, 0, self.imgH-1, 0), borderclr) set_color(data[i],", "batch of images to draw to inliers -- soft inlier", "number of points for i in range (0, n): for", "of points for i in range (0, n): for j", "self.imgW) rr, cc = circle(r, c, 2) set_color(data[i], (rr, cc),", "3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 1, 0) else: clr", "noise and distractor lines. Class also offers functionality for drawing", "of images. labels -- line parameters, array shape (NxMx2) where", "j]) return data def draw_models(self, labels, data=None, correct=None): ''' Draw", "data is None: # create new batch of images data", "circle estimate is correct ''' n = labels.shape[0] if data", "draw to, if empty a new batch wil be created", "int(points[i, 0, j] * self.imgH) c = int(points[i, 1, j]", "cY = int(cY * self.imgH) cX = int(cX * self.imgW)", "center cY -- y value of circle center r --", "self.imgW-1, self.imgH-1, self.imgW-1), borderclr) return data def draw_points(self, points, data,", "circles will be green, circles will be blue otherwise correct", "-- soft inlier score for each point, if given and", "number of points data -- batch of images to draw", "set_color(data[i], line(0, self.imgW-1, self.imgH-1, self.imgW-1), borderclr) return data def draw_points(self,", "np.zeros((n, 3), dtype=np.float32) for i in range (0, n): data[i]", "-- batch of images to draw to inliers -- soft", "i in range (0, n): self.draw_circle(data[i], labels[i, 0], labels[i, 1],", "= np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) labels = np.zeros((n,", "also offers functionality for drawing line parameters, hypotheses and point", "of images m = points.shape[2] # number of points for", "x value of circle center cY -- y value of", "0.5 point will be drawn green, red otherwise ''' n", "(0, m): lY1 = int(labels[i, j, 0] * self.imgH) lY2", "= int(cX * self.imgW) r = int(r * self.imgW) rr,", "self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) labels = np.zeros((n, 3), dtype=np.float32)", "-- circle parameters, array shape (Nx3) where N is the", "circle center r -- radius of circle clr -- line", "with ground truth parameters. n -- number of images to", "data is None: data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32)", "self.imgH-1, self.imgW-1), borderclr) set_color(data[i], line(0, self.imgW-1, self.imgH-1, self.imgW-1), borderclr) return", "set_color(data[i], (rr, cc), clr) return data def samples(self, n): '''", "shape (N) indicating whether a circle estimate is correct '''", "points data -- batch of images to draw to inliers", "# create new batch of images data = np.zeros((n, self.imgH,", "n): for j in range(0, m): clr = (0.2, 0.2,", "in the batch M is the number of hypotheses per", "c = int(points[i, 1, j] * self.imgW) rr, cc =", "Draw a circle with the given color and opacity. data", "= labels.shape[0] if data is None: data = np.zeros((n, self.imgH,", "-- image to draw to cX -- x value of", "data -- batch of images to draw to, if empty", "values alpha -- opacity (default 1.0) ''' cY = int(cY", "drawing line parameters, hypotheses and point predictions. ''' def __init__(self,", "* self.imgW) r = int(r * self.imgW) rr, cc, val", "self.imgW-1), borderclr) return data def draw_points(self, points, data, inliers=None): '''", "of hypotheses if data is None: # create new batch", "imgW self.imgH = imgH self.margin = margin self.bg_clr = bg_clr", "number of images in the batch 3 is the number", "else: clr = (0, 0, 1) for i in range", "point will be drawn green, red otherwise ''' n =", "set_color(data[i], line(self.imgH-1, 0, self.imgH-1, self.imgW-1), borderclr) set_color(data[i], line(0, self.imgW-1, self.imgH-1,", "3 is the number of circles parameters (center x, center", "batch of images. points -- 2D points, array shape (Nx2xM)", "0] * self.imgH) lY2 = int(labels[i, j, 1] * self.imgW", "be drawn green, red otherwise ''' n = points.shape[0] #", "for i in range (0, n): for j in range(0,", "with higher opacity data -- batch of images to draw", "batch 2 is the number of point dimensions (x, y)", "def samples(self, n): ''' Create new input images of random", "m): lY1 = int(labels[i, j, 0] * self.imgH) lY2 =", "Images will have 1 random circle each, filled with noise", "int(r * self.imgW) rr, cc, val = circle_perimeter_aa(cY, cX, r)", "labels[i, j, 0] * self.imgH) self.draw_line(data[i], 0, lY1, self.imgW, lY2,", "# draw predicted points as dark circles if inliers is", "random import numpy as np import math from skimage.draw import", "''' Draw 2D points for a batch of images. points", "is None: data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr)", "in range (0, m): lY1 = int(labels[i, j, 0] *", "images. labels -- line parameters, array shape (NxMx2) where N", "triple of values alpha -- opacity (default 1.0) ''' cY", "y, radius) data -- batch of images to draw to,", "0, lY1, self.imgW, lY2, clr, scores[i, j]) return data def", "circle center cY -- y value of circle center r", "array shape (Nx2xM) where N is the number of images", "1] * self.imgW + labels[i, j, 0] * self.imgH) self.draw_line(data[i],", "to the shape of labels and circles will be green,", "0) else: borderclr = (1, 0, 0) set_color(data[i], line(0, 0,", "-- background intensity (default 0.5) ''' self.imgW = imgW self.imgH", "points for i in range (0, n): for j in", "n = points.shape[0] # number of images m = points.shape[2]", "a set of line hypothesis for a batch of images.", "N is the number of images in the batch 2", "(rr, cc), clr) return data def samples(self, n): ''' Create", "images in the batch 3 is the number of circles", "the image (default -5) bg_clr -- background intensity (default 0.5)", "otherwise correct -- array of shape (N) indicating whether a", "be created according to the shape of labels ''' n", "will be blue otherwise correct -- array of shape (N)", "dtype=np.float32) data.fill(self.bg_clr) clr = (0, 1, 0) else: clr =", "the number of points data -- batch of images to", "lines segments are sampled within this margin, negative value means", "data.fill(self.bg_clr) clr = (0, 0, 1) for i in range", "to cX -- x value of circle center cY --", "number of images in the batch M is the number", "segments class ICircleDataset: ''' Generator of circle segment images. Images", "number of point dimensions (x, y) M is the number", "images. points -- 2D points, array shape (Nx2xM) where N", "correct is not None: # draw border green if estiamte", "= circle(r, c, 2) set_color(data[i], (rr, cc), clr) return data", "(0.7, 0.7, 0.7) # draw inliers as light circles r", "clr -- line color, triple of values alpha -- opacity", "Class also offers functionality for drawing line parameters, hypotheses and", "val) def draw_hyps(self, labels, scores, data=None): ''' Draw a set", "higher score will be drawn with higher opacity data --", "of shape (N) indicating whether a circle estimate is correct", "in range (0, n): for j in range(0, m): clr", "3), dtype=np.float32) for i in range (0, n): data[i] =", "of points data -- batch of images to draw to", "labels = np.zeros((n, 3), dtype=np.float32) for i in range (0,", "(0, n): for j in range (0, m): lY1 =", "int(labels[i, j, 1] * self.imgW + labels[i, j, 0] *", "self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 1, 0) else:", "0, self.imgH-1, 0), borderclr) set_color(data[i], line(self.imgH-1, 0, self.imgH-1, self.imgW-1), borderclr)", "if correct[i]: borderclr = (0, 1, 0) else: borderclr =", "a batch of images. labels -- line parameters, array shape", "int(labels[i, j, 0] * self.imgH) lY2 = int(labels[i, j, 1]", "random circle each, filled with noise and distractor lines. Class", "with noise and distractor lines. Class also offers functionality for", "indicating whether a circle estimate is correct ''' n =", "to draw to cX -- x value of circle center", "''' n = labels.shape[0] # number of images m =", "cc, val = circle_perimeter_aa(cY, cX, r) set_color(data, (rr, cc), clr,", "def draw_circle(self, data, cX, cY, r, clr, alpha=1.0): ''' Draw", "empty a new batch wil be created according to the", "2D points for a batch of images. points -- 2D", "in the batch 3 is the number of circles parameters", "self.imgW-1), borderclr) set_color(data[i], line(0, self.imgW-1, self.imgH-1, self.imgW-1), borderclr) return data", "point dimensions (x, y) M is the number of points", "j in range(0, m): clr = (0.2, 0.2, 0.2) #", "-- radius of circle clr -- line color, triple of", "of circle clr -- line color, triple of values alpha", "a line segment can start or end outside the image", "red otherwise if correct[i]: borderclr = (0, 1, 0) else:", "is the number of hypotheses per image 2 is the", "of images data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr)", "None: data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr", "clr) return data def samples(self, n): ''' Create new input", "created according to the shape of labels and circles will", "new batch wil be created according to the shape of", "points for a batch of images. points -- 2D points,", "line(0, self.imgW-1, self.imgH-1, self.imgW-1), borderclr) return data def draw_points(self, points,", "''' n = labels.shape[0] if data is None: data =", "N is the number of images in the batch M", "minLength = 20 # restrict the minimum length of line", "of circle segment images. Images will have 1 random circle", "for drawing line parameters, hypotheses and point predictions. ''' def", "i in range (0, n): data[i] = random_noise(data[i], mode='speckle') return", "length of line segments class ICircleDataset: ''' Generator of circle", "segment images. Images will have 1 random circle each, filled", "correct ''' n = labels.shape[0] if data is None: data", "higher opacity data -- batch of images to draw to,", "the number of images in the batch 2 is the", "as dark circles if inliers is not None and inliers[i,", "shape of labels and circles will be green, circles will", "1.0) ''' cY = int(cY * self.imgH) cX = int(cX", "a batch of images. labels -- circle parameters, array shape", "circles parameters (center x, center y, radius) data -- batch", "radius) data -- batch of images to draw to, if", "dtype=np.float32) data.fill(self.bg_clr) labels = np.zeros((n, 3), dtype=np.float32) for i in", "images to draw to inliers -- soft inlier score for", "labels[i, 0], labels[i, 1], labels[i, 2], clr) if correct is", "= np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32) data.fill(self.bg_clr) clr = (0,", "64) imgH -- image height (default 64) margin -- lines", "margin, negative value means that a line segment can start", "= margin self.bg_clr = bg_clr def draw_circle(self, data, cX, cY,", "draw_circle(self, data, cX, cY, r, clr, alpha=1.0): ''' Draw a", "lY2, clr, scores[i, j]) return data def draw_models(self, labels, data=None,", "data=None, correct=None): ''' Draw circles for a batch of images.", "if inliers is not None and inliers[i, j] > 0.5:", "for i in range (0, n): self.draw_circle(data[i], labels[i, 0], labels[i,", "circle segment images. Images will have 1 random circle each,", "numpy as np import math from skimage.draw import line, line_aa,", "''' Draw circles for a batch of images. labels --", "1, j] * self.imgW) rr, cc = circle(r, c, 2)", "images m = labels.shape[1] # number of hypotheses if data", "# number of hypotheses if data is None: # create", "and opacity. data -- image to draw to cX --", "of circles parameters (center x, center y, radius) data --", "line(0, 0, 0, self.imgW-1), borderclr) set_color(data[i], line(0, 0, self.imgH-1, 0),", "bg_clr def draw_circle(self, data, cX, cY, r, clr, alpha=1.0): '''", "the batch 3 is the number of circles parameters (center", "x, center y, radius) data -- batch of images to", "for a batch of images. labels -- circle parameters, array", "cc), clr) return data def samples(self, n): ''' Create new", "set_color, circle_perimeter_aa from skimage.io import imsave from skimage.util import random_noise", "to inliers -- soft inlier score for each point, if", "and distractors along with ground truth parameters. n -- number", "circles if inliers is not None and inliers[i, j] >", "cX, cY, r, clr, alpha=1.0): ''' Draw a circle with", "3), dtype=np.float32) data.fill(self.bg_clr) clr = (0, 0, 1) for i", "outside the image (default -5) bg_clr -- background intensity (default", "64, imgH = 64, margin = -5, bg_clr = 0.5):", "batch of images. labels -- line parameters, array shape (NxMx2)", "the maximum slope of generated lines for stability minLength =", "def draw_hyps(self, labels, scores, data=None): ''' Draw a set of", "data.fill(self.bg_clr) clr = (0, 1, 0) else: clr = (0,", "of images in the batch 2 is the number of", "circle, set_color, circle_perimeter_aa from skimage.io import imsave from skimage.util import", "hypotheses if data is None: # create new batch of", "new input images of random line segments and distractors along", "if estiamte is correct, red otherwise if correct[i]: borderclr =", "self.imgW-1), borderclr) set_color(data[i], line(0, 0, self.imgH-1, 0), borderclr) set_color(data[i], line(self.imgH-1,", "20 # restrict the minimum length of line segments class", "parameters, array shape (Nx3) where N is the number of", "data -- image to draw to cX -- x value", "# restrict the maximum slope of generated lines for stability", "to draw to inliers -- soft inlier score for each", "range (0, n): self.draw_circle(data[i], labels[i, 0], labels[i, 1], labels[i, 2],", "scores, array shape (NxM), see above, higher score will be", "range(0, m): clr = (0.2, 0.2, 0.2) # draw predicted", "for stability minLength = 20 # restrict the minimum length", "line parameters (intercept, slope) scores -- hypotheses scores, array shape", "number of images in the batch 2 is the number", "n = labels.shape[0] # number of images m = labels.shape[1]", "images m = points.shape[2] # number of points for i", "3), dtype=np.float32) data.fill(self.bg_clr) labels = np.zeros((n, 3), dtype=np.float32) for i", "center y, radius) data -- batch of images to draw", "''' Draw a set of line hypothesis for a batch", "above, higher score will be drawn with higher opacity data", "(Nx3) where N is the number of images in the", "1, 0) else: clr = (0, 0, 1) for i", "imgH = 64, margin = -5, bg_clr = 0.5): '''", "''' Generator of circle segment images. Images will have 1", "= labels.shape[1] # number of hypotheses if data is None:", "green if estiamte is correct, red otherwise if correct[i]: borderclr", "= int(labels[i, j, 0] * self.imgH) lY2 = int(labels[i, j,", "data.fill(self.bg_clr) labels = np.zeros((n, 3), dtype=np.float32) for i in range", "and score < 0.5 point will be drawn green, red", "import numpy as np import math from skimage.draw import line,", "line segment can start or end outside the image (default", "array shape (Nx3) where N is the number of images", "line hypothesis for a batch of images. labels -- line", "random_noise maxSlope = 10 # restrict the maximum slope of", "correct -- array of shape (N) indicating whether a circle", "n): self.draw_circle(data[i], labels[i, 0], labels[i, 1], labels[i, 2], clr) if", "= 64, imgH = 64, margin = -5, bg_clr =", "(center x, center y, radius) data -- batch of images", "data def draw_points(self, points, data, inliers=None): ''' Draw 2D points", "= np.zeros((n, 3), dtype=np.float32) for i in range (0, n):", "(NxM), see above, higher score will be drawn with higher", "0, 0) set_color(data[i], line(0, 0, 0, self.imgW-1), borderclr) set_color(data[i], line(0,", "= int(cY * self.imgH) cX = int(cX * self.imgW) r", "set_color(data[i], line(0, 0, 0, self.imgW-1), borderclr) set_color(data[i], line(0, 0, self.imgH-1,", "''' def __init__(self, imgW = 64, imgH = 64, margin", "images of random line segments and distractors along with ground", "-5) bg_clr -- background intensity (default 0.5) ''' self.imgW =", "array shape (NxMx2) where N is the number of images", "intensity (default 0.5) ''' self.imgW = imgW self.imgH = imgH", "end outside the image (default -5) bg_clr -- background intensity", "and circles will be green, circles will be blue otherwise", "None: # create new batch of images data = np.zeros((n,", "= 0.5): ''' Constructor. imgW -- image width (default 64)", "can start or end outside the image (default -5) bg_clr", "if given and score < 0.5 point will be drawn", "batch of images data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32)", "number of images m = points.shape[2] # number of points", "labels.shape[0] # number of images m = labels.shape[1] # number", "# number of points for i in range (0, n):", "import random import numpy as np import math from skimage.draw", "start or end outside the image (default -5) bg_clr --", "from skimage.draw import line, line_aa, circle, set_color, circle_perimeter_aa from skimage.io", "circle(r, c, 2) set_color(data[i], (rr, cc), clr) return data def", "import imsave from skimage.util import random_noise maxSlope = 10 #" ]
[ "format # Parameters for track generation (specifically filtering) p_min =", "Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model Parameters latent_dim = 124 input_dim =", "New Tracks from Latent Samples') # Decode samples using VAE", "file `generation_utils` to have our trained model create entirely new", "latent_vecs = get_latent_vecs(model, dataset, batch_size) # Sample from normal distribution", "# Filter Track decoded_tracks = filter_tracks(decoded_tracks, p_min) # Plot first", "10 print('Generating Latent Samples to Generate {} New Tracks'.format(num_songs)) #", "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save our wav tracks to appropriate files (be", "Plot first decoded track print(\"Example Model Generated Track\") plot_track(decoded_tracks[0]) #", "NES music. \"\"\" # Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE - nesmdb", "coding: utf-8 -*- \"\"\" Created on Wed Apr 1 17:14:19", "import numpy as np import os, json ### Load Mappings", "seprsco_tracks = generate_seprsco(decoded_tracks, int2labels_map) ### Convert to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #", "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters for shape of dataset (note these are", "Latent Samples to Generate {} New Tracks'.format(num_songs)) # Grab distributions", "-*- coding: utf-8 -*- \"\"\" Created on Wed Apr 1", "functions from the file `generation_utils` to have our trained model", "Then we use functions from the file `generation_utils` to have", "track in seprsco_tracks: wav = nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ### Save WAV", "# Seprsco files can later be converted to valid NES", "train_save_filename, measures = measures, measure_len = measure_len) ### Reinitiate Model", "latent space # Parameters for sampling num_songs = 10 print('Generating", "are also used for model def.) measures = 8 measure_len", "Track decoded_tracks = filter_tracks(decoded_tracks, p_min) # Plot first filtered track", "tracks using our model and the random samples # Seprsco", "first decoded track print(\"Example Model Generated Track\") plot_track(decoded_tracks[0]) # Filter", "tracks to WAV files so we can listen!!! print('Converting Seprsco", "plot_eigenvalues = True sample_vecs = latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues) ### Generate", "Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create new seprsco tracks using our model", "more effectively sample from the orthogonal components # of our", "= generate_seprsco(decoded_tracks, int2labels_map) ### Convert to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert", "= 'model_gen_files/' for i in range(len(wav_tracks)): wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file,", "also used for model def.) measures = 8 measure_len =", "if save_latent_var: print('Saving Latent Variables for Generated Tracks') latent_filename =", "NESM track. To do so we first reconstruct our model", "in an NESM track. To do so we first reconstruct", "reproduce songs we like # Save WAV tracks save_wav =", "os, json ### Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters for shape", "model = VAE(latent_dim, input_dim, measures, measure_len, dropout, maxnorm, vae_b1 ,", "Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model Parameters latent_dim = 124 input_dim", "have our trained model create entirely new and original NES", "(note these are also used for model def.) measures =", "get_latent_vecs(model, dataset, batch_size) # Sample from normal distribution rand_vecs =", "print('Saving Latent Variables for Generated Tracks') latent_filename = os.path.join(wav_folder, \"latent_variables.json\")", "maxnorm, vae_b1 , vae_b2) # Reload Saved Weights checkpoint_dir =", "pre-trained VAE model to generate brand new NES music soundtracks.", "samples # Seprsco files can later be converted to valid", "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE - nesmdb folder manually added to environment", "filtering) p_min = .5 print('Generating New Tracks from Latent Samples')", "in seprsco_tracks: wav = nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ### Save WAV Files", "Print Summary of Model model.summary() ### Sample Latent Variable Distributions", "tracks to seprsco format print('Converting Model Output to Seprsco') seprsco_tracks", "plot_eigenvalues) ### Generate New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create new seprsco", "Output to Seprsco') seprsco_tracks = generate_seprsco(decoded_tracks, int2labels_map) ### Convert to", ".02 , .1 print('Reinitiating VAE Model') # Build Model model", "wav_folder = 'model_gen_files/' for i in range(len(wav_tracks)): wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i)", "nesm_generator.py ~~~~~~~~~~~~~~~~~ This file serves as a script for using", "to Seprsco') seprsco_tracks = generate_seprsco(decoded_tracks, int2labels_map) ### Convert to WAV", ", labels2int_map , int2labels_map = \\ load_training(training_foldername, train_save_filename, measures =", "### Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model Parameters latent_dim = 124", "wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i]) # Save Latent Variables save_latent_var = False", "first reconstruct our model using the file VAE class defined", "to generate brand new NES music soundtracks. NOTE - using", "rand_vecs, plot_eigenvalues) ### Generate New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create new", "os.path.join(wav_folder, \"latent_variables.json\") with open(latent_filename, 'w') as f: json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist()", "### Save WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save our wav tracks", "of the four voices present in an NESM track. To", "### Convert to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert seprsco tracks to", "WAV Audio') wav_tracks = [] for track in seprsco_tracks: wav", "measures = 8 measure_len = 96 # load data training_foldername", "\"\"\" # Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE - nesmdb folder manually", "VAE import VAE from generation_utils import generate_seprsco, latent_SVD, get_latent_vecs,\\ plot_track,", "import generate_seprsco, latent_SVD, get_latent_vecs,\\ plot_track, filter_tracks import nesmdb from nesmdb.vgm.vgm_to_wav", "open(latent_filename, 'w') as f: json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for i in", "melodic voice for each track rather than each of the", "using VAE decoded_tracks = model.decoder(sample_vecs) # Plot first decoded track", "= measure_len) ### Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model Parameters latent_dim", "plot_track, filter_tracks import nesmdb from nesmdb.vgm.vgm_to_wav import save_vgmwav import tensorflow", "model we only generate the first melodic voice for each", "int2labels_map) ### Convert to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert seprsco tracks", "= os.path.join(wav_folder, \"latent_variables.json\") with open(latent_filename, 'w') as f: json.dump({ 'VAE_NESM_{}.wav'.format(i):", "300 latent_vecs = get_latent_vecs(model, dataset, batch_size) # Sample from normal", "model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures, measure_len, ])) # Print Summary of Model", "Parameters for sampling num_songs = 10 print('Generating Latent Samples to", "later be converted to valid NES music format # Parameters", "we use functions from the file `generation_utils` to have our", "Created on Wed Apr 1 17:14:19 2020 @author: Mitchell nesm_generator.py", "Model Parameters latent_dim = 124 input_dim = len(int2labels_map) - 1", "2020 @author: Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~ This file serves as a", "vae_b1 , vae_b2) # Reload Saved Weights checkpoint_dir = './training_checkpoints'", "to WAV Audio') wav_tracks = [] for track in seprsco_tracks:", "# NOTE - nesmdb folder manually added to environment libraries", "# Plot first filtered track print(\"Example Filtered Track\") plot_track(decoded_tracks[0]) #", "Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save our wav tracks to appropriate files", "run in batches due to size of the dataset batch_size", "than each of the four voices present in an NESM", "= .1 maxnorm = None vae_b1 , vae_b2 = .02", "Variables for Generated Tracks') latent_filename = os.path.join(wav_folder, \"latent_variables.json\") with open(latent_filename,", "we first reconstruct our model using the file VAE class", "= '../../nesmdb24_seprsco/train/' train_save_filename = 'transformed_dataset.json' dataset , labels2int_map , int2labels_map", "used in `model_training`. Then we use functions from the file", "to seprsco format print('Converting Model Output to Seprsco') seprsco_tracks =", "8 measure_len = 96 # load data training_foldername = '../../nesmdb24_seprsco/train/'", "= 96 # load data training_foldername = '../../nesmdb24_seprsco/train/' train_save_filename =", "in `VAE.py` and the same parameters used in `model_training`. Then", "Model model.summary() ### Sample Latent Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here", "SVD to more effectively sample from the orthogonal components #", "'model_gen_files/' for i in range(len(wav_tracks)): wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i])", "of the dataset batch_size = 300 latent_vecs = get_latent_vecs(model, dataset,", "for i in range(sample_vecs.shape[0]) }, f) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #----------------------------------END FILE------------------------------------ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "measure_len, dropout, maxnorm, vae_b1 , vae_b2) # Reload Saved Weights", "new seprsco tracks using our model and the random samples", "model.decoder(sample_vecs) # Plot first decoded track print(\"Example Model Generated Track\")", "and the same parameters used in `model_training`. Then we use", "dataset (note these are also used for model def.) measures", "plot_track(decoded_tracks[0]) # Convert tracks to seprsco format print('Converting Model Output", "checkpoint_prefix = os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures, measure_len, ])) #", "17:14:19 2020 @author: Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~ This file serves as", "to valid NES music format # Parameters for track generation", "p_min) # Plot first filtered track print(\"Example Filtered Track\") plot_track(decoded_tracks[0])", "NOTE - using the reduced model we only generate the", "using our pre-trained VAE model to generate brand new NES", "the first melodic voice for each track rather than each", "sample_vecs[i].tolist() for i in range(sample_vecs.shape[0]) }, f) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #----------------------------------END FILE------------------------------------", "from VAE import VAE from generation_utils import generate_seprsco, latent_SVD, get_latent_vecs,\\", "for using our pre-trained VAE model to generate brand new", "track generation (specifically filtering) p_min = .5 print('Generating New Tracks", "we can listen!!! print('Converting Seprsco to WAV Audio') wav_tracks =", "json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for i in range(sample_vecs.shape[0]) }, f) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "if save_wav: print('Saving Generated WAV Audio Tracks') wav_folder = 'model_gen_files/'", "new and original NES music. \"\"\" # Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #", "# Have to run in batches due to size of", "samples using VAE decoded_tracks = model.decoder(sample_vecs) # Plot first decoded", "len(int2labels_map) - 1 dropout = .1 maxnorm = None vae_b1", "(be sure not to overwrite existing) # Also save latent", "to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert seprsco tracks to WAV files", "save_vgmwav import tensorflow as tf import numpy as np import", "# Also save latent variables so we can reproduce songs", "print('Generating New Tracks from Latent Samples') # Decode samples using", "# Parameters for sampling num_songs = 10 print('Generating Latent Samples", "[] for track in seprsco_tracks: wav = nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ###", "Generate {} New Tracks'.format(num_songs)) # Grab distributions of dataset over", "Seprsco') seprsco_tracks = generate_seprsco(decoded_tracks, int2labels_map) ### Convert to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "using the file VAE class defined in `VAE.py` and the", "= \\ load_training(training_foldername, train_save_filename, measures = measures, measure_len = measure_len)", "import nesmdb from nesmdb.vgm.vgm_to_wav import save_vgmwav import tensorflow as tf", "WAV Audio Tracks') wav_folder = 'model_gen_files/' for i in range(len(wav_tracks)):", "= filter_tracks(decoded_tracks, p_min) # Plot first filtered track print(\"Example Filtered", "wav_tracks = [] for track in seprsco_tracks: wav = nesmdb.convert.seprsco_to_wav(track)", "rather than each of the four voices present in an", "Reload Saved Weights checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, \"model_ckpt\")", "### Model Parameters latent_dim = 124 input_dim = len(int2labels_map) -", "`model_training`. Then we use functions from the file `generation_utils` to", "Track\") plot_track(decoded_tracks[0]) # Filter Track decoded_tracks = filter_tracks(decoded_tracks, p_min) #", "effectively sample from the orthogonal components # of our latent", "create entirely new and original NES music. \"\"\" # Imports", "from Latent Samples') # Decode samples using VAE decoded_tracks =", "vae_b2) # Reload Saved Weights checkpoint_dir = './training_checkpoints' checkpoint_prefix =", "NES music soundtracks. NOTE - using the reduced model we", "generation_utils import generate_seprsco, latent_SVD, get_latent_vecs,\\ plot_track, filter_tracks import nesmdb from", ", vae_b2 = .02 , .1 print('Reinitiating VAE Model') #", "filtered track print(\"Example Filtered Track\") plot_track(decoded_tracks[0]) # Convert tracks to", "Latent Variables save_latent_var = False if save_latent_var: print('Saving Latent Variables", "= 300 latent_vecs = get_latent_vecs(model, dataset, batch_size) # Sample from", "filter_tracks(decoded_tracks, p_min) # Plot first filtered track print(\"Example Filtered Track\")", "vae_b1 , vae_b2 = .02 , .1 print('Reinitiating VAE Model')", "# Save Latent Variables save_latent_var = False if save_latent_var: print('Saving", "'w') as f: json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for i in range(sample_vecs.shape[0])", "maxnorm = None vae_b1 , vae_b2 = .02 , .1", "the dataset batch_size = 300 latent_vecs = get_latent_vecs(model, dataset, batch_size)", "seprsco_tracks: wav = nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ### Save WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "same parameters used in `model_training`. Then we use functions from", "p_min = .5 print('Generating New Tracks from Latent Samples') #", "as tf import numpy as np import os, json ###", "nesmdb.vgm.vgm_to_wav import save_vgmwav import tensorflow as tf import numpy as", "track rather than each of the four voices present in", "import VAE from generation_utils import generate_seprsco, latent_SVD, get_latent_vecs,\\ plot_track, filter_tracks", "so we first reconstruct our model using the file VAE", "dataset , labels2int_map , int2labels_map = \\ load_training(training_foldername, train_save_filename, measures", "to overwrite existing) # Also save latent variables so we", "os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures, measure_len, ])) # Print Summary", "load_training(training_foldername, train_save_filename, measures = measures, measure_len = measure_len) ### Reinitiate", "To do so we first reconstruct our model using the", "import save_vgmwav import tensorflow as tf import numpy as np", "we like # Save WAV tracks save_wav = False if", "Samples to Generate {} New Tracks'.format(num_songs)) # Grab distributions of", "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert seprsco tracks to WAV files so we", ".1 print('Reinitiating VAE Model') # Build Model model = VAE(latent_dim,", "sample from the orthogonal components # of our latent space", "track. To do so we first reconstruct our model using", "input_dim, measures, measure_len, dropout, maxnorm, vae_b1 , vae_b2) # Reload", "Seprsco files can later be converted to valid NES music", "print(\"Example Filtered Track\") plot_track(decoded_tracks[0]) # Convert tracks to seprsco format", "model to generate brand new NES music soundtracks. NOTE -", "Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here we use SVD to more", "= os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures, measure_len, ])) # Print", "model create entirely new and original NES music. \"\"\" #", "with open(latent_filename, 'w') as f: json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for i", "the same parameters used in `model_training`. Then we use functions", "latent variables so we can reproduce songs we like #", "files (be sure not to overwrite existing) # Also save", "measures = measures, measure_len = measure_len) ### Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "our wav tracks to appropriate files (be sure not to", "sure not to overwrite existing) # Also save latent variables", "-*- \"\"\" Created on Wed Apr 1 17:14:19 2020 @author:", "the random samples # Seprsco files can later be converted", "defined in `VAE.py` and the same parameters used in `model_training`.", "Parameters for shape of dataset (note these are also used", "so we can reproduce songs we like # Save WAV", "= VAE(latent_dim, input_dim, measures, measure_len, dropout, maxnorm, vae_b1 , vae_b2)", "~~~~~~~~~~~~~~~~~ This file serves as a script for using our", "in range(len(wav_tracks)): wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i]) # Save Latent", "Tracks'.format(num_songs)) # Grab distributions of dataset over latent space #", "= True sample_vecs = latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues) ### Generate New", "dropout = .1 maxnorm = None vae_b1 , vae_b2 =", "import os, json ### Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters for", "batch_size) # Sample from normal distribution rand_vecs = np.random.normal(0.0, 1.0,", "# Save our wav tracks to appropriate files (be sure", "measures, measure_len, ])) # Print Summary of Model model.summary() ###", "for model def.) measures = 8 measure_len = 96 #", "Variables save_latent_var = False if save_latent_var: print('Saving Latent Variables for", "be converted to valid NES music format # Parameters for", "= .02 , .1 print('Reinitiating VAE Model') # Build Model", "\"\"\" Created on Wed Apr 1 17:14:19 2020 @author: Mitchell", "np import os, json ### Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters", "Convert to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert seprsco tracks to WAV", "Latent Variables for Generated Tracks') latent_filename = os.path.join(wav_folder, \"latent_variables.json\") with", "as a script for using our pre-trained VAE model to", "= len(int2labels_map) - 1 dropout = .1 maxnorm = None", "save_latent_var: print('Saving Latent Variables for Generated Tracks') latent_filename = os.path.join(wav_folder,", "from normal distribution rand_vecs = np.random.normal(0.0, 1.0, (num_songs, latent_dim)) #", "# Print Summary of Model model.summary() ### Sample Latent Variable", "Audio') wav_tracks = [] for track in seprsco_tracks: wav =", "save_wav = False if save_wav: print('Saving Generated WAV Audio Tracks')", "NES music format # Parameters for track generation (specifically filtering)", "overwrite existing) # Also save latent variables so we can", "(num_songs, latent_dim)) # perform SVD plot_eigenvalues = True sample_vecs =", "\\ load_training(training_foldername, train_save_filename, measures = measures, measure_len = measure_len) ###", "our latent space # Parameters for sampling num_songs = 10", "# of our latent space # Parameters for sampling num_songs", "96 # load data training_foldername = '../../nesmdb24_seprsco/train/' train_save_filename = 'transformed_dataset.json'", "numpy as np import os, json ### Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "the orthogonal components # of our latent space # Parameters", "print('Converting Seprsco to WAV Audio') wav_tracks = [] for track", "measures, measure_len, dropout, maxnorm, vae_b1 , vae_b2) # Reload Saved", "print('Converting Model Output to Seprsco') seprsco_tracks = generate_seprsco(decoded_tracks, int2labels_map) ###", "utf-8 -*- \"\"\" Created on Wed Apr 1 17:14:19 2020", "= measures, measure_len = measure_len) ### Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###", "nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ### Save WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save our", "# Convert tracks to seprsco format print('Converting Model Output to", "Seprsco to WAV Audio') wav_tracks = [] for track in", "latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues) ### Generate New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create", "voices present in an NESM track. To do so we", "from the file `generation_utils` to have our trained model create", "brand new NES music soundtracks. NOTE - using the reduced", "- nesmdb folder manually added to environment libraries from dataset_utils", "generate_seprsco, latent_SVD, get_latent_vecs,\\ plot_track, filter_tracks import nesmdb from nesmdb.vgm.vgm_to_wav import", "we use SVD to more effectively sample from the orthogonal", "save_vgmwav(wav_file, wav_tracks[i]) # Save Latent Variables save_latent_var = False if", "This file serves as a script for using our pre-trained", "# -*- coding: utf-8 -*- \"\"\" Created on Wed Apr", "False if save_latent_var: print('Saving Latent Variables for Generated Tracks') latent_filename", "save_latent_var = False if save_latent_var: print('Saving Latent Variables for Generated", ", .1 print('Reinitiating VAE Model') # Build Model model =", "as np import os, json ### Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #", "Build Model model = VAE(latent_dim, input_dim, measures, measure_len, dropout, maxnorm,", "a script for using our pre-trained VAE model to generate", "import load_training from VAE import VAE from generation_utils import generate_seprsco,", "files can later be converted to valid NES music format", "use SVD to more effectively sample from the orthogonal components", "latent space # Have to run in batches due to", "measures, measure_len = measure_len) ### Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model", "Parameters latent_dim = 124 input_dim = len(int2labels_map) - 1 dropout", "dataset over latent space # Have to run in batches", "wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i]) # Save Latent Variables save_latent_var", "VAE from generation_utils import generate_seprsco, latent_SVD, get_latent_vecs,\\ plot_track, filter_tracks import", "Convert tracks to seprsco format print('Converting Model Output to Seprsco')", "file serves as a script for using our pre-trained VAE", "VAE Model') # Build Model model = VAE(latent_dim, input_dim, measures,", "variables so we can reproduce songs we like # Save", "range(len(wav_tracks)): wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i]) # Save Latent Variables", "`generation_utils` to have our trained model create entirely new and", "seprsco tracks to WAV files so we can listen!!! print('Converting", "voice for each track rather than each of the four", "for Generated Tracks') latent_filename = os.path.join(wav_folder, \"latent_variables.json\") with open(latent_filename, 'w')", "due to size of the dataset batch_size = 300 latent_vecs", "'../../nesmdb24_seprsco/train/' train_save_filename = 'transformed_dataset.json' dataset , labels2int_map , int2labels_map =", "def.) measures = 8 measure_len = 96 # load data", "\"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures, measure_len, ])) # Print Summary of", "serves as a script for using our pre-trained VAE model", "latent_filename = os.path.join(wav_folder, \"latent_variables.json\") with open(latent_filename, 'w') as f: json.dump({", "each track rather than each of the four voices present", "json ### Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters for shape of", "# Sample from normal distribution rand_vecs = np.random.normal(0.0, 1.0, (num_songs,", "{} New Tracks'.format(num_songs)) # Grab distributions of dataset over latent", "Sample from normal distribution rand_vecs = np.random.normal(0.0, 1.0, (num_songs, latent_dim))", "Filter Track decoded_tracks = filter_tracks(decoded_tracks, p_min) # Plot first filtered", "Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~ This file serves as a script for", "to appropriate files (be sure not to overwrite existing) #", "the file `generation_utils` to have our trained model create entirely", "batch_size = 300 latent_vecs = get_latent_vecs(model, dataset, batch_size) # Sample", "dataset, batch_size) # Sample from normal distribution rand_vecs = np.random.normal(0.0,", "to size of the dataset batch_size = 300 latent_vecs =", "added to environment libraries from dataset_utils import load_training from VAE", "from generation_utils import generate_seprsco, latent_SVD, get_latent_vecs,\\ plot_track, filter_tracks import nesmdb", "track print(\"Example Model Generated Track\") plot_track(decoded_tracks[0]) # Filter Track decoded_tracks", "dataset_utils import load_training from VAE import VAE from generation_utils import", "model.build(tf.TensorShape([None, measures, measure_len, ])) # Print Summary of Model model.summary()", "wav = nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ### Save WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #", "VAE class defined in `VAE.py` and the same parameters used", "= False if save_wav: print('Saving Generated WAV Audio Tracks') wav_folder", "model def.) measures = 8 measure_len = 96 # load", "and the random samples # Seprsco files can later be", "print('Saving Generated WAV Audio Tracks') wav_folder = 'model_gen_files/' for i", "the four voices present in an NESM track. To do", "wav_tracks.append(wav) ### Save WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save our wav", "Tracks from Latent Samples') # Decode samples using VAE decoded_tracks", "only generate the first melodic voice for each track rather", "= None vae_b1 , vae_b2 = .02 , .1 print('Reinitiating", "Model Output to Seprsco') seprsco_tracks = generate_seprsco(decoded_tracks, int2labels_map) ### Convert", "music format # Parameters for track generation (specifically filtering) p_min", "= np.random.normal(0.0, 1.0, (num_songs, latent_dim)) # perform SVD plot_eigenvalues =", "for track generation (specifically filtering) p_min = .5 print('Generating New", "Decode samples using VAE decoded_tracks = model.decoder(sample_vecs) # Plot first", "Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters for shape of dataset (note", "listen!!! print('Converting Seprsco to WAV Audio') wav_tracks = [] for", "shape of dataset (note these are also used for model", "reduced model we only generate the first melodic voice for", "= latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues) ### Generate New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #", "Tracks') latent_filename = os.path.join(wav_folder, \"latent_variables.json\") with open(latent_filename, 'w') as f:", "to more effectively sample from the orthogonal components # of", "music soundtracks. NOTE - using the reduced model we only", "= False if save_latent_var: print('Saving Latent Variables for Generated Tracks')", "like # Save WAV tracks save_wav = False if save_wav:", "None vae_b1 , vae_b2 = .02 , .1 print('Reinitiating VAE", "appropriate files (be sure not to overwrite existing) # Also", "= 8 measure_len = 96 # load data training_foldername =", "dataset batch_size = 300 latent_vecs = get_latent_vecs(model, dataset, batch_size) #", "can later be converted to valid NES music format #", "track print(\"Example Filtered Track\") plot_track(decoded_tracks[0]) # Convert tracks to seprsco", "to have our trained model create entirely new and original", "perform SVD plot_eigenvalues = True sample_vecs = latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues)", "of our latent space # Parameters for sampling num_songs =", "Save Latent Variables save_latent_var = False if save_latent_var: print('Saving Latent", "from nesmdb.vgm.vgm_to_wav import save_vgmwav import tensorflow as tf import numpy", "for each track rather than each of the four voices", "Samples') # Decode samples using VAE decoded_tracks = model.decoder(sample_vecs) #", "tf import numpy as np import os, json ### Load", ", vae_b2) # Reload Saved Weights checkpoint_dir = './training_checkpoints' checkpoint_prefix", "# Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE - nesmdb folder manually added", "music. \"\"\" # Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE - nesmdb folder", "over latent space # Have to run in batches due", "])) # Print Summary of Model model.summary() ### Sample Latent", "seprsco format print('Converting Model Output to Seprsco') seprsco_tracks = generate_seprsco(decoded_tracks,", "input_dim = len(int2labels_map) - 1 dropout = .1 maxnorm =", "'transformed_dataset.json' dataset , labels2int_map , int2labels_map = \\ load_training(training_foldername, train_save_filename,", "for i in range(len(wav_tracks)): wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i]) #", "measure_len = 96 # load data training_foldername = '../../nesmdb24_seprsco/train/' train_save_filename", "latent_dim = 124 input_dim = len(int2labels_map) - 1 dropout =", "load_training from VAE import VAE from generation_utils import generate_seprsco, latent_SVD,", ".5 print('Generating New Tracks from Latent Samples') # Decode samples", ", int2labels_map = \\ load_training(training_foldername, train_save_filename, measures = measures, measure_len", "# Parameters for shape of dataset (note these are also", "on Wed Apr 1 17:14:19 2020 @author: Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~", "using our model and the random samples # Seprsco files", "- using the reduced model we only generate the first", "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here we use SVD to more effectively sample", "we can reproduce songs we like # Save WAV tracks", "save_wav: print('Saving Generated WAV Audio Tracks') wav_folder = 'model_gen_files/' for", "model and the random samples # Seprsco files can later", "soundtracks. NOTE - using the reduced model we only generate", "- 1 dropout = .1 maxnorm = None vae_b1 ,", "# Here we use SVD to more effectively sample from", "measure_len) ### Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model Parameters latent_dim =", "SVD plot_eigenvalues = True sample_vecs = latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues) ###", "WAV files so we can listen!!! print('Converting Seprsco to WAV", "for track in seprsco_tracks: wav = nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ### Save", "original NES music. \"\"\" # Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE -", "converted to valid NES music format # Parameters for track", "an NESM track. To do so we first reconstruct our", "can reproduce songs we like # Save WAV tracks save_wav", "four voices present in an NESM track. To do so", "data training_foldername = '../../nesmdb24_seprsco/train/' train_save_filename = 'transformed_dataset.json' dataset , labels2int_map", "of Model model.summary() ### Sample Latent Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #", "batches due to size of the dataset batch_size = 300", "do so we first reconstruct our model using the file", "as f: json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for i in range(sample_vecs.shape[0]) },", "= './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures, measure_len,", "VAE model to generate brand new NES music soundtracks. NOTE", "True sample_vecs = latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues) ### Generate New Tracks", "these are also used for model def.) measures = 8", "plot_track(decoded_tracks[0]) # Filter Track decoded_tracks = filter_tracks(decoded_tracks, p_min) # Plot", "so we can listen!!! print('Converting Seprsco to WAV Audio') wav_tracks", "= model.decoder(sample_vecs) # Plot first decoded track print(\"Example Model Generated", "libraries from dataset_utils import load_training from VAE import VAE from", "New Tracks'.format(num_songs)) # Grab distributions of dataset over latent space", "nesmdb folder manually added to environment libraries from dataset_utils import", "trained model create entirely new and original NES music. \"\"\"", "1.0, (num_songs, latent_dim)) # perform SVD plot_eigenvalues = True sample_vecs", "# Save WAV tracks save_wav = False if save_wav: print('Saving", "WAV tracks save_wav = False if save_wav: print('Saving Generated WAV", ".1 maxnorm = None vae_b1 , vae_b2 = .02 ,", "Weights checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None,", "our trained model create entirely new and original NES music.", "1 17:14:19 2020 @author: Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~ This file serves", "and original NES music. \"\"\" # Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE", "to run in batches due to size of the dataset", "Plot first filtered track print(\"Example Filtered Track\") plot_track(decoded_tracks[0]) # Convert", "valid NES music format # Parameters for track generation (specifically", "measure_len = measure_len) ### Reinitiate Model #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model Parameters", "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### Model Parameters latent_dim = 124 input_dim = len(int2labels_map)", "model.summary() ### Sample Latent Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here we", "reconstruct our model using the file VAE class defined in", "Filtered Track\") plot_track(decoded_tracks[0]) # Convert tracks to seprsco format print('Converting", "space # Have to run in batches due to size", "first filtered track print(\"Example Filtered Track\") plot_track(decoded_tracks[0]) # Convert tracks", "= wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i]) # Save Latent Variables save_latent_var =", "= nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav) ### Save WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save", "normal distribution rand_vecs = np.random.normal(0.0, 1.0, (num_songs, latent_dim)) # perform", "Model Generated Track\") plot_track(decoded_tracks[0]) # Filter Track decoded_tracks = filter_tracks(decoded_tracks,", "training_foldername = '../../nesmdb24_seprsco/train/' train_save_filename = 'transformed_dataset.json' dataset , labels2int_map ,", "wav tracks to appropriate files (be sure not to overwrite", "measure_len, ])) # Print Summary of Model model.summary() ### Sample", "wav_tracks[i]) # Save Latent Variables save_latent_var = False if save_latent_var:", "dropout, maxnorm, vae_b1 , vae_b2) # Reload Saved Weights checkpoint_dir", "generate brand new NES music soundtracks. NOTE - using the", "# load data training_foldername = '../../nesmdb24_seprsco/train/' train_save_filename = 'transformed_dataset.json' dataset", "# Create new seprsco tracks using our model and the", "from dataset_utils import load_training from VAE import VAE from generation_utils", "Convert seprsco tracks to WAV files so we can listen!!!", "Here we use SVD to more effectively sample from the", "model using the file VAE class defined in `VAE.py` and", "num_songs = 10 print('Generating Latent Samples to Generate {} New", "parameters used in `model_training`. Then we use functions from the", "the reduced model we only generate the first melodic voice", "size of the dataset batch_size = 300 latent_vecs = get_latent_vecs(model,", "Save WAV tracks save_wav = False if save_wav: print('Saving Generated", "# Build Model model = VAE(latent_dim, input_dim, measures, measure_len, dropout,", "space # Parameters for sampling num_songs = 10 print('Generating Latent", "get_latent_vecs,\\ plot_track, filter_tracks import nesmdb from nesmdb.vgm.vgm_to_wav import save_vgmwav import", "decoded_tracks = filter_tracks(decoded_tracks, p_min) # Plot first filtered track print(\"Example", "### Generate New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create new seprsco tracks", "songs we like # Save WAV tracks save_wav = False", "tensorflow as tf import numpy as np import os, json", "script for using our pre-trained VAE model to generate brand", "= get_latent_vecs(model, dataset, batch_size) # Sample from normal distribution rand_vecs", "import tensorflow as tf import numpy as np import os,", "using the reduced model we only generate the first melodic", "`VAE.py` and the same parameters used in `model_training`. Then we", "for sampling num_songs = 10 print('Generating Latent Samples to Generate", "use functions from the file `generation_utils` to have our trained", "our model using the file VAE class defined in `VAE.py`", "each of the four voices present in an NESM track.", "VAE(latent_dim, input_dim, measures, measure_len, dropout, maxnorm, vae_b1 , vae_b2) #", "Latent Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here we use SVD to", "@author: Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~ This file serves as a script", "vae_b2 = .02 , .1 print('Reinitiating VAE Model') # Build", "Track\") plot_track(decoded_tracks[0]) # Convert tracks to seprsco format print('Converting Model", "= 10 print('Generating Latent Samples to Generate {} New Tracks'.format(num_songs))", "Apr 1 17:14:19 2020 @author: Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~ This file", "orthogonal components # of our latent space # Parameters for", "decoded_tracks = model.decoder(sample_vecs) # Plot first decoded track print(\"Example Model", "Have to run in batches due to size of the", "i in range(len(wav_tracks)): wav_file = wav_folder+'VAE_NESM_{}.wav'.format(i) save_vgmwav(wav_file, wav_tracks[i]) # Save", "= .5 print('Generating New Tracks from Latent Samples') # Decode", "# Reload Saved Weights checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir,", "generation (specifically filtering) p_min = .5 print('Generating New Tracks from", "# Plot first decoded track print(\"Example Model Generated Track\") plot_track(decoded_tracks[0])", "<reponame>youngmg1995/NES-Music-Maker # -*- coding: utf-8 -*- \"\"\" Created on Wed", "can listen!!! print('Converting Seprsco to WAV Audio') wav_tracks = []", "\"latent_variables.json\") with open(latent_filename, 'w') as f: json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for", "124 input_dim = len(int2labels_map) - 1 dropout = .1 maxnorm", "used for model def.) measures = 8 measure_len = 96", "folder manually added to environment libraries from dataset_utils import load_training", "(specifically filtering) p_min = .5 print('Generating New Tracks from Latent", "Generated Tracks') latent_filename = os.path.join(wav_folder, \"latent_variables.json\") with open(latent_filename, 'w') as", "labels2int_map , int2labels_map = \\ load_training(training_foldername, train_save_filename, measures = measures,", "manually added to environment libraries from dataset_utils import load_training from", "from the orthogonal components # of our latent space #", "'./training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures, measure_len, ]))", "New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create new seprsco tracks using our", "# Decode samples using VAE decoded_tracks = model.decoder(sample_vecs) # Plot", "generate the first melodic voice for each track rather than", "# Convert seprsco tracks to WAV files so we can", "f: json.dump({ 'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for i in range(sample_vecs.shape[0]) }, f)", "to WAV files so we can listen!!! print('Converting Seprsco to", "# Grab distributions of dataset over latent space # Have", "class defined in `VAE.py` and the same parameters used in", "Saved Weights checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix)", "int2labels_map = \\ load_training(training_foldername, train_save_filename, measures = measures, measure_len =", "Save our wav tracks to appropriate files (be sure not", "print(\"Example Model Generated Track\") plot_track(decoded_tracks[0]) # Filter Track decoded_tracks =", "Wed Apr 1 17:14:19 2020 @author: Mitchell nesm_generator.py ~~~~~~~~~~~~~~~~~ This", "# Parameters for track generation (specifically filtering) p_min = .5", "Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here we use SVD to more effectively", "= 'transformed_dataset.json' dataset , labels2int_map , int2labels_map = \\ load_training(training_foldername,", "our model and the random samples # Seprsco files can", "generate_seprsco(decoded_tracks, int2labels_map) ### Convert to WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert seprsco", "our pre-trained VAE model to generate brand new NES music", "Grab distributions of dataset over latent space # Have to", "latent_SVD, get_latent_vecs,\\ plot_track, filter_tracks import nesmdb from nesmdb.vgm.vgm_to_wav import save_vgmwav", "present in an NESM track. To do so we first", "load data training_foldername = '../../nesmdb24_seprsco/train/' train_save_filename = 'transformed_dataset.json' dataset ,", "Audio Tracks') wav_folder = 'model_gen_files/' for i in range(len(wav_tracks)): wav_file", "'VAE_NESM_{}.wav'.format(i): sample_vecs[i].tolist() for i in range(sample_vecs.shape[0]) }, f) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #----------------------------------END", "of dataset (note these are also used for model def.)", "Save WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save our wav tracks to", "Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters for shape of dataset (note these", "save latent variables so we can reproduce songs we like", "train_save_filename = 'transformed_dataset.json' dataset , labels2int_map , int2labels_map = \\", "Sample Latent Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here we use SVD", "format print('Converting Model Output to Seprsco') seprsco_tracks = generate_seprsco(decoded_tracks, int2labels_map)", "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create new seprsco tracks using our model and", "nesmdb from nesmdb.vgm.vgm_to_wav import save_vgmwav import tensorflow as tf import", "in `model_training`. Then we use functions from the file `generation_utils`", "Model model = VAE(latent_dim, input_dim, measures, measure_len, dropout, maxnorm, vae_b1", "existing) # Also save latent variables so we can reproduce", "Summary of Model model.summary() ### Sample Latent Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "# perform SVD plot_eigenvalues = True sample_vecs = latent_SVD(latent_vecs, rand_vecs,", "new NES music soundtracks. NOTE - using the reduced model", "files so we can listen!!! print('Converting Seprsco to WAV Audio')", "sample_vecs = latent_SVD(latent_vecs, rand_vecs, plot_eigenvalues) ### Generate New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "rand_vecs = np.random.normal(0.0, 1.0, (num_songs, latent_dim)) # perform SVD plot_eigenvalues", "file VAE class defined in `VAE.py` and the same parameters", "1 dropout = .1 maxnorm = None vae_b1 , vae_b2", "Also save latent variables so we can reproduce songs we", "the file VAE class defined in `VAE.py` and the same", "= [] for track in seprsco_tracks: wav = nesmdb.convert.seprsco_to_wav(track) wav_tracks.append(wav)", "we only generate the first melodic voice for each track", "print('Reinitiating VAE Model') # Build Model model = VAE(latent_dim, input_dim,", "of dataset over latent space # Have to run in", "Generate New Tracks #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create new seprsco tracks using", "Create new seprsco tracks using our model and the random", "tracks save_wav = False if save_wav: print('Saving Generated WAV Audio", "in batches due to size of the dataset batch_size =", "components # of our latent space # Parameters for sampling", "### Load Mappings #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parameters for shape of dataset", "first melodic voice for each track rather than each of", "= 124 input_dim = len(int2labels_map) - 1 dropout = .1", "False if save_wav: print('Saving Generated WAV Audio Tracks') wav_folder =", "### Sample Latent Variable Distributions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Here we use", "WAV Files #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save our wav tracks to appropriate", "distributions of dataset over latent space # Have to run", "VAE decoded_tracks = model.decoder(sample_vecs) # Plot first decoded track print(\"Example", "checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, \"model_ckpt\") model.load_weights(checkpoint_prefix) model.build(tf.TensorShape([None, measures,", "NOTE - nesmdb folder manually added to environment libraries from", "tracks to appropriate files (be sure not to overwrite existing)", "Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # NOTE - nesmdb folder manually added to", "Parameters for track generation (specifically filtering) p_min = .5 print('Generating", "seprsco tracks using our model and the random samples #", "environment libraries from dataset_utils import load_training from VAE import VAE", "Generated WAV Audio Tracks') wav_folder = 'model_gen_files/' for i in", "distribution rand_vecs = np.random.normal(0.0, 1.0, (num_songs, latent_dim)) # perform SVD", "np.random.normal(0.0, 1.0, (num_songs, latent_dim)) # perform SVD plot_eigenvalues = True", "random samples # Seprsco files can later be converted to", "Tracks') wav_folder = 'model_gen_files/' for i in range(len(wav_tracks)): wav_file =", "for shape of dataset (note these are also used for", "sampling num_songs = 10 print('Generating Latent Samples to Generate {}", "latent_dim)) # perform SVD plot_eigenvalues = True sample_vecs = latent_SVD(latent_vecs,", "decoded track print(\"Example Model Generated Track\") plot_track(decoded_tracks[0]) # Filter Track", "to Generate {} New Tracks'.format(num_songs)) # Grab distributions of dataset", "filter_tracks import nesmdb from nesmdb.vgm.vgm_to_wav import save_vgmwav import tensorflow as", "entirely new and original NES music. \"\"\" # Imports #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "to environment libraries from dataset_utils import load_training from VAE import", "Model') # Build Model model = VAE(latent_dim, input_dim, measures, measure_len,", "print('Generating Latent Samples to Generate {} New Tracks'.format(num_songs)) # Grab", "Generated Track\") plot_track(decoded_tracks[0]) # Filter Track decoded_tracks = filter_tracks(decoded_tracks, p_min)", "WAV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert seprsco tracks to WAV files so", "not to overwrite existing) # Also save latent variables so", "Latent Samples') # Decode samples using VAE decoded_tracks = model.decoder(sample_vecs)" ]
[ "not in (False, 0): if isinstance(self.syslog, (list, tuple)): _addr =", "'LOGLEVEL' in os.environ: self.level = os.environ['LOGLEVEL'].upper() else: self.level = default_loglevel.upper()", "in (False, 0): if isinstance(self.syslog, (list, tuple)): _addr = tuple(self.syslog)", "fmt=None, syslog=None): self.name = name self.syslog = syslog self.fmt =", "else \"%(asctime)-15s %(name)s %(levelname)s %(message)s\" if 'LOGLEVEL' in os.environ: self.level", "= name self.syslog = syslog self.fmt = fmt if fmt", "logging.basicConfig(format=self.fmt) self.logger = logging.getLogger(self.name) self.logger.setLevel(self.level) if self.syslog is not None", "os.environ: self.level = os.environ['LOGLEVEL'].upper() else: self.level = default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger", "name self.syslog = syslog self.fmt = fmt if fmt is", "__init__(self, name, default_loglevel='INFO', fmt=None, syslog=None): self.name = name self.syslog =", "= syslog self.fmt = fmt if fmt is not None", "= \"/dev/log\" if os.path.exists(\"/dev/log\") else None if _addr is not", "if fmt is not None else \"%(asctime)-15s %(name)s %(levelname)s %(message)s\"", "0): if isinstance(self.syslog, (list, tuple)): _addr = tuple(self.syslog) elif isinstance(self.syslog,", "import logging import logging.handlers import os class Logger(object): def __init__(self,", "tuple)): _addr = tuple(self.syslog) elif isinstance(self.syslog, str): _addr = self.syslog", "if self.syslog is not None and self.syslog not in (False,", "fmt is not None else \"%(asctime)-15s %(name)s %(levelname)s %(message)s\" if", "_addr = self.syslog else: _addr = \"/dev/log\" if os.path.exists(\"/dev/log\") else", "None else \"%(asctime)-15s %(name)s %(levelname)s %(message)s\" if 'LOGLEVEL' in os.environ:", "None and self.syslog not in (False, 0): if isinstance(self.syslog, (list,", "name, default_loglevel='INFO', fmt=None, syslog=None): self.name = name self.syslog = syslog", "(False, 0): if isinstance(self.syslog, (list, tuple)): _addr = tuple(self.syslog) elif", "isinstance(self.syslog, (list, tuple)): _addr = tuple(self.syslog) elif isinstance(self.syslog, str): _addr", "= logging.getLogger(self.name) self.logger.setLevel(self.level) if self.syslog is not None and self.syslog", "%(name)s %(levelname)s %(message)s\" if 'LOGLEVEL' in os.environ: self.level = os.environ['LOGLEVEL'].upper()", "in os.environ: self.level = os.environ['LOGLEVEL'].upper() else: self.level = default_loglevel.upper() logging.basicConfig(format=self.fmt)", "and self.syslog not in (False, 0): if isinstance(self.syslog, (list, tuple)):", "os.path.exists(\"/dev/log\") else None if _addr is not None: handler =", "else: self.level = default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger = logging.getLogger(self.name) self.logger.setLevel(self.level) if", "self.logger = logging.getLogger(self.name) self.logger.setLevel(self.level) if self.syslog is not None and", "import os class Logger(object): def __init__(self, name, default_loglevel='INFO', fmt=None, syslog=None):", "fmt if fmt is not None else \"%(asctime)-15s %(name)s %(levelname)s", "self.syslog else: _addr = \"/dev/log\" if os.path.exists(\"/dev/log\") else None if", "self.fmt = fmt if fmt is not None else \"%(asctime)-15s", "= default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger = logging.getLogger(self.name) self.logger.setLevel(self.level) if self.syslog is", "is not None else \"%(asctime)-15s %(name)s %(levelname)s %(message)s\" if 'LOGLEVEL'", "not None else \"%(asctime)-15s %(name)s %(levelname)s %(message)s\" if 'LOGLEVEL' in", "_addr is not None: handler = logging.handlers.SysLogHandler(address=_addr) self.logger.addHandler(handler) def get(self):", "not None: handler = logging.handlers.SysLogHandler(address=_addr) self.logger.addHandler(handler) def get(self): return self.logger", "else None if _addr is not None: handler = logging.handlers.SysLogHandler(address=_addr)", "self.level = default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger = logging.getLogger(self.name) self.logger.setLevel(self.level) if self.syslog", "if os.path.exists(\"/dev/log\") else None if _addr is not None: handler", "str): _addr = self.syslog else: _addr = \"/dev/log\" if os.path.exists(\"/dev/log\")", "%(message)s\" if 'LOGLEVEL' in os.environ: self.level = os.environ['LOGLEVEL'].upper() else: self.level", "= fmt if fmt is not None else \"%(asctime)-15s %(name)s", "self.syslog = syslog self.fmt = fmt if fmt is not", "elif isinstance(self.syslog, str): _addr = self.syslog else: _addr = \"/dev/log\"", "logging.handlers import os class Logger(object): def __init__(self, name, default_loglevel='INFO', fmt=None,", "if _addr is not None: handler = logging.handlers.SysLogHandler(address=_addr) self.logger.addHandler(handler) def", "if isinstance(self.syslog, (list, tuple)): _addr = tuple(self.syslog) elif isinstance(self.syslog, str):", "= tuple(self.syslog) elif isinstance(self.syslog, str): _addr = self.syslog else: _addr", "is not None and self.syslog not in (False, 0): if", "os.environ['LOGLEVEL'].upper() else: self.level = default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger = logging.getLogger(self.name) self.logger.setLevel(self.level)", "default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger = logging.getLogger(self.name) self.logger.setLevel(self.level) if self.syslog is not", "_addr = \"/dev/log\" if os.path.exists(\"/dev/log\") else None if _addr is", "self.syslog is not None and self.syslog not in (False, 0):", "logging import logging.handlers import os class Logger(object): def __init__(self, name,", "default_loglevel='INFO', fmt=None, syslog=None): self.name = name self.syslog = syslog self.fmt", "not None and self.syslog not in (False, 0): if isinstance(self.syslog,", "\"/dev/log\" if os.path.exists(\"/dev/log\") else None if _addr is not None:", "self.level = os.environ['LOGLEVEL'].upper() else: self.level = default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger =", "isinstance(self.syslog, str): _addr = self.syslog else: _addr = \"/dev/log\" if", "None if _addr is not None: handler = logging.handlers.SysLogHandler(address=_addr) self.logger.addHandler(handler)", "def __init__(self, name, default_loglevel='INFO', fmt=None, syslog=None): self.name = name self.syslog", "if 'LOGLEVEL' in os.environ: self.level = os.environ['LOGLEVEL'].upper() else: self.level =", "syslog self.fmt = fmt if fmt is not None else", "self.logger.setLevel(self.level) if self.syslog is not None and self.syslog not in", "= self.syslog else: _addr = \"/dev/log\" if os.path.exists(\"/dev/log\") else None", "self.name = name self.syslog = syslog self.fmt = fmt if", "os class Logger(object): def __init__(self, name, default_loglevel='INFO', fmt=None, syslog=None): self.name", "_addr = tuple(self.syslog) elif isinstance(self.syslog, str): _addr = self.syslog else:", "= os.environ['LOGLEVEL'].upper() else: self.level = default_loglevel.upper() logging.basicConfig(format=self.fmt) self.logger = logging.getLogger(self.name)", "is not None: handler = logging.handlers.SysLogHandler(address=_addr) self.logger.addHandler(handler) def get(self): return", "import logging.handlers import os class Logger(object): def __init__(self, name, default_loglevel='INFO',", "class Logger(object): def __init__(self, name, default_loglevel='INFO', fmt=None, syslog=None): self.name =", "else: _addr = \"/dev/log\" if os.path.exists(\"/dev/log\") else None if _addr", "%(levelname)s %(message)s\" if 'LOGLEVEL' in os.environ: self.level = os.environ['LOGLEVEL'].upper() else:", "self.syslog not in (False, 0): if isinstance(self.syslog, (list, tuple)): _addr", "syslog=None): self.name = name self.syslog = syslog self.fmt = fmt", "tuple(self.syslog) elif isinstance(self.syslog, str): _addr = self.syslog else: _addr =", "\"%(asctime)-15s %(name)s %(levelname)s %(message)s\" if 'LOGLEVEL' in os.environ: self.level =", "(list, tuple)): _addr = tuple(self.syslog) elif isinstance(self.syslog, str): _addr =", "Logger(object): def __init__(self, name, default_loglevel='INFO', fmt=None, syslog=None): self.name = name", "logging.getLogger(self.name) self.logger.setLevel(self.level) if self.syslog is not None and self.syslog not" ]
[ "print(\"Hello World\") hello_list = [\"Hello World\"] print(hello_list[0]) for i in", "#Author <NAME> print(\"Hello World\") hello_list = [\"Hello World\"] print(hello_list[0]) for", "World\") hello_list = [\"Hello World\"] print(hello_list[0]) for i in hello_list:", "hello_list = [\"Hello World\"] print(hello_list[0]) for i in hello_list: print(i)", "<NAME> print(\"Hello World\") hello_list = [\"Hello World\"] print(hello_list[0]) for i" ]
[ "= _fake_ext(qtype, kb_ident) self.text = text def __str__(self): return f\"<[MOCKED", "import namedtuple from unittest.mock import MagicMock _fake_ext = namedtuple('_', ['qtype',", "from collections import namedtuple from unittest.mock import MagicMock _fake_ext =", "['qtype', 'kb_ident']) class FakeDoc: def __init__(self, text, qtype, kb_ident): self._", "import MagicMock _fake_ext = namedtuple('_', ['qtype', 'kb_ident']) class FakeDoc: def", "kb_ident): self._ = _fake_ext(qtype, kb_ident) self.text = text def __str__(self):", "collections import namedtuple from unittest.mock import MagicMock _fake_ext = namedtuple('_',", "class FakeDoc: def __init__(self, text, qtype, kb_ident): self._ = _fake_ext(qtype,", "<filename>question_answering/stubs.py from collections import namedtuple from unittest.mock import MagicMock _fake_ext", "MagicMock _fake_ext = namedtuple('_', ['qtype', 'kb_ident']) class FakeDoc: def __init__(self,", "unittest.mock import MagicMock _fake_ext = namedtuple('_', ['qtype', 'kb_ident']) class FakeDoc:", "FakeDoc: def __init__(self, text, qtype, kb_ident): self._ = _fake_ext(qtype, kb_ident)", "_fake_ext = namedtuple('_', ['qtype', 'kb_ident']) class FakeDoc: def __init__(self, text,", "_fake_ext(qtype, kb_ident) self.text = text def __str__(self): return f\"<[MOCKED NLP]{self.text}>\"", "from unittest.mock import MagicMock _fake_ext = namedtuple('_', ['qtype', 'kb_ident']) class", "namedtuple('_', ['qtype', 'kb_ident']) class FakeDoc: def __init__(self, text, qtype, kb_ident):", "__init__(self, text, qtype, kb_ident): self._ = _fake_ext(qtype, kb_ident) self.text =", "namedtuple from unittest.mock import MagicMock _fake_ext = namedtuple('_', ['qtype', 'kb_ident'])", "= namedtuple('_', ['qtype', 'kb_ident']) class FakeDoc: def __init__(self, text, qtype,", "def __init__(self, text, qtype, kb_ident): self._ = _fake_ext(qtype, kb_ident) self.text", "text, qtype, kb_ident): self._ = _fake_ext(qtype, kb_ident) self.text = text", "'kb_ident']) class FakeDoc: def __init__(self, text, qtype, kb_ident): self._ =", "qtype, kb_ident): self._ = _fake_ext(qtype, kb_ident) self.text = text def", "self._ = _fake_ext(qtype, kb_ident) self.text = text def __str__(self): return" ]
[ "asset_held: float, current_price: Callable[[str], float]) -> Tuple[float, float, float, float]:", "commissionPercent: float, maxSlippagePercent: float, base_precision: int, asset_precision: int, min_cost_limit: float,", "float, current_price: Callable[[str], float]) -> Tuple[float, float, float, float]: raise", "@abstractmethod def trade(self, action: int, n_discrete_actions: int, balance: float, asset_held:", "@abstractmethod def __init__(self, commissionPercent: float, maxSlippagePercent: float, base_precision: int, asset_precision:", "maxSlippagePercent: float, base_precision: int, asset_precision: int, min_cost_limit: float, min_amount_limit: float):", "BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod def __init__(self, commissionPercent: float, maxSlippagePercent: float, base_precision:", "int, min_cost_limit: float, min_amount_limit: float): pass @abstractmethod def trade(self, action:", "__init__(self, commissionPercent: float, maxSlippagePercent: float, base_precision: int, asset_precision: int, min_cost_limit:", "min_amount_limit: float): pass @abstractmethod def trade(self, action: int, n_discrete_actions: int,", "float, base_precision: int, asset_precision: int, min_cost_limit: float, min_amount_limit: float): pass", "metaclass=ABCMeta): @abstractmethod def __init__(self, commissionPercent: float, maxSlippagePercent: float, base_precision: int,", "Tuple, Callable class BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod def __init__(self, commissionPercent: float,", "class BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod def __init__(self, commissionPercent: float, maxSlippagePercent: float,", "base_precision: int, asset_precision: int, min_cost_limit: float, min_amount_limit: float): pass @abstractmethod", "balance: float, asset_held: float, current_price: Callable[[str], float]) -> Tuple[float, float,", "pass @abstractmethod def trade(self, action: int, n_discrete_actions: int, balance: float,", "int, n_discrete_actions: int, balance: float, asset_held: float, current_price: Callable[[str], float])", "from typing import Tuple, Callable class BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod def", "int, balance: float, asset_held: float, current_price: Callable[[str], float]) -> Tuple[float,", "asset_precision: int, min_cost_limit: float, min_amount_limit: float): pass @abstractmethod def trade(self,", "def __init__(self, commissionPercent: float, maxSlippagePercent: float, base_precision: int, asset_precision: int,", "float, min_amount_limit: float): pass @abstractmethod def trade(self, action: int, n_discrete_actions:", "float, maxSlippagePercent: float, base_precision: int, asset_precision: int, min_cost_limit: float, min_amount_limit:", "abstractmethod from typing import Tuple, Callable class BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod", "trade(self, action: int, n_discrete_actions: int, balance: float, asset_held: float, current_price:", "Callable class BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod def __init__(self, commissionPercent: float, maxSlippagePercent:", "min_cost_limit: float, min_amount_limit: float): pass @abstractmethod def trade(self, action: int,", "current_price: Callable[[str], float]) -> Tuple[float, float, float, float]: raise NotImplementedError()", "import ABCMeta, abstractmethod from typing import Tuple, Callable class BaseTradeStrategy(object,", "float): pass @abstractmethod def trade(self, action: int, n_discrete_actions: int, balance:", "from abc import ABCMeta, abstractmethod from typing import Tuple, Callable", "n_discrete_actions: int, balance: float, asset_held: float, current_price: Callable[[str], float]) ->", "action: int, n_discrete_actions: int, balance: float, asset_held: float, current_price: Callable[[str],", "def trade(self, action: int, n_discrete_actions: int, balance: float, asset_held: float,", "import Tuple, Callable class BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod def __init__(self, commissionPercent:", "abc import ABCMeta, abstractmethod from typing import Tuple, Callable class", "int, asset_precision: int, min_cost_limit: float, min_amount_limit: float): pass @abstractmethod def", "float, asset_held: float, current_price: Callable[[str], float]) -> Tuple[float, float, float,", "ABCMeta, abstractmethod from typing import Tuple, Callable class BaseTradeStrategy(object, metaclass=ABCMeta):", "typing import Tuple, Callable class BaseTradeStrategy(object, metaclass=ABCMeta): @abstractmethod def __init__(self," ]
[ "category = '소설' # Class 멤버 b1 = Book(); print(b1.category)", "b1; print(b2.category) print(Book.category) Book.category = '수필' print(b2.category); print(b1.category) ; print(Book.category)", "# Book04_1.py class Book: category = '소설' # Class 멤버", "= '소설' # Class 멤버 b1 = Book(); print(b1.category) b2", "print(b2.category) print(Book.category) Book.category = '수필' print(b2.category); print(b1.category) ; print(Book.category) b2.category", "b2 = b1; print(b2.category) print(Book.category) Book.category = '수필' print(b2.category); print(b1.category)", "= b1; print(b2.category) print(Book.category) Book.category = '수필' print(b2.category); print(b1.category) ;", "# Class 멤버 b1 = Book(); print(b1.category) b2 = b1;", "<reponame>jsjang93/joony<gh_stars>0 # Book04_1.py class Book: category = '소설' # Class", "Book(); print(b1.category) b2 = b1; print(b2.category) print(Book.category) Book.category = '수필'", "print(b1.category) ; print(Book.category) b2.category = 'IT' print(b2.category); print(b1.category) ; print(Book.category)", "print(Book.category) Book.category = '수필' print(b2.category); print(b1.category) ; print(Book.category) b2.category =", "Book04_1.py class Book: category = '소설' # Class 멤버 b1", "Book: category = '소설' # Class 멤버 b1 = Book();", "class Book: category = '소설' # Class 멤버 b1 =", "= Book(); print(b1.category) b2 = b1; print(b2.category) print(Book.category) Book.category =", "'소설' # Class 멤버 b1 = Book(); print(b1.category) b2 =", "= '수필' print(b2.category); print(b1.category) ; print(Book.category) b2.category = 'IT' print(b2.category);", "Book.category = '수필' print(b2.category); print(b1.category) ; print(Book.category) b2.category = 'IT'", "멤버 b1 = Book(); print(b1.category) b2 = b1; print(b2.category) print(Book.category)", "b1 = Book(); print(b1.category) b2 = b1; print(b2.category) print(Book.category) Book.category", "print(b2.category); print(b1.category) ; print(Book.category) b2.category = 'IT' print(b2.category); print(b1.category) ;", "'수필' print(b2.category); print(b1.category) ; print(Book.category) b2.category = 'IT' print(b2.category); print(b1.category)", "Class 멤버 b1 = Book(); print(b1.category) b2 = b1; print(b2.category)", "print(b1.category) b2 = b1; print(b2.category) print(Book.category) Book.category = '수필' print(b2.category);" ]
[ "ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "SUCH DAMAGE. # # Lead Maintainer: <NAME> Inc. <<EMAIL>> from", "Security, Inc. # # All rights reserved. # # Redistribution", "# # Redistribution and use in source and binary forms,", "following disclaimer. # # (2) Redistributions in binary form must", "CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "def alg_id(self): \"\"\"Provide algorithm identificator.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result", "return instance def restore_alg_info(self, alg_info): \"\"\"Restore algorithm configuration from the", "WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", "and the following disclaimer in # the documentation and/or other", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING # IN", "in binary form must reproduce the above copyright # notice,", "without specific prior written permission. # # THIS SOFTWARE IS", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR", "= VscfKdf1() self._c_impl = None self._ctx = None self.ctx =", "GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS;", "# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS''", "inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = c_ctx return inst @classmethod def", "from # this software without specific prior written permission. #", "IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT", "def use_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx", "and the following disclaimer. # # (2) Redistributions in binary", "A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL", "algorithm configuration from the given object.\"\"\" status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl)", "modification, are permitted provided that the following conditions are #", "C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def alg_id(self):", "= None self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self, instance): \"\"\"Destroy underlying", "endorse or promote products derived from # this software without", "PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR", "take_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx =", "# # Lead Maintainer: <NAME> Inc. <<EMAIL>> from ctypes import", ".alg import Alg from .kdf import Kdf class Kdf1(Alg, Kdf):", "inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst @property def c_impl(self): return self._c_impl @property def", "return inst @property def c_impl(self): return self._c_impl @property def ctx(self):", "source and binary forms, with or without # modification, are", "documentation and/or other materials provided with the # distribution. #", "@classmethod def use_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1()", "conditions and the following disclaimer in # the documentation and/or", "PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE", "None self._ctx = None self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self, instance):", "= c_ctx return inst @classmethod def use_c_ctx(cls, c_ctx): inst =", "@ctx.setter def ctx(self, value): self._ctx = self._lib_vscf_kdf1.vscf_kdf1_shallow_copy(value) self._c_impl = self._lib_vscf_kdf1.vscf_kdf1_impl(self.ctx)", "THE AUTHOR BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL,", "Kdf): \"\"\"Virgil Security implementation of the KDF1 (ISO-18033-2) algorithm.\"\"\" def", "# (1) Redistributions of source code must retain the above", "def __init__(self): \"\"\"Create underlying C context.\"\"\" self._lib_vscf_kdf1 = VscfKdf1() self._c_impl", "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT", "context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def alg_id(self): \"\"\"Provide", "SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED.", "OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE", "OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "produce_alg_info(self): \"\"\"Produce object with algorithm information and configuration parameters.\"\"\" result", "context.\"\"\" self._lib_vscf_kdf1 = VscfKdf1() self._c_impl = None self._ctx = None", "the KDF1 (ISO-18033-2) algorithm.\"\"\" def __init__(self): \"\"\"Create underlying C context.\"\"\"", "INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "and binary forms, with or without # modification, are permitted", "Inc. # # All rights reserved. # # Redistribution and", "names of its # contributors may be used to endorse", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO,", "are # met: # # (1) Redistributions of source code", "form must reproduce the above copyright # notice, this list", "the following conditions are # met: # # (1) Redistributions", "d_data.data, key_len, key.c_buffer) return key.get_bytes() @classmethod def take_c_ctx(cls, c_ctx): inst", "= self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result def produce_alg_info(self): \"\"\"Produce object with algorithm", "# met: # # (1) Redistributions of source code must", "AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT", "def __delete__(self, instance): \"\"\"Destroy underlying C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self,", "= self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def derive(self, data, key_len): \"\"\"Derive key", "= Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len, key.c_buffer) return key.get_bytes() @classmethod def", "c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx)", "this software without specific prior written permission. # # THIS", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "import Kdf class Kdf1(Alg, Kdf): \"\"\"Virgil Security implementation of the", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE", "underlying C context.\"\"\" self._lib_vscf_kdf1 = VscfKdf1() self._c_impl = None self._ctx", "VscfStatus.handle_status(status) def derive(self, data, key_len): \"\"\"Derive key of the requested", "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES;", "from .alg import Alg from .kdf import Kdf class Kdf1(Alg,", "notice, this list of conditions and the following disclaimer. #", "BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY", "WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF", "from the given data.\"\"\" d_data = Data(data) key = Buffer(key_len)", "materials provided with the # distribution. # # (3) Neither", "reproduce the above copyright # notice, this list of conditions", "software without specific prior written permission. # # THIS SOFTWARE", "inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst @property def c_impl(self): return self._c_impl", "Alg from .kdf import Kdf class Kdf1(Alg, Kdf): \"\"\"Virgil Security", "self._ctx @ctx.setter def ctx(self, value): self._ctx = self._lib_vscf_kdf1.vscf_kdf1_shallow_copy(value) self._c_impl =", "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED", "must retain the above copyright # notice, this list of", "cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = c_ctx return inst @classmethod", "disclaimer in # the documentation and/or other materials provided with", "OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT", "parameters.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance", "BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF", "# Lead Maintainer: <NAME> Inc. <<EMAIL>> from ctypes import *", "def c_impl(self): return self._c_impl @property def ctx(self): return self._ctx @ctx.setter", "VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self, alg_info): \"\"\"Restore algorithm configuration", "ARE # DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE", "object.\"\"\" status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def derive(self, data, key_len):", "C context.\"\"\" self._lib_vscf_kdf1 = VscfKdf1() self._c_impl = None self._ctx =", "met: # # (1) Redistributions of source code must retain", "of source code must retain the above copyright # notice,", "distribution. # # (3) Neither the name of the copyright", "VscfStatus from virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge import Buffer from", "ARISING # IN ANY WAY OUT OF THE USE OF", "\"\"\"Destroy underlying C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl)", "name of the copyright holder nor the names of its", "Buffer from .alg import Alg from .kdf import Kdf class", "# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE", "# this software without specific prior written permission. # #", "hash.c_impl) def alg_id(self): \"\"\"Provide algorithm identificator.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return", "instance def restore_alg_info(self, alg_info): \"\"\"Restore algorithm configuration from the given", "from ._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge", "key_len): \"\"\"Derive key of the requested length from the given", "SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, # INDIRECT,", "def set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def alg_id(self): \"\"\"Provide algorithm identificator.\"\"\"", "following disclaimer in # the documentation and/or other materials provided", "Virgil Security, Inc. # # All rights reserved. # #", "Copyright (C) 2015-2021 Virgil Security, Inc. # # All rights", "AUTHOR BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL,", "or without # modification, are permitted provided that the following", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN", "Redistribution and use in source and binary forms, with or", "inst @classmethod def use_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 =", "def restore_alg_info(self, alg_info): \"\"\"Restore algorithm configuration from the given object.\"\"\"", "identificator.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result def produce_alg_info(self): \"\"\"Produce object", "# POSSIBILITY OF SUCH DAMAGE. # # Lead Maintainer: <NAME>", "use_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx =", "provided that the following conditions are # met: # #", "with algorithm information and configuration parameters.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance", "EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "retain the above copyright # notice, this list of conditions", "import Data from virgil_crypto_lib.common._c_bridge import Buffer from .alg import Alg", "DAMAGE. # # Lead Maintainer: <NAME> Inc. <<EMAIL>> from ctypes", "return self._c_impl @property def ctx(self): return self._ctx @ctx.setter def ctx(self,", "VscfKdf1() self._c_impl = None self._ctx = None self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new()", "rights reserved. # # Redistribution and use in source and", "EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.", "binary form must reproduce the above copyright # notice, this", "import VscfStatus from virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge import Buffer", "derive(self, data, key_len): \"\"\"Derive key of the requested length from", "nor the names of its # contributors may be used", "import VscfImplTag from ._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge import Data", "from ._c_bridge import VscfImplTag from ._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge", "with the # distribution. # # (3) Neither the name", "configuration parameters.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return", "VscfKdf1 from ._c_bridge import VscfImplTag from ._c_bridge import VscfStatus from", "<<EMAIL>> from ctypes import * from ._c_bridge import VscfKdf1 from", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING # IN ANY", "length from the given data.\"\"\" d_data = Data(data) key =", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #", "algorithm information and configuration parameters.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance =", "above copyright # notice, this list of conditions and the", "inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return", "THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "of conditions and the following disclaimer. # # (2) Redistributions", "key.get_bytes() @classmethod def take_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 =", "in source and binary forms, with or without # modification,", "OTHERWISE) ARISING # IN ANY WAY OUT OF THE USE", "key of the requested length from the given data.\"\"\" d_data", "alg_id(self): \"\"\"Provide algorithm identificator.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result def", "def ctx(self): return self._ctx @ctx.setter def ctx(self, value): self._ctx =", "self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self, instance): \"\"\"Destroy underlying C context.\"\"\"", "hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def alg_id(self): \"\"\"Provide algorithm identificator.\"\"\" result =", "must reproduce the above copyright # notice, this list of", "restore_alg_info(self, alg_info): \"\"\"Restore algorithm configuration from the given object.\"\"\" status", "self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def derive(self, data, key_len): \"\"\"Derive key of", "products derived from # this software without specific prior written", "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT", "NEGLIGENCE OR OTHERWISE) ARISING # IN ANY WAY OUT OF", "= cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = c_ctx return inst", "__delete__(self, instance): \"\"\"Destroy underlying C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self, hash):", "use in source and binary forms, with or without #", "VscfImplTag from ._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge import Data from", "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,", "\"\"\"Restore algorithm configuration from the given object.\"\"\" status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx,", "<NAME> Inc. <<EMAIL>> from ctypes import * from ._c_bridge import", "= cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst", "IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE AUTHOR", "set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def alg_id(self): \"\"\"Provide algorithm identificator.\"\"\" result", "and configuration parameters.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1])))", "USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #", "self._c_impl = None self._ctx = None self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new() def", "key = Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len, key.c_buffer) return key.get_bytes() @classmethod", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT", "= VscfKdf1() inst.ctx = c_ctx return inst @classmethod def use_c_ctx(cls,", "* from ._c_bridge import VscfKdf1 from ._c_bridge import VscfImplTag from", "permitted provided that the following conditions are # met: #", "instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self, alg_info): \"\"\"Restore", "# contributors may be used to endorse or promote products", "THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF", "POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self, alg_info): \"\"\"Restore algorithm configuration from", "import Alg from .kdf import Kdf class Kdf1(Alg, Kdf): \"\"\"Virgil", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) #", "LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR", "OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED", "USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED", "result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result def produce_alg_info(self): \"\"\"Produce object with", "OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "object with algorithm information and configuration parameters.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx)", "VscfKdf1() inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst @property def c_impl(self): return", "with or without # modification, are permitted provided that the", "key.c_buffer) return key.get_bytes() @classmethod def take_c_ctx(cls, c_ctx): inst = cls.__new__(cls)", "PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY", "data.\"\"\" d_data = Data(data) key = Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len,", "LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING", "AUTHOR ''AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES,", "self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result def produce_alg_info(self): \"\"\"Produce object with algorithm information", "# # All rights reserved. # # Redistribution and use", "cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst @property", "and/or other materials provided with the # distribution. # #", "DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR", "Data(data) key = Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len, key.c_buffer) return key.get_bytes()", "ctx(self): return self._ctx @ctx.setter def ctx(self, value): self._ctx = self._lib_vscf_kdf1.vscf_kdf1_shallow_copy(value)", "self._lib_vscf_kdf1 = VscfKdf1() self._c_impl = None self._ctx = None self.ctx", "NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,", "key_len, key.c_buffer) return key.get_bytes() @classmethod def take_c_ctx(cls, c_ctx): inst =", "EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, #", "(C) 2015-2021 Virgil Security, Inc. # # All rights reserved.", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "the requested length from the given data.\"\"\" d_data = Data(data)", "FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL", "@property def c_impl(self): return self._c_impl @property def ctx(self): return self._ctx", "OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON", "(2) Redistributions in binary form must reproduce the above copyright", "FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT", "and use in source and binary forms, with or without", "data, key_len): \"\"\"Derive key of the requested length from the", "# # (1) Redistributions of source code must retain the", "from virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge import Buffer from .alg", "the copyright holder nor the names of its # contributors", "from the given object.\"\"\" status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def", "copyright holder nor the names of its # contributors may", "configuration from the given object.\"\"\" status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status)", "IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #", "THE # POSSIBILITY OF SUCH DAMAGE. # # Lead Maintainer:", "information and configuration parameters.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result,", "PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE,", "d_data = Data(data) key = Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len, key.c_buffer)", "# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF", "THE AUTHOR ''AS IS'' AND ANY EXPRESS OR # IMPLIED", "# # (2) Redistributions in binary form must reproduce the", "be used to endorse or promote products derived from #", "forms, with or without # modification, are permitted provided that", "binary forms, with or without # modification, are permitted provided", "(1) Redistributions of source code must retain the above copyright", "following conditions are # met: # # (1) Redistributions of", "copyright # notice, this list of conditions and the following", "\"\"\"Derive key of the requested length from the given data.\"\"\"", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "contributors may be used to endorse or promote products derived", "VscfKdf1() inst.ctx = c_ctx return inst @classmethod def use_c_ctx(cls, c_ctx):", "= inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst @property def c_impl(self): return self._c_impl @property", "# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER", "ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # #", "\"\"\"Provide algorithm identificator.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result def produce_alg_info(self):", "TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF", "# # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS", "self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len, key.c_buffer) return key.get_bytes() @classmethod def take_c_ctx(cls, c_ctx):", "the above copyright # notice, this list of conditions and", "the name of the copyright holder nor the names of", "Maintainer: <NAME> Inc. <<EMAIL>> from ctypes import * from ._c_bridge", "# All rights reserved. # # Redistribution and use in", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN", "# Redistribution and use in source and binary forms, with", "# # (3) Neither the name of the copyright holder", "AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN", "import VscfKdf1 from ._c_bridge import VscfImplTag from ._c_bridge import VscfStatus", "THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR", "code must retain the above copyright # notice, this list", "AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, #", "# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED", "provided with the # distribution. # # (3) Neither the", "given object.\"\"\" status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def derive(self, data,", "import Buffer from .alg import Alg from .kdf import Kdf", "import * from ._c_bridge import VscfKdf1 from ._c_bridge import VscfImplTag", ".kdf import Kdf class Kdf1(Alg, Kdf): \"\"\"Virgil Security implementation of", "# modification, are permitted provided that the following conditions are", "from ._c_bridge import VscfKdf1 from ._c_bridge import VscfImplTag from ._c_bridge", "self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self, instance): \"\"\"Destroy underlying C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def", "conditions are # met: # # (1) Redistributions of source", "self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self, alg_info):", "LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS", "FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO", "INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF", "OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY", "of conditions and the following disclaimer in # the documentation", "instance): \"\"\"Destroy underlying C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx,", "may be used to endorse or promote products derived from", "# notice, this list of conditions and the following disclaimer.", "alg_info): \"\"\"Restore algorithm configuration from the given object.\"\"\" status =", "= None self._ctx = None self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self,", "given data.\"\"\" d_data = Data(data) key = Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data,", "status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def derive(self, data, key_len): \"\"\"Derive", "inst.ctx = c_ctx return inst @classmethod def use_c_ctx(cls, c_ctx): inst", "._c_bridge import VscfKdf1 from ._c_bridge import VscfImplTag from ._c_bridge import", "ctypes import * from ._c_bridge import VscfKdf1 from ._c_bridge import", "or promote products derived from # this software without specific", "OR OTHERWISE) ARISING # IN ANY WAY OUT OF THE", "NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND", "self._ctx = None self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self, instance): \"\"\"Destroy", "Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len, key.c_buffer) return key.get_bytes() @classmethod def take_c_ctx(cls,", "OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA,", "# the documentation and/or other materials provided with the #", "of the KDF1 (ISO-18033-2) algorithm.\"\"\" def __init__(self): \"\"\"Create underlying C", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND", "SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH", "disclaimer. # # (2) Redistributions in binary form must reproduce", "._c_bridge import VscfImplTag from ._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge import", "the names of its # contributors may be used to", "other materials provided with the # distribution. # # (3)", "DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES #", "Lead Maintainer: <NAME> Inc. <<EMAIL>> from ctypes import * from", "promote products derived from # this software without specific prior", "virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge import Buffer from .alg import", "\"\"\"Produce object with algorithm information and configuration parameters.\"\"\" result =", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING #", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES", "# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE", "Security implementation of the KDF1 (ISO-18033-2) algorithm.\"\"\" def __init__(self): \"\"\"Create", "def derive(self, data, key_len): \"\"\"Derive key of the requested length", "def take_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx", "return self._ctx @ctx.setter def ctx(self, value): self._ctx = self._lib_vscf_kdf1.vscf_kdf1_shallow_copy(value) self._c_impl", "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS", "permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR", "underlying C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def", "inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst @property def", "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND", "this list of conditions and the following disclaimer. # #", "notice, this list of conditions and the following disclaimer in", "from ctypes import * from ._c_bridge import VscfKdf1 from ._c_bridge", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "the given data.\"\"\" d_data = Data(data) key = Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx,", "OF THE # POSSIBILITY OF SUCH DAMAGE. # # Lead", "All rights reserved. # # Redistribution and use in source", "without # modification, are permitted provided that the following conditions", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY", "\"\"\"Create underlying C context.\"\"\" self._lib_vscf_kdf1 = VscfKdf1() self._c_impl = None", "# notice, this list of conditions and the following disclaimer", "# distribution. # # (3) Neither the name of the", "used to endorse or promote products derived from # this", "virgil_crypto_lib.common._c_bridge import Buffer from .alg import Alg from .kdf import", "__init__(self): \"\"\"Create underlying C context.\"\"\" self._lib_vscf_kdf1 = VscfKdf1() self._c_impl =", "return key.get_bytes() @classmethod def take_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1", "OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER", "= VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self, alg_info): \"\"\"Restore algorithm", "of the copyright holder nor the names of its #", "Inc. <<EMAIL>> from ctypes import * from ._c_bridge import VscfKdf1", "the given object.\"\"\" status = self._lib_vscf_kdf1.vscf_kdf1_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def derive(self,", "= VscfKdf1() inst.ctx = inst._lib_vscf_kdf1.vscf_kdf1_shallow_copy(c_ctx) return inst @property def c_impl(self):", "self._c_impl @property def ctx(self): return self._ctx @ctx.setter def ctx(self, value):", "self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def alg_id(self): \"\"\"Provide algorithm identificator.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx)", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING # IN ANY WAY", "def produce_alg_info(self): \"\"\"Produce object with algorithm information and configuration parameters.\"\"\"", "return inst @classmethod def use_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1", "@classmethod def take_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1()", "reserved. # # Redistribution and use in source and binary", "\"\"\"Virgil Security implementation of the KDF1 (ISO-18033-2) algorithm.\"\"\" def __init__(self):", "ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "algorithm.\"\"\" def __init__(self): \"\"\"Create underlying C context.\"\"\" self._lib_vscf_kdf1 = VscfKdf1()", "IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS", "self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx) def set_hash(self, hash): self._lib_vscf_kdf1.vscf_kdf1_use_hash(self.ctx, hash.c_impl) def alg_id(self): \"\"\"Provide algorithm", "# (2) Redistributions in binary form must reproduce the above", "result = self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def", "from .kdf import Kdf class Kdf1(Alg, Kdf): \"\"\"Virgil Security implementation", "ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY,", "# (3) Neither the name of the copyright holder nor", "Redistributions of source code must retain the above copyright #", "# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING", "Data from virgil_crypto_lib.common._c_bridge import Buffer from .alg import Alg from", "the following disclaimer. # # (2) Redistributions in binary form", "class Kdf1(Alg, Kdf): \"\"\"Virgil Security implementation of the KDF1 (ISO-18033-2)", "TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "''AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING,", "the # distribution. # # (3) Neither the name of", "list of conditions and the following disclaimer. # # (2)", "BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "alg_info.c_impl) VscfStatus.handle_status(status) def derive(self, data, key_len): \"\"\"Derive key of the", "from virgil_crypto_lib.common._c_bridge import Buffer from .alg import Alg from .kdf", "KDF1 (ISO-18033-2) algorithm.\"\"\" def __init__(self): \"\"\"Create underlying C context.\"\"\" self._lib_vscf_kdf1", "requested length from the given data.\"\"\" d_data = Data(data) key", "= self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self, instance): \"\"\"Destroy underlying C context.\"\"\" self._lib_vscf_kdf1.vscf_kdf1_delete(self.ctx)", "# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS", "= self._lib_vscf_kdf1.vscf_kdf1_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self,", "the following disclaimer in # the documentation and/or other materials", "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING # IN ANY WAY OUT", "holder nor the names of its # contributors may be", "2015-2021 Virgil Security, Inc. # # All rights reserved. #", "c_ctx): inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = c_ctx", "(3) Neither the name of the copyright holder nor the", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #", "@property def ctx(self): return self._ctx @ctx.setter def ctx(self, value): self._ctx", "are permitted provided that the following conditions are # met:", "THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "None self.ctx = self._lib_vscf_kdf1.vscf_kdf1_new() def __delete__(self, instance): \"\"\"Destroy underlying C", "of the requested length from the given data.\"\"\" d_data =", "to endorse or promote products derived from # this software", "the documentation and/or other materials provided with the # distribution.", "Redistributions in binary form must reproduce the above copyright #", "OF SUCH DAMAGE. # # Lead Maintainer: <NAME> Inc. <<EMAIL>>", "._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge import", "implementation of the KDF1 (ISO-18033-2) algorithm.\"\"\" def __init__(self): \"\"\"Create underlying", "result def produce_alg_info(self): \"\"\"Produce object with algorithm information and configuration", "its # contributors may be used to endorse or promote", "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY", "inst @property def c_impl(self): return self._c_impl @property def ctx(self): return", "source code must retain the above copyright # notice, this", "conditions and the following disclaimer. # # (2) Redistributions in", "of its # contributors may be used to endorse or", "BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR #", "SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY", "# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING,", "that the following conditions are # met: # # (1)", "this list of conditions and the following disclaimer in #", "# Copyright (C) 2015-2021 Virgil Security, Inc. # # All", "# IN ANY WAY OUT OF THE USE OF THIS", "inst = cls.__new__(cls) inst._lib_vscf_kdf1 = VscfKdf1() inst.ctx = c_ctx return", "list of conditions and the following disclaimer in # the", "Kdf class Kdf1(Alg, Kdf): \"\"\"Virgil Security implementation of the KDF1", "algorithm identificator.\"\"\" result = self._lib_vscf_kdf1.vscf_kdf1_alg_id(self.ctx) return result def produce_alg_info(self): \"\"\"Produce", "derived from # this software without specific prior written permission.", "(ISO-18033-2) algorithm.\"\"\" def __init__(self): \"\"\"Create underlying C context.\"\"\" self._lib_vscf_kdf1 =", "<filename>wrappers/python/virgil_crypto_lib/foundation/kdf1.py # Copyright (C) 2015-2021 Virgil Security, Inc. # #", "Kdf1(Alg, Kdf): \"\"\"Virgil Security implementation of the KDF1 (ISO-18033-2) algorithm.\"\"\"", "return result def produce_alg_info(self): \"\"\"Produce object with algorithm information and", "DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE", "BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #", "in # the documentation and/or other materials provided with the", "c_ctx return inst @classmethod def use_c_ctx(cls, c_ctx): inst = cls.__new__(cls)", "c_impl(self): return self._c_impl @property def ctx(self): return self._ctx @ctx.setter def", "POSSIBILITY OF SUCH DAMAGE. # # Lead Maintainer: <NAME> Inc.", "Neither the name of the copyright holder nor the names", "= Data(data) key = Buffer(key_len) self._lib_vscf_kdf1.vscf_kdf1_derive(self.ctx, d_data.data, key_len, key.c_buffer) return" ]
[ "= models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof') def test_cat_says(self): \"\"\"test cat says meow", "models class AnimalTestCase(TestCase): \"\"\"Test animals' sound \"\"\" def test_dog_says(self): \"\"\"test", "from django.test import TestCase from zoo import models class AnimalTestCase(TestCase):", "def test_dog_says(self): \"\"\"test dog says woof or not \"\"\" dog", "test_cat_says(self): \"\"\"test cat says meow of not \"\"\" cat =", "utf-8 from django.test import TestCase from zoo import models class", "says meow of not \"\"\" cat = models.Cat(name='Garfield') self.assertEqual(cat.says(), 'meow')", "TestCase from zoo import models class AnimalTestCase(TestCase): \"\"\"Test animals' sound", "import models class AnimalTestCase(TestCase): \"\"\"Test animals' sound \"\"\" def test_dog_says(self):", "#!/usr/bin/env python # encoding: utf-8 from django.test import TestCase from", "class AnimalTestCase(TestCase): \"\"\"Test animals' sound \"\"\" def test_dog_says(self): \"\"\"test dog", "python # encoding: utf-8 from django.test import TestCase from zoo", "\"\"\"test cat says meow of not \"\"\" cat = models.Cat(name='Garfield')", "encoding: utf-8 from django.test import TestCase from zoo import models", "\"\"\"test dog says woof or not \"\"\" dog = models.Dog(name='Snoopy')", "dog = models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof') def test_cat_says(self): \"\"\"test cat says", "from zoo import models class AnimalTestCase(TestCase): \"\"\"Test animals' sound \"\"\"", "self.assertEqual(dog.says(), 'woof') def test_cat_says(self): \"\"\"test cat says meow of not", "AnimalTestCase(TestCase): \"\"\"Test animals' sound \"\"\" def test_dog_says(self): \"\"\"test dog says", "def test_cat_says(self): \"\"\"test cat says meow of not \"\"\" cat", "\"\"\"Test animals' sound \"\"\" def test_dog_says(self): \"\"\"test dog says woof", "sound \"\"\" def test_dog_says(self): \"\"\"test dog says woof or not", "test_dog_says(self): \"\"\"test dog says woof or not \"\"\" dog =", "'woof') def test_cat_says(self): \"\"\"test cat says meow of not \"\"\"", "says woof or not \"\"\" dog = models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof')", "models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof') def test_cat_says(self): \"\"\"test cat says meow of", "\"\"\" def test_dog_says(self): \"\"\"test dog says woof or not \"\"\"", "cat says meow of not \"\"\" cat = models.Cat(name='Garfield') self.assertEqual(cat.says(),", "# encoding: utf-8 from django.test import TestCase from zoo import", "django.test import TestCase from zoo import models class AnimalTestCase(TestCase): \"\"\"Test", "woof or not \"\"\" dog = models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof') def", "or not \"\"\" dog = models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof') def test_cat_says(self):", "\"\"\" dog = models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof') def test_cat_says(self): \"\"\"test cat", "zoo import models class AnimalTestCase(TestCase): \"\"\"Test animals' sound \"\"\" def", "animals' sound \"\"\" def test_dog_says(self): \"\"\"test dog says woof or", "import TestCase from zoo import models class AnimalTestCase(TestCase): \"\"\"Test animals'", "dog says woof or not \"\"\" dog = models.Dog(name='Snoopy') self.assertEqual(dog.says(),", "not \"\"\" dog = models.Dog(name='Snoopy') self.assertEqual(dog.says(), 'woof') def test_cat_says(self): \"\"\"test" ]
[ "seu nome completo: ') nome = input().strip().upper() print('Seu nome tem", "print('Digite seu nome completo: ') nome = input().strip().upper() print('Seu nome", "nome = input().strip().upper() print('Seu nome tem \"Silva\"?') print('SILVA' in nome)", "') nome = input().strip().upper() print('Seu nome tem \"Silva\"?') print('SILVA' in", "nome completo: ') nome = input().strip().upper() print('Seu nome tem \"Silva\"?')", "completo: ') nome = input().strip().upper() print('Seu nome tem \"Silva\"?') print('SILVA'" ]
[ "vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True, ) train_data = dict( samples_per_gpu=16, workers_per_gpu=1,", "glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt', ),", "+ annotation_path + 'imdb_subtrain.npy', val=data_root + annotation_path + 'imdb_subval.npy', test=data_root", "glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict( wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root +", "+ 'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict( wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec',", "= 'data/datasets/stvqa/defaults/features/' ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/' annotation_path = 'data/datasets/stvqa/defaults/annotations/' vocab_path =", "annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) info_cpler_cfg = dict( type='STVQAInfoCpler', glove_weights=dict(", "+ 'imdb_subval.npy', test=data_root + annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) info_cpler_cfg", "), datasets=train_datasets) info_cpler_cfg = dict( type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt',", "answers_st_5k=data_root + vocab_path + 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root + vocab_path + 'vocabulary_100k.txt',", "val=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', test=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb',", "+ 'ocr_en_frcn_features.lmdb', val=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', test=data_root + ocr_feature_path", "'data/datasets/stvqa/defaults/features/' ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/' annotation_path = 'data/datasets/stvqa/defaults/annotations/' vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/'", "+ 'detectron.lmdb', test=data_root + feature_path + 'detectron.lmdb', ), mix_ocr_features=dict( train=data_root", "data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800)) test_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type,", "feature_path + 'detectron.lmdb', test=data_root + feature_path + 'detectron.lmdb', ), mix_ocr_features=dict(", "'imdb_subval.npy', test=data_root + annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) reader_test_cfg =", "'/home/datasets/mix_data/iMIX/' feature_path = 'data/datasets/stvqa/defaults/features/' ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/' annotation_path = 'data/datasets/stvqa/defaults/annotations/'", "+ ocr_feature_path + 'ocr_en_frcn_features.lmdb', val=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', test=data_root", "samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800)) test_data = dict( samples_per_gpu=16,", "'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets = ['train'] test_datasets = ['val'] reader_train_cfg = dict(", "= 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets = ['train'] test_datasets = ['val'] reader_train_cfg =", "+ annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) info_cpler_cfg = dict( type='STVQAInfoCpler',", "'ocr_en_frcn_features.lmdb', test=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', ), mix_annotations=dict( train=data_root +", "train=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', val=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb',", "vocab_path + 'vocabulary_100k.txt', ), max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d',", "glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root", "fasttext_weights=dict( wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root + 'fasttext/wiki.en.bin',", "'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root + 'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root", "+ 'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root + vocab_path", "glove_weights=dict( glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt',", "wiki_bin=data_root + 'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root +", "datasets=train_datasets) info_cpler_cfg = dict( type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root", "val=data_root + feature_path + 'detectron.lmdb', test=data_root + feature_path + 'detectron.lmdb',", "reader_train_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root + feature_path +", "'imdb_subtrain.npy', val=data_root + annotation_path + 'imdb_subval.npy', test=data_root + annotation_path +", "max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True, ) train_data", "ocr_feature_path + 'ocr_en_frcn_features.lmdb', val=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', test=data_root +", "datasets=train_datasets) reader_test_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root + feature_path", "+ feature_path + 'detectron.lmdb', val=data_root + feature_path + 'detectron.lmdb', test=data_root", "+ 'imdb_subval.npy', test=data_root + annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) reader_test_cfg", "= ['train'] test_datasets = ['val'] reader_train_cfg = dict( type='STVQAREADER', card='default',", "'detectron.lmdb', ), mix_ocr_features=dict( train=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', val=data_root +", "'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root + vocab_path + 'vocabulary_100k.txt', ), max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0,", "word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True, ) train_data = dict(", "['val'] reader_train_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root + feature_path", "train_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800)) test_data", "train_datasets = ['train'] test_datasets = ['val'] reader_train_cfg = dict( type='STVQAREADER',", "annotation_path = 'data/datasets/stvqa/defaults/annotations/' vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets = ['train'] test_datasets", "wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root + 'fasttext/wiki.en.bin', ),", "dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800)) test_data = dict(", "val=data_root + annotation_path + 'imdb_subval.npy', test=data_root + annotation_path + 'imdb_test_task3.npy',", "dataset_type = 'STVQADATASET' data_root = '/home/datasets/mix_data/iMIX/' feature_path = 'data/datasets/stvqa/defaults/features/' ocr_feature_path", "'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict( wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root", "glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True, ) train_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type,", "mix_ocr_features=dict( train=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', val=data_root + ocr_feature_path +", "vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True, ) train_data = dict( samples_per_gpu=16,", "train=data_root + annotation_path + 'imdb_subtrain.npy', val=data_root + annotation_path + 'imdb_subval.npy',", "data_root = '/home/datasets/mix_data/iMIX/' feature_path = 'data/datasets/stvqa/defaults/features/' ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/' annotation_path", "+ 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict(", "'glove/glove.6B.50d.txt.pt', glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt',", "+ 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root + vocab_path + 'vocabulary_100k.txt', ), max_seg_lenth=20, max_ocr_lenth=10,", "'imdb_subval.npy', test=data_root + annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) info_cpler_cfg =", "= '/home/datasets/mix_data/iMIX/' feature_path = 'data/datasets/stvqa/defaults/features/' ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/' annotation_path =", "wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root + 'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt',", "), datasets=train_datasets) reader_test_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root +", "= dict( type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt',", "['train'] test_datasets = ['val'] reader_train_cfg = dict( type='STVQAREADER', card='default', mix_features=dict(", "feature_path + 'detectron.lmdb', ), mix_ocr_features=dict( train=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb',", "+ 'imdb_test_task3.npy', ), datasets=train_datasets) info_cpler_cfg = dict( type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root", "'glove/glove.6B.200d.txt.pt', glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict( wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root", "'STVQADATASET' data_root = '/home/datasets/mix_data/iMIX/' feature_path = 'data/datasets/stvqa/defaults/features/' ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/'", "ocr_feature_path + 'ocr_en_frcn_features.lmdb', test=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', ), mix_annotations=dict(", "test=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', ), mix_annotations=dict( train=data_root + annotation_path", "), tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root + vocab_path + 'fixed_answer_vocab_stvqa_5k.txt',", "+ vocab_path + 'vocabulary_100k.txt', ), max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k',", "+ 'ocr_en_frcn_features.lmdb', test=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', ), mix_annotations=dict( train=data_root", "annotation_path + 'imdb_subval.npy', test=data_root + annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets)", "dict( type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root", "= ['val'] reader_train_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root +", "mix_annotations=dict( train=data_root + annotation_path + 'imdb_subtrain.npy', val=data_root + annotation_path +", "+ annotation_path + 'imdb_subval.npy', test=data_root + annotation_path + 'imdb_test_task3.npy', ),", "'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root + vocab_path + 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root + vocab_path", "vocabulary_100k=data_root + vocab_path + 'vocabulary_100k.txt', ), max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k',", "= dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800)) test_data =", "= 'STVQADATASET' data_root = '/home/datasets/mix_data/iMIX/' feature_path = 'data/datasets/stvqa/defaults/features/' ocr_feature_path =", "ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/' annotation_path = 'data/datasets/stvqa/defaults/annotations/' vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets", "mix_features=dict( train=data_root + feature_path + 'detectron.lmdb', val=data_root + feature_path +", "'data/datasets/stvqa/defaults/ocr_features/' annotation_path = 'data/datasets/stvqa/defaults/annotations/' vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets = ['train']", "annotation_path + 'imdb_subtrain.npy', val=data_root + annotation_path + 'imdb_subval.npy', test=data_root +", "+ ocr_feature_path + 'ocr_en_frcn_features.lmdb', ), mix_annotations=dict( train=data_root + annotation_path +", "info_cpler_cfg = dict( type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root +", "+ 'imdb_test_task3.npy', ), datasets=train_datasets) reader_test_cfg = dict( type='STVQAREADER', card='default', mix_features=dict(", "vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets = ['train'] test_datasets = ['val'] reader_train_cfg", "= dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root + feature_path + 'detectron.lmdb',", "+ 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root + 'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt', mix_vocab=dict(", "mix_vocab=dict( answers_st_5k=data_root + vocab_path + 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root + vocab_path +", "+ 'imdb_subtrain.npy', val=data_root + annotation_path + 'imdb_subval.npy', test=data_root + annotation_path", "+ 'detectron.lmdb', val=data_root + feature_path + 'detectron.lmdb', test=data_root + feature_path", "max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True, ) train_data =", "'ocr_en_frcn_features.lmdb', ), mix_annotations=dict( train=data_root + annotation_path + 'imdb_subtrain.npy', val=data_root +", "workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800)) test_data = dict( samples_per_gpu=16, workers_per_gpu=1,", "+ 'ocr_en_frcn_features.lmdb', ), mix_annotations=dict( train=data_root + annotation_path + 'imdb_subtrain.npy', val=data_root", "= 'data/datasets/stvqa/defaults/ocr_features/' annotation_path = 'data/datasets/stvqa/defaults/annotations/' vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets =", "train=data_root + feature_path + 'detectron.lmdb', val=data_root + feature_path + 'detectron.lmdb',", "'imdb_test_task3.npy', ), datasets=train_datasets) info_cpler_cfg = dict( type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root +", "'detectron.lmdb', val=data_root + feature_path + 'detectron.lmdb', test=data_root + feature_path +", ") train_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800))", "'glove/glove.6B.100d.txt.pt', glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict( wiki300d1m=data_root", "+ vocab_path + 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root + vocab_path + 'vocabulary_100k.txt', ),", "+ 'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root + vocab_path + 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root +", "annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) reader_test_cfg = dict( type='STVQAREADER', card='default',", "'data/datasets/stvqa/defaults/annotations/' vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets = ['train'] test_datasets = ['val']", "reader=reader_train_cfg, info_cpler=info_cpler_cfg, limit_nums=800)) test_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_test_cfg,", "'imdb_test_task3.npy', ), datasets=train_datasets) reader_test_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root", "type='STVQAREADER', card='default', mix_features=dict( train=data_root + feature_path + 'detectron.lmdb', val=data_root +", "test=data_root + annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) reader_test_cfg = dict(", "vocab_path + 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root + vocab_path + 'vocabulary_100k.txt', ), max_seg_lenth=20,", "reader_test_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root + feature_path +", "'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root + vocab_path +", "= 'data/datasets/stvqa/defaults/annotations/' vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/' train_datasets = ['train'] test_datasets =", "ocr_feature_path + 'ocr_en_frcn_features.lmdb', ), mix_annotations=dict( train=data_root + annotation_path + 'imdb_subtrain.npy',", "+ ocr_feature_path + 'ocr_en_frcn_features.lmdb', test=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', ),", "+ annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) reader_test_cfg = dict( type='STVQAREADER',", "feature_path + 'detectron.lmdb', val=data_root + feature_path + 'detectron.lmdb', test=data_root +", "test=data_root + annotation_path + 'imdb_test_task3.npy', ), datasets=train_datasets) info_cpler_cfg = dict(", "'ocr_en_frcn_features.lmdb', val=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', test=data_root + ocr_feature_path +", "'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root + 'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/' +", "+ 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root + 'fasttext/wiki.en.bin', ), tokenizer='/home/datasets/VQA/bert/'", "type='STVQAInfoCpler', glove_weights=dict( glove6b50d=data_root + 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root +", "test=data_root + feature_path + 'detectron.lmdb', ), mix_ocr_features=dict( train=data_root + ocr_feature_path", "+ 'glove/glove.6B.50d.txt.pt', glove6b100d=data_root + 'glove/glove.6B.100d.txt.pt', glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root +", "glove6b200d=data_root + 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict( wiki300d1m=data_root +", "feature_path = 'data/datasets/stvqa/defaults/features/' ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/' annotation_path = 'data/datasets/stvqa/defaults/annotations/' vocab_path", "info_cpler=info_cpler_cfg, limit_nums=800)) test_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_test_cfg, info_cpler=info_cpler_cfg),", "dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root + feature_path + 'detectron.lmdb', val=data_root", "'vocabulary_100k.txt', ), max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True,", "test_datasets = ['val'] reader_train_cfg = dict( type='STVQAREADER', card='default', mix_features=dict( train=data_root", "limit_nums=800)) test_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_test_cfg, info_cpler=info_cpler_cfg), )", "+ feature_path + 'detectron.lmdb', test=data_root + feature_path + 'detectron.lmdb', ),", "fasttext_name='wiki_bin', if_bert=True, ) train_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg,", "+ 'vocabulary_100k.txt', ), max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin',", "+ 'glove/glove.6B.200d.txt.pt', glove6b300d=data_root + 'glove/glove.6B.300d.txt.pt', ), fasttext_weights=dict( wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec',", "tokenizer='/home/datasets/VQA/bert/' + 'bert-base-uncased-vocab.txt', mix_vocab=dict( answers_st_5k=data_root + vocab_path + 'fixed_answer_vocab_stvqa_5k.txt', vocabulary_100k=data_root", "), max_seg_lenth=20, max_ocr_lenth=10, word_mask_ratio=0.0, vocab_name='vocabulary_100k', vocab_answer_name='answers_st_5k', glove_name='glove6b300d', fasttext_name='wiki_bin', if_bert=True, )", "card='default', mix_features=dict( train=data_root + feature_path + 'detectron.lmdb', val=data_root + feature_path", "), mix_annotations=dict( train=data_root + annotation_path + 'imdb_subtrain.npy', val=data_root + annotation_path", "+ feature_path + 'detectron.lmdb', ), mix_ocr_features=dict( train=data_root + ocr_feature_path +", "), mix_ocr_features=dict( train=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', val=data_root + ocr_feature_path", "if_bert=True, ) train_data = dict( samples_per_gpu=16, workers_per_gpu=1, data=dict(type=dataset_type, reader=reader_train_cfg, info_cpler=info_cpler_cfg,", "+ 'detectron.lmdb', ), mix_ocr_features=dict( train=data_root + ocr_feature_path + 'ocr_en_frcn_features.lmdb', val=data_root", "), fasttext_weights=dict( wiki300d1m=data_root + 'fasttext/wiki-news-300d-1M.vec', wiki300d1msub=data_root + 'fasttext/wiki-news-300d-1M-subword.vec', wiki_bin=data_root +", "'detectron.lmdb', test=data_root + feature_path + 'detectron.lmdb', ), mix_ocr_features=dict( train=data_root +" ]
[ "dependencies = [ ('rpocore', '0006_auto_20160921_1924'), ] operations = [ migrations.CreateModel(", "Migration(migrations.Migration): dependencies = [ ('rpocore', '0006_auto_20160921_1924'), ] operations = [", "name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal statements'), ), migrations.AlterField( model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True,", "'verbose_name_plural': 'Supporting organizations', 'ordering': ('_order',), 'verbose_name': 'Supporting organization', }, ),", "[ ('rpocore', '0006_auto_20160921_1924'), ] operations = [ migrations.CreateModel( name='SupportingOrganization', fields=[", "verbose_name='Supporter page'), ), migrations.AlterField( model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'), ),", "), migrations.AlterField( model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter page'),", "serialize=False, verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('logo', models.ImageField(upload_to='',", "operations = [ migrations.CreateModel( name='SupportingOrganization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,", "from django.db import migrations, models import django.db.models.deletion import mezzanine.core.fields class", "name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement',", "verbose_name='Order')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('logo', models.ImageField(upload_to='', verbose_name='Logo of organization')), ('url',", "model_name='homepagepage', name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='notablesupporter', name='supporter_page',", "('rpocore', '0006_auto_20160921_1924'), ] operations = [ migrations.CreateModel( name='SupportingOrganization', fields=[ ('id',", "verbose_name='Informal statements'), ), migrations.AlterField( model_name='supporter', name='support_group', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='rpocore.SupportGroup', verbose_name='Support", "], options={ 'verbose_name_plural': 'Supporting organizations', 'ordering': ('_order',), 'verbose_name': 'Supporting organization',", "related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'), ), migrations.AlterField( model_name='homepagepage', name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process',", "mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('rpocore', '0006_auto_20160921_1924'), ] operations", "verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('logo', models.ImageField(upload_to='', verbose_name='Logo", "), migrations.AlterField( model_name='homepagepage', name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField(", "on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters',", "('name', models.CharField(max_length=100, verbose_name='Name')), ('logo', models.ImageField(upload_to='', verbose_name='Logo of organization')), ('url', models.CharField(max_length=200,", "on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter page'), ), migrations.AlterField( model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "migrations.CreateModel( name='SupportingOrganization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True,", "import django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('rpocore',", "to='rpocore.HomepagePage', verbose_name='Homepage'), ), migrations.AlterField( model_name='homepagepage', name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'),", "1.10 on 2016-09-27 13:17 from __future__ import unicode_literals from django.db", "models.CharField(max_length=100, verbose_name='Name')), ('logo', models.ImageField(upload_to='', verbose_name='Logo of organization')), ('url', models.CharField(max_length=200, verbose_name='URL')),", "utf-8 -*- # Generated by Django 1.10 on 2016-09-27 13:17", "verbose_name='Formal statements'), ), migrations.AlterField( model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal statements'),", "to='rpocore.SupporterPage', verbose_name='Supporter page'), ), migrations.AlterField( model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'),", "model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal statements'), ), migrations.AlterField( model_name='statementpage', name='informal_statements',", "# Generated by Django 1.10 on 2016-09-27 13:17 from __future__", "[ migrations.CreateModel( name='SupportingOrganization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_order',", "statements'), ), migrations.AlterField( model_name='supporter', name='support_group', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='rpocore.SupportGroup', verbose_name='Support group'),", "'ordering': ('_order',), 'verbose_name': 'Supporting organization', }, ), migrations.AlterField( model_name='carouselitem', name='homepage',", "by Django 1.10 on 2016-09-27 13:17 from __future__ import unicode_literals", "}, ), migrations.AlterField( model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'), ),", "django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('rpocore', '0006_auto_20160921_1924'),", "('logo', models.ImageField(upload_to='', verbose_name='Logo of organization')), ('url', models.CharField(max_length=200, verbose_name='URL')), ], options={", "models.CharField(max_length=200, verbose_name='URL')), ], options={ 'verbose_name_plural': 'Supporting organizations', 'ordering': ('_order',), 'verbose_name':", "migrations.AlterField( model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter page'), ),", "primary_key=True, serialize=False, verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('logo',", "migrations.AlterField( model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='statementpage', name='formal_statements',", "= [ ('rpocore', '0006_auto_20160921_1924'), ] operations = [ migrations.CreateModel( name='SupportingOrganization',", "verbose_name='URL')), ], options={ 'verbose_name_plural': 'Supporting organizations', 'ordering': ('_order',), 'verbose_name': 'Supporting", "__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion", "import unicode_literals from django.db import migrations, models import django.db.models.deletion import", "to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage',", "'Supporting organization', }, ), migrations.AlterField( model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage',", "verbose_name='Process'), ), migrations.AlterField( model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal statements'), ),", "('_order',), 'verbose_name': 'Supporting organization', }, ), migrations.AlterField( model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "Django 1.10 on 2016-09-27 13:17 from __future__ import unicode_literals from", "class Migration(migrations.Migration): dependencies = [ ('rpocore', '0006_auto_20160921_1924'), ] operations =", "organization')), ('url', models.CharField(max_length=200, verbose_name='URL')), ], options={ 'verbose_name_plural': 'Supporting organizations', 'ordering':", "verbose_name='Process'), ), migrations.AlterField( model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter", "migrations, models import django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration): dependencies =", "unicode_literals from django.db import migrations, models import django.db.models.deletion import mezzanine.core.fields", "), migrations.AlterField( model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='statementpage',", "('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('logo', models.ImageField(upload_to='', verbose_name='Logo of", "organizations', 'ordering': ('_order',), 'verbose_name': 'Supporting organization', }, ), migrations.AlterField( model_name='carouselitem',", "), migrations.AlterField( model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'), ), migrations.AlterField(", "field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal statements'), ), migrations.AlterField( model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement',", "statements'), ), migrations.AlterField( model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal statements'), ),", "model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal statements'), ), migrations.AlterField( model_name='supporter', name='support_group',", "('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name', models.CharField(max_length=100,", "2016-09-27 13:17 from __future__ import unicode_literals from django.db import migrations,", "of organization')), ('url', models.CharField(max_length=200, verbose_name='URL')), ], options={ 'verbose_name_plural': 'Supporting organizations',", "field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal", "related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter page'), ), migrations.AlterField( model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process',", "-*- # Generated by Django 1.10 on 2016-09-27 13:17 from", "fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name',", "), migrations.AlterField( model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal statements'), ), migrations.AlterField(", "model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter page'), ), migrations.AlterField(", "model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True,", "field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE,", "), migrations.AlterField( model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal statements'), ), migrations.AlterField(", "13:17 from __future__ import unicode_literals from django.db import migrations, models", "import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('rpocore', '0006_auto_20160921_1924'), ]", "Generated by Django 1.10 on 2016-09-27 13:17 from __future__ import", "from __future__ import unicode_literals from django.db import migrations, models import", "'Supporting organizations', 'ordering': ('_order',), 'verbose_name': 'Supporting organization', }, ), migrations.AlterField(", "models import django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [", "page'), ), migrations.AlterField( model_name='phase', name='process', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField(", "organization', }, ), migrations.AlterField( model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'),", "name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'), ), migrations.AlterField( model_name='homepagepage', name='process', field=models.ForeignKey(null=True,", "migrations.AlterField( model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal statements'), ), migrations.AlterField( model_name='statementpage',", "verbose_name='Homepage'), ), migrations.AlterField( model_name='homepagepage', name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'), ),", "'0006_auto_20160921_1924'), ] operations = [ migrations.CreateModel( name='SupportingOrganization', fields=[ ('id', models.AutoField(auto_created=True,", "verbose_name='Name')), ('logo', models.ImageField(upload_to='', verbose_name='Logo of organization')), ('url', models.CharField(max_length=200, verbose_name='URL')), ],", "options={ 'verbose_name_plural': 'Supporting organizations', 'ordering': ('_order',), 'verbose_name': 'Supporting organization', },", "migrations.AlterField( model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'), ), migrations.AlterField( model_name='homepagepage',", "models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name', models.CharField(max_length=100, verbose_name='Name')),", "to='rpocore.FormalStatement', verbose_name='Formal statements'), ), migrations.AlterField( model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal", "coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-27", "django.db import migrations, models import django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration):", "import migrations, models import django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration): dependencies", "] operations = [ migrations.CreateModel( name='SupportingOrganization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,", "on 2016-09-27 13:17 from __future__ import unicode_literals from django.db import", "migrations.AlterField( model_name='supporter', name='support_group', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='rpocore.SupportGroup', verbose_name='Support group'), ), ]", "verbose_name='Logo of organization')), ('url', models.CharField(max_length=200, verbose_name='URL')), ], options={ 'verbose_name_plural': 'Supporting", "mezzanine.core.fields.OrderField(null=True, verbose_name='Order')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('logo', models.ImageField(upload_to='', verbose_name='Logo of organization')),", "migrations.AlterField( model_name='statementpage', name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal statements'), ), migrations.AlterField( model_name='supporter',", "# -*- coding: utf-8 -*- # Generated by Django 1.10", "), migrations.AlterField( model_name='supporter', name='support_group', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='rpocore.SupportGroup', verbose_name='Support group'), ),", "-*- coding: utf-8 -*- # Generated by Django 1.10 on", "to='rpocore.InformalStatement', verbose_name='Informal statements'), ), migrations.AlterField( model_name='supporter', name='support_group', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='rpocore.SupportGroup',", "name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='notablesupporter', name='supporter_page', field=models.ForeignKey(null=True,", "field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'), ), migrations.AlterField( model_name='homepagepage', name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL,", "'verbose_name': 'Supporting organization', }, ), migrations.AlterField( model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items',", "to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='statementpage', name='formal_statements', field=models.ManyToManyField(blank=True, to='rpocore.FormalStatement', verbose_name='Formal statements'),", "('url', models.CharField(max_length=200, verbose_name='URL')), ], options={ 'verbose_name_plural': 'Supporting organizations', 'ordering': ('_order',),", "field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal statements'), ), migrations.AlterField( model_name='supporter', name='support_group', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT,", "model_name='carouselitem', name='homepage', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carousel_items', to='rpocore.HomepagePage', verbose_name='Homepage'), ), migrations.AlterField( model_name='homepagepage', name='process',", "name='supporter_page', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter page'), ), migrations.AlterField( model_name='phase',", "name='SupportingOrganization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_order', mezzanine.core.fields.OrderField(null=True, verbose_name='Order')),", "field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notable_supporters', to='rpocore.SupporterPage', verbose_name='Supporter page'), ), migrations.AlterField( model_name='phase', name='process',", "models.ImageField(upload_to='', verbose_name='Logo of organization')), ('url', models.CharField(max_length=200, verbose_name='URL')), ], options={ 'verbose_name_plural':", "= [ migrations.CreateModel( name='SupportingOrganization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "name='informal_statements', field=models.ManyToManyField(blank=True, to='rpocore.InformalStatement', verbose_name='Informal statements'), ), migrations.AlterField( model_name='supporter', name='support_group', field=models.ForeignKey(null=True,", "migrations.AlterField( model_name='homepagepage', name='process', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='rpocore.Process', verbose_name='Process'), ), migrations.AlterField( model_name='notablesupporter'," ]
[ "time import sleep from signal import pause def lineDetected(): print('line", "signal import pause def lineDetected(): print('line detected') def noLineDetected(): print('no", "print('line detected') def noLineDetected(): print('no line detected') sensor = LineSensor(14)", "= LineSensor(14) sensor.when_line = lineDetected sensor.when_no_line = noLineDetected pause() sensor.close()", "from time import sleep from signal import pause def lineDetected():", "gpiozero import LineSensor from time import sleep from signal import", "import LineSensor from time import sleep from signal import pause", "import pause def lineDetected(): print('line detected') def noLineDetected(): print('no line", "test from gpiozero import LineSensor from time import sleep from", "print('no line detected') sensor = LineSensor(14) sensor.when_line = lineDetected sensor.when_no_line", "sleep from signal import pause def lineDetected(): print('line detected') def", "noLineDetected(): print('no line detected') sensor = LineSensor(14) sensor.when_line = lineDetected", "detected') sensor = LineSensor(14) sensor.when_line = lineDetected sensor.when_no_line = noLineDetected", "from gpiozero import LineSensor from time import sleep from signal", "import sleep from signal import pause def lineDetected(): print('line detected')", "def lineDetected(): print('line detected') def noLineDetected(): print('no line detected') sensor", "detected') def noLineDetected(): print('no line detected') sensor = LineSensor(14) sensor.when_line", "lineDetected(): print('line detected') def noLineDetected(): print('no line detected') sensor =", "pause def lineDetected(): print('line detected') def noLineDetected(): print('no line detected')", "from signal import pause def lineDetected(): print('line detected') def noLineDetected():", "#LineSensor test from gpiozero import LineSensor from time import sleep", "line detected') sensor = LineSensor(14) sensor.when_line = lineDetected sensor.when_no_line =", "def noLineDetected(): print('no line detected') sensor = LineSensor(14) sensor.when_line =", "LineSensor from time import sleep from signal import pause def", "sensor = LineSensor(14) sensor.when_line = lineDetected sensor.when_no_line = noLineDetected pause()" ]
[ "Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 3,", "* from litex.build.generic_platform import * from litex.build.gowin.platform import GowinPlatform from", "Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1, Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2, Pins(\"141\"), IOStandard(\"LVCMOS33\")),", "(\"user_sw\", 0, Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 1, Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 2,", "[\"J2\", \"- 136 135 134 133 132 131 130 129", "Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 3, Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 4, Pins(\"80\"), IOStandard(\"LVCMOS33\")),", "part of LiteX-Boards. # # Copyright (c) 2021 <NAME> <<EMAIL>>", "IOStandard(\"LVCMOS33\")), (\"user_sw\", 2, Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 3, Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\",", "to # connect an external USB<->serial adapter (\"serial\", 0, Subsignal(\"tx\",", "Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 2, Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")),", "interface -> use (arbitrary) two pins from J2 to #", "41 42 43 44 66 67 68 69 70 71", "6, Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 7, Pins(\"30\"), IOStandard(\"LVCMOS33\")), # RGB led,", "# # This file is part of LiteX-Boards. # #", "IOStandard(\"LVCMOS33\")), (\"user_sw\", 6, Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 7, Pins(\"83\"), IOStandard(\"LVCMOS33\")), #", "IOStandard(\"LVCMOS33\")), (\"user_led\", 5, Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 6, Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\",", "RGB led, active-low (\"rgb_led\", 0, Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\",", "Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 1, Subsignal(\"r\", Pins(\"106\")),", "GowinPlatform from litex.build.openfpgaloader import OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io =", "Switches (\"user_sw\", 0, Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 1, Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\",", "(\"rgb_led\", 1, Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"), ),", "Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 5, Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 6, Pins(\"64\"), IOStandard(\"LVCMOS33\")),", "0, Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 1, Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 2, Pins(\"25\"),", "2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from migen import *", "IOStandard(\"LVCMOS33\")), (\"user_led\", 7, Pins(\"30\"), IOStandard(\"LVCMOS33\")), # RGB led, active-low (\"rgb_led\",", "Pins(\"65\"), IOStandard(\"LVCMOS33\")), # Serial. # FT232H has only one interface", "# Seven Segment (\"seven_seg_dig\", 0, Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1, Pins(\"140\"),", "(\"user_led\", 0, Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 1, Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 2,", "-\"], ] # Platform ----------------------------------------------------------------------------------------- class Platform(GowinPlatform): default_clk_name = \"clk12\"", "9 11 12 139 8 10\"), IOStandard(\"LVCMOS33\")), ] # Connectors", "8 10\"), IOStandard(\"LVCMOS33\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [", "toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] = 1 def create_programmer(self): return OpenFPGALoader(\"runber\") def", "Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 7, Pins(\"83\"), IOStandard(\"LVCMOS33\")), # Buttons. (\"user_btn\", 0,", "2, Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 3, Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 4, Pins(\"27\"),", "123 122 121 120 119 118 117 116 115 -\"],", "(\"user_btn\", 3, Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 4, Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 5,", "(\"seven_seg_dig\", 3, Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0, Pins(\"138 142 9 11", "Segment (\"seven_seg_dig\", 0, Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1, Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\",", "IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2, Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3, Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\",", "1, Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2, Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3, Pins(\"7\"),", "(\"user_btn\", 0, Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 1, Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 2,", "Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 3, Subsignal(\"r\", Pins(\"98\")),", "66 67 68 69 70 71 72 96 95 94", "one interface -> use (arbitrary) two pins from J2 to", "-> use (arbitrary) two pins from J2 to # connect", "39 40 41 42 43 44 66 67 68 69", "USB<->serial adapter (\"serial\", 0, Subsignal(\"tx\", Pins(\"116\")), # J2.17 Subsignal(\"rx\", Pins(\"115\")),", "\"GW1N-UV4LQ144C6/I5\", _io, _connectors, toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] = 1 def create_programmer(self):", "J2.17 Subsignal(\"rx\", Pins(\"115\")), # J2.18 IOStandard(\"LVCMOS33\") ), # Seven Segment", "71 72 96 95 94 93 -\"], [\"J2\", \"- 136", "IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst (\"clk12\",", "return OpenFPGALoader(\"runber\") def do_finalize(self, fragment): GowinPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk12\", loose=True), 1e9/12e6)", "12 139 8 10\"), IOStandard(\"LVCMOS33\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors", "migen import * from litex.build.generic_platform import * from litex.build.gowin.platform import", "IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3, Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0, Pins(\"138 142 9", "131 130 129 128 123 122 121 120 119 118", "(\"rgb_led\", 3, Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"), ),", "(\"user_led\", 6, Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 7, Pins(\"30\"), IOStandard(\"LVCMOS33\")), # RGB", "117 116 115 -\"], ] # Platform ----------------------------------------------------------------------------------------- class Platform(GowinPlatform):", "Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"), ), # Switches (\"user_sw\",", "0, Subsignal(\"tx\", Pins(\"116\")), # J2.17 Subsignal(\"rx\", Pins(\"115\")), # J2.18 IOStandard(\"LVCMOS33\")", "121 120 119 118 117 116 115 -\"], ] #", "IOStandard(\"LVCMOS33\")), (\"user_btn\", 3, Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 4, Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\",", "2, Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 3, Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 4, Pins(\"62\"),", "1, Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 2, Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 3, Pins(\"79\"),", "IOStandard(\"LVCMOS33\") ), # Seven Segment (\"seven_seg_dig\", 0, Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\",", "J2 to # connect an external USB<->serial adapter (\"serial\", 0,", "(\"seven_seg_dig\", 2, Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3, Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0,", "This file is part of LiteX-Boards. # # Copyright (c)", "6, Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 7, Pins(\"65\"), IOStandard(\"LVCMOS33\")), # Serial. #", "2, Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3, Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0, Pins(\"138", "115 -\"], ] # Platform ----------------------------------------------------------------------------------------- class Platform(GowinPlatform): default_clk_name =", "[ [\"J1\", \"- 38 39 40 41 42 43 44", "), # Switches (\"user_sw\", 0, Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 1, Pins(\"76\"),", "(\"user_led\", 3, Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 4, Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 5,", "Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 5, Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 6, Pins(\"29\"), IOStandard(\"LVCMOS33\")),", "(\"user_sw\", 6, Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 7, Pins(\"83\"), IOStandard(\"LVCMOS33\")), # Buttons.", "Platform(GowinPlatform): default_clk_name = \"clk12\" default_clk_period = 1e9/12e6 def __init__(self, toolchain=\"gowin\"):", "Connectors --------------------------------------------------------------------------------------- _connectors = [ [\"J1\", \"- 38 39 40", "Pins(\"83\"), IOStandard(\"LVCMOS33\")), # Buttons. (\"user_btn\", 0, Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 1,", "7, Pins(\"83\"), IOStandard(\"LVCMOS33\")), # Buttons. (\"user_btn\", 0, Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\",", "Copyright (c) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from migen", "(arbitrary) two pins from J2 to # connect an external", "(\"user_btn\", 5, Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 6, Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 7,", "<<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from migen import * from litex.build.generic_platform", "Pins(\"113\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 1, Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\",", "default_clk_name = \"clk12\" default_clk_period = 1e9/12e6 def __init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self,", "44 66 67 68 69 70 71 72 96 95", "use (arbitrary) two pins from J2 to # connect an", "1 def create_programmer(self): return OpenFPGALoader(\"runber\") def do_finalize(self, fragment): GowinPlatform.do_finalize(self, fragment)", "118 117 116 115 -\"], ] # Platform ----------------------------------------------------------------------------------------- class", "129 128 123 122 121 120 119 118 117 116", "Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 3, Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 4, Pins(\"62\"), IOStandard(\"LVCMOS33\")),", "(\"user_btn\", 7, Pins(\"65\"), IOStandard(\"LVCMOS33\")), # Serial. # FT232H has only", "136 135 134 133 132 131 130 129 128 123", "Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 4, Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 5, Pins(\"28\"), IOStandard(\"LVCMOS33\")),", "_io = [ # Clk / Rst (\"clk12\", 0, Pins(\"4\"),", "Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 6, Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 7, Pins(\"30\"), IOStandard(\"LVCMOS33\")),", "38 39 40 41 42 43 44 66 67 68", "led, active-low (\"rgb_led\", 0, Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")),", "Leds (\"user_led\", 0, Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 1, Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\",", "119 118 117 116 115 -\"], ] # Platform -----------------------------------------------------------------------------------------", "IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 3, Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")),", "= [ [\"J1\", \"- 38 39 40 41 42 43", "(\"user_led\", 2, Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 3, Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 4,", "3, Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 4, Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 5, Pins(\"63\"),", "(\"user_led\", 1, Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 2, Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 3,", "0, Pins(\"138 142 9 11 12 139 8 10\"), IOStandard(\"LVCMOS33\")),", "has only one interface -> use (arbitrary) two pins from", "Platform ----------------------------------------------------------------------------------------- class Platform(GowinPlatform): default_clk_name = \"clk12\" default_clk_period = 1e9/12e6", "5, Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 6, Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 7, Pins(\"83\"),", "Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 3, Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")),", "IOStandard(\"LVCMOS33\")), (\"user_sw\", 3, Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 4, Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\",", "Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 5, Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 6, Pins(\"82\"), IOStandard(\"LVCMOS33\")),", "95 94 93 -\"], [\"J2\", \"- 136 135 134 133", "68 69 70 71 72 96 95 94 93 -\"],", "Pins(\"30\"), IOStandard(\"LVCMOS33\")), # RGB led, active-low (\"rgb_led\", 0, Subsignal(\"r\", Pins(\"112\")),", "LiteX-Boards. # # Copyright (c) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier:", "IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 1, Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")),", "Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 2, Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 3, Pins(\"79\"), IOStandard(\"LVCMOS33\")),", "Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"), ), # Switches", "4, Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 5, Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 6, Pins(\"29\"),", "--------------------------------------------------------------------------------------- _connectors = [ [\"J1\", \"- 38 39 40 41", "120 119 118 117 116 115 -\"], ] # Platform", "# Buttons. (\"user_btn\", 0, Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 1, Pins(\"59\"), IOStandard(\"LVCMOS33\")),", "----------------------------------------------------------------------------------------- class Platform(GowinPlatform): default_clk_name = \"clk12\" default_clk_period = 1e9/12e6 def", "IOStandard(\"LVCMOS33\")), (\"user_btn\", 7, Pins(\"65\"), IOStandard(\"LVCMOS33\")), # Serial. # FT232H has", "Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 6, Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 7, Pins(\"65\"), IOStandard(\"LVCMOS33\")),", "from litex.build.openfpgaloader import OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io = [", "Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2, Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3, Pins(\"7\"), IOStandard(\"LVCMOS33\")),", "Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 2, Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\",", "Subsignal(\"rx\", Pins(\"115\")), # J2.18 IOStandard(\"LVCMOS33\") ), # Seven Segment (\"seven_seg_dig\",", "BSD-2-Clause from migen import * from litex.build.generic_platform import * from", "import OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk", "# IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst", "Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"), ), # Switches (\"user_sw\", 0,", "litex.build.generic_platform import * from litex.build.gowin.platform import GowinPlatform from litex.build.openfpgaloader import", "0, Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 1, Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 2, Pins(\"78\"),", "Buttons. (\"user_btn\", 0, Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 1, Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\",", "litex.build.gowin.platform import GowinPlatform from litex.build.openfpgaloader import OpenFPGALoader # IOs ----------------------------------------------------------------------------------------------", "IOStandard(\"LVCMOS33\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [ [\"J1\", \"-", "(\"user_led\", 4, Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 5, Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 6,", "Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 1, Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 2, Pins(\"25\"), IOStandard(\"LVCMOS33\")),", "IOStandard(\"LVCMOS33\")), (\"user_sw\", 1, Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 2, Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\",", "96 95 94 93 -\"], [\"J2\", \"- 136 135 134", "(\"user_sw\", 7, Pins(\"83\"), IOStandard(\"LVCMOS33\")), # Buttons. (\"user_btn\", 0, Pins(\"58\"), IOStandard(\"LVCMOS33\")),", "= \"clk12\" default_clk_period = 1e9/12e6 def __init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\",", "import GowinPlatform from litex.build.openfpgaloader import OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io", "Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0, Pins(\"138 142 9 11 12 139", "def create_programmer(self): return OpenFPGALoader(\"runber\") def do_finalize(self, fragment): GowinPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk12\",", "93 -\"], [\"J2\", \"- 136 135 134 133 132 131", "), (\"rgb_led\", 3, Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"),", "IOStandard(\"LVCMOS33\")), (\"user_sw\", 7, Pins(\"83\"), IOStandard(\"LVCMOS33\")), # Buttons. (\"user_btn\", 0, Pins(\"58\"),", "# This file is part of LiteX-Boards. # # Copyright", "(\"user_sw\", 1, Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 2, Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 3,", "FT232H has only one interface -> use (arbitrary) two pins", "/ Rst (\"clk12\", 0, Pins(\"4\"), IOStandard(\"LVCMOS33\")), # Leds (\"user_led\", 0,", "from litex.build.gowin.platform import GowinPlatform from litex.build.openfpgaloader import OpenFPGALoader # IOs", "<NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from migen import * from", "IOStandard(\"LVCMOS33\")), # RGB led, active-low (\"rgb_led\", 0, Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\",", "Subsignal(\"tx\", Pins(\"116\")), # J2.17 Subsignal(\"rx\", Pins(\"115\")), # J2.18 IOStandard(\"LVCMOS33\") ),", "Pins(\"138 142 9 11 12 139 8 10\"), IOStandard(\"LVCMOS33\")), ]", "_io, _connectors, toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] = 1 def create_programmer(self): return", "7, Pins(\"30\"), IOStandard(\"LVCMOS33\")), # RGB led, active-low (\"rgb_led\", 0, Subsignal(\"r\",", "(\"user_btn\", 2, Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 3, Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 4,", "(\"rgb_led\", 0, Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"), ),", "IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1, Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2, Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\",", "Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 2, Subsignal(\"r\", Pins(\"101\")),", "Pins(\"99\")), IOStandard(\"LVCMOS33\"), ), # Switches (\"user_sw\", 0, Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\",", "4, Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 5, Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 6, Pins(\"64\"),", "OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk /", "IOStandard(\"LVCMOS33\")), (\"user_btn\", 2, Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 3, Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\",", "3, Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 4, Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 5, Pins(\"81\"),", "Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 7, Pins(\"30\"), IOStandard(\"LVCMOS33\")), # RGB led, active-low", "0, Pins(\"4\"), IOStandard(\"LVCMOS33\")), # Leds (\"user_led\", 0, Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\",", "an external USB<->serial adapter (\"serial\", 0, Subsignal(\"tx\", Pins(\"116\")), # J2.17", "-\"], [\"J2\", \"- 136 135 134 133 132 131 130", "(\"seven_seg\", 0, Pins(\"138 142 9 11 12 139 8 10\"),", "# Platform ----------------------------------------------------------------------------------------- class Platform(GowinPlatform): default_clk_name = \"clk12\" default_clk_period =", "Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 2, Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 3, Pins(\"61\"), IOStandard(\"LVCMOS33\")),", "Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 4, Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 5, Pins(\"81\"), IOStandard(\"LVCMOS33\")),", "_connectors, toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] = 1 def create_programmer(self): return OpenFPGALoader(\"runber\")", "Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 1, Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 2, Pins(\"60\"), IOStandard(\"LVCMOS33\")),", "132 131 130 129 128 123 122 121 120 119", "__init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io, _connectors, toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] =", "toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io, _connectors, toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] = 1", "IOStandard(\"LVCMOS33\")), (\"user_btn\", 4, Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 5, Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\",", "0, Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 1, Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 2, Pins(\"60\"),", "94 93 -\"], [\"J2\", \"- 136 135 134 133 132", "(\"seven_seg_dig\", 1, Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2, Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3,", "3, Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0, Pins(\"138 142 9 11 12", "IOStandard(\"LVCMOS33\"), ), # Switches (\"user_sw\", 0, Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 1,", "Pins(\"61\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 4, Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 5, Pins(\"63\"), IOStandard(\"LVCMOS33\")),", "2, Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 3, Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 4, Pins(\"80\"),", "external USB<->serial adapter (\"serial\", 0, Subsignal(\"tx\", Pins(\"116\")), # J2.17 Subsignal(\"rx\",", "adapter (\"serial\", 0, Subsignal(\"tx\", Pins(\"116\")), # J2.17 Subsignal(\"rx\", Pins(\"115\")), #", "# SPDX-License-Identifier: BSD-2-Clause from migen import * from litex.build.generic_platform import", "= [ # Clk / Rst (\"clk12\", 0, Pins(\"4\"), IOStandard(\"LVCMOS33\")),", "(\"user_btn\", 4, Pins(\"62\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 5, Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 6,", "IOStandard(\"LVCMOS33\")), # Leds (\"user_led\", 0, Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 1, Pins(\"24\"),", "devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] = 1 def create_programmer(self): return OpenFPGALoader(\"runber\") def do_finalize(self,", "] # Platform ----------------------------------------------------------------------------------------- class Platform(GowinPlatform): default_clk_name = \"clk12\" default_clk_period", "default_clk_period = 1e9/12e6 def __init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io, _connectors,", "69 70 71 72 96 95 94 93 -\"], [\"J2\",", "of LiteX-Boards. # # Copyright (c) 2021 <NAME> <<EMAIL>> #", "Pins(\"116\")), # J2.17 Subsignal(\"rx\", Pins(\"115\")), # J2.18 IOStandard(\"LVCMOS33\") ), #", "connect an external USB<->serial adapter (\"serial\", 0, Subsignal(\"tx\", Pins(\"116\")), #", "(\"seven_seg_dig\", 0, Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1, Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2,", "(\"user_led\", 5, Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 6, Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 7,", "# connect an external USB<->serial adapter (\"serial\", 0, Subsignal(\"tx\", Pins(\"116\")),", "# FT232H has only one interface -> use (arbitrary) two", "1, Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 2, Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 3, Pins(\"26\"),", "is part of LiteX-Boards. # # Copyright (c) 2021 <NAME>", "Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 1, Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\",", "7, Pins(\"65\"), IOStandard(\"LVCMOS33\")), # Serial. # FT232H has only one", "(\"user_sw\", 4, Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 5, Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 6,", "IOStandard(\"LVCMOS33\")), (\"user_btn\", 1, Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 2, Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\",", "import * from litex.build.generic_platform import * from litex.build.gowin.platform import GowinPlatform", "# RGB led, active-low (\"rgb_led\", 0, Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")),", "J2.18 IOStandard(\"LVCMOS33\") ), # Seven Segment (\"seven_seg_dig\", 0, Pins(\"137\"), IOStandard(\"LVCMOS33\")),", "Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 3, Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\",", "Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 1, Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")),", "\"- 38 39 40 41 42 43 44 66 67", "# J2.17 Subsignal(\"rx\", Pins(\"115\")), # J2.18 IOStandard(\"LVCMOS33\") ), # Seven", "), # Seven Segment (\"seven_seg_dig\", 0, Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1,", "Pins(\"110\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 2, Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\",", "Pins(\"102\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 3, Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\",", "(\"clk12\", 0, Pins(\"4\"), IOStandard(\"LVCMOS33\")), # Leds (\"user_led\", 0, Pins(\"23\"), IOStandard(\"LVCMOS33\")),", "---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst (\"clk12\", 0,", "134 133 132 131 130 129 128 123 122 121", "create_programmer(self): return OpenFPGALoader(\"runber\") def do_finalize(self, fragment): GowinPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk12\", loose=True),", "IOStandard(\"LVCMOS33\")), (\"user_led\", 3, Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 4, Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\",", "142 9 11 12 139 8 10\"), IOStandard(\"LVCMOS33\")), ] #", "128 123 122 121 120 119 118 117 116 115", "from J2 to # connect an external USB<->serial adapter (\"serial\",", "40 41 42 43 44 66 67 68 69 70", "Pins(\"4\"), IOStandard(\"LVCMOS33\")), # Leds (\"user_led\", 0, Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 1,", "# Leds (\"user_led\", 0, Pins(\"23\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 1, Pins(\"24\"), IOStandard(\"LVCMOS33\")),", "only one interface -> use (arbitrary) two pins from J2", "# Connectors --------------------------------------------------------------------------------------- _connectors = [ [\"J1\", \"- 38 39", "IOStandard(\"LVCMOS33\")), # Buttons. (\"user_btn\", 0, Pins(\"58\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 1, Pins(\"59\"),", "42 43 44 66 67 68 69 70 71 72", "IOStandard(\"LVCMOS33\")), (\"user_btn\", 5, Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 6, Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\",", "IOStandard(\"LVCMOS33\")), # Serial. # FT232H has only one interface ->", "(\"user_sw\", 5, Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 6, Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 7,", "0, Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1, Pins(\"140\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 2, Pins(\"141\"),", "Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 2,", "0, Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\",", "IOStandard(\"LVCMOS33\")), (\"user_sw\", 5, Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 6, Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\",", "# J2.18 IOStandard(\"LVCMOS33\") ), # Seven Segment (\"seven_seg_dig\", 0, Pins(\"137\"),", "Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 7, Pins(\"65\"), IOStandard(\"LVCMOS33\")), # Serial. # FT232H", "), (\"rgb_led\", 1, Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"),", "IOStandard(\"LVCMOS33\")), (\"user_sw\", 4, Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 5, Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\",", "130 129 128 123 122 121 120 119 118 117", "= 1 def create_programmer(self): return OpenFPGALoader(\"runber\") def do_finalize(self, fragment): GowinPlatform.do_finalize(self,", "def __init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io, _connectors, toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"]", "\"- 136 135 134 133 132 131 130 129 128", "class Platform(GowinPlatform): default_clk_name = \"clk12\" default_clk_period = 1e9/12e6 def __init__(self,", "litex.build.openfpgaloader import OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io = [ #", "# Clk / Rst (\"clk12\", 0, Pins(\"4\"), IOStandard(\"LVCMOS33\")), # Leds", "1, Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 2, Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 3, Pins(\"61\"),", "_connectors = [ [\"J1\", \"- 38 39 40 41 42", "Pins(\"141\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 3, Pins(\"7\"), IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0, Pins(\"138 142", "Pins(\"115\")), # J2.18 IOStandard(\"LVCMOS33\") ), # Seven Segment (\"seven_seg_dig\", 0,", "active-low (\"rgb_led\", 0, Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"),", "(\"rgb_led\", 2, Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"), ),", "* from litex.build.gowin.platform import GowinPlatform from litex.build.openfpgaloader import OpenFPGALoader #", "11 12 139 8 10\"), IOStandard(\"LVCMOS33\")), ] # Connectors ---------------------------------------------------------------------------------------", "[ # Clk / Rst (\"clk12\", 0, Pins(\"4\"), IOStandard(\"LVCMOS33\")), #", "two pins from J2 to # connect an external USB<->serial", "IOStandard(\"LVCMOS33\")), (\"user_led\", 2, Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 3, Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\",", "from migen import * from litex.build.generic_platform import * from litex.build.gowin.platform", "10\"), IOStandard(\"LVCMOS33\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [ [\"J1\",", "4, Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 5, Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 6, Pins(\"82\"),", "# Switches (\"user_sw\", 0, Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 1, Pins(\"76\"), IOStandard(\"LVCMOS33\")),", "139 8 10\"), IOStandard(\"LVCMOS33\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors =", "(\"user_sw\", 2, Pins(\"78\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 3, Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 4,", "(\"user_btn\", 6, Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 7, Pins(\"65\"), IOStandard(\"LVCMOS33\")), # Serial.", "43 44 66 67 68 69 70 71 72 96", "3, Subsignal(\"r\", Pins(\"98\")), Subsignal(\"g\", Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"), ), #", "5, Pins(\"63\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 6, Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 7, Pins(\"65\"),", "IOStandard(\"LVCMOS33\")), (\"user_led\", 6, Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 7, Pins(\"30\"), IOStandard(\"LVCMOS33\")), #", "IOStandard(\"LVCMOS33\")), (\"user_btn\", 6, Pins(\"64\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 7, Pins(\"65\"), IOStandard(\"LVCMOS33\")), #", "Subsignal(\"r\", Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 1,", "file is part of LiteX-Boards. # # Copyright (c) 2021", "from litex.build.generic_platform import * from litex.build.gowin.platform import GowinPlatform from litex.build.openfpgaloader", "pins from J2 to # connect an external USB<->serial adapter", "3, Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 4, Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 5, Pins(\"28\"),", "Pins(\"100\")), Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"), ), # Switches (\"user_sw\", 0, Pins(\"75\"),", "70 71 72 96 95 94 93 -\"], [\"J2\", \"-", "GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io, _connectors, toolchain=toolchain, devicename=\"GW1N-4\") self.toolchain.options[\"use_mspi_as_gpio\"] = 1 def", "(c) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from migen import", "(\"user_btn\", 1, Pins(\"59\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 2, Pins(\"60\"), IOStandard(\"LVCMOS33\")), (\"user_btn\", 3,", "IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 2, Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")),", "Subsignal(\"b\", Pins(\"99\")), IOStandard(\"LVCMOS33\"), ), # Switches (\"user_sw\", 0, Pins(\"75\"), IOStandard(\"LVCMOS33\")),", "Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 3, Subsignal(\"r\",", "SPDX-License-Identifier: BSD-2-Clause from migen import * from litex.build.generic_platform import *", "# Serial. # FT232H has only one interface -> use", "Pins(\"75\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 1, Pins(\"76\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 2, Pins(\"78\"), IOStandard(\"LVCMOS33\")),", "116 115 -\"], ] # Platform ----------------------------------------------------------------------------------------- class Platform(GowinPlatform): default_clk_name", "[\"J1\", \"- 38 39 40 41 42 43 44 66", "IOStandard(\"LVCMOS33\")), (\"user_led\", 1, Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 2, Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\",", "135 134 133 132 131 130 129 128 123 122", "Serial. # FT232H has only one interface -> use (arbitrary)", "# Copyright (c) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from", "IOStandard(\"LVCMOS33\")), (\"user_led\", 4, Pins(\"27\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 5, Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\",", "= 1e9/12e6 def __init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io, _connectors, toolchain=toolchain,", "122 121 120 119 118 117 116 115 -\"], ]", "Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 3, Pins(\"26\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 4, Pins(\"27\"), IOStandard(\"LVCMOS33\")),", "Pins(\"112\")), Subsignal(\"g\", Pins(\"114\")), Subsignal(\"b\", Pins(\"113\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 1, Subsignal(\"r\",", "1e9/12e6 def __init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io, _connectors, toolchain=toolchain, devicename=\"GW1N-4\")", "] # Connectors --------------------------------------------------------------------------------------- _connectors = [ [\"J1\", \"- 38", "\"clk12\" default_clk_period = 1e9/12e6 def __init__(self, toolchain=\"gowin\"): GowinPlatform.__init__(self, \"GW1N-UV4LQ144C6/I5\", _io,", "133 132 131 130 129 128 123 122 121 120", "2, Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\",", "72 96 95 94 93 -\"], [\"J2\", \"- 136 135", "(\"user_sw\", 3, Pins(\"79\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 4, Pins(\"80\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 5,", "(\"user_led\", 7, Pins(\"30\"), IOStandard(\"LVCMOS33\")), # RGB led, active-low (\"rgb_led\", 0,", "67 68 69 70 71 72 96 95 94 93", "Rst (\"clk12\", 0, Pins(\"4\"), IOStandard(\"LVCMOS33\")), # Leds (\"user_led\", 0, Pins(\"23\"),", "Pins(\"81\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 6, Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 7, Pins(\"83\"), IOStandard(\"LVCMOS33\")),", "import * from litex.build.gowin.platform import GowinPlatform from litex.build.openfpgaloader import OpenFPGALoader", "Clk / Rst (\"clk12\", 0, Pins(\"4\"), IOStandard(\"LVCMOS33\")), # Leds (\"user_led\",", "Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\", 2, Subsignal(\"r\",", "Seven Segment (\"seven_seg_dig\", 0, Pins(\"137\"), IOStandard(\"LVCMOS33\")), (\"seven_seg_dig\", 1, Pins(\"140\"), IOStandard(\"LVCMOS33\")),", "self.toolchain.options[\"use_mspi_as_gpio\"] = 1 def create_programmer(self): return OpenFPGALoader(\"runber\") def do_finalize(self, fragment):", "6, Pins(\"82\"), IOStandard(\"LVCMOS33\")), (\"user_sw\", 7, Pins(\"83\"), IOStandard(\"LVCMOS33\")), # Buttons. (\"user_btn\",", "1, Subsignal(\"r\", Pins(\"106\")), Subsignal(\"g\", Pins(\"111\")), Subsignal(\"b\", Pins(\"110\")), IOStandard(\"LVCMOS33\"), ), (\"rgb_led\",", "5, Pins(\"28\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 6, Pins(\"29\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 7, Pins(\"30\"),", "), (\"rgb_led\", 2, Subsignal(\"r\", Pins(\"101\")), Subsignal(\"g\", Pins(\"104\")), Subsignal(\"b\", Pins(\"102\")), IOStandard(\"LVCMOS33\"),", "Pins(\"24\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 2, Pins(\"25\"), IOStandard(\"LVCMOS33\")), (\"user_led\", 3, Pins(\"26\"), IOStandard(\"LVCMOS33\")),", "# # Copyright (c) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause", "(\"serial\", 0, Subsignal(\"tx\", Pins(\"116\")), # J2.17 Subsignal(\"rx\", Pins(\"115\")), # J2.18", "IOStandard(\"LVCMOS33\")), (\"seven_seg\", 0, Pins(\"138 142 9 11 12 139 8" ]
[ "Z=Z) def random_search(self, max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True): N = int(num_search_each_probe)", "copy import combo.misc import cPickle as pickle from results import", "config=None): self.predictor = None self.training = variable() self.test = self._set_test(test_X)", "seed np.random.seed(self.seed) def delete_actions(self, index, actions=None): actions = self._set_unchosed_actions(actions) return", "is_disp=True): N = int(num_search_each_probe) if int(max_num_probes) * N > len(self.actions):", "try: predictor.update(train, virtual_train) except: predictor.prepare(train) f[n, :] = self.get_score(mode, predictor,", "bayes_search(self, training=None, max_num_probes=None, num_search_each_probe=1, predictor=None, is_disp=True, simulator=None, score='TS', interval=0, num_rand_basis=0):", "virtual_train) except: predictor.prepare(train) f[n, :] = self.get_score(mode, predictor, train) return", "self.training = variable() self.training.load(file_training) if file_predictor is not None: with", "\\ = self.predictor.get_predict_samples(self.training, new_test, N) for n in xrange(N): predictor", "seed): self.seed = seed np.random.seed(self.seed) def delete_actions(self, index, actions=None): actions", "virtual_train.Z is None: train.add(virtual_train.X, virtual_train.t) else: train.add(virtual_train.X, virtual_train.t, virtual_train.Z) try:", "self.history.write(t, action) self.training.add(X=X, t=t, Z=Z) def random_search(self, max_num_probes, num_search_each_probe=1, simulator=None,", "return self.predictor def export_training(self): return self.training def export_history(self): return self.history", "virtual_train.Z) try: predictor.update(train, virtual_train) except: predictor.prepare(train) f[n, :] = self.get_score(mode,", "for n in xrange(0, max_num_probes): if is_disp and N >", "action t, X = call_simulator(simulator, action) self.write(action, t, X) if", "f = combo.search.score.EI(predictor, training, test) elif mode == 'PI': f", "int(num_search_each_probe) for n in xrange(max_num_probes): if utility.is_learning(n, interval): self.predictor.fit(self.training, num_rand_basis)", "is None: actions = self.actions return actions def _set_test(self, test_X):", "= self.delete_actions(temp) chosed_actions = np.zeros(N, dtype=int) chosed_actions[0] = action for", "is None: N = self.history.total_num_search X = self.test.X[self.history.chosed_actions[0:N], :] t", "t, X) if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def bayes_search(self,", "= np.argmax(f) action = self.actions[temp] self.actions = self.delete_actions(temp) chosed_actions =", "self.training def export_history(self): return self.history def _set_predictor(self, predictor=None): if predictor", "self.seed = seed np.random.seed(self.seed) def delete_actions(self, index, actions=None): actions =", "virtual_t \\ = self.predictor.get_predict_samples(self.training, new_test, N) for n in xrange(N):", "self.predictor.get_basis(X) \\ if self.predictor is not None else None self.new_data", "except: self.predictor.prepare(self.training) if num_search_each_probe != 1: utility.show_start_message_multi_search(self.history.num_runs, score) K =", "len(self.actions): raise ValueError('max_num_probes * num_search_each_probe must \\ be smaller than", "= self.actions test = self.test.get_subset(actions) if mode == 'EI': f", "None: X = self.test.X[action, :] Z = self.test.Z[action, :] if", "def bayes_search(self, training=None, max_num_probes=None, num_search_each_probe=1, predictor=None, is_disp=True, simulator=None, score='TS', interval=0,", "action for n in xrange(1, N): f = self.get_marginal_score(mode, chosed_actions[0:n],", "def _set_unchosed_actions(self, actions=None): if actions is None: actions = self.actions", "self.actions[temp] self.actions = self.delete_actions(temp) return chosed_actions def get_random_action(self, N): random_index", "return test def _set_config(self, config=None): if config is None: config", "...variable import variable from ..call_simulator import call_simulator from ... import", "if num_search_each_probe != 1: utility.show_start_message_multi_search(self.history.num_runs, score) K = self.config.search.multi_probe_num_sampling alpha", "config=None): if config is None: config = combo.misc.set_config() return config", "None: with open(file_predictor) as f: self.predictor = pickle.load(f) def export_predictor(self):", "= combo.search.score.PI(predictor, training, test) elif mode == 'TS': f =", "actions def _set_test(self, test_X): if isinstance(test_X, np.ndarray): test = variable(X=test_X)", "score='TS', interval=0, num_rand_basis=0): if max_num_probes is None: max_num_probes = 1", "self.actions test = self.test.get_subset(actions) if mode == 'EI': f =", "predictor is None: predictor = self.predictor return predictor def _init_predictor(self,", "NotImplementedError('mode must be EI, PI or TS.') return f def", "test, alpha) else: raise NotImplementedError('mode must be EI, PI or", "def get_marginal_score(self, mode, chosed_actions, N, alpha): f = np.zeros((N, len(self.actions)))", "is_disp: utility.show_interactive_mode(simulator, self.history) for n in xrange(0, max_num_probes): if is_disp", "chosed_actions[0:n], K, alpha) temp = np.argmax(np.mean(f, 0)) chosed_actions[n] = self.actions[temp]", "return self.predictor def _set_training(self, training=None): if training is None: training", "int(20000) class policy: def __init__(self, test_X, config=None): self.predictor = None", "> 1: utility.show_start_message_multi_search(self.history.num_runs) action = self.get_random_action(N) if simulator is None:", "np.ndarray): test = variable(X=test_X) elif isinstance(test_X, variable): test = test_X", "t=t, Z=Z) def random_search(self, max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True): N =", "self.training return training def _set_unchosed_actions(self, actions=None): if actions is None:", "N > 1: utility.show_start_message_multi_search(self.history.num_runs) action = self.get_random_action(N) if simulator is", "np.argmax(f) action = self.actions[temp] self.actions = self.delete_actions(temp) chosed_actions = np.zeros(N,", "1 simulator = None is_rand_expans = False if num_rand_basis ==", "= gp_predictor(self.config) return self.predictor def _set_training(self, training=None): if training is", "candidates') if is_disp: utility.show_interactive_mode(simulator, self.history) for n in xrange(0, max_num_probes):", "training def _set_unchosed_actions(self, actions=None): if actions is None: actions =", "* N > len(self.actions): raise ValueError('max_num_probes * num_search_each_probe must \\", "else: try: self.predictor.update(self.training, self.new_data) except: self.predictor.prepare(self.training) if num_search_each_probe != 1:", "= 1 simulator = None is_rand_expans = False if num_rand_basis", "f = self.get_score(mode, self.predictor, self.training, alpha) temp = np.argmax(f) action", "file_training is None: N = self.history.total_num_search X = self.test.X[self.history.chosed_actions[0:N], :]", "== 'EI': f = combo.search.score.EI(predictor, training, test) elif mode ==", "action def load(self, file_history, file_training=None, file_predictor=None): self.history.load(file_history) if file_training is", "as gp_predictor from ...blm import predictor as blm_predictor import combo.search.score", "def set_seed(self, seed): self.seed = seed np.random.seed(self.seed) def delete_actions(self, index,", "test_X): if isinstance(test_X, np.ndarray): test = variable(X=test_X) elif isinstance(test_X, variable):", "self.predictor.prepare(self.training) if num_search_each_probe != 1: utility.show_start_message_multi_search(self.history.num_runs, score) K = self.config.search.multi_probe_num_sampling", "combo.search.score.PI(predictor, training, test) elif mode == 'TS': f = combo.search.score.TS(predictor,", "self.delete_actions(index) return action def load(self, file_history, file_training=None, file_predictor=None): self.history.load(file_history) if", "is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def get_score(self, mode, predictor=None, training=None,", "N): random_index = np.random.permutation(xrange(self.actions.shape[0])) index = random_index[0:N] action = self.actions[index]", "predictor = self.predictor return predictor def _init_predictor(self, is_rand_expans, predictor=None): self.predictor", "t=t) else: self.training = variable() self.training.load(file_training) if file_predictor is not", "def export_predictor(self): return self.predictor def export_training(self): return self.training def export_history(self):", "None: if is_rand_expans: self.predictor = blm_predictor(self.config) else: self.predictor = gp_predictor(self.config)", "delete_actions(self, index, actions=None): actions = self._set_unchosed_actions(actions) return np.delete(actions, index) def", "def delete_actions(self, index, actions=None): actions = self._set_unchosed_actions(actions) return np.delete(actions, index)", "max_num_probes = 1 simulator = None is_rand_expans = False if", "...blm import predictor as blm_predictor import combo.search.score MAX_SEACH = int(20000)", "= self.test.X[action, :] Z = self.test.Z[action, :] if self.test.Z is", "'TS': f = combo.search.score.TS(predictor, training, test, alpha) else: raise NotImplementedError('mode", "num_search_each_probe=1, predictor=None, is_disp=True, simulator=None, score='TS', interval=0, num_rand_basis=0): if max_num_probes is", "t, Z) self.history.write(t, action) self.training.add(X=X, t=t, Z=Z) def random_search(self, max_num_probes,", "set_seed(self, seed): self.seed = seed np.random.seed(self.seed) def delete_actions(self, index, actions=None):", "self.predictor, self.training, alpha) temp = np.argmax(f) action = self.actions[temp] self.actions", "def export_history(self): return self.history def _set_predictor(self, predictor=None): if predictor is", "blm_predictor(self.config) else: self.predictor = gp_predictor(self.config) return self.predictor def _set_training(self, training=None):", "= new_test virtual_train.t = virtual_t[n, :] if virtual_train.Z is None:", "self.test.X[self.history.chosed_actions[0:N], :] t = self.history.fx[0:N] self.training = variable(X=X, t=t) else:", "of candidates') if is_disp: utility.show_interactive_mode(simulator, self.history) for n in xrange(0,", "np import copy import combo.misc import cPickle as pickle from", "as pickle from results import history from .. import utility", "f: self.predictor = pickle.load(f) def export_predictor(self): return self.predictor def export_training(self):", "self.history.fx[0:N] self.training = variable(X=X, t=t) else: self.training = variable() self.training.load(file_training)", "self._set_unchosed_actions(actions) return np.delete(actions, index) def write(self, action, t, X=None): if", "np.delete(actions, index) def write(self, action, t, X=None): if X is", "= self.training return training def _set_unchosed_actions(self, actions=None): if actions is", "test def _set_config(self, config=None): if config is None: config =", "self.actions = np.arange(0, self.test.X.shape[0]) self.history = history() self.config = self._set_config(config)", "alpha) temp = np.argmax(np.mean(f, 0)) chosed_actions[n] = self.actions[temp] self.actions =", "and N > 1: utility.show_start_message_multi_search(self.history.num_runs) action = self.get_random_action(N) if simulator", "predictor = copy.deepcopy(self.predictor) train = copy.deepcopy(self.training) virtual_train = new_test virtual_train.t", "= self.get_score(mode, predictor, train) return f def get_actions(self, mode, N,", "int(max_num_probes) * N > len(self.actions): raise ValueError('max_num_probes * num_search_each_probe must", "def write(self, action, t, X=None): if X is None: X", "combo.misc import cPickle as pickle from results import history from", "X = call_simulator(simulator, action) self.write(action, t, X) if is_disp: utility.show_search_results(self.history,", "utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def bayes_search(self, training=None, max_num_probes=None, num_search_each_probe=1, predictor=None,", "= seed np.random.seed(self.seed) def delete_actions(self, index, actions=None): actions = self._set_unchosed_actions(actions)", "index) def write(self, action, t, X=None): if X is None:", "in xrange(1, N): f = self.get_marginal_score(mode, chosed_actions[0:n], K, alpha) temp", "import numpy as np import copy import combo.misc import cPickle", "alpha) temp = np.argmax(f) action = self.actions[temp] self.actions = self.delete_actions(temp)", "as blm_predictor import combo.search.score MAX_SEACH = int(20000) class policy: def", "alpha): f = self.get_score(mode, self.predictor, self.training, alpha) temp = np.argmax(f)", "self.predictor.update(self.training, self.new_data) except: self.predictor.prepare(self.training) if num_search_each_probe != 1: utility.show_start_message_multi_search(self.history.num_runs, score)", "def _set_config(self, config=None): if config is None: config = combo.misc.set_config()", "the length of candidates') if is_disp: utility.show_interactive_mode(simulator, self.history) for n", "= predictor N = int(num_search_each_probe) for n in xrange(max_num_probes): if", "f = self.get_marginal_score(mode, chosed_actions[0:n], K, alpha) temp = np.argmax(np.mean(f, 0))", "N) for n in xrange(N): predictor = copy.deepcopy(self.predictor) train =", "self.test = self._set_test(test_X) self.actions = np.arange(0, self.test.X.shape[0]) self.history = history()", "N > len(self.actions): raise ValueError('max_num_probes * num_search_each_probe must \\ be", "= self.get_marginal_score(mode, chosed_actions[0:n], K, alpha) temp = np.argmax(np.mean(f, 0)) chosed_actions[n]", "training, test) elif mode == 'TS': f = combo.search.score.TS(predictor, training,", "xrange(1, N): f = self.get_marginal_score(mode, chosed_actions[0:n], K, alpha) temp =", "if self.predictor is not None else None self.new_data = variable(X,", "is None: max_num_probes = 1 simulator = None is_rand_expans =", "if file_predictor is not None: with open(file_predictor) as f: self.predictor", "self.predictor = self._init_predictor(is_rand_expans) else: self.predictor = predictor N = int(num_search_each_probe)", "len(self.actions))) new_test = self.test.get_subset(chosed_actions) virtual_t \\ = self.predictor.get_predict_samples(self.training, new_test, N)", "= self.config.search.multi_probe_num_sampling alpha = self.config.search.alpha action = self.get_actions(score, N, K,", "in xrange(max_num_probes): if utility.is_learning(n, interval): self.predictor.fit(self.training, num_rand_basis) self.test.Z = self.predictor.get_basis(self.test.X)", "isinstance(test_X, np.ndarray): test = variable(X=test_X) elif isinstance(test_X, variable): test =", "t, X = call_simulator(simulator, action) self.write(action, t, X) if is_disp:", "= np.random.permutation(xrange(self.actions.shape[0])) index = random_index[0:N] action = self.actions[index] self.actions =", "try: self.predictor.update(self.training, self.new_data) except: self.predictor.prepare(self.training) if num_search_each_probe != 1: utility.show_start_message_multi_search(self.history.num_runs,", "self.write(action, t, X) if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def", "== 'PI': f = combo.search.score.PI(predictor, training, test) elif mode ==", "not None: with open(file_predictor) as f: self.predictor = pickle.load(f) def", "predictor def _init_predictor(self, is_rand_expans, predictor=None): self.predictor = self._set_predictor(predictor) if self.predictor", "train.add(virtual_train.X, virtual_train.t) else: train.add(virtual_train.X, virtual_train.t, virtual_train.Z) try: predictor.update(train, virtual_train) except:", "pickle.load(f) def export_predictor(self): return self.predictor def export_training(self): return self.training def", "if utility.is_learning(n, interval): self.predictor.fit(self.training, num_rand_basis) self.test.Z = self.predictor.get_basis(self.test.X) self.training.Z =", "utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def get_score(self, mode, predictor=None, training=None, alpha=1):", "self.predictor = pickle.load(f) def export_predictor(self): return self.predictor def export_training(self): return", "== 'TS': f = combo.search.score.TS(predictor, training, test, alpha) else: raise", "\\ if self.predictor is not None else None self.new_data =", "virtual_train.t = virtual_t[n, :] if virtual_train.Z is None: train.add(virtual_train.X, virtual_train.t)", "> len(self.actions): raise ValueError('max_num_probes * num_search_each_probe must \\ be smaller", "= combo.search.score.EI(predictor, training, test) elif mode == 'PI': f =", "virtual_train.t, virtual_train.Z) try: predictor.update(train, virtual_train) except: predictor.prepare(train) f[n, :] =", "get_actions(self, mode, N, K, alpha): f = self.get_score(mode, self.predictor, self.training,", "= variable(X=test_X) elif isinstance(test_X, variable): test = test_X else: raise", "None: predictor = self.predictor return predictor def _init_predictor(self, is_rand_expans, predictor=None):", "elif isinstance(test_X, variable): test = test_X else: raise TypeError('The type", "== 0 else True self.training = self._set_training(training) if predictor is", "from .. import utility from ...variable import variable from ..call_simulator", "if is_disp: utility.show_interactive_mode(simulator, self.history) for n in xrange(0, max_num_probes): if", "training=None): if training is None: training = self.training return training", "as np import copy import combo.misc import cPickle as pickle", "max_num_probes): if is_disp and N > 1: utility.show_start_message_multi_search(self.history.num_runs) action =", "must \\ be smaller than the length of candidates') if", "'PI': f = combo.search.score.PI(predictor, training, test) elif mode == 'TS':", "= np.zeros(N, dtype=int) chosed_actions[0] = action for n in xrange(1,", "None else: Z = self.predictor.get_basis(X) \\ if self.predictor is not", "else: Z = self.predictor.get_basis(X) \\ if self.predictor is not None", "= self.get_score(mode, self.predictor, self.training, alpha) temp = np.argmax(f) action =", "gp_predictor(self.config) return self.predictor def _set_training(self, training=None): if training is None:", "not None else None self.new_data = variable(X, t, Z) self.history.write(t,", "= self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else: try: self.predictor.update(self.training, self.new_data) except: self.predictor.prepare(self.training) if", "= self._init_predictor(is_rand_expans) else: self.predictor = predictor N = int(num_search_each_probe) for", "f def get_marginal_score(self, mode, chosed_actions, N, alpha): f = np.zeros((N,", "predictor from ...gp import predictor as gp_predictor from ...blm import", "t, X=None): if X is None: X = self.test.X[action, :]", "import predictor as blm_predictor import combo.search.score MAX_SEACH = int(20000) class", "predictor N = int(num_search_each_probe) for n in xrange(max_num_probes): if utility.is_learning(n,", "= call_simulator(simulator, action) self.write(action, t, X) if is_disp: utility.show_search_results(self.history, N)", "f = np.zeros((N, len(self.actions))) new_test = self.test.get_subset(chosed_actions) virtual_t \\ =", "action = self.actions[temp] self.actions = self.delete_actions(temp) chosed_actions = np.zeros(N, dtype=int)", "..call_simulator import call_simulator from ... import predictor from ...gp import", "... import predictor from ...gp import predictor as gp_predictor from", "utility.show_start_message_multi_search(self.history.num_runs, score) K = self.config.search.multi_probe_num_sampling alpha = self.config.search.alpha action =", "else: raise NotImplementedError('mode must be EI, PI or TS.') return", "num_search_each_probe != 1: utility.show_start_message_multi_search(self.history.num_runs, score) K = self.config.search.multi_probe_num_sampling alpha =", "import utility from ...variable import variable from ..call_simulator import call_simulator", "action) self.write(action, t, X) if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history)", "if self.test.Z is not None else None else: Z =", "self.actions[index] self.actions = self.delete_actions(index) return action def load(self, file_history, file_training=None,", "= np.arange(0, self.test.X.shape[0]) self.history = history() self.config = self._set_config(config) def", "= history() self.config = self._set_config(config) def set_seed(self, seed): self.seed =", "= int(20000) class policy: def __init__(self, test_X, config=None): self.predictor =", "mode == 'TS': f = combo.search.score.TS(predictor, training, test, alpha) else:", "if num_rand_basis == 0 else True self.training = self._set_training(training) if", "virtual_train = new_test virtual_train.t = virtual_t[n, :] if virtual_train.Z is", "= np.argmax(np.mean(f, 0)) chosed_actions[n] = self.actions[temp] self.actions = self.delete_actions(temp) return", "actions = self._set_unchosed_actions(actions) return np.delete(actions, index) def write(self, action, t,", "= self.predictor.get_basis(self.test.X) self.training.Z = self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else: try: self.predictor.update(self.training, self.new_data)", "except: predictor.prepare(train) f[n, :] = self.get_score(mode, predictor, train) return f", "predictor=None): if predictor is None: predictor = self.predictor return predictor", "cPickle as pickle from results import history from .. import", "self.get_actions(score, N, K, alpha) if simulator is None: return action", "np.zeros((N, len(self.actions))) new_test = self.test.get_subset(chosed_actions) virtual_t \\ = self.predictor.get_predict_samples(self.training, new_test,", "_init_predictor(self, is_rand_expans, predictor=None): self.predictor = self._set_predictor(predictor) if self.predictor is None:", "if X is None: X = self.test.X[action, :] Z =", "self.training, alpha) temp = np.argmax(f) action = self.actions[temp] self.actions =", "return copy.deepcopy(self.history) def bayes_search(self, training=None, max_num_probes=None, num_search_each_probe=1, predictor=None, is_disp=True, simulator=None,", "t = self.history.fx[0:N] self.training = variable(X=X, t=t) else: self.training =", "self.test.X.shape[0]) self.history = history() self.config = self._set_config(config) def set_seed(self, seed):", "n in xrange(max_num_probes): if utility.is_learning(n, interval): self.predictor.fit(self.training, num_rand_basis) self.test.Z =", "predictor as gp_predictor from ...blm import predictor as blm_predictor import", "self.get_marginal_score(mode, chosed_actions[0:n], K, alpha) temp = np.argmax(np.mean(f, 0)) chosed_actions[n] =", "is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def bayes_search(self, training=None, max_num_probes=None, num_search_each_probe=1,", "must \\ take ndarray or combo.variable') return test def _set_config(self,", "self.actions return actions def _set_test(self, test_X): if isinstance(test_X, np.ndarray): test", "None else None else: Z = self.predictor.get_basis(X) \\ if self.predictor", "self.history.total_num_search X = self.test.X[self.history.chosed_actions[0:N], :] t = self.history.fx[0:N] self.training =", "export_predictor(self): return self.predictor def export_training(self): return self.training def export_history(self): return", "N): f = self.get_marginal_score(mode, chosed_actions[0:n], K, alpha) temp = np.argmax(np.mean(f,", "if training is None: training = self.training return training def", "history from .. import utility from ...variable import variable from", "ndarray or combo.variable') return test def _set_config(self, config=None): if config", "simulator is None: return action t, X = call_simulator(simulator, action)", "self.training = variable(X=X, t=t) else: self.training = variable() self.training.load(file_training) if", "type of test_X must \\ take ndarray or combo.variable') return", "self.predictor = gp_predictor(self.config) return self.predictor def _set_training(self, training=None): if training", "np.random.seed(self.seed) def delete_actions(self, index, actions=None): actions = self._set_unchosed_actions(actions) return np.delete(actions,", "alpha=1): self._set_training(training) self._set_predictor(predictor) actions = self.actions test = self.test.get_subset(actions) if", "as f: self.predictor = pickle.load(f) def export_predictor(self): return self.predictor def", "N) return copy.deepcopy(self.history) def bayes_search(self, training=None, max_num_probes=None, num_search_each_probe=1, predictor=None, is_disp=True,", "Z = self.test.Z[action, :] if self.test.Z is not None else", "self._set_training(training) self._set_predictor(predictor) actions = self.actions test = self.test.get_subset(actions) if mode", "if is_rand_expans: self.predictor = blm_predictor(self.config) else: self.predictor = gp_predictor(self.config) return", "actions = self.actions return actions def _set_test(self, test_X): if isinstance(test_X,", "test_X, config=None): self.predictor = None self.training = variable() self.test =", "call_simulator(simulator, action) self.write(action, t, X) if is_disp: utility.show_search_results(self.history, N) return", "= self.test.Z[action, :] if self.test.Z is not None else None", "import call_simulator from ... import predictor from ...gp import predictor", "self.test.get_subset(chosed_actions) virtual_t \\ = self.predictor.get_predict_samples(self.training, new_test, N) for n in", "for n in xrange(max_num_probes): if utility.is_learning(n, interval): self.predictor.fit(self.training, num_rand_basis) self.test.Z", "copy.deepcopy(self.history) def get_score(self, mode, predictor=None, training=None, alpha=1): self._set_training(training) self._set_predictor(predictor) actions", "virtual_train.t) else: train.add(virtual_train.X, virtual_train.t, virtual_train.Z) try: predictor.update(train, virtual_train) except: predictor.prepare(train)", "f def get_actions(self, mode, N, K, alpha): f = self.get_score(mode,", "if actions is None: actions = self.actions return actions def", "training is None: training = self.training return training def _set_unchosed_actions(self,", "= combo.search.score.TS(predictor, training, test, alpha) else: raise NotImplementedError('mode must be", "= variable() self.test = self._set_test(test_X) self.actions = np.arange(0, self.test.X.shape[0]) self.history", "elif mode == 'TS': f = combo.search.score.TS(predictor, training, test, alpha)", "self.test.Z[action, :] if self.test.Z is not None else None else:", "pickle from results import history from .. import utility from", "is None: self.predictor = self._init_predictor(is_rand_expans) else: self.predictor = predictor N", "return copy.deepcopy(self.history) def get_score(self, mode, predictor=None, training=None, alpha=1): self._set_training(training) self._set_predictor(predictor)", "chosed_actions def get_random_action(self, N): random_index = np.random.permutation(xrange(self.actions.shape[0])) index = random_index[0:N]", "self.actions = self.delete_actions(temp) chosed_actions = np.zeros(N, dtype=int) chosed_actions[0] = action", "\\ take ndarray or combo.variable') return test def _set_config(self, config=None):", "from ...gp import predictor as gp_predictor from ...blm import predictor", "history() self.config = self._set_config(config) def set_seed(self, seed): self.seed = seed", "self.predictor.prepare(self.training) else: try: self.predictor.update(self.training, self.new_data) except: self.predictor.prepare(self.training) if num_search_each_probe !=", "max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True): N = int(num_search_each_probe) if int(max_num_probes) *", "temp = np.argmax(f) action = self.actions[temp] self.actions = self.delete_actions(temp) chosed_actions", "chosed_actions[0] = action for n in xrange(1, N): f =", "else True self.training = self._set_training(training) if predictor is None: self.predictor", "X = self.test.X[action, :] Z = self.test.Z[action, :] if self.test.Z", "mode, predictor=None, training=None, alpha=1): self._set_training(training) self._set_predictor(predictor) actions = self.actions test", "self.new_data = variable(X, t, Z) self.history.write(t, action) self.training.add(X=X, t=t, Z=Z)", "K, alpha) if simulator is None: return action t, X", "= variable(X=X, t=t) else: self.training = variable() self.training.load(file_training) if file_predictor", "import history from .. import utility from ...variable import variable", "import copy import combo.misc import cPickle as pickle from results", "None: return action t, X = call_simulator(simulator, action) self.write(action, t,", "is not None: with open(file_predictor) as f: self.predictor = pickle.load(f)", "variable(X=X, t=t) else: self.training = variable() self.training.load(file_training) if file_predictor is", "with open(file_predictor) as f: self.predictor = pickle.load(f) def export_predictor(self): return", "def _init_predictor(self, is_rand_expans, predictor=None): self.predictor = self._set_predictor(predictor) if self.predictor is", "raise ValueError('max_num_probes * num_search_each_probe must \\ be smaller than the", "copy.deepcopy(self.history) def bayes_search(self, training=None, max_num_probes=None, num_search_each_probe=1, predictor=None, is_disp=True, simulator=None, score='TS',", "class policy: def __init__(self, test_X, config=None): self.predictor = None self.training", "variable() self.training.load(file_training) if file_predictor is not None: with open(file_predictor) as", "if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def get_score(self, mode, predictor=None,", "dtype=int) chosed_actions[0] = action for n in xrange(1, N): f", "None: training = self.training return training def _set_unchosed_actions(self, actions=None): if", "0)) chosed_actions[n] = self.actions[temp] self.actions = self.delete_actions(temp) return chosed_actions def", "return self.training def export_history(self): return self.history def _set_predictor(self, predictor=None): if", "alpha) if simulator is None: return action t, X =", "is None: return action t, X = call_simulator(simulator, action) self.write(action,", "def load(self, file_history, file_training=None, file_predictor=None): self.history.load(file_history) if file_training is None:", "self.actions = self.delete_actions(index) return action def load(self, file_history, file_training=None, file_predictor=None):", "is_disp and N > 1: utility.show_start_message_multi_search(self.history.num_runs) action = self.get_random_action(N) if", "training=None, alpha=1): self._set_training(training) self._set_predictor(predictor) actions = self.actions test = self.test.get_subset(actions)", "= self._set_test(test_X) self.actions = np.arange(0, self.test.X.shape[0]) self.history = history() self.config", "self.test.get_subset(actions) if mode == 'EI': f = combo.search.score.EI(predictor, training, test)", "self.training = self._set_training(training) if predictor is None: self.predictor = self._init_predictor(is_rand_expans)", "= self.actions[temp] self.actions = self.delete_actions(temp) return chosed_actions def get_random_action(self, N):", "write(self, action, t, X=None): if X is None: X =", "open(file_predictor) as f: self.predictor = pickle.load(f) def export_predictor(self): return self.predictor", "self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else: try: self.predictor.update(self.training, self.new_data) except: self.predictor.prepare(self.training) if num_search_each_probe", "score) K = self.config.search.multi_probe_num_sampling alpha = self.config.search.alpha action = self.get_actions(score,", "action, t, X=None): if X is None: X = self.test.X[action,", "predictor.update(train, virtual_train) except: predictor.prepare(train) f[n, :] = self.get_score(mode, predictor, train)", "= None is_rand_expans = False if num_rand_basis == 0 else", "self._set_test(test_X) self.actions = np.arange(0, self.test.X.shape[0]) self.history = history() self.config =", "not None else None else: Z = self.predictor.get_basis(X) \\ if", "get_random_action(self, N): random_index = np.random.permutation(xrange(self.actions.shape[0])) index = random_index[0:N] action =", "random_index[0:N] action = self.actions[index] self.actions = self.delete_actions(index) return action def", "actions=None): if actions is None: actions = self.actions return actions", "is not None else None else: Z = self.predictor.get_basis(X) \\", "= self.config.search.alpha action = self.get_actions(score, N, K, alpha) if simulator", "blm_predictor import combo.search.score MAX_SEACH = int(20000) class policy: def __init__(self,", "self.get_score(mode, self.predictor, self.training, alpha) temp = np.argmax(f) action = self.actions[temp]", "t, X) if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def get_score(self,", "N) return copy.deepcopy(self.history) def get_score(self, mode, predictor=None, training=None, alpha=1): self._set_training(training)", "= self.actions[temp] self.actions = self.delete_actions(temp) chosed_actions = np.zeros(N, dtype=int) chosed_actions[0]", "if self.predictor is None: if is_rand_expans: self.predictor = blm_predictor(self.config) else:", "virtual_t[n, :] if virtual_train.Z is None: train.add(virtual_train.X, virtual_train.t) else: train.add(virtual_train.X,", "= blm_predictor(self.config) else: self.predictor = gp_predictor(self.config) return self.predictor def _set_training(self,", "utility.show_interactive_mode(simulator, self.history) for n in xrange(0, max_num_probes): if is_disp and", "test) elif mode == 'TS': f = combo.search.score.TS(predictor, training, test,", "is_rand_expans: self.predictor = blm_predictor(self.config) else: self.predictor = gp_predictor(self.config) return self.predictor", "self.history) for n in xrange(0, max_num_probes): if is_disp and N", "np.zeros(N, dtype=int) chosed_actions[0] = action for n in xrange(1, N):", "self.actions = self.delete_actions(temp) return chosed_actions def get_random_action(self, N): random_index =", "None else None self.new_data = variable(X, t, Z) self.history.write(t, action)", "def get_actions(self, mode, N, K, alpha): f = self.get_score(mode, self.predictor,", "N = int(num_search_each_probe) for n in xrange(max_num_probes): if utility.is_learning(n, interval):", "def export_training(self): return self.training def export_history(self): return self.history def _set_predictor(self,", "K, alpha) temp = np.argmax(np.mean(f, 0)) chosed_actions[n] = self.actions[temp] self.actions", "predictor=None, training=None, alpha=1): self._set_training(training) self._set_predictor(predictor) actions = self.actions test =", "return training def _set_unchosed_actions(self, actions=None): if actions is None: actions", "temp = np.argmax(np.mean(f, 0)) chosed_actions[n] = self.actions[temp] self.actions = self.delete_actions(temp)", "K, alpha): f = self.get_score(mode, self.predictor, self.training, alpha) temp =", "results import history from .. import utility from ...variable import", "train) return f def get_actions(self, mode, N, K, alpha): f", "mode, chosed_actions, N, alpha): f = np.zeros((N, len(self.actions))) new_test =", "file_history, file_training=None, file_predictor=None): self.history.load(file_history) if file_training is None: N =", "return action t, X = call_simulator(simulator, action) self.write(action, t, X)", "predictor=None, is_disp=True, simulator=None, score='TS', interval=0, num_rand_basis=0): if max_num_probes is None:", "if predictor is None: predictor = self.predictor return predictor def", "else: raise TypeError('The type of test_X must \\ take ndarray", "0 else True self.training = self._set_training(training) if predictor is None:", "policy: def __init__(self, test_X, config=None): self.predictor = None self.training =", "PI or TS.') return f def get_marginal_score(self, mode, chosed_actions, N,", "else: self.predictor = gp_predictor(self.config) return self.predictor def _set_training(self, training=None): if", "mode, N, K, alpha): f = self.get_score(mode, self.predictor, self.training, alpha)", "return self.history def _set_predictor(self, predictor=None): if predictor is None: predictor", "self.config.search.alpha action = self.get_actions(score, N, K, alpha) if simulator is", "self.test.Z is not None else None else: Z = self.predictor.get_basis(X)", "chosed_actions[n] = self.actions[temp] self.actions = self.delete_actions(temp) return chosed_actions def get_random_action(self,", "import combo.misc import cPickle as pickle from results import history", "self.predictor is not None else None self.new_data = variable(X, t,", "combo.search.score MAX_SEACH = int(20000) class policy: def __init__(self, test_X, config=None):", "if predictor is None: self.predictor = self._init_predictor(is_rand_expans) else: self.predictor =", "None is_rand_expans = False if num_rand_basis == 0 else True", "be EI, PI or TS.') return f def get_marginal_score(self, mode,", "if is_disp and N > 1: utility.show_start_message_multi_search(self.history.num_runs) action = self.get_random_action(N)", "np.random.permutation(xrange(self.actions.shape[0])) index = random_index[0:N] action = self.actions[index] self.actions = self.delete_actions(index)", "num_rand_basis == 0 else True self.training = self._set_training(training) if predictor", "train = copy.deepcopy(self.training) virtual_train = new_test virtual_train.t = virtual_t[n, :]", "utility.show_start_message_multi_search(self.history.num_runs) action = self.get_random_action(N) if simulator is None: return action", "_set_config(self, config=None): if config is None: config = combo.misc.set_config() return", "actions is None: actions = self.actions return actions def _set_test(self,", "_set_test(self, test_X): if isinstance(test_X, np.ndarray): test = variable(X=test_X) elif isinstance(test_X,", "if max_num_probes is None: max_num_probes = 1 simulator = None", "def random_search(self, max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True): N = int(num_search_each_probe) if", "= self.predictor.get_basis(X) \\ if self.predictor is not None else None", "interval=0, num_rand_basis=0): if max_num_probes is None: max_num_probes = 1 simulator", "else None else: Z = self.predictor.get_basis(X) \\ if self.predictor is", "def __init__(self, test_X, config=None): self.predictor = None self.training = variable()", "N, alpha): f = np.zeros((N, len(self.actions))) new_test = self.test.get_subset(chosed_actions) virtual_t", "get_score(self, mode, predictor=None, training=None, alpha=1): self._set_training(training) self._set_predictor(predictor) actions = self.actions", "None: N = self.history.total_num_search X = self.test.X[self.history.chosed_actions[0:N], :] t =", "def get_score(self, mode, predictor=None, training=None, alpha=1): self._set_training(training) self._set_predictor(predictor) actions =", "= self.predictor return predictor def _init_predictor(self, is_rand_expans, predictor=None): self.predictor =", "TypeError('The type of test_X must \\ take ndarray or combo.variable')", "!= 1: utility.show_start_message_multi_search(self.history.num_runs, score) K = self.config.search.multi_probe_num_sampling alpha = self.config.search.alpha", "action = self.actions[index] self.actions = self.delete_actions(index) return action def load(self,", "is None: train.add(virtual_train.X, virtual_train.t) else: train.add(virtual_train.X, virtual_train.t, virtual_train.Z) try: predictor.update(train,", ".. import utility from ...variable import variable from ..call_simulator import", "self.predictor = blm_predictor(self.config) else: self.predictor = gp_predictor(self.config) return self.predictor def", "= self._set_config(config) def set_seed(self, seed): self.seed = seed np.random.seed(self.seed) def", "for n in xrange(N): predictor = copy.deepcopy(self.predictor) train = copy.deepcopy(self.training)", ":] t = self.history.fx[0:N] self.training = variable(X=X, t=t) else: self.training", "new_test, N) for n in xrange(N): predictor = copy.deepcopy(self.predictor) train", "self.history = history() self.config = self._set_config(config) def set_seed(self, seed): self.seed", "variable from ..call_simulator import call_simulator from ... import predictor from", "interval): self.predictor.fit(self.training, num_rand_basis) self.test.Z = self.predictor.get_basis(self.test.X) self.training.Z = self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training)", "predictor is None: self.predictor = self._init_predictor(is_rand_expans) else: self.predictor = predictor", "test) elif mode == 'PI': f = combo.search.score.PI(predictor, training, test)", "simulator=None, is_disp=True): N = int(num_search_each_probe) if int(max_num_probes) * N >", "= test_X else: raise TypeError('The type of test_X must \\", "np.arange(0, self.test.X.shape[0]) self.history = history() self.config = self._set_config(config) def set_seed(self,", "combo.search.score.TS(predictor, training, test, alpha) else: raise NotImplementedError('mode must be EI,", "self.config.search.multi_probe_num_sampling alpha = self.config.search.alpha action = self.get_actions(score, N, K, alpha)", "combo.variable') return test def _set_config(self, config=None): if config is None:", "else None self.new_data = variable(X, t, Z) self.history.write(t, action) self.training.add(X=X,", "if mode == 'EI': f = combo.search.score.EI(predictor, training, test) elif", "file_predictor=None): self.history.load(file_history) if file_training is None: N = self.history.total_num_search X", "import variable from ..call_simulator import call_simulator from ... import predictor", "def get_random_action(self, N): random_index = np.random.permutation(xrange(self.actions.shape[0])) index = random_index[0:N] action", "action = self.get_random_action(N) if simulator is None: return action t,", "return np.delete(actions, index) def write(self, action, t, X=None): if X", "_set_predictor(self, predictor=None): if predictor is None: predictor = self.predictor return", "test_X else: raise TypeError('The type of test_X must \\ take", "from ..call_simulator import call_simulator from ... import predictor from ...gp", "self.predictor = None self.training = variable() self.test = self._set_test(test_X) self.actions", "training = self.training return training def _set_unchosed_actions(self, actions=None): if actions", "self.test.X[action, :] Z = self.test.Z[action, :] if self.test.Z is not", "= np.zeros((N, len(self.actions))) new_test = self.test.get_subset(chosed_actions) virtual_t \\ = self.predictor.get_predict_samples(self.training,", "length of candidates') if is_disp: utility.show_interactive_mode(simulator, self.history) for n in", "is None: predictor = self.predictor return predictor def _init_predictor(self, is_rand_expans,", "= self.test.get_subset(chosed_actions) virtual_t \\ = self.predictor.get_predict_samples(self.training, new_test, N) for n", "test = test_X else: raise TypeError('The type of test_X must", "= self.actions return actions def _set_test(self, test_X): if isinstance(test_X, np.ndarray):", "actions = self.actions test = self.test.get_subset(actions) if mode == 'EI':", "= self.predictor.get_predict_samples(self.training, new_test, N) for n in xrange(N): predictor =", "num_search_each_probe=1, simulator=None, is_disp=True): N = int(num_search_each_probe) if int(max_num_probes) * N", "else: self.predictor = predictor N = int(num_search_each_probe) for n in", "_set_training(self, training=None): if training is None: training = self.training return", "or TS.') return f def get_marginal_score(self, mode, chosed_actions, N, alpha):", "is None: if is_rand_expans: self.predictor = blm_predictor(self.config) else: self.predictor =", "training=None, max_num_probes=None, num_search_each_probe=1, predictor=None, is_disp=True, simulator=None, score='TS', interval=0, num_rand_basis=0): if", "self.predictor def export_training(self): return self.training def export_history(self): return self.history def", "alpha = self.config.search.alpha action = self.get_actions(score, N, K, alpha) if", "copy.deepcopy(self.training) virtual_train = new_test virtual_train.t = virtual_t[n, :] if virtual_train.Z", "in xrange(N): predictor = copy.deepcopy(self.predictor) train = copy.deepcopy(self.training) virtual_train =", "in xrange(0, max_num_probes): if is_disp and N > 1: utility.show_start_message_multi_search(self.history.num_runs)", "= self._set_predictor(predictor) if self.predictor is None: if is_rand_expans: self.predictor =", "self._set_predictor(predictor) if self.predictor is None: if is_rand_expans: self.predictor = blm_predictor(self.config)", "self.training.Z = self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else: try: self.predictor.update(self.training, self.new_data) except: self.predictor.prepare(self.training)", "predictor=None): self.predictor = self._set_predictor(predictor) if self.predictor is None: if is_rand_expans:", "X=None): if X is None: X = self.test.X[action, :] Z", "from ...blm import predictor as blm_predictor import combo.search.score MAX_SEACH =", "None: self.predictor = self._init_predictor(is_rand_expans) else: self.predictor = predictor N =", "call_simulator from ... import predictor from ...gp import predictor as", ":] Z = self.test.Z[action, :] if self.test.Z is not None", "__init__(self, test_X, config=None): self.predictor = None self.training = variable() self.test", "self.get_random_action(N) if simulator is None: return action t, X =", ":] if self.test.Z is not None else None else: Z", "self._set_training(training) if predictor is None: self.predictor = self._init_predictor(is_rand_expans) else: self.predictor", "= self.test.X[self.history.chosed_actions[0:N], :] t = self.history.fx[0:N] self.training = variable(X=X, t=t)", "else: self.training = variable() self.training.load(file_training) if file_predictor is not None:", "EI, PI or TS.') return f def get_marginal_score(self, mode, chosed_actions,", "self.predictor.get_predict_samples(self.training, new_test, N) for n in xrange(N): predictor = copy.deepcopy(self.predictor)", "test_X must \\ take ndarray or combo.variable') return test def", "return chosed_actions def get_random_action(self, N): random_index = np.random.permutation(xrange(self.actions.shape[0])) index =", "export_history(self): return self.history def _set_predictor(self, predictor=None): if predictor is None:", "1: utility.show_start_message_multi_search(self.history.num_runs, score) K = self.config.search.multi_probe_num_sampling alpha = self.config.search.alpha action", "= pickle.load(f) def export_predictor(self): return self.predictor def export_training(self): return self.training", "self.delete_actions(temp) return chosed_actions def get_random_action(self, N): random_index = np.random.permutation(xrange(self.actions.shape[0])) index", "f[n, :] = self.get_score(mode, predictor, train) return f def get_actions(self,", "np.argmax(np.mean(f, 0)) chosed_actions[n] = self.actions[temp] self.actions = self.delete_actions(temp) return chosed_actions", "chosed_actions, N, alpha): f = np.zeros((N, len(self.actions))) new_test = self.test.get_subset(chosed_actions)", "False if num_rand_basis == 0 else True self.training = self._set_training(training)", "of test_X must \\ take ndarray or combo.variable') return test", "variable(X, t, Z) self.history.write(t, action) self.training.add(X=X, t=t, Z=Z) def random_search(self,", "Z = self.predictor.get_basis(X) \\ if self.predictor is not None else", "f = combo.search.score.PI(predictor, training, test) elif mode == 'TS': f", "mode == 'EI': f = combo.search.score.EI(predictor, training, test) elif mode", "if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def bayes_search(self, training=None, max_num_probes=None,", ":] if virtual_train.Z is None: train.add(virtual_train.X, virtual_train.t) else: train.add(virtual_train.X, virtual_train.t,", "predictor as blm_predictor import combo.search.score MAX_SEACH = int(20000) class policy:", "return f def get_actions(self, mode, N, K, alpha): f =", "smaller than the length of candidates') if is_disp: utility.show_interactive_mode(simulator, self.history)", "N = int(num_search_each_probe) if int(max_num_probes) * N > len(self.actions): raise", "= self.delete_actions(temp) return chosed_actions def get_random_action(self, N): random_index = np.random.permutation(xrange(self.actions.shape[0]))", "is_rand_expans, predictor=None): self.predictor = self._set_predictor(predictor) if self.predictor is None: if", "variable() self.test = self._set_test(test_X) self.actions = np.arange(0, self.test.X.shape[0]) self.history =", "num_search_each_probe must \\ be smaller than the length of candidates')", "self.test.Z = self.predictor.get_basis(self.test.X) self.training.Z = self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else: try: self.predictor.update(self.training,", "else: train.add(virtual_train.X, virtual_train.t, virtual_train.Z) try: predictor.update(train, virtual_train) except: predictor.prepare(train) f[n,", "variable): test = test_X else: raise TypeError('The type of test_X", "self.predictor = self._set_predictor(predictor) if self.predictor is None: if is_rand_expans: self.predictor", "self.training.load(file_training) if file_predictor is not None: with open(file_predictor) as f:", "'EI': f = combo.search.score.EI(predictor, training, test) elif mode == 'PI':", "numpy as np import copy import combo.misc import cPickle as", "= self.history.total_num_search X = self.test.X[self.history.chosed_actions[0:N], :] t = self.history.fx[0:N] self.training", "is not None else None self.new_data = variable(X, t, Z)", "= action for n in xrange(1, N): f = self.get_marginal_score(mode,", "self.config = self._set_config(config) def set_seed(self, seed): self.seed = seed np.random.seed(self.seed)", "isinstance(test_X, variable): test = test_X else: raise TypeError('The type of", "= self.actions[index] self.actions = self.delete_actions(index) return action def load(self, file_history,", "self.delete_actions(temp) chosed_actions = np.zeros(N, dtype=int) chosed_actions[0] = action for n", "None self.new_data = variable(X, t, Z) self.history.write(t, action) self.training.add(X=X, t=t,", ":] = self.get_score(mode, predictor, train) return f def get_actions(self, mode,", "utility from ...variable import variable from ..call_simulator import call_simulator from", "random_search(self, max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True): N = int(num_search_each_probe) if int(max_num_probes)", "combo.search.score.EI(predictor, training, test) elif mode == 'PI': f = combo.search.score.PI(predictor,", "file_training=None, file_predictor=None): self.history.load(file_history) if file_training is None: N = self.history.total_num_search", "self.predictor = predictor N = int(num_search_each_probe) for n in xrange(max_num_probes):", "return predictor def _init_predictor(self, is_rand_expans, predictor=None): self.predictor = self._set_predictor(predictor) if", "= self.test.get_subset(actions) if mode == 'EI': f = combo.search.score.EI(predictor, training,", "if simulator is None: return action t, X = call_simulator(simulator,", "int(num_search_each_probe) if int(max_num_probes) * N > len(self.actions): raise ValueError('max_num_probes *", "from ... import predictor from ...gp import predictor as gp_predictor", "raise TypeError('The type of test_X must \\ take ndarray or", "= None self.training = variable() self.test = self._set_test(test_X) self.actions =", "def _set_predictor(self, predictor=None): if predictor is None: predictor = self.predictor", "= copy.deepcopy(self.training) virtual_train = new_test virtual_train.t = virtual_t[n, :] if", "def _set_training(self, training=None): if training is None: training = self.training", "None: train.add(virtual_train.X, virtual_train.t) else: train.add(virtual_train.X, virtual_train.t, virtual_train.Z) try: predictor.update(train, virtual_train)", "test = self.test.get_subset(actions) if mode == 'EI': f = combo.search.score.EI(predictor,", "self.training = variable() self.test = self._set_test(test_X) self.actions = np.arange(0, self.test.X.shape[0])", "True self.training = self._set_training(training) if predictor is None: self.predictor =", "chosed_actions = np.zeros(N, dtype=int) chosed_actions[0] = action for n in", "self.history.load(file_history) if file_training is None: N = self.history.total_num_search X =", "max_num_probes=None, num_search_each_probe=1, predictor=None, is_disp=True, simulator=None, score='TS', interval=0, num_rand_basis=0): if max_num_probes", "if virtual_train.Z is None: train.add(virtual_train.X, virtual_train.t) else: train.add(virtual_train.X, virtual_train.t, virtual_train.Z)", "index = random_index[0:N] action = self.actions[index] self.actions = self.delete_actions(index) return", "...gp import predictor as gp_predictor from ...blm import predictor as", "N = self.history.total_num_search X = self.test.X[self.history.chosed_actions[0:N], :] t = self.history.fx[0:N]", "predictor, train) return f def get_actions(self, mode, N, K, alpha):", "= self.get_random_action(N) if simulator is None: return action t, X", "1: utility.show_start_message_multi_search(self.history.num_runs) action = self.get_random_action(N) if simulator is None: return", "self.predictor is None: if is_rand_expans: self.predictor = blm_predictor(self.config) else: self.predictor", "self._set_predictor(predictor) actions = self.actions test = self.test.get_subset(actions) if mode ==", "train.add(virtual_train.X, virtual_train.t, virtual_train.Z) try: predictor.update(train, virtual_train) except: predictor.prepare(train) f[n, :]", "return action def load(self, file_history, file_training=None, file_predictor=None): self.history.load(file_history) if file_training", "= int(num_search_each_probe) for n in xrange(max_num_probes): if utility.is_learning(n, interval): self.predictor.fit(self.training,", "self.new_data) except: self.predictor.prepare(self.training) if num_search_each_probe != 1: utility.show_start_message_multi_search(self.history.num_runs, score) K", "or combo.variable') return test def _set_config(self, config=None): if config is", "take ndarray or combo.variable') return test def _set_config(self, config=None): if", "= copy.deepcopy(self.predictor) train = copy.deepcopy(self.training) virtual_train = new_test virtual_train.t =", "import predictor as gp_predictor from ...blm import predictor as blm_predictor", "import cPickle as pickle from results import history from ..", "elif mode == 'PI': f = combo.search.score.PI(predictor, training, test) elif", "= self.delete_actions(index) return action def load(self, file_history, file_training=None, file_predictor=None): self.history.load(file_history)", "simulator = None is_rand_expans = False if num_rand_basis == 0", "new_test = self.test.get_subset(chosed_actions) virtual_t \\ = self.predictor.get_predict_samples(self.training, new_test, N) for", "from results import history from .. import utility from ...variable", "max_num_probes is None: max_num_probes = 1 simulator = None is_rand_expans", "if isinstance(test_X, np.ndarray): test = variable(X=test_X) elif isinstance(test_X, variable): test", "is_rand_expans = False if num_rand_basis == 0 else True self.training", "must be EI, PI or TS.') return f def get_marginal_score(self,", "index, actions=None): actions = self._set_unchosed_actions(actions) return np.delete(actions, index) def write(self,", "N, K, alpha): f = self.get_score(mode, self.predictor, self.training, alpha) temp", "export_training(self): return self.training def export_history(self): return self.history def _set_predictor(self, predictor=None):", "n in xrange(0, max_num_probes): if is_disp and N > 1:", "num_rand_basis=0): if max_num_probes is None: max_num_probes = 1 simulator =", "for n in xrange(1, N): f = self.get_marginal_score(mode, chosed_actions[0:n], K,", "= random_index[0:N] action = self.actions[index] self.actions = self.delete_actions(index) return action", "MAX_SEACH = int(20000) class policy: def __init__(self, test_X, config=None): self.predictor", "copy.deepcopy(self.predictor) train = copy.deepcopy(self.training) virtual_train = new_test virtual_train.t = virtual_t[n,", "if file_training is None: N = self.history.total_num_search X = self.test.X[self.history.chosed_actions[0:N],", "is None: X = self.test.X[action, :] Z = self.test.Z[action, :]", "mode == 'PI': f = combo.search.score.PI(predictor, training, test) elif mode", "return f def get_marginal_score(self, mode, chosed_actions, N, alpha): f =", "self.actions[temp] self.actions = self.delete_actions(temp) chosed_actions = np.zeros(N, dtype=int) chosed_actions[0] =", "= virtual_t[n, :] if virtual_train.Z is None: train.add(virtual_train.X, virtual_train.t) else:", "actions=None): actions = self._set_unchosed_actions(actions) return np.delete(actions, index) def write(self, action,", "random_index = np.random.permutation(xrange(self.actions.shape[0])) index = random_index[0:N] action = self.actions[index] self.actions", "N, K, alpha) if simulator is None: return action t,", "gp_predictor from ...blm import predictor as blm_predictor import combo.search.score MAX_SEACH", "X) if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def bayes_search(self, training=None,", "_set_unchosed_actions(self, actions=None): if actions is None: actions = self.actions return", "self.get_score(mode, predictor, train) return f def get_actions(self, mode, N, K,", "is_disp=True, simulator=None, score='TS', interval=0, num_rand_basis=0): if max_num_probes is None: max_num_probes", "ValueError('max_num_probes * num_search_each_probe must \\ be smaller than the length", "self.predictor.get_basis(self.test.X) self.training.Z = self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else: try: self.predictor.update(self.training, self.new_data) except:", "xrange(0, max_num_probes): if is_disp and N > 1: utility.show_start_message_multi_search(self.history.num_runs) action", "* num_search_each_probe must \\ be smaller than the length of", "get_marginal_score(self, mode, chosed_actions, N, alpha): f = np.zeros((N, len(self.actions))) new_test", "self.predictor return predictor def _init_predictor(self, is_rand_expans, predictor=None): self.predictor = self._set_predictor(predictor)", "simulator=None, score='TS', interval=0, num_rand_basis=0): if max_num_probes is None: max_num_probes =", "num_rand_basis) self.test.Z = self.predictor.get_basis(self.test.X) self.training.Z = self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else: try:", "if int(max_num_probes) * N > len(self.actions): raise ValueError('max_num_probes * num_search_each_probe", "\\ be smaller than the length of candidates') if is_disp:", "= variable() self.training.load(file_training) if file_predictor is not None: with open(file_predictor)", "import predictor from ...gp import predictor as gp_predictor from ...blm", "Z) self.history.write(t, action) self.training.add(X=X, t=t, Z=Z) def random_search(self, max_num_probes, num_search_each_probe=1,", "alpha) else: raise NotImplementedError('mode must be EI, PI or TS.')", "TS.') return f def get_marginal_score(self, mode, chosed_actions, N, alpha): f", "= self.history.fx[0:N] self.training = variable(X=X, t=t) else: self.training = variable()", "predictor.prepare(train) f[n, :] = self.get_score(mode, predictor, train) return f def", "= self._set_training(training) if predictor is None: self.predictor = self._init_predictor(is_rand_expans) else:", "self.training.add(X=X, t=t, Z=Z) def random_search(self, max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True): N", "= self._set_unchosed_actions(actions) return np.delete(actions, index) def write(self, action, t, X=None):", "= variable(X, t, Z) self.history.write(t, action) self.training.add(X=X, t=t, Z=Z) def", "be smaller than the length of candidates') if is_disp: utility.show_interactive_mode(simulator,", "self._set_config(config) def set_seed(self, seed): self.seed = seed np.random.seed(self.seed) def delete_actions(self,", "action) self.training.add(X=X, t=t, Z=Z) def random_search(self, max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True):", "None: actions = self.actions return actions def _set_test(self, test_X): if", "new_test virtual_train.t = virtual_t[n, :] if virtual_train.Z is None: train.add(virtual_train.X,", "self.history def _set_predictor(self, predictor=None): if predictor is None: predictor =", "import combo.search.score MAX_SEACH = int(20000) class policy: def __init__(self, test_X,", "file_predictor is not None: with open(file_predictor) as f: self.predictor =", "self.predictor.fit(self.training, num_rand_basis) self.test.Z = self.predictor.get_basis(self.test.X) self.training.Z = self.predictor.get_basis(self.training.X) self.predictor.prepare(self.training) else:", "None self.training = variable() self.test = self._set_test(test_X) self.actions = np.arange(0,", "utility.is_learning(n, interval): self.predictor.fit(self.training, num_rand_basis) self.test.Z = self.predictor.get_basis(self.test.X) self.training.Z = self.predictor.get_basis(self.training.X)", "X = self.test.X[self.history.chosed_actions[0:N], :] t = self.history.fx[0:N] self.training = variable(X=X,", "= int(num_search_each_probe) if int(max_num_probes) * N > len(self.actions): raise ValueError('max_num_probes", "= self.get_actions(score, N, K, alpha) if simulator is None: return", "f = combo.search.score.TS(predictor, training, test, alpha) else: raise NotImplementedError('mode must", "= False if num_rand_basis == 0 else True self.training =", "self._init_predictor(is_rand_expans) else: self.predictor = predictor N = int(num_search_each_probe) for n", "test = variable(X=test_X) elif isinstance(test_X, variable): test = test_X else:", "from ...variable import variable from ..call_simulator import call_simulator from ...", "training, test, alpha) else: raise NotImplementedError('mode must be EI, PI", "K = self.config.search.multi_probe_num_sampling alpha = self.config.search.alpha action = self.get_actions(score, N,", "self.predictor def _set_training(self, training=None): if training is None: training =", "n in xrange(1, N): f = self.get_marginal_score(mode, chosed_actions[0:n], K, alpha)", "action = self.get_actions(score, N, K, alpha) if simulator is None:", "load(self, file_history, file_training=None, file_predictor=None): self.history.load(file_history) if file_training is None: N", "variable(X=test_X) elif isinstance(test_X, variable): test = test_X else: raise TypeError('The", "n in xrange(N): predictor = copy.deepcopy(self.predictor) train = copy.deepcopy(self.training) virtual_train", "X is None: X = self.test.X[action, :] Z = self.test.Z[action,", "None: max_num_probes = 1 simulator = None is_rand_expans = False", "xrange(N): predictor = copy.deepcopy(self.predictor) train = copy.deepcopy(self.training) virtual_train = new_test", "is None: training = self.training return training def _set_unchosed_actions(self, actions=None):", "training, test) elif mode == 'PI': f = combo.search.score.PI(predictor, training,", "return actions def _set_test(self, test_X): if isinstance(test_X, np.ndarray): test =", "xrange(max_num_probes): if utility.is_learning(n, interval): self.predictor.fit(self.training, num_rand_basis) self.test.Z = self.predictor.get_basis(self.test.X) self.training.Z", "X) if is_disp: utility.show_search_results(self.history, N) return copy.deepcopy(self.history) def get_score(self, mode,", "than the length of candidates') if is_disp: utility.show_interactive_mode(simulator, self.history) for", "alpha): f = np.zeros((N, len(self.actions))) new_test = self.test.get_subset(chosed_actions) virtual_t \\", "raise NotImplementedError('mode must be EI, PI or TS.') return f", "def _set_test(self, test_X): if isinstance(test_X, np.ndarray): test = variable(X=test_X) elif" ]
[ "_disable_linecache(): import linecache def fake_getline(*args, **kwargs): return \"\" linecache.orig_getline =", "def fake_getline(*args, **kwargs): return \"\" linecache.orig_getline = linecache.getline linecache.getline =", "def _disable_linecache(): import linecache def fake_getline(*args, **kwargs): return \"\" linecache.orig_getline", "fake_getline(*args, **kwargs): return \"\" linecache.orig_getline = linecache.getline linecache.getline = fake_getline", "<filename>venv/lib/python3.9/site-packages/py2app/bootstrap/disable_linecache.py def _disable_linecache(): import linecache def fake_getline(*args, **kwargs): return \"\"", "import linecache def fake_getline(*args, **kwargs): return \"\" linecache.orig_getline = linecache.getline", "**kwargs): return \"\" linecache.orig_getline = linecache.getline linecache.getline = fake_getline _disable_linecache()", "linecache def fake_getline(*args, **kwargs): return \"\" linecache.orig_getline = linecache.getline linecache.getline" ]
[ "#create folder for located imgs if not os.path.exists('imgs'): os.makedirs('imgs') #open", "os #source url = '' # the source you want", "folder for located imgs if not os.path.exists('imgs'): os.makedirs('imgs') #open the", "imgs if not os.path.exists('imgs'): os.makedirs('imgs') #open the new folder os.chdir('imgs')", "you want the bot take images from #down page page", "page = requests.get(url) html = bs(page.text, 'html.parser') #locate image_loc =", "from bs4 import BeautifulSoup as bs import os #source url", "'' # the source you want the bot take images", "os.makedirs('imgs') #open the new folder os.chdir('imgs') image0 = 0 #img", "as bs import os #source url = '' # the", "+ str(image0) + '.jpg', 'png') as mkimg: mkimg.write(requests.get(url).content) mkimg.close() image0", "image_loc = html.findAll('img') #create folder for located imgs if not", "#down page page = requests.get(url) html = bs(page.text, 'html.parser') #locate", "#img name #get images for image in image_loc: try: url", "os.path.exists('imgs'): os.makedirs('imgs') #open the new folder os.chdir('imgs') image0 = 0", "image0 = 0 #img name #get images for image in", "import requests from bs4 import BeautifulSoup as bs import os", "os.chdir('imgs') image0 = 0 #img name #get images for image", "open('img-' + str(image0) + '.jpg', 'png') as mkimg: mkimg.write(requests.get(url).content) mkimg.close()", "html.findAll('img') #create folder for located imgs if not os.path.exists('imgs'): os.makedirs('imgs')", "folder os.chdir('imgs') image0 = 0 #img name #get images for", "'png') as mkimg: mkimg.write(requests.get(url).content) mkimg.close() image0 += 1 except: pass", "'html.parser') #locate image_loc = html.findAll('img') #create folder for located imgs", "take images from #down page page = requests.get(url) html =", "source.status_code == 200: with open('img-' + str(image0) + '.jpg', 'png')", "source you want the bot take images from #down page", "image in image_loc: try: url = image['src'] source = requests.get(url)", "html = bs(page.text, 'html.parser') #locate image_loc = html.findAll('img') #create folder", "not os.path.exists('imgs'): os.makedirs('imgs') #open the new folder os.chdir('imgs') image0 =", "'.jpg', 'png') as mkimg: mkimg.write(requests.get(url).content) mkimg.close() image0 += 1 except:", "image['src'] source = requests.get(url) if source.status_code == 200: with open('img-'", "#get images for image in image_loc: try: url = image['src']", "images for image in image_loc: try: url = image['src'] source", "bs4 import BeautifulSoup as bs import os #source url =", "if not os.path.exists('imgs'): os.makedirs('imgs') #open the new folder os.chdir('imgs') image0", "page page = requests.get(url) html = bs(page.text, 'html.parser') #locate image_loc", "try: url = image['src'] source = requests.get(url) if source.status_code ==", "+ '.jpg', 'png') as mkimg: mkimg.write(requests.get(url).content) mkimg.close() image0 += 1", "for located imgs if not os.path.exists('imgs'): os.makedirs('imgs') #open the new", "located imgs if not os.path.exists('imgs'): os.makedirs('imgs') #open the new folder", "#locate image_loc = html.findAll('img') #create folder for located imgs if", "new folder os.chdir('imgs') image0 = 0 #img name #get images", "bs import os #source url = '' # the source", "# the source you want the bot take images from", "= image['src'] source = requests.get(url) if source.status_code == 200: with", "#open the new folder os.chdir('imgs') image0 = 0 #img name", "== 200: with open('img-' + str(image0) + '.jpg', 'png') as", "import os #source url = '' # the source you", "from #down page page = requests.get(url) html = bs(page.text, 'html.parser')", "with open('img-' + str(image0) + '.jpg', 'png') as mkimg: mkimg.write(requests.get(url).content)", "BeautifulSoup as bs import os #source url = '' #", "= 0 #img name #get images for image in image_loc:", "<reponame>s403o/tw_bot import requests from bs4 import BeautifulSoup as bs import", "the new folder os.chdir('imgs') image0 = 0 #img name #get", "= requests.get(url) html = bs(page.text, 'html.parser') #locate image_loc = html.findAll('img')", "for image in image_loc: try: url = image['src'] source =", "want the bot take images from #down page page =", "requests.get(url) html = bs(page.text, 'html.parser') #locate image_loc = html.findAll('img') #create", "name #get images for image in image_loc: try: url =", "url = image['src'] source = requests.get(url) if source.status_code == 200:", "import BeautifulSoup as bs import os #source url = ''", "the source you want the bot take images from #down", "url = '' # the source you want the bot", "source = requests.get(url) if source.status_code == 200: with open('img-' +", "0 #img name #get images for image in image_loc: try:", "requests.get(url) if source.status_code == 200: with open('img-' + str(image0) +", "= html.findAll('img') #create folder for located imgs if not os.path.exists('imgs'):", "images from #down page page = requests.get(url) html = bs(page.text,", "in image_loc: try: url = image['src'] source = requests.get(url) if", "bot take images from #down page page = requests.get(url) html", "bs(page.text, 'html.parser') #locate image_loc = html.findAll('img') #create folder for located", "requests from bs4 import BeautifulSoup as bs import os #source", "#source url = '' # the source you want the", "= bs(page.text, 'html.parser') #locate image_loc = html.findAll('img') #create folder for", "200: with open('img-' + str(image0) + '.jpg', 'png') as mkimg:", "str(image0) + '.jpg', 'png') as mkimg: mkimg.write(requests.get(url).content) mkimg.close() image0 +=", "the bot take images from #down page page = requests.get(url)", "= '' # the source you want the bot take", "= requests.get(url) if source.status_code == 200: with open('img-' + str(image0)", "image_loc: try: url = image['src'] source = requests.get(url) if source.status_code", "if source.status_code == 200: with open('img-' + str(image0) + '.jpg'," ]
[ "/F /IM node.exe /t' subprocess.getoutput(win) def start_server(self): self.kill_server() command =", "self.device = self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port = self.device.get('port') self.name", "= 'netstat -ano | findstr %s' % self.port time.sleep(3) while", "time from appium import webdriver import queue # 声明一个python队列 driver_queue", "{deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command : %s' % command) subprocess.Popen(command, stdout=open(SYSTEMPATH,", "command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True) def test_server(self): #", "port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command : %s' % command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'),", "端口启动失败。5秒后重试。' % self.port) time.sleep(5) return True def start_driver(self): url =", "webdriver.Remote(url, self.device) driver_queue.put(driver) if __name__ == '__main__': controller = Controller()", "True def start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester)", "= subprocess.getoutput(win) if data: time.sleep(10) print('%s 端口启动成功。' % self.port) break", "self.devices = self.config.get('devices') self.device = self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port", "''' 1、启动appium服务 subproccess 配置文件 1.1、校验服务是否启动 1.2、杀掉上一次的服务 2、启动driver ''' from lib.tools", "from lib.path import SYSTEMPATH, ERRORPATH import time from appium import", "grep|grep %s' % self.port win = 'netstat -ano | findstr", "import Tool import subprocess from lib.path import SYSTEMPATH, ERRORPATH import", "-9 \" $2}'|sh''' % self.port win = 'taskkill /F /IM", "self.config.get('tester') self.device_type = self.config.get('device_type') # 获取到所有的手机信息 self.devices = self.config.get('devices') self.device", "% self.port win = 'taskkill /F /IM node.exe /t' subprocess.getoutput(win)", "self.kill_server() command = 'appium -a {ip} -p {port} -U {deviceName}'.format(ip=self.device.get('ip'),", "subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True) def test_server(self): # mac", "= '''ps -ef|grep appium|grep -v grep|grep %s|awk '{print \"kill -9", "stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True) def test_server(self): # mac =", "from lib.tools import Tool import subprocess from lib.path import SYSTEMPATH,", "deviceName=self.device.get('deviceName')) print('command : %s' % command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH,", "'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester) driver = webdriver.Remote(url, self.device) driver_queue.put(driver)", "test_server(self): # mac = 'ps -ef|grep appium|grep -v grep|grep %s'", "获取配置信息 self.config = Tool().get_config self.tester = self.config.get('tester') self.device_type = self.config.get('device_type')", "driver = webdriver.Remote(url, self.device) driver_queue.put(driver) if __name__ == '__main__': controller", "__init__(self): # 获取配置信息 self.config = Tool().get_config self.tester = self.config.get('tester') self.device_type", "用于校验服务是否启动 self.port = self.device.get('port') self.name = self.device.get('name') def kill_server(self): mac", "class Controller(object): def __init__(self): # 获取配置信息 self.config = Tool().get_config self.tester", "data = subprocess.getoutput(win) if data: time.sleep(10) print('%s 端口启动成功。' % self.port)", "-a {ip} -p {port} -U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command :", "mac = 'ps -ef|grep appium|grep -v grep|grep %s' % self.port", "else: print('%s 端口启动失败。5秒后重试。' % self.port) time.sleep(5) return True def start_driver(self):", ": %s' % command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True)", "self.port = self.device.get('port') self.name = self.device.get('name') def kill_server(self): mac =", "# 获取到所有的手机信息 self.devices = self.config.get('devices') self.device = self.devices.get(self.device_type)[0] # port", "% self.port time.sleep(3) while True: data = subprocess.getoutput(win) if data:", "# 合并手机信息和包名入口 self.device.update(self.tester) driver = webdriver.Remote(url, self.device) driver_queue.put(driver) if __name__", "= self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port = self.device.get('port') self.name =", "端口启动成功。' % self.port) break else: print('%s 端口启动失败。5秒后重试。' % self.port) time.sleep(5)", "subprocess.getoutput(win) def start_server(self): self.kill_server() command = 'appium -a {ip} -p", "driver_queue.put(driver) if __name__ == '__main__': controller = Controller() controller.start_server() if", "# 获取配置信息 self.config = Tool().get_config self.tester = self.config.get('tester') self.device_type =", "1.2、杀掉上一次的服务 2、启动driver ''' from lib.tools import Tool import subprocess from", "# port 用于校验服务是否启动 self.port = self.device.get('port') self.name = self.device.get('name') def", "data: time.sleep(10) print('%s 端口启动成功。' % self.port) break else: print('%s 端口启动失败。5秒后重试。'", "= queue.Queue() class Controller(object): def __init__(self): # 获取配置信息 self.config =", "-v grep|grep %s' % self.port win = 'netstat -ano |", "start_server(self): self.kill_server() command = 'appium -a {ip} -p {port} -U", "<filename>lib/appController.py ''' 1、启动appium服务 subproccess 配置文件 1.1、校验服务是否启动 1.2、杀掉上一次的服务 2、启动driver ''' from", "'ps -ef|grep appium|grep -v grep|grep %s' % self.port win =", "self.tester = self.config.get('tester') self.device_type = self.config.get('device_type') # 获取到所有的手机信息 self.devices =", "self.device.update(self.tester) driver = webdriver.Remote(url, self.device) driver_queue.put(driver) if __name__ == '__main__':", "-p {port} -U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command : %s' %", "subprocess.getoutput(win) if data: time.sleep(10) print('%s 端口启动成功。' % self.port) break else:", "kill_server(self): mac = '''ps -ef|grep appium|grep -v grep|grep %s|awk '{print", "self.device.get('name') def kill_server(self): mac = '''ps -ef|grep appium|grep -v grep|grep", "%s' % self.port win = 'netstat -ano | findstr %s'", "self.name = self.device.get('name') def kill_server(self): mac = '''ps -ef|grep appium|grep", "print('command : %s' % command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'),", "% command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True) def test_server(self):", "grep|grep %s|awk '{print \"kill -9 \" $2}'|sh''' % self.port win", "def test_server(self): # mac = 'ps -ef|grep appium|grep -v grep|grep", "__name__ == '__main__': controller = Controller() controller.start_server() if controller.test_server(): controller.start_driver()", "self.config.get('device_type') # 获取到所有的手机信息 self.devices = self.config.get('devices') self.device = self.devices.get(self.device_type)[0] #", "self.port time.sleep(3) while True: data = subprocess.getoutput(win) if data: time.sleep(10)", "-ef|grep appium|grep -v grep|grep %s|awk '{print \"kill -9 \" $2}'|sh'''", "findstr %s' % self.port time.sleep(3) while True: data = subprocess.getoutput(win)", "/t' subprocess.getoutput(win) def start_server(self): self.kill_server() command = 'appium -a {ip}", "-ef|grep appium|grep -v grep|grep %s' % self.port win = 'netstat", "self.config.get('devices') self.device = self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port = self.device.get('port')", "self.device_type = self.config.get('device_type') # 获取到所有的手机信息 self.devices = self.config.get('devices') self.device =", "self.device.get('port') self.name = self.device.get('name') def kill_server(self): mac = '''ps -ef|grep", "self.device) driver_queue.put(driver) if __name__ == '__main__': controller = Controller() controller.start_server()", "webdriver import queue # 声明一个python队列 driver_queue = queue.Queue() class Controller(object):", "def __init__(self): # 获取配置信息 self.config = Tool().get_config self.tester = self.config.get('tester')", "command = 'appium -a {ip} -p {port} -U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'),", "-U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command : %s' % command) subprocess.Popen(command,", "'a+'), shell=True) def test_server(self): # mac = 'ps -ef|grep appium|grep", "url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester) driver = webdriver.Remote(url,", "声明一个python队列 driver_queue = queue.Queue() class Controller(object): def __init__(self): # 获取配置信息", "= self.config.get('device_type') # 获取到所有的手机信息 self.devices = self.config.get('devices') self.device = self.devices.get(self.device_type)[0]", "Tool().get_config self.tester = self.config.get('tester') self.device_type = self.config.get('device_type') # 获取到所有的手机信息 self.devices", "Tool import subprocess from lib.path import SYSTEMPATH, ERRORPATH import time", "-v grep|grep %s|awk '{print \"kill -9 \" $2}'|sh''' % self.port", "{port} -U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command : %s' % command)", "import time from appium import webdriver import queue # 声明一个python队列", "self.port win = 'netstat -ano | findstr %s' % self.port", "= 'taskkill /F /IM node.exe /t' subprocess.getoutput(win) def start_server(self): self.kill_server()", "= 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester) driver = webdriver.Remote(url, self.device)", "node.exe /t' subprocess.getoutput(win) def start_server(self): self.kill_server() command = 'appium -a", "print('%s 端口启动成功。' % self.port) break else: print('%s 端口启动失败。5秒后重试。' % self.port)", "SYSTEMPATH, ERRORPATH import time from appium import webdriver import queue", "'{print \"kill -9 \" $2}'|sh''' % self.port win = 'taskkill", "= 'ps -ef|grep appium|grep -v grep|grep %s' % self.port win", "if __name__ == '__main__': controller = Controller() controller.start_server() if controller.test_server():", "ERRORPATH import time from appium import webdriver import queue #", "'taskkill /F /IM node.exe /t' subprocess.getoutput(win) def start_server(self): self.kill_server() command", "shell=True) def test_server(self): # mac = 'ps -ef|grep appium|grep -v", "self.port) time.sleep(5) return True def start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port)", "self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port = self.device.get('port') self.name = self.device.get('name')", "break else: print('%s 端口启动失败。5秒后重试。' % self.port) time.sleep(5) return True def", "'appium -a {ip} -p {port} -U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command", "-ano | findstr %s' % self.port time.sleep(3) while True: data", "if data: time.sleep(10) print('%s 端口启动成功。' % self.port) break else: print('%s", "appium|grep -v grep|grep %s|awk '{print \"kill -9 \" $2}'|sh''' %", "port 用于校验服务是否启动 self.port = self.device.get('port') self.name = self.device.get('name') def kill_server(self):", "= self.device.get('port') self.name = self.device.get('name') def kill_server(self): mac = '''ps", "{ip} -p {port} -U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command : %s'", "\"kill -9 \" $2}'|sh''' % self.port win = 'taskkill /F", "self.config = Tool().get_config self.tester = self.config.get('tester') self.device_type = self.config.get('device_type') #", "driver_queue = queue.Queue() class Controller(object): def __init__(self): # 获取配置信息 self.config", "stderr=open(ERRORPATH, 'a+'), shell=True) def test_server(self): # mac = 'ps -ef|grep", "= webdriver.Remote(url, self.device) driver_queue.put(driver) if __name__ == '__main__': controller =", "% self.port) break else: print('%s 端口启动失败。5秒后重试。' % self.port) time.sleep(5) return", "/IM node.exe /t' subprocess.getoutput(win) def start_server(self): self.kill_server() command = 'appium", "合并手机信息和包名入口 self.device.update(self.tester) driver = webdriver.Remote(url, self.device) driver_queue.put(driver) if __name__ ==", "''' from lib.tools import Tool import subprocess from lib.path import", "queue # 声明一个python队列 driver_queue = queue.Queue() class Controller(object): def __init__(self):", "subproccess 配置文件 1.1、校验服务是否启动 1.2、杀掉上一次的服务 2、启动driver ''' from lib.tools import Tool", "'netstat -ano | findstr %s' % self.port time.sleep(3) while True:", "time.sleep(10) print('%s 端口启动成功。' % self.port) break else: print('%s 端口启动失败。5秒后重试。' %", "return True def start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口", "self.port win = 'taskkill /F /IM node.exe /t' subprocess.getoutput(win) def", "1、启动appium服务 subproccess 配置文件 1.1、校验服务是否启动 1.2、杀掉上一次的服务 2、启动driver ''' from lib.tools import", "win = 'taskkill /F /IM node.exe /t' subprocess.getoutput(win) def start_server(self):", "= self.config.get('devices') self.device = self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port =", "print('%s 端口启动失败。5秒后重试。' % self.port) time.sleep(5) return True def start_driver(self): url", "lib.tools import Tool import subprocess from lib.path import SYSTEMPATH, ERRORPATH", "queue.Queue() class Controller(object): def __init__(self): # 获取配置信息 self.config = Tool().get_config", "import SYSTEMPATH, ERRORPATH import time from appium import webdriver import", "# 声明一个python队列 driver_queue = queue.Queue() class Controller(object): def __init__(self): #", "| findstr %s' % self.port time.sleep(3) while True: data =", "time.sleep(5) return True def start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) #", "mac = '''ps -ef|grep appium|grep -v grep|grep %s|awk '{print \"kill", "def start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester) driver", "配置文件 1.1、校验服务是否启动 1.2、杀掉上一次的服务 2、启动driver ''' from lib.tools import Tool import", "\" $2}'|sh''' % self.port win = 'taskkill /F /IM node.exe", "'a+'), stderr=open(ERRORPATH, 'a+'), shell=True) def test_server(self): # mac = 'ps", "win = 'netstat -ano | findstr %s' % self.port time.sleep(3)", "while True: data = subprocess.getoutput(win) if data: time.sleep(10) print('%s 端口启动成功。'", "lib.path import SYSTEMPATH, ERRORPATH import time from appium import webdriver", "appium|grep -v grep|grep %s' % self.port win = 'netstat -ano", "start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester) driver =", "= 'appium -a {ip} -p {port} -U {deviceName}'.format(ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName'))", "Controller(object): def __init__(self): # 获取配置信息 self.config = Tool().get_config self.tester =", "%s|awk '{print \"kill -9 \" $2}'|sh''' % self.port win =", "def kill_server(self): mac = '''ps -ef|grep appium|grep -v grep|grep %s|awk", "$2}'|sh''' % self.port win = 'taskkill /F /IM node.exe /t'", "%s' % self.port time.sleep(3) while True: data = subprocess.getoutput(win) if", "%s' % command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True) def", "appium import webdriver import queue # 声明一个python队列 driver_queue = queue.Queue()", "import webdriver import queue # 声明一个python队列 driver_queue = queue.Queue() class", "port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester) driver = webdriver.Remote(url, self.device) driver_queue.put(driver) if", "= self.config.get('tester') self.device_type = self.config.get('device_type') # 获取到所有的手机信息 self.devices = self.config.get('devices')", "time.sleep(3) while True: data = subprocess.getoutput(win) if data: time.sleep(10) print('%s", "1.1、校验服务是否启动 1.2、杀掉上一次的服务 2、启动driver ''' from lib.tools import Tool import subprocess", "subprocess from lib.path import SYSTEMPATH, ERRORPATH import time from appium", "True: data = subprocess.getoutput(win) if data: time.sleep(10) print('%s 端口启动成功。' %", "2、启动driver ''' from lib.tools import Tool import subprocess from lib.path", "# mac = 'ps -ef|grep appium|grep -v grep|grep %s' %", "= self.device.get('name') def kill_server(self): mac = '''ps -ef|grep appium|grep -v", "% self.port win = 'netstat -ano | findstr %s' %", "'''ps -ef|grep appium|grep -v grep|grep %s|awk '{print \"kill -9 \"", "from appium import webdriver import queue # 声明一个python队列 driver_queue =", "获取到所有的手机信息 self.devices = self.config.get('devices') self.device = self.devices.get(self.device_type)[0] # port 用于校验服务是否启动", "def start_server(self): self.kill_server() command = 'appium -a {ip} -p {port}", "= Tool().get_config self.tester = self.config.get('tester') self.device_type = self.config.get('device_type') # 获取到所有的手机信息", "self.port) break else: print('%s 端口启动失败。5秒后重试。' % self.port) time.sleep(5) return True", "import subprocess from lib.path import SYSTEMPATH, ERRORPATH import time from", "% self.port) time.sleep(5) return True def start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'),", "import queue # 声明一个python队列 driver_queue = queue.Queue() class Controller(object): def" ]
[ "if (iR, iC + 1) in flag: ans.add((iR, iC +", "flag: tmpArea = 0 mydueque = deque() mydueque.append(flag.pop()) while mydueque:", "+ 1)) return ans flag = {(i,j) for j in", "@Author @Version @Desciption ------------ ------- -------- ----------- 2020-03-07 zhan 1.0", "(iR-1,iC-1) in flag: ans.add((iR-1,iC-1)) if (iR-1,iC) in flag: ans.add((iR-1,iC)) if", "iC) in flag: ans.add((iR + 1, iC)) if (iR+1, iC", "for j in range(len(land[0])) for i in range(len(land)) if land[i][j]", "------- -------- ----------- 2020-03-07 zhan 1.0 None ''' from typing", "{(i,j) for j in range(len(land[0])) for i in range(len(land)) if", "< len(land[i]) <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time @Author @Version", "1, iC-1) in flag: ans.add((iR + 1, iC-1)) if (iR", "Solution: def pondSizes(self, land: List[List[int]]) -> List[int]: def neighbors(iR,iC,flag): ans", "in range(len(land[0])) for i in range(len(land)) if land[i][j] == 0}", "[1,2,4] 提示: 0 < len(land) <= 1000 0 < len(land[i])", "len(land[i]) <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time @Author @Version @Desciption", "1)) return ans flag = {(i,j) for j in range(len(land[0]))", "你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] 输出:", "'__main__': a = [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] ans", "class Solution: def pondSizes(self, land: List[List[int]]) -> List[int]: def neighbors(iR,iC,flag):", ": pondSizes.py @Contact : <EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入:", "输出: [1,2,4] 提示: 0 < len(land) <= 1000 0 <", "-------- ----------- 2020-03-07 zhan 1.0 None ''' from typing import", "if (iR+1, iC + 1) in flag: ans.add((iR+1, iC +", "链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time @Author @Version @Desciption ------------ ------- -------- -----------", "[1,1,0,1], [0,1,0,1] ] 输出: [1,2,4] 提示: 0 < len(land) <=", "ans.add((iR + 1, iC-1)) if (iR + 1, iC) in", "flag: ans.add((iR-1,iC+1)) if (iR,iC-1) in flag: ans.add((iR,iC-1)) if (iR, iC", "示例: 输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] 输出: [1,2,4]", "if (iR-1,iC) in flag: ans.add((iR-1,iC)) if (iR-1,iC+1) in flag: ans.add((iR-1,iC+1))", "1) in flag: ans.add((iR, iC + 1)) if (iR +", "from typing import List from collections import deque class Solution:", "in neighbors(curEle[0], curEle[1], flag): mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea) ans.sort() return ans", "<EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1],", "deque class Solution: def pondSizes(self, land: List[List[int]]) -> List[int]: def", "List[int]: def neighbors(iR,iC,flag): ans = set() if (iR-1,iC-1) in flag:", "iC + 1) in flag: ans.add((iR, iC + 1)) if", "----------- 2020-03-07 zhan 1.0 None ''' from typing import List", "= 0 mydueque = deque() mydueque.append(flag.pop()) while mydueque: curEle =", "a = [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] ans =", "land: List[List[int]]) -> List[int]: def neighbors(iR,iC,flag): ans = set() if", "-> List[int]: def neighbors(iR,iC,flag): ans = set() if (iR-1,iC-1) in", "ans.sort() return ans if __name__ == '__main__': a = [", "''' from typing import List from collections import deque class", "curEle = mydueque.popleft() tmpArea +=1 for neighbor in neighbors(curEle[0], curEle[1],", "set() if (iR-1,iC-1) in flag: ans.add((iR-1,iC-1)) if (iR-1,iC) in flag:", "ans.add((iR-1,iC)) if (iR-1,iC+1) in flag: ans.add((iR-1,iC+1)) if (iR,iC-1) in flag:", "neighbors(curEle[0], curEle[1], flag): mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea) ans.sort() return ans if", "for neighbor in neighbors(curEle[0], curEle[1], flag): mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea) ans.sort()", "[0,1,0,1] ] 输出: [1,2,4] 提示: 0 < len(land) <= 1000", "in flag: ans.add((iR-1,iC+1)) if (iR,iC-1) in flag: ans.add((iR,iC-1)) if (iR,", "= mydueque.popleft() tmpArea +=1 for neighbor in neighbors(curEle[0], curEle[1], flag):", "= deque() mydueque.append(flag.pop()) while mydueque: curEle = mydueque.popleft() tmpArea +=1", "[0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] 输出: [1,2,4] 提示: 0 <", "land[i][j] == 0} ans = [] while flag: tmpArea =", "@Contact : <EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [ [0,2,1,0],", "1.0 None ''' from typing import List from collections import", "from collections import deque class Solution: def pondSizes(self, land: List[List[int]])", "mydueque = deque() mydueque.append(flag.pop()) while mydueque: curEle = mydueque.popleft() tmpArea", "@File : pondSizes.py @Contact : <EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例:", "def neighbors(iR,iC,flag): ans = set() if (iR-1,iC-1) in flag: ans.add((iR-1,iC-1))", "neighbors(iR,iC,flag): ans = set() if (iR-1,iC-1) in flag: ans.add((iR-1,iC-1)) if", "range(len(land[0])) for i in range(len(land)) if land[i][j] == 0} ans", "flag: ans.add((iR,iC-1)) if (iR, iC + 1) in flag: ans.add((iR,", "ans if __name__ == '__main__': a = [ [0,2,1,0], [0,1,0,1],", "iC + 1)) if (iR + 1, iC-1) in flag:", "ans.add((iR + 1, iC)) if (iR+1, iC + 1) in", "in range(len(land)) if land[i][j] == 0} ans = [] while", "def pondSizes(self, land: List[List[int]]) -> List[int]: def neighbors(iR,iC,flag): ans =", "in flag: ans.add((iR + 1, iC-1)) if (iR + 1,", "neighbor in neighbors(curEle[0], curEle[1], flag): mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea) ans.sort() return", "len(land) <= 1000 0 < len(land[i]) <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci", "if (iR + 1, iC-1) in flag: ans.add((iR + 1,", "ans.add((iR,iC-1)) if (iR, iC + 1) in flag: ans.add((iR, iC", "iC + 1)) return ans flag = {(i,j) for j", "in flag: ans.add((iR+1, iC + 1)) return ans flag =", "(iR + 1, iC) in flag: ans.add((iR + 1, iC))", "ans.add((iR, iC + 1)) if (iR + 1, iC-1) in", "1, iC) in flag: ans.add((iR + 1, iC)) if (iR+1,", "''' @project : LeetCode @File : pondSizes.py @Contact : <EMAIL>", "= [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] ans = Solution().pondSizes(a)", "None ''' from typing import List from collections import deque", "# -*- encoding: utf-8 -*- ''' @project : LeetCode @File", "-*- encoding: utf-8 -*- ''' @project : LeetCode @File :", "if (iR-1,iC-1) in flag: ans.add((iR-1,iC-1)) if (iR-1,iC) in flag: ans.add((iR-1,iC))", "@Version @Desciption ------------ ------- -------- ----------- 2020-03-07 zhan 1.0 None", "if (iR-1,iC+1) in flag: ans.add((iR-1,iC+1)) if (iR,iC-1) in flag: ans.add((iR,iC-1))", "if (iR + 1, iC) in flag: ans.add((iR + 1,", "------------ ------- -------- ----------- 2020-03-07 zhan 1.0 None ''' from", "iC)) if (iR+1, iC + 1) in flag: ans.add((iR+1, iC", "tmpArea +=1 for neighbor in neighbors(curEle[0], curEle[1], flag): mydueque.append(neighbor) flag.remove(neighbor)", "@project : LeetCode @File : pondSizes.py @Contact : <EMAIL> @Desc", "in flag: ans.add((iR-1,iC-1)) if (iR-1,iC) in flag: ans.add((iR-1,iC)) if (iR-1,iC+1)", "(iR, iC + 1) in flag: ans.add((iR, iC + 1))", "ans.append(tmpArea) ans.sort() return ans if __name__ == '__main__': a =", "[] while flag: tmpArea = 0 mydueque = deque() mydueque.append(flag.pop())", "< len(land) <= 1000 0 < len(land[i]) <= 1000 来源:力扣(LeetCode)", "[ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] 输出: [1,2,4] 提示: 0", "(iR,iC-1) in flag: ans.add((iR,iC-1)) if (iR, iC + 1) in", "+ 1) in flag: ans.add((iR, iC + 1)) if (iR", "mydueque.append(flag.pop()) while mydueque: curEle = mydueque.popleft() tmpArea +=1 for neighbor", "0} ans = [] while flag: tmpArea = 0 mydueque", "for i in range(len(land)) if land[i][j] == 0} ans =", "(iR-1,iC+1) in flag: ans.add((iR-1,iC+1)) if (iR,iC-1) in flag: ans.add((iR,iC-1)) if", "+ 1, iC-1) in flag: ans.add((iR + 1, iC-1)) if", "(iR-1,iC) in flag: ans.add((iR-1,iC)) if (iR-1,iC+1) in flag: ans.add((iR-1,iC+1)) if", "+ 1) in flag: ans.add((iR+1, iC + 1)) return ans", "iC + 1) in flag: ans.add((iR+1, iC + 1)) return", "1000 0 < len(land[i]) <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time", "deque() mydueque.append(flag.pop()) while mydueque: curEle = mydueque.popleft() tmpArea +=1 for", "0 mydueque = deque() mydueque.append(flag.pop()) while mydueque: curEle = mydueque.popleft()", "List from collections import deque class Solution: def pondSizes(self, land:", "if (iR,iC-1) in flag: ans.add((iR,iC-1)) if (iR, iC + 1)", "return ans if __name__ == '__main__': a = [ [0,2,1,0],", "in flag: ans.add((iR + 1, iC)) if (iR+1, iC +", "0 < len(land) <= 1000 0 < len(land[i]) <= 1000", ": <EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [ [0,2,1,0], [0,1,0,1],", "return ans flag = {(i,j) for j in range(len(land[0])) for", "flag: ans.add((iR-1,iC-1)) if (iR-1,iC) in flag: ans.add((iR-1,iC)) if (iR-1,iC+1) in", "[ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] ans = Solution().pondSizes(a) print(ans)", ": 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ]", "pondSizes.py @Contact : <EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [", "flag: ans.add((iR + 1, iC-1)) if (iR + 1, iC)", "1, iC-1)) if (iR + 1, iC) in flag: ans.add((iR", "j in range(len(land[0])) for i in range(len(land)) if land[i][j] ==", "+ 1)) if (iR + 1, iC-1) in flag: ans.add((iR", "flag): mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea) ans.sort() return ans if __name__ ==", "flag.remove(neighbor) ans.append(tmpArea) ans.sort() return ans if __name__ == '__main__': a", "__name__ == '__main__': a = [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1]", "1) in flag: ans.add((iR+1, iC + 1)) return ans flag", "0 < len(land[i]) <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time @Author", "(iR + 1, iC-1) in flag: ans.add((iR + 1, iC-1))", "@Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1]", "in flag: ans.add((iR,iC-1)) if (iR, iC + 1) in flag:", "ans.add((iR+1, iC + 1)) return ans flag = {(i,j) for", "@Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2020-03-07", "iC-1)) if (iR + 1, iC) in flag: ans.add((iR +", "1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time @Author @Version @Desciption ------------ -------", "mydueque: curEle = mydueque.popleft() tmpArea +=1 for neighbor in neighbors(curEle[0],", "typing import List from collections import deque class Solution: def", "+ 1, iC)) if (iR+1, iC + 1) in flag:", "in flag: ans.add((iR-1,iC)) if (iR-1,iC+1) in flag: ans.add((iR-1,iC+1)) if (iR,iC-1)", "== '__main__': a = [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ]", "flag: ans.add((iR+1, iC + 1)) return ans flag = {(i,j)", "<= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time @Author @Version @Desciption ------------", "zhan 1.0 None ''' from typing import List from collections", "] 输出: [1,2,4] 提示: 0 < len(land) <= 1000 0", "if land[i][j] == 0} ans = [] while flag: tmpArea", "while flag: tmpArea = 0 mydueque = deque() mydueque.append(flag.pop()) while", "i in range(len(land)) if land[i][j] == 0} ans = []", "输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] 输出: [1,2,4] 提示:", "@Desciption ------------ ------- -------- ----------- 2020-03-07 zhan 1.0 None '''", "flag = {(i,j) for j in range(len(land[0])) for i in", "ans.add((iR-1,iC+1)) if (iR,iC-1) in flag: ans.add((iR,iC-1)) if (iR, iC +", "[0,1,0,1], [1,1,0,1], [0,1,0,1] ] 输出: [1,2,4] 提示: 0 < len(land)", "import List from collections import deque class Solution: def pondSizes(self,", "ans = [] while flag: tmpArea = 0 mydueque =", "Time @Author @Version @Desciption ------------ ------- -------- ----------- 2020-03-07 zhan", "import deque class Solution: def pondSizes(self, land: List[List[int]]) -> List[int]:", "flag: ans.add((iR, iC + 1)) if (iR + 1, iC-1)", "= {(i,j) for j in range(len(land[0])) for i in range(len(land))", "-*- ''' @project : LeetCode @File : pondSizes.py @Contact :", "mydueque.popleft() tmpArea +=1 for neighbor in neighbors(curEle[0], curEle[1], flag): mydueque.append(neighbor)", "iC-1) in flag: ans.add((iR + 1, iC-1)) if (iR +", "range(len(land)) if land[i][j] == 0} ans = [] while flag:", "2020-03-07 zhan 1.0 None ''' from typing import List from", "ans = set() if (iR-1,iC-1) in flag: ans.add((iR-1,iC-1)) if (iR-1,iC)", "ans.add((iR-1,iC-1)) if (iR-1,iC) in flag: ans.add((iR-1,iC)) if (iR-1,iC+1) in flag:", "ans flag = {(i,j) for j in range(len(land[0])) for i", "pondSizes(self, land: List[List[int]]) -> List[int]: def neighbors(iR,iC,flag): ans = set()", "if __name__ == '__main__': a = [ [0,2,1,0], [0,1,0,1], [1,1,0,1],", "List[List[int]]) -> List[int]: def neighbors(iR,iC,flag): ans = set() if (iR-1,iC-1)", "collections import deque class Solution: def pondSizes(self, land: List[List[int]]) ->", "utf-8 -*- ''' @project : LeetCode @File : pondSizes.py @Contact", "+ 1, iC) in flag: ans.add((iR + 1, iC)) if", "= [] while flag: tmpArea = 0 mydueque = deque()", ": LeetCode @File : pondSizes.py @Contact : <EMAIL> @Desc :", "提示: 0 < len(land) <= 1000 0 < len(land[i]) <=", "1, iC)) if (iR+1, iC + 1) in flag: ans.add((iR+1,", "encoding: utf-8 -*- ''' @project : LeetCode @File : pondSizes.py", "== 0} ans = [] while flag: tmpArea = 0", "tmpArea = 0 mydueque = deque() mydueque.append(flag.pop()) while mydueque: curEle", "+ 1, iC-1)) if (iR + 1, iC) in flag:", "while mydueque: curEle = mydueque.popleft() tmpArea +=1 for neighbor in", "+=1 for neighbor in neighbors(curEle[0], curEle[1], flag): mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea)", "来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify Time @Author @Version @Desciption ------------ ------- --------", "1)) if (iR + 1, iC-1) in flag: ans.add((iR +", "curEle[1], flag): mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea) ans.sort() return ans if __name__", "flag: ans.add((iR-1,iC)) if (iR-1,iC+1) in flag: ans.add((iR-1,iC+1)) if (iR,iC-1) in", "<= 1000 0 < len(land[i]) <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pond-sizes-lcci @Modify", "flag: ans.add((iR + 1, iC)) if (iR+1, iC + 1)", "(iR+1, iC + 1) in flag: ans.add((iR+1, iC + 1))", "mydueque.append(neighbor) flag.remove(neighbor) ans.append(tmpArea) ans.sort() return ans if __name__ == '__main__':", "in flag: ans.add((iR, iC + 1)) if (iR + 1,", "= set() if (iR-1,iC-1) in flag: ans.add((iR-1,iC-1)) if (iR-1,iC) in", "LeetCode @File : pondSizes.py @Contact : <EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。" ]
[ "... out[start:end] = bytearray(link, encoding=\"ascii\", errors=\"replace\") ... offset += (len(link)", "a map link, using the given substitution function. The substitution", "matched by :obj:`parser.parser_re` to degrees, minutes, and seconds. >>> _cleanup({'latdir':", "setcontext, ExtendedContext from geolucidate.links.google import google_maps_link from geolucidate.links.tools import MapLink", "'longdeg':'50','longmin':'40'}) ['S', '60', '30', '00', 'W', '50', '40', '00'] >>>", "'50', '40.90', '00'] \"\"\" latdir = (parts['latdir'] or parts['latdir2']).upper()[0] longdir", "normalized degrees, minutes, and seconds to decimal degrees. Quantize the", ">>> _convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333') >>> _convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833') \"\"\" if", "out = bytearray(test_string, encoding=\"ascii\", errors=\"replace\") >>> for (match, link) in", "in replacements.items(): ... start = match.start() + offset ... end", "'') longdecsec = parts.get('longdecsec', '') if (latdecsec and longdecsec): latmin", "parts.get('latmin', '00') or '00' longmin = parts.get('longmin', '00') or '00'", "original_string = match.group() (latitude, longitude) = _convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string, latitude,", "['S', '60', '30.50', '00', 'W', '50', '40.90', '00'] \"\"\" latdir", "for match in matches: (latitude, longitude) = _convert(*_cleanup(match.groupdict())) substitutions[match] =", "seconds. >>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'})", "return a 2-tuple of strings. >>> _convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333') >>>", "start = match.start() + offset ... end = match.end() +", "\"\"\" Replace detected coordinates with a map link, using the", "which will be substituted by :func:`re.sub` in place of the", "58147N/07720W\") ... #doctest: +ELLIPSIS {<re.Match object...>: '<a href=\"...\" title=\"...\">4630 NORTH", "'30.50', '00', 'W', '50', '40.90', '00'] \"\"\" latdir = (parts['latdir']", "-*- from decimal import Decimal, setcontext, ExtendedContext from geolucidate.links.google import", "longmin, longsec): \"\"\" Convert normalized degrees, minutes, and seconds to", "= match.end() + offset ... out[start:end] = bytearray(link, encoding=\"ascii\", errors=\"replace\")", "elif (latmin != '00' or longmin != '00'): precision =", "replacement cannot be performed through ordinary string substitution by :func:`re.sub`,", "== replace(test_string) True \"\"\" substitutions = {} matches = parser_re.finditer(string)", "59 or longsec > 59: # Assume that 'seconds' greater", "latsec = parts.get('latsec', '') or '00' longsec = parts.get('longsec', '')", "longsec = Decimal(longsec) if latsec > 59 or longsec >", "= Decimal('0.001') else: precision = Decimal('1') latitude = Decimal(latdeg) latmin", ">>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S',", "or '00' return [latdir, latdeg, latmin, latsec, longdir, longdeg, longmin,", "title=\"...\">4630 NORTH 5705 WEST</a>', <re.Match object...>: '<a href=\"...\" title=\"...\">58147N/07720W</a>'} >>>", "ExtendedContext from geolucidate.links.google import google_maps_link from geolucidate.links.tools import MapLink from", "(latitude, longitude) = _convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string, latitude, longitude)) return parser_re.sub(do_replace,", "= parts.get('latmin', '00') or '00' longmin = parts.get('longmin', '00') or", "'00') or '00' latdecsec = parts.get('latdecsec', '') longdecsec = parts.get('longdecsec',", ">>> replace(\"58N/077W\", bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58, -77)\">58N/077W</a>' \"\"\" def", "seconds to decimal degrees. Quantize the converted value based on", "'00' longmin = parts.get('longmin', '00') or '00' latdecsec = parts.get('latdecsec',", "coordinates. >>> replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\",", ">>> test_string = \"4630 NORTH 5705 WEST 58147N/07720W\" >>> replacements", "to decimal degrees. Quantize the converted value based on the", "59: # Assume that 'seconds' greater than 59 are actually", ">>> get_replacements(\"4630 NORTH 5705 WEST 58147N/07720W\") ... #doctest: +ELLIPSIS {<re.Match", "Decimal(latsec) longitude = Decimal(longdeg) longmin = Decimal(longmin) longsec = Decimal(longsec)", "or '00' longmin = parts.get('longmin', '00') or '00' latdecsec =", "(latsec / Decimal('100'))) / Decimal('60') longitude += (longmin + (longsec", "if (latsec != '00' or longsec != '00'): precision =", "= bytearray(link, encoding=\"ascii\", errors=\"replace\") ... offset += (len(link) - len(match.group()))", "= (parts['longdir'] or parts['longdir2']).upper()[0] latdeg = parts.get('latdeg') longdeg = parts.get('longdeg')", "['S', '60', '30', '00', 'W', '50', '40', '00'] >>> _cleanup({'latdir':", "get_replacements(test_string) >>> offset = 0 >>> out = bytearray(test_string, encoding=\"ascii\",", "offset ... end = match.end() + offset ... out[start:end] =", "'00'] \"\"\" latdir = (parts['latdir'] or parts['latdir2']).upper()[0] longdir = (parts['longdir']", "google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>' >>> from geolucidate.links.bing import", "bytearray(test_string, encoding=\"ascii\", errors=\"replace\") >>> for (match, link) in replacements.items(): ...", "59 are actually a decimal # fraction of minutes latitude", "/ Decimal('60') longitude += (longmin + (longsec / Decimal('60'))) /", "latdeg, latmin, latsec, longdir, longdeg, longmin, longsec): \"\"\" Convert normalized", "title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\", google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233,", "'<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58, -77)\">58N/077W</a>' \"\"\" def do_replace(match): original_string =", "a string which will be substituted by :func:`re.sub` in place", "Decimal(latmin) latsec = Decimal(latsec) longitude = Decimal(longdeg) longmin = Decimal(longmin)", "0 >>> out = bytearray(test_string, encoding=\"ascii\", errors=\"replace\") >>> for (match,", "longitude) = _convert(*_cleanup(match.groupdict())) substitutions[match] = sub_function(MapLink(match.group(), latitude, longitude)) return substitutions", "bing_maps_link >>> replace(\"58N/077W\", bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58, -77)\">58N/077W</a>' \"\"\"", "longitude)) return parser_re.sub(do_replace, string) def get_replacements(string, sub_function=google_maps_link()): \"\"\" Return a", "#doctest: +ELLIPSIS {<re.Match object...>: '<a href=\"...\" title=\"...\">4630 NORTH 5705 WEST</a>',", "'00'] >>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', 'latdecsec':'.50', ...", "longsec] def _convert(latdir, latdeg, latmin, latsec, longdir, longdeg, longmin, longsec):", "'') or '00' longsec = parts.get('longsec', '') or '00' return", "replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\", google_maps_link('satellite')) '<a", "/ Decimal('60') longitude += (longmin + (longsec / Decimal('100'))) /", "Replace detected coordinates with a map link, using the given", "latmin, latsec, longdir, longdeg, longmin, longsec] def _convert(latdir, latdeg, latmin,", "match.end() + offset ... out[start:end] = bytearray(link, encoding=\"ascii\", errors=\"replace\") ...", "get_replacements(string, sub_function=google_maps_link()): \"\"\" Return a dict whose keys are instances", "58147N/07720W\" >>> replacements = get_replacements(test_string) >>> offset = 0 >>>", "match.start() + offset ... end = match.end() + offset ...", "MapLink from geolucidate.parser import parser_re setcontext(ExtendedContext) def _cleanup(parts): \"\"\" Normalize", "geolucidate.links.tools import MapLink from geolucidate.parser import parser_re setcontext(ExtendedContext) def _cleanup(parts):", "matches: (latitude, longitude) = _convert(*_cleanup(match.groupdict())) substitutions[match] = sub_function(MapLink(match.group(), latitude, longitude))", "parts.get('latdeg') longdeg = parts.get('longdeg') latmin = parts.get('latmin', '00') or '00'", "NORTH 5705 WEST 58147N/07720W\") ... #doctest: +ELLIPSIS {<re.Match object...>: '<a", "and should return a string which will be substituted by", "longmin, longsec] def _convert(latdir, latdeg, latmin, latsec, longdir, longdeg, longmin,", "offset += (len(link) - len(match.group())) >>> out.decode(encoding=\"ascii\") == replace(test_string) True", "out.decode(encoding=\"ascii\") == replace(test_string) True \"\"\" substitutions = {} matches =", "the corresponding replacements. Use :func:`get_replacements` when the replacement cannot be", "up the parts matched by :obj:`parser.parser_re` to degrees, minutes, and", "from geolucidate.links.tools import MapLink from geolucidate.parser import parser_re setcontext(ExtendedContext) def", "Decimal('60') longitude += (longmin + (longsec / Decimal('100'))) / Decimal('60')", "latitude *= Decimal('-1') if longdir == 'W': longitude *= Decimal('-1')", "'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', 'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60',", "replacements. Use :func:`get_replacements` when the replacement cannot be performed through", "\"\"\" def do_replace(match): original_string = match.group() (latitude, longitude) = _convert(*_cleanup(match.groupdict()))", "else: precision = Decimal('1') latitude = Decimal(latdeg) latmin = Decimal(latmin)", "(longmin + (longsec / Decimal('100'))) / Decimal('60') else: latitude +=", "str(latitude.quantize(precision)) long_str = str(longitude.quantize(precision)) return (lat_str, long_str) def replace(string, sub_function=google_maps_link()):", "5705 WEST</a>', <re.Match object...>: '<a href=\"...\" title=\"...\">58147N/07720W</a>'} >>> test_string =", "latsec, longdir, longdeg, longmin, longsec): \"\"\" Convert normalized degrees, minutes,", "latdecsec = parts.get('latdecsec', '') longdecsec = parts.get('longdecsec', '') if (latdecsec", "are actually a decimal # fraction of minutes latitude +=", "lat_str = str(latitude.quantize(precision)) long_str = str(longitude.quantize(precision)) return (lat_str, long_str) def", "latitude, longitude)) return parser_re.sub(do_replace, string) def get_replacements(string, sub_function=google_maps_link()): \"\"\" Return", "should return a string which will be substituted by :func:`re.sub`", "+ offset ... end = match.end() + offset ... out[start:end]", "5705 WEST 58147N/07720W\") ... #doctest: +ELLIPSIS {<re.Match object...>: '<a href=\"...\"", "latmin, latsec, longdir, longdeg, longmin, longsec): \"\"\" Convert normalized degrees,", "= bytearray(test_string, encoding=\"ascii\", errors=\"replace\") >>> for (match, link) in replacements.items():", "of minutes latitude += (latmin + (latsec / Decimal('100'))) /", "replace(test_string) True \"\"\" substitutions = {} matches = parser_re.finditer(string) for", "will be substituted by :func:`re.sub` in place of the detected", "= Decimal(latdeg) latmin = Decimal(latmin) latsec = Decimal(latsec) longitude =", "latsec = Decimal(latsec) longitude = Decimal(longdeg) longmin = Decimal(longmin) longsec", "href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58, -77)\">58N/077W</a>' \"\"\" def do_replace(match): original_string = match.group()", "NORTH 5705 WEST</a>', <re.Match object...>: '<a href=\"...\" title=\"...\">58147N/07720W</a>'} >>> test_string", "and whose values are the corresponding replacements. Use :func:`get_replacements` when", "longsec): \"\"\" Convert normalized degrees, minutes, and seconds to decimal", "offset ... out[start:end] = bytearray(link, encoding=\"ascii\", errors=\"replace\") ... offset +=", "... 'longdeg':'50','longmin':'40'}) ['S', '60', '30', '00', 'W', '50', '40', '00']", "def replace(string, sub_function=google_maps_link()): \"\"\" Replace detected coordinates with a map", "import parser_re setcontext(ExtendedContext) def _cleanup(parts): \"\"\" Normalize up the parts", "strings. >>> _convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333') >>> _convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833') \"\"\"", "encoding=\"ascii\", errors=\"replace\") >>> for (match, link) in replacements.items(): ... start", "> 59 or longsec > 59: # Assume that 'seconds'", "'60', '30.50', '00', 'W', '50', '40.90', '00'] \"\"\" latdir =", "from geolucidate.parser import parser_re setcontext(ExtendedContext) def _cleanup(parts): \"\"\" Normalize up", "'00' return [latdir, latdeg, latmin, latsec, longdir, longdeg, longmin, longsec]", "longmin = parts.get('longmin', '00') or '00' latdecsec = parts.get('latdecsec', '')", "= Decimal(longdeg) longmin = Decimal(longmin) longsec = Decimal(longsec) if latsec", "str(longitude.quantize(precision)) return (lat_str, long_str) def replace(string, sub_function=google_maps_link()): \"\"\" Replace detected", "Decimal('0.001') else: precision = Decimal('1') latitude = Decimal(latdeg) latmin =", "value based on the input precision and return a 2-tuple", "latmin += latdecsec longmin += longdecsec latsec = '00' longsec", "= match.start() + offset ... end = match.end() + offset", "= parts.get('latsec', '') or '00' longsec = parts.get('longsec', '') or", "def do_replace(match): original_string = match.group() (latitude, longitude) = _convert(*_cleanup(match.groupdict())) return", "The substitution function will be passed a :class:`~.MapLink` instance, and", "'west', ... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S', '60', '30', '00', 'W',", "place of the detected coordinates. >>> replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W", "'00', 'W', '50', '40', '00'] >>> _cleanup({'latdir': 'south', 'longdir': 'west',", ">>> replace(\"5814N/07720W\", google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>' >>> from", "= Decimal(latsec) longitude = Decimal(longdeg) longmin = Decimal(longmin) longsec =", "\"\"\" substitutions = {} matches = parser_re.finditer(string) for match in", "to degrees, minutes, and seconds. >>> _cleanup({'latdir': 'south', 'longdir': 'west',", "minutes, and seconds. >>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30',", "import bing_maps_link >>> replace(\"58N/077W\", bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58, -77)\">58N/077W</a>'", "'00'): precision = Decimal('0.000001') elif (latmin != '00' or longmin", "'00' longsec = '00' else: latsec = parts.get('latsec', '') or", "/ Decimal('100'))) / Decimal('60') else: latitude += (latmin + (latsec", "== 'S': latitude *= Decimal('-1') if longdir == 'W': longitude", "substitution by :func:`re.sub`, as in :func:`replace`. >>> get_replacements(\"4630 NORTH 5705", "\"\"\" if (latsec != '00' or longsec != '00'): precision", "(match, link) in replacements.items(): ... start = match.start() + offset", "utf-8 -*- from decimal import Decimal, setcontext, ExtendedContext from geolucidate.links.google", "detected coordinates with a map link, using the given substitution", "when the replacement cannot be performed through ordinary string substitution", "'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60', '30.50', '00', 'W', '50', '40.90', '00'] \"\"\"", "... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60', '30.50', '00', 'W', '50', '40.90', '00']", "substituted by :func:`re.sub` in place of the detected coordinates. >>>", "'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S', '60', '30', '00', 'W', '50', '40',", "a :class:`~.MapLink` instance, and should return a string which will", "'') if (latdecsec and longdecsec): latmin += latdecsec longmin +=", "Decimal, setcontext, ExtendedContext from geolucidate.links.google import google_maps_link from geolucidate.links.tools import", "long_str = str(longitude.quantize(precision)) return (lat_str, long_str) def replace(string, sub_function=google_maps_link()): \"\"\"", "bytearray(link, encoding=\"ascii\", errors=\"replace\") ... offset += (len(link) - len(match.group())) >>>", ">>> offset = 0 >>> out = bytearray(test_string, encoding=\"ascii\", errors=\"replace\")", "using the given substitution function. The substitution function will be", "href=\"...\" title=\"...\">4630 NORTH 5705 WEST</a>', <re.Match object...>: '<a href=\"...\" title=\"...\">58147N/07720W</a>'}", "or parts['latdir2']).upper()[0] longdir = (parts['longdir'] or parts['longdir2']).upper()[0] latdeg = parts.get('latdeg')", "longdecsec = parts.get('longdecsec', '') if (latdecsec and longdecsec): latmin +=", "!= '00' or longsec != '00'): precision = Decimal('0.000001') elif", "/ Decimal('60') else: latitude += (latmin + (latsec / Decimal('60')))", "latmin = parts.get('latmin', '00') or '00' longmin = parts.get('longmin', '00')", "a 2-tuple of strings. >>> _convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333') >>> _convert('N','50','27','55','W','127','27','65')", "latitude += (latmin + (latsec / Decimal('60'))) / Decimal('60') longitude", "link) in replacements.items(): ... start = match.start() + offset ...", "replacements.items(): ... start = match.start() + offset ... end =", "... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S', '60', '30', '00', 'W', '50',", "actually a decimal # fraction of minutes latitude += (latmin", "= \"4630 NORTH 5705 WEST 58147N/07720W\" >>> replacements = get_replacements(test_string)", "== 'W': longitude *= Decimal('-1') lat_str = str(latitude.quantize(precision)) long_str =", "of the detected coordinates. >>> replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278,", "setcontext(ExtendedContext) def _cleanup(parts): \"\"\" Normalize up the parts matched by", "offset = 0 >>> out = bytearray(test_string, encoding=\"ascii\", errors=\"replace\") >>>", "parts.get('latdecsec', '') longdecsec = parts.get('longdecsec', '') if (latdecsec and longdecsec):", "= parts.get('longdeg') latmin = parts.get('latmin', '00') or '00' longmin =", ">>> replacements = get_replacements(test_string) >>> offset = 0 >>> out", "= str(longitude.quantize(precision)) return (lat_str, long_str) def replace(string, sub_function=google_maps_link()): \"\"\" Replace", "longitude) = _convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string, latitude, longitude)) return parser_re.sub(do_replace, string)", "Decimal('100'))) / Decimal('60') longitude += (longmin + (longsec / Decimal('100')))", "are the corresponding replacements. Use :func:`get_replacements` when the replacement cannot", "'40.90', '00'] \"\"\" latdir = (parts['latdir'] or parts['latdir2']).upper()[0] longdir =", "(latsec != '00' or longsec != '00'): precision = Decimal('0.000001')", "decimal import Decimal, setcontext, ExtendedContext from geolucidate.links.google import google_maps_link from", "/ Decimal('60'))) / Decimal('60') longitude += (longmin + (longsec /", "WEST</a>', <re.Match object...>: '<a href=\"...\" title=\"...\">58147N/07720W</a>'} >>> test_string = \"4630", "= (parts['latdir'] or parts['latdir2']).upper()[0] longdir = (parts['longdir'] or parts['longdir2']).upper()[0] latdeg", "'-50.508333') >>> _convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833') \"\"\" if (latsec != '00'", "geolucidate.links.google import google_maps_link from geolucidate.links.tools import MapLink from geolucidate.parser import", "detected coordinates. >>> replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>' >>>", "on the input precision and return a 2-tuple of strings.", "degrees, minutes, and seconds. >>> _cleanup({'latdir': 'south', 'longdir': 'west', ...", "title=\"...\">58147N/07720W</a>'} >>> test_string = \"4630 NORTH 5705 WEST 58147N/07720W\" >>>", "= Decimal('0.000001') elif (latmin != '00' or longmin != '00'):", "replacements = get_replacements(test_string) >>> offset = 0 >>> out =", "= {} matches = parser_re.finditer(string) for match in matches: (latitude,", "end = match.end() + offset ... out[start:end] = bytearray(link, encoding=\"ascii\",", "= str(latitude.quantize(precision)) long_str = str(longitude.quantize(precision)) return (lat_str, long_str) def replace(string,", "else: latsec = parts.get('latsec', '') or '00' longsec = parts.get('longsec',", "title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>' >>> from geolucidate.links.bing import bing_maps_link >>> replace(\"58N/077W\",", "Assume that 'seconds' greater than 59 are actually a decimal", "out[start:end] = bytearray(link, encoding=\"ascii\", errors=\"replace\") ... offset += (len(link) -", "'longdir': 'west', ... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S', '60', '30', '00',", "= parts.get('longsec', '') or '00' return [latdir, latdeg, latmin, latsec,", "and longdecsec): latmin += latdecsec longmin += longdecsec latsec =", "if latdir == 'S': latitude *= Decimal('-1') if longdir ==", "'') or '00' return [latdir, latdeg, latmin, latsec, longdir, longdeg,", "parser_re.finditer(string) for match in matches: (latitude, longitude) = _convert(*_cleanup(match.groupdict())) substitutions[match]", "than 59 are actually a decimal # fraction of minutes", "function. The substitution function will be passed a :class:`~.MapLink` instance,", "import MapLink from geolucidate.parser import parser_re setcontext(ExtendedContext) def _cleanup(parts): \"\"\"", "= parser_re.finditer(string) for match in matches: (latitude, longitude) = _convert(*_cleanup(match.groupdict()))", "!= '00' or longmin != '00'): precision = Decimal('0.001') else:", "*= Decimal('-1') if longdir == 'W': longitude *= Decimal('-1') lat_str", "'W', '50', '40.90', '00'] \"\"\" latdir = (parts['latdir'] or parts['latdir2']).upper()[0]", "converted value based on the input precision and return a", "degrees. Quantize the converted value based on the input precision", "+= longdecsec latsec = '00' longsec = '00' else: latsec", "sub_function=google_maps_link()): \"\"\" Return a dict whose keys are instances of", "_cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', 'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S',", "(58.233, -77.333)\">5814N/07720W</a>' >>> from geolucidate.links.bing import bing_maps_link >>> replace(\"58N/077W\", bing_maps_link('map'))", "- len(match.group())) >>> out.decode(encoding=\"ascii\") == replace(test_string) True \"\"\" substitutions =", "'00' latdecsec = parts.get('latdecsec', '') longdecsec = parts.get('longdecsec', '') if", "instances of :class:`re.Match` and whose values are the corresponding replacements.", "'40', '00'] >>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', 'latdecsec':'.50',", "\"\"\" latdir = (parts['latdir'] or parts['latdir2']).upper()[0] longdir = (parts['longdir'] or", "+ (longsec / Decimal('100'))) / Decimal('60') else: latitude += (latmin", "_cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S', '60',", "instance, and should return a string which will be substituted", "'seconds' greater than 59 are actually a decimal # fraction", "else: latitude += (latmin + (latsec / Decimal('60'))) / Decimal('60')", "'W': longitude *= Decimal('-1') lat_str = str(latitude.quantize(precision)) long_str = str(longitude.quantize(precision))", "by :func:`re.sub` in place of the detected coordinates. >>> replace(\"58147N/07720W\")", "errors=\"replace\") >>> for (match, link) in replacements.items(): ... start =", "string substitution by :func:`re.sub`, as in :func:`replace`. >>> get_replacements(\"4630 NORTH", "'50', '40', '00'] >>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30',", "_convert(latdir, latdeg, latmin, latsec, longdir, longdeg, longmin, longsec): \"\"\" Convert", "WEST 58147N/07720W\") ... #doctest: +ELLIPSIS {<re.Match object...>: '<a href=\"...\" title=\"...\">4630", "+= (len(link) - len(match.group())) >>> out.decode(encoding=\"ascii\") == replace(test_string) True \"\"\"", "the converted value based on the input precision and return", "'longdir': 'west', ... 'latdeg':'60','latmin':'30', 'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60', '30.50',", "+ offset ... out[start:end] = bytearray(link, encoding=\"ascii\", errors=\"replace\") ... offset", "# -*- coding: utf-8 -*- from decimal import Decimal, setcontext,", "longdir == 'W': longitude *= Decimal('-1') lat_str = str(latitude.quantize(precision)) long_str", "href=\"...\" title=\"...\">58147N/07720W</a>'} >>> test_string = \"4630 NORTH 5705 WEST 58147N/07720W\"", "the given substitution function. The substitution function will be passed", "= '00' else: latsec = parts.get('latsec', '') or '00' longsec", "'00'): precision = Decimal('0.001') else: precision = Decimal('1') latitude =", "input precision and return a 2-tuple of strings. >>> _convert('S','50','30','30','W','50','30','30')", "(latmin + (latsec / Decimal('60'))) / Decimal('60') longitude += (longmin", "(58, -77)\">58N/077W</a>' \"\"\" def do_replace(match): original_string = match.group() (latitude, longitude)", "parts.get('longmin', '00') or '00' latdecsec = parts.get('latdecsec', '') longdecsec =", "+= (latmin + (latsec / Decimal('100'))) / Decimal('60') longitude +=", "title=\"58N/077W (58, -77)\">58N/077W</a>' \"\"\" def do_replace(match): original_string = match.group() (latitude,", "True \"\"\" substitutions = {} matches = parser_re.finditer(string) for match", ">>> out = bytearray(test_string, encoding=\"ascii\", errors=\"replace\") >>> for (match, link)", "\"\"\" Convert normalized degrees, minutes, and seconds to decimal degrees.", "minutes, and seconds to decimal degrees. Quantize the converted value", ">>> replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\", google_maps_link('satellite'))", "= _convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string, latitude, longitude)) return parser_re.sub(do_replace, string) def", "minutes latitude += (latmin + (latsec / Decimal('100'))) / Decimal('60')", "(longsec / Decimal('60'))) / Decimal('60') if latdir == 'S': latitude", "matches = parser_re.finditer(string) for match in matches: (latitude, longitude) =", "in matches: (latitude, longitude) = _convert(*_cleanup(match.groupdict())) substitutions[match] = sub_function(MapLink(match.group(), latitude,", "'00' longsec = parts.get('longsec', '') or '00' return [latdir, latdeg,", "+= latdecsec longmin += longdecsec latsec = '00' longsec =", "cannot be performed through ordinary string substitution by :func:`re.sub`, as", "whose values are the corresponding replacements. Use :func:`get_replacements` when the", "(latsec / Decimal('60'))) / Decimal('60') longitude += (longmin + (longsec", "= parts.get('longmin', '00') or '00' latdecsec = parts.get('latdecsec', '') longdecsec", "or longsec != '00'): precision = Decimal('0.000001') elif (latmin !=", "Decimal(longdeg) longmin = Decimal(longmin) longsec = Decimal(longsec) if latsec >", "from decimal import Decimal, setcontext, ExtendedContext from geolucidate.links.google import google_maps_link", "as in :func:`replace`. >>> get_replacements(\"4630 NORTH 5705 WEST 58147N/07720W\") ...", "sub_function(MapLink(original_string, latitude, longitude)) return parser_re.sub(do_replace, string) def get_replacements(string, sub_function=google_maps_link()): \"\"\"", "coordinates with a map link, using the given substitution function.", "!= '00'): precision = Decimal('0.001') else: precision = Decimal('1') latitude", ":func:`re.sub`, as in :func:`replace`. >>> get_replacements(\"4630 NORTH 5705 WEST 58147N/07720W\")", "= get_replacements(test_string) >>> offset = 0 >>> out = bytearray(test_string,", "keys are instances of :class:`re.Match` and whose values are the", "(58.235278, -77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\", google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>'", "longmin != '00'): precision = Decimal('0.001') else: precision = Decimal('1')", "longdeg = parts.get('longdeg') latmin = parts.get('latmin', '00') or '00' longmin", "-77)\">58N/077W</a>' \"\"\" def do_replace(match): original_string = match.group() (latitude, longitude) =", "longsec = '00' else: latsec = parts.get('latsec', '') or '00'", "that 'seconds' greater than 59 are actually a decimal #", "if (latdecsec and longdecsec): latmin += latdecsec longmin += longdecsec", "= Decimal('1') latitude = Decimal(latdeg) latmin = Decimal(latmin) latsec =", ">>> for (match, link) in replacements.items(): ... start = match.start()", "Decimal('60') if latdir == 'S': latitude *= Decimal('-1') if longdir", "longsec > 59: # Assume that 'seconds' greater than 59", "of :class:`re.Match` and whose values are the corresponding replacements. Use", "(len(link) - len(match.group())) >>> out.decode(encoding=\"ascii\") == replace(test_string) True \"\"\" substitutions", "latitude += (latmin + (latsec / Decimal('100'))) / Decimal('60') longitude", "Decimal('100'))) / Decimal('60') else: latitude += (latmin + (latsec /", "= parts.get('latdecsec', '') longdecsec = parts.get('longdecsec', '') if (latdecsec and", "(lat_str, long_str) def replace(string, sub_function=google_maps_link()): \"\"\" Replace detected coordinates with", "if longdir == 'W': longitude *= Decimal('-1') lat_str = str(latitude.quantize(precision))", "latsec > 59 or longsec > 59: # Assume that", "'W', '50', '40', '00'] >>> _cleanup({'latdir': 'south', 'longdir': 'west', ...", "-77.333)\">5814N/07720W</a>' >>> from geolucidate.links.bing import bing_maps_link >>> replace(\"58N/077W\", bing_maps_link('map')) '<a", "substitution function. The substitution function will be passed a :class:`~.MapLink`", "be passed a :class:`~.MapLink` instance, and should return a string", "the replacement cannot be performed through ordinary string substitution by", "through ordinary string substitution by :func:`re.sub`, as in :func:`replace`. >>>", "and seconds to decimal degrees. Quantize the converted value based", "the detected coordinates. >>> replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>'", "'00' else: latsec = parts.get('latsec', '') or '00' longsec =", ">>> out.decode(encoding=\"ascii\") == replace(test_string) True \"\"\" substitutions = {} matches", "degrees, minutes, and seconds to decimal degrees. Quantize the converted", "/ Decimal('60'))) / Decimal('60') if latdir == 'S': latitude *=", "= '00' longsec = '00' else: latsec = parts.get('latsec', '')", "object...>: '<a href=\"...\" title=\"...\">58147N/07720W</a>'} >>> test_string = \"4630 NORTH 5705", "for (match, link) in replacements.items(): ... start = match.start() +", "... 'latdeg':'60','latmin':'30', 'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60', '30.50', '00', 'W',", "'<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\", google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\"", "= Decimal(longmin) longsec = Decimal(longsec) if latsec > 59 or", "return (lat_str, long_str) def replace(string, sub_function=google_maps_link()): \"\"\" Replace detected coordinates", "bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58, -77)\">58N/077W</a>' \"\"\" def do_replace(match): original_string", "a decimal # fraction of minutes latitude += (latmin +", "def _cleanup(parts): \"\"\" Normalize up the parts matched by :obj:`parser.parser_re`", "_convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833') \"\"\" if (latsec != '00' or longsec", "'<a href=\"...\" title=\"...\">58147N/07720W</a>'} >>> test_string = \"4630 NORTH 5705 WEST", "Decimal('-1') if longdir == 'W': longitude *= Decimal('-1') lat_str =", "by :func:`re.sub`, as in :func:`replace`. >>> get_replacements(\"4630 NORTH 5705 WEST", "import Decimal, setcontext, ExtendedContext from geolucidate.links.google import google_maps_link from geolucidate.links.tools", "parts.get('latsec', '') or '00' longsec = parts.get('longsec', '') or '00'", "(parts['latdir'] or parts['latdir2']).upper()[0] longdir = (parts['longdir'] or parts['longdir2']).upper()[0] latdeg =", "parser_re.sub(do_replace, string) def get_replacements(string, sub_function=google_maps_link()): \"\"\" Return a dict whose", "Decimal('-1') lat_str = str(latitude.quantize(precision)) long_str = str(longitude.quantize(precision)) return (lat_str, long_str)", ":func:`get_replacements` when the replacement cannot be performed through ordinary string", "> 59: # Assume that 'seconds' greater than 59 are", "!= '00'): precision = Decimal('0.000001') elif (latmin != '00' or", "{<re.Match object...>: '<a href=\"...\" title=\"...\">4630 NORTH 5705 WEST</a>', <re.Match object...>:", "geolucidate.links.bing import bing_maps_link >>> replace(\"58N/077W\", bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58,", "= match.group() (latitude, longitude) = _convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string, latitude, longitude))", "_cleanup(parts): \"\"\" Normalize up the parts matched by :obj:`parser.parser_re` to", "Decimal(longsec) if latsec > 59 or longsec > 59: #", "('50.459167', '-127.460833') \"\"\" if (latsec != '00' or longsec !=", "def _convert(latdir, latdeg, latmin, latsec, longdir, longdeg, longmin, longsec): \"\"\"", "longsec != '00'): precision = Decimal('0.000001') elif (latmin != '00'", "Decimal('60'))) / Decimal('60') longitude += (longmin + (longsec / Decimal('60')))", "+ELLIPSIS {<re.Match object...>: '<a href=\"...\" title=\"...\">4630 NORTH 5705 WEST</a>', <re.Match", "<filename>geolucidate/functions.py # -*- coding: utf-8 -*- from decimal import Decimal,", "'00' or longmin != '00'): precision = Decimal('0.001') else: precision", "in place of the detected coordinates. >>> replace(\"58147N/07720W\") '<a href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\"", "Use :func:`get_replacements` when the replacement cannot be performed through ordinary", "or longmin != '00'): precision = Decimal('0.001') else: precision =", "# Assume that 'seconds' greater than 59 are actually a", "-77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\", google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>' >>>", "get_replacements(\"4630 NORTH 5705 WEST 58147N/07720W\") ... #doctest: +ELLIPSIS {<re.Match object...>:", "{} matches = parser_re.finditer(string) for match in matches: (latitude, longitude)", ":func:`re.sub` in place of the detected coordinates. >>> replace(\"58147N/07720W\") '<a", "a dict whose keys are instances of :class:`re.Match` and whose", "precision and return a 2-tuple of strings. >>> _convert('S','50','30','30','W','50','30','30') ('-50.508333',", "longdeg, longmin, longsec] def _convert(latdir, latdeg, latmin, latsec, longdir, longdeg,", "'<a href=\"...\" title=\"...\">4630 NORTH 5705 WEST</a>', <re.Match object...>: '<a href=\"...\"", "performed through ordinary string substitution by :func:`re.sub`, as in :func:`replace`.", "parser_re setcontext(ExtendedContext) def _cleanup(parts): \"\"\" Normalize up the parts matched", "return a string which will be substituted by :func:`re.sub` in", "parts['latdir2']).upper()[0] longdir = (parts['longdir'] or parts['longdir2']).upper()[0] latdeg = parts.get('latdeg') longdeg", "dict whose keys are instances of :class:`re.Match` and whose values", "map link, using the given substitution function. The substitution function", "and seconds. >>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', ...", "*= Decimal('-1') lat_str = str(latitude.quantize(precision)) long_str = str(longitude.quantize(precision)) return (lat_str,", "= parts.get('longdecsec', '') if (latdecsec and longdecsec): latmin += latdecsec", "return parser_re.sub(do_replace, string) def get_replacements(string, sub_function=google_maps_link()): \"\"\" Return a dict", ">>> _convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833') \"\"\" if (latsec != '00' or", "def get_replacements(string, sub_function=google_maps_link()): \"\"\" Return a dict whose keys are", "/ Decimal('100'))) / Decimal('60') longitude += (longmin + (longsec /", "longdir, longdeg, longmin, longsec] def _convert(latdir, latdeg, latmin, latsec, longdir,", "\"\"\" Normalize up the parts matched by :obj:`parser.parser_re` to degrees,", "Decimal(longmin) longsec = Decimal(longsec) if latsec > 59 or longsec", "precision = Decimal('1') latitude = Decimal(latdeg) latmin = Decimal(latmin) latsec", "long_str) def replace(string, sub_function=google_maps_link()): \"\"\" Replace detected coordinates with a", "will be passed a :class:`~.MapLink` instance, and should return a", "encoding=\"ascii\", errors=\"replace\") ... offset += (len(link) - len(match.group())) >>> out.decode(encoding=\"ascii\")", "(latitude, longitude) = _convert(*_cleanup(match.groupdict())) substitutions[match] = sub_function(MapLink(match.group(), latitude, longitude)) return", "+= (longmin + (longsec / Decimal('100'))) / Decimal('60') else: latitude", "'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60', '30.50', '00', 'W', '50', '40.90',", "'00', 'W', '50', '40.90', '00'] \"\"\" latdir = (parts['latdir'] or", "or parts['longdir2']).upper()[0] latdeg = parts.get('latdeg') longdeg = parts.get('longdeg') latmin =", "latdecsec longmin += longdecsec latsec = '00' longsec = '00'", "'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S', '60', '30',", "... end = match.end() + offset ... out[start:end] = bytearray(link,", "be performed through ordinary string substitution by :func:`re.sub`, as in", "or longsec > 59: # Assume that 'seconds' greater than", "parts.get('longdecsec', '') if (latdecsec and longdecsec): latmin += latdecsec longmin", "[latdir, latdeg, latmin, latsec, longdir, longdeg, longmin, longsec] def _convert(latdir,", "Return a dict whose keys are instances of :class:`re.Match` and", "decimal # fraction of minutes latitude += (latmin + (latsec", "latdeg = parts.get('latdeg') longdeg = parts.get('longdeg') latmin = parts.get('latmin', '00')", "parts.get('longsec', '') or '00' return [latdir, latdeg, latmin, latsec, longdir,", "substitutions = {} matches = parser_re.finditer(string) for match in matches:", "+ (longsec / Decimal('60'))) / Decimal('60') if latdir == 'S':", "latdir = (parts['latdir'] or parts['latdir2']).upper()[0] longdir = (parts['longdir'] or parts['longdir2']).upper()[0]", "replace(\"58N/077W\", bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W (58, -77)\">58N/077W</a>' \"\"\" def do_replace(match):", "longitude = Decimal(longdeg) longmin = Decimal(longmin) longsec = Decimal(longsec) if", "parts['longdir2']).upper()[0] latdeg = parts.get('latdeg') longdeg = parts.get('longdeg') latmin = parts.get('latmin',", "precision = Decimal('0.000001') elif (latmin != '00' or longmin !=", "in :func:`replace`. >>> get_replacements(\"4630 NORTH 5705 WEST 58147N/07720W\") ... #doctest:", "Decimal('60') else: latitude += (latmin + (latsec / Decimal('60'))) /", "Decimal(latdeg) latmin = Decimal(latmin) latsec = Decimal(latsec) longitude = Decimal(longdeg)", "do_replace(match): original_string = match.group() (latitude, longitude) = _convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string,", "parts matched by :obj:`parser.parser_re` to degrees, minutes, and seconds. >>>", "of strings. >>> _convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333') >>> _convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833')", "'west', ... 'latdeg':'60','latmin':'30', 'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60', '30.50', '00',", "= 0 >>> out = bytearray(test_string, encoding=\"ascii\", errors=\"replace\") >>> for", "+= (longmin + (longsec / Decimal('60'))) / Decimal('60') if latdir", "google_maps_link from geolucidate.links.tools import MapLink from geolucidate.parser import parser_re setcontext(ExtendedContext)", "href=\"http://maps.google.com/maps?q=58.235278%2C-77.333333+%2858147N%2F07720W%29&ll=58.235278%2C-77.333333&t=h\" title=\"58147N/07720W (58.235278, -77.333333)\">58147N/07720W</a>' >>> replace(\"5814N/07720W\", google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W", "based on the input precision and return a 2-tuple of", "(longmin + (longsec / Decimal('60'))) / Decimal('60') if latdir ==", "whose keys are instances of :class:`re.Match` and whose values are", ":class:`re.Match` and whose values are the corresponding replacements. Use :func:`get_replacements`", "\"\"\" Return a dict whose keys are instances of :class:`re.Match`", "'60', '30', '00', 'W', '50', '40', '00'] >>> _cleanup({'latdir': 'south',", "longmin = Decimal(longmin) longsec = Decimal(longsec) if latsec > 59", "given substitution function. The substitution function will be passed a", "parts.get('longdeg') latmin = parts.get('latmin', '00') or '00' longmin = parts.get('longmin',", "ordinary string substitution by :func:`re.sub`, as in :func:`replace`. >>> get_replacements(\"4630", "longdir, longdeg, longmin, longsec): \"\"\" Convert normalized degrees, minutes, and", "the input precision and return a 2-tuple of strings. >>>", "Decimal('60'))) / Decimal('60') if latdir == 'S': latitude *= Decimal('-1')", "match.group() (latitude, longitude) = _convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string, latitude, longitude)) return", "'latdeg':'60','latmin':'30', 'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'}) ['S', '60', '30.50', '00', 'W', '50',", "+= (latmin + (latsec / Decimal('60'))) / Decimal('60') longitude +=", "+ (latsec / Decimal('60'))) / Decimal('60') longitude += (longmin +", "'<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>' >>> from geolucidate.links.bing import bing_maps_link", "longdecsec): latmin += latdecsec longmin += longdecsec latsec = '00'", "'00') or '00' longmin = parts.get('longmin', '00') or '00' latdecsec", "(latdecsec and longdecsec): latmin += latdecsec longmin += longdecsec latsec", ">>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', 'latdecsec':'.50', ... 'longdeg':'50','longmin':'40','longdecsec':'.90'})", "longitude += (longmin + (longsec / Decimal('100'))) / Decimal('60') else:", "if latsec > 59 or longsec > 59: # Assume", "(parts['longdir'] or parts['longdir2']).upper()[0] latdeg = parts.get('latdeg') longdeg = parts.get('longdeg') latmin", "latsec, longdir, longdeg, longmin, longsec] def _convert(latdir, latdeg, latmin, latsec,", "precision = Decimal('0.001') else: precision = Decimal('1') latitude = Decimal(latdeg)", "= Decimal(latmin) latsec = Decimal(latsec) longitude = Decimal(longdeg) longmin =", "string) def get_replacements(string, sub_function=google_maps_link()): \"\"\" Return a dict whose keys", "-*- coding: utf-8 -*- from decimal import Decimal, setcontext, ExtendedContext", "or '00' longsec = parts.get('longsec', '') or '00' return [latdir,", "Decimal('60') longitude += (longmin + (longsec / Decimal('60'))) / Decimal('60')", "corresponding replacements. Use :func:`get_replacements` when the replacement cannot be performed", "coding: utf-8 -*- from decimal import Decimal, setcontext, ExtendedContext from", "_convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333') >>> _convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833') \"\"\" if (latsec", "values are the corresponding replacements. Use :func:`get_replacements` when the replacement", "be substituted by :func:`re.sub` in place of the detected coordinates.", "Decimal('0.000001') elif (latmin != '00' or longmin != '00'): precision", "'S': latitude *= Decimal('-1') if longdir == 'W': longitude *=", "are instances of :class:`re.Match` and whose values are the corresponding", "import google_maps_link from geolucidate.links.tools import MapLink from geolucidate.parser import parser_re", "string which will be substituted by :func:`re.sub` in place of", ":obj:`parser.parser_re` to degrees, minutes, and seconds. >>> _cleanup({'latdir': 'south', 'longdir':", "\"4630 NORTH 5705 WEST 58147N/07720W\" >>> replacements = get_replacements(test_string) >>>", "substitution function will be passed a :class:`~.MapLink` instance, and should", "test_string = \"4630 NORTH 5705 WEST 58147N/07720W\" >>> replacements =", "or '00' latdecsec = parts.get('latdecsec', '') longdecsec = parts.get('longdecsec', '')", "Convert normalized degrees, minutes, and seconds to decimal degrees. Quantize", "fraction of minutes latitude += (latmin + (latsec / Decimal('100')))", "link, using the given substitution function. The substitution function will", "'30', '00', 'W', '50', '40', '00'] >>> _cleanup({'latdir': 'south', 'longdir':", "longdecsec latsec = '00' longsec = '00' else: latsec =", "the parts matched by :obj:`parser.parser_re` to degrees, minutes, and seconds.", "'-127.460833') \"\"\" if (latsec != '00' or longsec != '00'):", "/ Decimal('60') if latdir == 'S': latitude *= Decimal('-1') if", "function will be passed a :class:`~.MapLink` instance, and should return", "from geolucidate.links.google import google_maps_link from geolucidate.links.tools import MapLink from geolucidate.parser", "by :obj:`parser.parser_re` to degrees, minutes, and seconds. >>> _cleanup({'latdir': 'south',", "decimal degrees. Quantize the converted value based on the input", "with a map link, using the given substitution function. The", "errors=\"replace\") ... offset += (len(link) - len(match.group())) >>> out.decode(encoding=\"ascii\") ==", "longdeg, longmin, longsec): \"\"\" Convert normalized degrees, minutes, and seconds", "5705 WEST 58147N/07720W\" >>> replacements = get_replacements(test_string) >>> offset =", "# fraction of minutes latitude += (latmin + (latsec /", "latdeg, latmin, latsec, longdir, longdeg, longmin, longsec] def _convert(latdir, latdeg,", "return [latdir, latdeg, latmin, latsec, longdir, longdeg, longmin, longsec] def", "... start = match.start() + offset ... end = match.end()", "longdir = (parts['longdir'] or parts['longdir2']).upper()[0] latdeg = parts.get('latdeg') longdeg =", "geolucidate.parser import parser_re setcontext(ExtendedContext) def _cleanup(parts): \"\"\" Normalize up the", "longitude += (longmin + (longsec / Decimal('60'))) / Decimal('60') if", "replace(\"5814N/07720W\", google_maps_link('satellite')) '<a href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>' >>> from geolucidate.links.bing", "Quantize the converted value based on the input precision and", "... #doctest: +ELLIPSIS {<re.Match object...>: '<a href=\"...\" title=\"...\">4630 NORTH 5705", "return sub_function(MapLink(original_string, latitude, longitude)) return parser_re.sub(do_replace, string) def get_replacements(string, sub_function=google_maps_link()):", "'00' or longsec != '00'): precision = Decimal('0.000001') elif (latmin", ":class:`~.MapLink` instance, and should return a string which will be", "replace(string, sub_function=google_maps_link()): \"\"\" Replace detected coordinates with a map link,", "<re.Match object...>: '<a href=\"...\" title=\"...\">58147N/07720W</a>'} >>> test_string = \"4630 NORTH", "sub_function=google_maps_link()): \"\"\" Replace detected coordinates with a map link, using", "... offset += (len(link) - len(match.group())) >>> out.decode(encoding=\"ascii\") == replace(test_string)", "('-50.508333', '-50.508333') >>> _convert('N','50','27','55','W','127','27','65') ('50.459167', '-127.460833') \"\"\" if (latsec !=", "(latmin + (latsec / Decimal('100'))) / Decimal('60') longitude += (longmin", "latmin = Decimal(latmin) latsec = Decimal(latsec) longitude = Decimal(longdeg) longmin", "latsec = '00' longsec = '00' else: latsec = parts.get('latsec',", "Normalize up the parts matched by :obj:`parser.parser_re` to degrees, minutes,", "and return a 2-tuple of strings. >>> _convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333')", "(longsec / Decimal('100'))) / Decimal('60') else: latitude += (latmin +", "NORTH 5705 WEST 58147N/07720W\" >>> replacements = get_replacements(test_string) >>> offset", "2-tuple of strings. >>> _convert('S','50','30','30','W','50','30','30') ('-50.508333', '-50.508333') >>> _convert('N','50','27','55','W','127','27','65') ('50.459167',", "= parts.get('latdeg') longdeg = parts.get('longdeg') latmin = parts.get('latmin', '00') or", "passed a :class:`~.MapLink` instance, and should return a string which", "WEST 58147N/07720W\" >>> replacements = get_replacements(test_string) >>> offset = 0", "= Decimal(longsec) if latsec > 59 or longsec > 59:", "match in matches: (latitude, longitude) = _convert(*_cleanup(match.groupdict())) substitutions[match] = sub_function(MapLink(match.group(),", "latitude = Decimal(latdeg) latmin = Decimal(latmin) latsec = Decimal(latsec) longitude", "len(match.group())) >>> out.decode(encoding=\"ascii\") == replace(test_string) True \"\"\" substitutions = {}", "+ (latsec / Decimal('100'))) / Decimal('60') longitude += (longmin +", "longsec = parts.get('longsec', '') or '00' return [latdir, latdeg, latmin,", "_convert(*_cleanup(match.groupdict())) return sub_function(MapLink(original_string, latitude, longitude)) return parser_re.sub(do_replace, string) def get_replacements(string,", ":func:`replace`. >>> get_replacements(\"4630 NORTH 5705 WEST 58147N/07720W\") ... #doctest: +ELLIPSIS", "longmin += longdecsec latsec = '00' longsec = '00' else:", "latdir == 'S': latitude *= Decimal('-1') if longdir == 'W':", "greater than 59 are actually a decimal # fraction of", "from geolucidate.links.bing import bing_maps_link >>> replace(\"58N/077W\", bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\" title=\"58N/077W", "href=\"http://maps.google.com/maps?q=58.233%2C-77.333+%285814N%2F07720W%29&ll=58.233%2C-77.333&t=k\" title=\"5814N/07720W (58.233, -77.333)\">5814N/07720W</a>' >>> from geolucidate.links.bing import bing_maps_link >>>", "(latmin != '00' or longmin != '00'): precision = Decimal('0.001')", ">>> from geolucidate.links.bing import bing_maps_link >>> replace(\"58N/077W\", bing_maps_link('map')) '<a href=\"http://bing.com/maps/default.aspx?style=r&cp=58~-77&sp=Point.58_-77_58N%2F077W&v=2\"", "object...>: '<a href=\"...\" title=\"...\">4630 NORTH 5705 WEST</a>', <re.Match object...>: '<a", "longitude *= Decimal('-1') lat_str = str(latitude.quantize(precision)) long_str = str(longitude.quantize(precision)) return", "Decimal('1') latitude = Decimal(latdeg) latmin = Decimal(latmin) latsec = Decimal(latsec)" ]
[ "setuptools import setup, find_packages setup( name='Pokedex', version='0.1', zip_safe=False, packages=find_packages(), package_data={", "version='0.1', zip_safe=False, packages=find_packages(), package_data={ 'pokedex': ['data/csv/*.csv'] }, install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7',", "2.7\", \"Programming Language :: Python :: 3.4\", \"Programming Language ::", ":: Python :: 3.5\", \"Programming Language :: Python :: 3.7\",", "Python :: 2.7\", \"Programming Language :: Python :: 3.4\", \"Programming", "find_packages setup( name='Pokedex', version='0.1', zip_safe=False, packages=find_packages(), package_data={ 'pokedex': ['data/csv/*.csv'] },", "= pokedex.main:setuptools_entry', ], }, classifiers=[ \"Programming Language :: Python ::", "], entry_points={ 'console_scripts': [ 'pokedex = pokedex.main:setuptools_entry', ], }, classifiers=[", "Language :: Python :: 3.5\", \"Programming Language :: Python ::", "}, classifiers=[ \"Programming Language :: Python :: 2.7\", \"Programming Language", "'pokedex = pokedex.main:setuptools_entry', ], }, classifiers=[ \"Programming Language :: Python", "'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0', ], entry_points={ 'console_scripts': [ 'pokedex", "\"Programming Language :: Python :: 3.4\", \"Programming Language :: Python", ":: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language", "'six>=1.9.0', ], entry_points={ 'console_scripts': [ 'pokedex = pokedex.main:setuptools_entry', ], },", "Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming", "install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0', ], entry_points={ 'console_scripts': [", "\"Programming Language :: Python :: 3.5\", \"Programming Language :: Python", "zip_safe=False, packages=find_packages(), package_data={ 'pokedex': ['data/csv/*.csv'] }, install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1',", "setup( name='Pokedex', version='0.1', zip_safe=False, packages=find_packages(), package_data={ 'pokedex': ['data/csv/*.csv'] }, install_requires=[", "'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0', ], entry_points={ 'console_scripts': [ 'pokedex = pokedex.main:setuptools_entry',", "packages=find_packages(), package_data={ 'pokedex': ['data/csv/*.csv'] }, install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3',", "package_data={ 'pokedex': ['data/csv/*.csv'] }, install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0',", "Language :: Python :: 2.7\", \"Programming Language :: Python ::", "[ 'pokedex = pokedex.main:setuptools_entry', ], }, classifiers=[ \"Programming Language ::", "pokedex.main:setuptools_entry', ], }, classifiers=[ \"Programming Language :: Python :: 2.7\",", "Python :: 3.5\", \"Programming Language :: Python :: 3.7\", ]", "}, install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0', ], entry_points={ 'console_scripts':", ":: 2.7\", \"Programming Language :: Python :: 3.4\", \"Programming Language", ":: 3.5\", \"Programming Language :: Python :: 3.7\", ] )", "], }, classifiers=[ \"Programming Language :: Python :: 2.7\", \"Programming", "import setup, find_packages setup( name='Pokedex', version='0.1', zip_safe=False, packages=find_packages(), package_data={ 'pokedex':", "\"Programming Language :: Python :: 2.7\", \"Programming Language :: Python", "'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0', ], entry_points={ 'console_scripts': [ 'pokedex =", "'construct==2.5.3', 'six>=1.9.0', ], entry_points={ 'console_scripts': [ 'pokedex = pokedex.main:setuptools_entry', ],", "['data/csv/*.csv'] }, install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0', ], entry_points={", "classifiers=[ \"Programming Language :: Python :: 2.7\", \"Programming Language ::", "Language :: Python :: 3.4\", \"Programming Language :: Python ::", "name='Pokedex', version='0.1', zip_safe=False, packages=find_packages(), package_data={ 'pokedex': ['data/csv/*.csv'] }, install_requires=[ 'SQLAlchemy>=1.0,<2.0',", "entry_points={ 'console_scripts': [ 'pokedex = pokedex.main:setuptools_entry', ], }, classifiers=[ \"Programming", ":: Python :: 2.7\", \"Programming Language :: Python :: 3.4\",", ":: Python :: 3.4\", \"Programming Language :: Python :: 3.5\",", "setup, find_packages setup( name='Pokedex', version='0.1', zip_safe=False, packages=find_packages(), package_data={ 'pokedex': ['data/csv/*.csv']", "3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language ::", "from setuptools import setup, find_packages setup( name='Pokedex', version='0.1', zip_safe=False, packages=find_packages(),", "'console_scripts': [ 'pokedex = pokedex.main:setuptools_entry', ], }, classifiers=[ \"Programming Language", "'pokedex': ['data/csv/*.csv'] }, install_requires=[ 'SQLAlchemy>=1.0,<2.0', 'whoosh>=2.5,<2.7', 'markdown==2.4.1', 'construct==2.5.3', 'six>=1.9.0', ]," ]
[ "residual_index % p.residual_stride == p.residual_stride - 1: # Highway skip", "config for the convolution layer. p.input_shape = [None, None, 80,", "% (i) f_conv_lstm_p.inputs_shape = [None, 1, width, in_channel] f_conv_lstm_p.cell_shape =", "2.0 (the \"License\"); # you may not use this file", "= p.conv_lstm_tpl.Copy() f_conv_lstm_p.name = 'f_conv_lstm_%d' % (i) f_conv_lstm_p.inputs_shape = [None,", "following encoder # architecture: # # cnn/batch-norm/relu -> # cnn/batch-norm/relu", "i in range(p.num_lstm_layers): if i == 0: input_dim = self._first_lstm_input_dim", "if p.project_lstm_output and (i < p.num_lstm_layers - 1): # Projection", "second_dim, -1]), [1, 0, 2]) t_shape_new = tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]],", "forward_p.num_input_nodes = input_dim forward_p.num_output_nodes = p.lstm_cell_size backward_p = forward_p.Copy() backward_p.name", "= self._first_lstm_input_dim else: input_dim = 2 * p.lstm_cell_size forward_p =", "convlstm layer.') p.Define('conv_filter_shapes', None, 'Filter shapes for each conv layer.')", "Makes sure the lstm input dims is multiple of 16", "2 * p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers)", "name='inputs') paddings = tf.concat([paddings, paddings_pad], 1) def ReshapeForPlot(tensor, padding, name):", "= lstm_input_shape[2] * lstm_input_shape[3] if self._use_functional and (first_lstm_input_dim_unpadded % pad_to_multiple", "= p.proj_tpl.Copy() proj_p.input_dim = 2 * p.lstm_cell_size proj_p.output_dim = 2", "# bidirectional lstm -> # projection/batch-norm/relu -> # bidirectional lstm", "- 1: # Highway skip connection. if p.highway_skip: rnn_out =", "self).__init__(params) p = self.params assert p.packed_input is False, ('Packed inputs", "We assume that output from ConvLSTMBlock has the same #", "(1.0 - rnn_padding) plots.append( ReshapeForPlot( tf.transpose(rnn_out, [1, 0, 2]), tf.transpose(rnn_padding,", "input state. Not supported/ignored by this encoder. Returns: (outputs, out_paddings,", "return (plot_tensor, summary_utils.SequenceLength(padding)) plots = [ ReshapeForPlot( tf.transpose(inputs, [0, 1,", "[1, 0, 2]), tf.transpose(rnn_padding, [1, 0, 2]), 'rnn_%d_out' % i))", "layer.') p.Define('pad_steps', 6, 'Extra zero-padded timesteps to add to the", "conv-lstm part. conv_lstm_out = conv_out conv_lstm_out_padding = out_padding for i,", "conv_lstm_rnn_p.name = 'conv_lstm_rnn' conv_lstm_rnn_p.fwd = f_conv_lstm_p conv_lstm_rnn_p.bak = b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p)", "3, 'Number of rnn layers to create') p.Define('project_lstm_output', True, 'Include", "NOTE(yonghui): Fortunately, variational noise logic is currently not # implemented", "conv-lstm -> # cnn/batch-norm/relu # bidirectional lstm -> # projection/batch-norm/relu", "supported/ignored by this encoder. Returns: (outputs, out_paddings, state1) tuple. Outputs", "rnn_out *= (1.0 - rnn_padding) plots.append( ReshapeForPlot( tf.transpose(rnn_out, [1, 0,", "p.conv_filter_strides = [(2, 2), (2, 2)] p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) #", "from lingvo.core import model_helper ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn')) class", "with fields: src_inputs - The inputs tensor. It is expected", "License for the specific language governing permissions and # limitations", "a separate file. # Set some reasonable default values. #", "i in range(p.num_lstm_layers): rnn_out = self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding) residual_index =", "Reserved. # # Licensed under the Apache License, Version 2.0", "ensuring the # correctness of the conv-layers at the edges.", "model.\"\"\" from __future__ import absolute_import from __future__ import division from", "from bottom to top. plots.reverse() for tensor, seq_len in plots:", "set, residual connections from different layers are gated. ' 'Will", "= [None, 1, width, in_channel] b_conv_lstm_p = f_conv_lstm_p.Copy() b_conv_lstm_p.name =", "rnn_p = self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name = 'brnn_L%d' % (i) params_rnn_layers.append(rnn_p)", "* lstm_input_shape[3] if self._use_functional and (first_lstm_input_dim_unpadded % pad_to_multiple != 0):", "base_encoder from lingvo.core import base_layer from lingvo.core import layers from", "tf.reshape(tensor, [batch_size, max_len, -1]) plot_tensor = tf.transpose(plot_tensor, [0, 2, 1],", "time dimension to be the first. conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in", "conv_lstm_out_padding, 'conv_lstm_%d_out' % i)) # Need to do a reshape", "zip import tensorflow as tf from tensorflow.python.ops import inplace_ops from", "at the edges. if p.pad_steps > 0: # inplace_update() is", "+ 1 if p.residual_start > 0 and residual_index >= 0", "range(p.num_cnn_layers): conv_p = p.cnn_tpl.Copy() conv_p.name = 'conv_L%d' % (i) conv_p.filter_shape", "params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers) @property def _use_functional(self): return True def CreateBidirectionalRNNParams(self,", "the shape [time, batch, depth], and out_paddings is of the", "1, 'Number of conv lstm layers to create.') p.Define('num_lstm_layers', 3,", "p.conv_filter_shapes[i] conv_p.filter_stride = p.conv_filter_strides[i] conv_p.is_eval = p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers)", "= batch.src_inputs, batch.paddings with tf.name_scope(p.name): # Add a few extra", "from lingvo.core import layers from lingvo.core import plot from lingvo.core", "(i < p.num_lstm_layers - 1): proj_p = p.proj_tpl.Copy() proj_p.input_dim =", "model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p) def CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self, conv_output_shape,", "if p.residual_start > 0 and residual_index >= 0 and p.highway_skip:", "2)] p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise logic.", "padding on the input_generator, we may avoid this additional padding.", "[1, 3] # height (time), width (frequency) p.conv_lstm_tpl.inputs_shape = [None,", "forward_p.num_output_nodes = p.lstm_cell_size backward_p = forward_p.Copy() backward_p.name = 'bak_rnn_L%d' %", "in range(p.num_conv_lstm_layers): # NOTE(yonghui): We assume that output from ConvLSTMBlock", "if self._first_lstm_input_dim_pad: conv_lstm_out = tf.pad( conv_lstm_out, [[0, 0], [0, 0],", "summary_utils from lingvo.core import model_helper ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn'))", "p.packed_input is False, ('Packed inputs are not yet supported for", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "tf.shape(conv_lstm_out) new_shape = tf.concat([conv_lstm_out_shape[:2], [-1]], 0) conv_lstm_out = tf.reshape(conv_lstm_out, new_shape)", "first_lstm_input_dim_unpadded = lstm_input_shape[2] * lstm_input_shape[3] if self._use_functional and (first_lstm_input_dim_unpadded %", "1], name=name) return (plot_tensor, summary_utils.SequenceLength(padding)) plots = [ ReshapeForPlot( tf.transpose(inputs,", "conv_out, out_padding) plots.append( ReshapeForPlot( tf.transpose(conv_out, [0, 1, 3, 2]), out_padding,", "to in writing, software # distributed under the License is", "height, width, channel. params_conv_lstm_rnn = [] params_conv_lstm_cnn = [] for", "tf.shape(t)[2:]], 0) return tf.reshape(t_new, t_shape_new) # Now the conv-lstm part.", "1: # Highway skip connection. if p.highway_skip: rnn_out = self.highway_skip[num_skips].FProp(", "or agreed to in writing, software # distributed under the", "= inputs out_padding = paddings for i, conv_layer in enumerate(self.conv):", "part. conv_lstm_out = conv_out conv_lstm_out_padding = out_padding for i, (rnn,", "each conv layer.') p.Define('input_shape', [None, None, None, None], 'Shape of", "to do a reshape before starting the rnn layers. conv_lstm_out", "skip connection. if p.highway_skip: rnn_out = self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in, rnn_out)", "done # padding on the input_generator, we may avoid this", "out_padding, 'conv_%d_out' % i)) def TransposeFirstTwoDims(t): first_dim = tf.shape(t)[0] second_dim", "should a TensorShape with rank 4.') p.Define('lstm_cell_size', 256, 'LSTM cell", "width, channel. params_conv_lstm_rnn = [] params_conv_lstm_cnn = [] for i", "to be the second. cnn_in = TransposeFirstTwoDims(lstm_out) cnn_in = tf.squeeze(cnn_in,", "conv_lstm_out_padding = out_padding for i, (rnn, cnn) in enumerate( zip(self.conv_lstm_rnn,", "new_shape) if self._first_lstm_input_dim_pad: conv_lstm_out = tf.pad( conv_lstm_out, [[0, 0], [0,", "name = p.name with tf.variable_scope(name): # First create the conv", "shape [batch, time, feature_dim, channels]. paddings - The paddings tensor.", "compliance with the License. # You may obtain a copy", "All Rights Reserved. # # Licensed under the Apache License,", "1: rnn_out *= (1.0 - rnn_padding) plots.append( ReshapeForPlot( tf.transpose(rnn_out, [1,", "'func', 'Options: func, native_cudnn. ' 'func: BidirectionalFRNN, ' 'native_cudnn: BidirectionalNativeCuDNNLSTM.')", "@classmethod def Params(cls): \"\"\"Configs for AsrEncoder.\"\"\" p = super(AsrEncoder, cls).Params()", "(i) params_rnn_layers.append(rnn_p) if p.project_lstm_output and (i < p.num_lstm_layers - 1):", "title=tensor.name, xlabel='Time') fig.Finalize() rnn_padding = tf.squeeze(rnn_padding, [2]) return final_out, rnn_padding,", "p.name with tf.variable_scope(name): # First create the conv layers. assert", "'bidi_rnn_type', 'func', 'Options: func, native_cudnn. ' 'func: BidirectionalFRNN, ' 'native_cudnn:", "if residual_index % p.residual_stride == p.residual_stride - 1: # Highway", "NestedMap object containing weights' values of this layer and its", "= collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn')) class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder version 1.\"\"\"", "[None, None, None, None] p.conv_lstm_tpl.cell_shape = [None, None, None, None]", "= TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in = tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding = tf.expand_dims( tf.transpose(conv_lstm_out_padding),", "i)) # Need to do a reshape before starting the", "Not supported/ignored by this encoder. Returns: (outputs, out_paddings, state1) tuple.", "from lingvo.core import summary_utils from lingvo.core import model_helper ConvLSTMBlock =", "not use this file except in compliance with the License.", "f_conv_lstm_p.cell_shape = [None, 1, width, in_channel] b_conv_lstm_p = f_conv_lstm_p.Copy() b_conv_lstm_p.name", "tf.shape(t)[0] second_dim = tf.shape(t)[1] t_new = tf.transpose( tf.reshape(t, [first_dim, second_dim,", "is of shape [time, batch, depth] # rnn_padding is of", "you may not use this file except in compliance with", "any dimensions beyond the third into the third. batch_size =", "self.CreateChildren('conv', params_conv_layers) conv_output_shape = tf.TensorShape(p.input_shape) for i in range(p.num_cnn_layers): conv_output_shape", "# rnn_padding is of shape [time, batch, 1] # Now", "' 'func: BidirectionalFRNN, ' 'native_cudnn: BidirectionalNativeCuDNNLSTM.') # TODO(yonghui): Maybe move", "the highway skip layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs template for ConvLSTMCell.')", "1, width, in_channel] f_conv_lstm_p.cell_shape = [None, 1, width, in_channel] b_conv_lstm_p", "for AsrEncoder.\"\"\" p = super(AsrEncoder, cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs template", "0, 2]) rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) # rnn_in is of", "2 * p.lstm_cell_size proj_p.name = 'proj_L%d' % (i) proj_p.is_eval =", "22, 2016). # Default config for the projection layer. p.proj_tpl.params_init", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "cnn layer immediately follow the' ' convlstm layer.') p.Define('conv_filter_shapes', None,", "first_lstm_input_dim, first_lstm_input_dim_padding @property def supports_streaming(self): return False def zero_state(self, batch_size):", "language governing permissions and # limitations under the License. \"\"\"Encoders", "tf.transpose(rnn_padding, [1, 0, 2]), 'rnn_%d_out' % i)) rnn_in = rnn_out", "conv layer.') p.Define('conv_filter_strides', None, 'Filter strides for each conv layer.')", "time dimension to be the second. cnn_in = TransposeFirstTwoDims(lstm_out) cnn_in", "1) / pad_to_multiple) * pad_to_multiple else: first_lstm_input_dim = first_lstm_input_dim_unpadded first_lstm_input_dim_padding", "first. conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in = tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding =", "= py_utils.WeightInit.Uniform(0.1) # Default config for the convolution layer. p.input_shape", "Move time dimension to be the first. conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in)", "# Need to do a reshape before starting the rnn", "of this layer and its children layers. batch: A NestedMap", "None] p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape = [3, 3, None, None]", "f_conv_lstm_p.name = 'f_conv_lstm_%d' % (i) f_conv_lstm_p.inputs_shape = [None, 1, width,", "tensor, seq_len in plots: fig.AddSubplot( [tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time')", "2) # rnn_in is of shape [time, batch, depth] #", "First create the conv layers. assert p.num_cnn_layers == len(p.conv_filter_shapes) assert", "config below assumes the following encoder # architecture: # #", "rnn_in if self.cluster.add_summary: fig = plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8, len(plots) *", "params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui): Refactor ConvLSTMBlock into a layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn)", "== p.num_lstm_layers - 1: rnn_out *= (1.0 - rnn_padding) plots.append(", "= tf.shape(t)[0] second_dim = tf.shape(t)[1] t_new = tf.transpose( tf.reshape(t, [first_dim,", "conv_output_shape = tf.TensorShape(p.input_shape) for i in range(p.num_cnn_layers): conv_output_shape = self.conv[i].OutShape(conv_output_shape)", "1.\"\"\" @classmethod def Params(cls): \"\"\"Configs for AsrEncoder.\"\"\" p = super(AsrEncoder,", "= out_padding for i, (rnn, cnn) in enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)):", "p.after_conv_lstm_cnn_tpl.params_init = ( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride = [1, 1] return p", "time]. state0: Recurrent input state. Not supported/ignored by this encoder.", "dim, seq_len] shape.\"\"\" # Flatten any dimensions beyond the third", "= [3, 3, None, None] p.after_conv_lstm_cnn_tpl.params_init = ( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride", "2]) rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) # rnn_in is of shape", "out_paddings, state1) tuple. Outputs is of the shape [time, batch,", "pad_to_multiple - 1) / pad_to_multiple) * pad_to_multiple else: first_lstm_input_dim =", "(frequency) p.conv_lstm_tpl.inputs_shape = [None, None, None, None] p.conv_lstm_tpl.cell_shape = [None,", "represented by 'inputs' and 'paddings'. Args: theta: A NestedMap object", "tf.shape(tensor)[1] plot_tensor = tf.reshape(tensor, [batch_size, max_len, -1]) plot_tensor = tf.transpose(plot_tensor,", "if p.residual_start > 0 and residual_index >= 0: if residual_index", "2]), paddings, 'inputs') ] conv_out = inputs out_padding = paddings", "rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) # rnn_in is of shape [time,", "self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding) residual_index = i - p.residual_start + 1", "is enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs template for the highway skip", "params_rnn_layers) self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers) @property def _use_functional(self): return True", "\"\"\"Transposes and flattens channels to [batch, dim, seq_len] shape.\"\"\" #", "for i in range(p.num_cnn_layers): conv_p = p.cnn_tpl.Copy() conv_p.name = 'conv_L%d'", "# bidirectional conv-lstm -> # cnn/batch-norm/relu # bidirectional lstm ->", "= conv_out conv_lstm_out_padding = out_padding for i, (rnn, cnn) in", "feature_dim, channels]. paddings - The paddings tensor. It is expected", "for now. Since we have done # padding on the", "encoder version 1.\"\"\" @classmethod def Params(cls): \"\"\"Configs for AsrEncoder.\"\"\" p", "inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps), inputs.dtype) paddings_pad = tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps),", "= tf.concat([paddings, paddings_pad], 1) def ReshapeForPlot(tensor, padding, name): \"\"\"Transposes and", "0: input_dim = self._first_lstm_input_dim else: input_dim = 2 * p.lstm_cell_size", "[first_dim, second_dim, -1]), [1, 0, 2]) t_shape_new = tf.concat([[second_dim], [first_dim],", "from this lstm layer. ' 'Disabled if 0 or greater", "'If set, residual connections from different layers are gated. '", "width, in_channel] b_conv_lstm_p = f_conv_lstm_p.Copy() b_conv_lstm_p.name = 'b_conv_lstm_%d' % (i)", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "[0, 2, 1], name=name) return (plot_tensor, summary_utils.SequenceLength(padding)) plots = [", "p.num_lstm_layers - 1): proj_p = p.proj_tpl.Copy() proj_p.input_dim = 2 *", "0 and residual_index >= 0: if residual_index % p.residual_stride ==", "'Will only be used if residual_start is enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(),", "p.Define('pad_steps', 6, 'Extra zero-padded timesteps to add to the input", "3, 2]), out_padding, 'conv_%d_out' % i)) def TransposeFirstTwoDims(t): first_dim =", "width, in_channel] f_conv_lstm_p.cell_shape = [None, 1, width, in_channel] b_conv_lstm_p =", "import absolute_import from __future__ import division from __future__ import print_function", "tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding = tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2) lstm_out = rnn.FProp(theta.conv_lstm_rnn[i],", "tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) # rnn_in is of shape [time, batch, depth]", "batch_size): return py_utils.NestedMap() def FProp(self, theta, batch, state0=None): \"\"\"Encodes source", "= [1, 3] # height (time), width (frequency) p.conv_lstm_tpl.inputs_shape =", "-1]), [1, 0, 2]) t_shape_new = tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]], 0)", "CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16): lstm_input_shape = conv_output_shape", "conv_output_shape = conv_output_shape.as_list() assert len(conv_output_shape) == 4 # batch, height,", "encoder LSTM layer.') p.Define('pad_steps', 6, 'Extra zero-padded timesteps to add", "p.lstm_cell_size proj_p.output_dim = 2 * p.lstm_cell_size proj_p.name = 'proj_L%d' %", "file except in compliance with the License. # You may", "greater than num_lstm_layers.') p.Define('residual_stride', 1, 'Number of lstm layers to", "inputs are not yet supported for ' 'AsrEncoder.') name =", "of device placement. params_rnn_layers = [] params_proj_layers = [] params_highway_skip_layers", "= 2 * p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip',", "each conv layer.') p.Define('conv_filter_strides', None, 'Filter strides for each conv", "the third into the third. batch_size = tf.shape(tensor)[0] max_len =", "conv_lstm_out = py_utils.HasShape(conv_lstm_out, [-1, -1, self._first_lstm_input_dim]) # Transpose to move", "print_function import collections from six.moves import range from six.moves import", "params_conv_lstm_cnn = [] for i in range(p.num_conv_lstm_layers): # NOTE(yonghui): We", "src_inputs - The inputs tensor. It is expected to be", "- p.residual_start + 1 if p.residual_start > 0 and residual_index", "('rnn', 'cnn')) class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder version 1.\"\"\" @classmethod def", "different layers are gated. ' 'Will only be used if", "+= py_utils.HasShape(residual_in, tf.shape(rnn_out)) if p.project_lstm_output and (i < p.num_lstm_layers -", "first_lstm_input_dim_padding @property def supports_streaming(self): return False def zero_state(self, batch_size): return", "lstm_input_shape = conv_output_shape # Makes sure the lstm input dims", "p.Define( 'highway_skip', False, 'If set, residual connections from different layers", "import py_utils from lingvo.core import rnn_cell from lingvo.core import rnn_layers", "to skip per residual connection.') p.Define( 'bidi_rnn_type', 'func', 'Options: func,", "first. rnn_in = tf.transpose(conv_lstm_out, [1, 0, 2]) rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding),", "layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs template for ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(),", "ReshapeForPlot( tf.transpose(conv_out, [0, 1, 3, 2]), out_padding, 'conv_%d_out' % i))", "projection layer after each encoder LSTM layer.') p.Define('pad_steps', 6, 'Extra", "values of this layer and its children layers. batch: A", "KIND, either express or implied. # See the License for", "tf.transpose(plot_tensor, [0, 2, 1], name=name) return (plot_tensor, summary_utils.SequenceLength(padding)) plots =", "'bak_rnn_L%d' % (i) rnn_p = self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name = 'brnn_L%d'", "'Start residual connections from this lstm layer. ' 'Disabled if", "projection layer. p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise", "in range(p.num_cnn_layers): conv_p = p.cnn_tpl.Copy() conv_p.name = 'conv_L%d' % (i)", "- The inputs tensor. It is expected to be of", "0, 2]) t_shape_new = tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]], 0) return tf.reshape(t_new,", "(the \"License\"); # you may not use this file except", "'Configs template for the conv layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs template", "plot_tensor = tf.reshape(tensor, [batch_size, max_len, -1]) plot_tensor = tf.transpose(plot_tensor, [0,", "with tf.variable_scope(name): # First create the conv layers. assert p.num_cnn_layers", "py_utils.WeightInit.Uniform(0.1) # Default config for the convolution layer. p.input_shape =", "in range(p.num_cnn_layers): conv_output_shape = self.conv[i].OutShape(conv_output_shape) conv_output_shape = conv_output_shape.as_list() assert len(conv_output_shape)", "= super(AsrEncoder, cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs template for the RNN", "sure the lstm input dims is multiple of 16 (alignment", "None, 80, 3] p.conv_filter_shapes = [(3, 3, 3, 32), (3,", "paddings = tf.concat([paddings, paddings_pad], 1) def ReshapeForPlot(tensor, padding, name): \"\"\"Transposes", "p.highway_skip_tpl.Copy() highway_skip.name = 'enc_hwskip_%d' % len(params_highway_skip_layers) highway_skip.input_dim = 2 *", "p.num_lstm_layers - 1): # Projection layers. rnn_out = self.proj[i].FProp(theta.proj[i], rnn_out,", "= 2 * p.lstm_cell_size forward_p = p.lstm_tpl.Copy() forward_p.name = 'fwd_rnn_L%d'", "is multiple of 16 (alignment # requirement from FRNN). first_lstm_input_dim_unpadded", "1 if p.residual_start > 0 and residual_index >= 0 and", "# # Unless required by applicable law or agreed to", "def CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16): lstm_input_shape =", "zero_state(self, batch_size): return py_utils.NestedMap() def FProp(self, theta, batch, state0=None): \"\"\"Encodes", "implemented for ProjectionLayer yet (as of sep 22, 2016). p.conv_lstm_tpl.filter_shape", "p.Define('project_lstm_output', True, 'Include projection layer after each encoder LSTM layer.')", "config for the rnn layer. p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1) # Default", "of shape [time, batch, depth] # rnn_padding is of shape", "paddings.dtype) inputs = tf.concat([inputs, inputs_pad], 1, name='inputs') paddings = tf.concat([paddings,", "# Transpose to move the time dimension to be the", "'LSTM cell size for the RNN layer.') p.Define('num_cnn_layers', 2, 'Number", "connection.') p.Define( 'bidi_rnn_type', 'func', 'Options: func, native_cudnn. ' 'func: BidirectionalFRNN,", "Copyright 2018 The TensorFlow Authors. All Rights Reserved. # #", "out_padding for i, (rnn, cnn) in enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in", "p.conv_lstm_tpl.cell_shape = [None, None, None, None] p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape", "py_utils from lingvo.core import rnn_cell from lingvo.core import rnn_layers from", "= conv_output_shape.as_list() assert len(conv_output_shape) == 4 # batch, height, width,", "implied. # See the License for the specific language governing", "noise logic is currently not # implemented for ProjectionLayer yet", "seq_len] shape.\"\"\" # Flatten any dimensions beyond the third into", "else: # Residual skip connection. rnn_out += py_utils.HasShape(residual_in, tf.shape(rnn_out)) if", "gated. ' 'Will only be used if residual_start is enabled.')", "batch, height, width, channel. params_conv_lstm_rnn = [] params_conv_lstm_cnn = []", "highway_skip.name = 'enc_hwskip_%d' % len(params_highway_skip_layers) highway_skip.input_dim = 2 * p.lstm_cell_size", "\"\"\"Configs for AsrEncoder.\"\"\" p = super(AsrEncoder, cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs", "depth] # rnn_padding is of shape [time, batch, 1] #", "timesteps at the end. This is for ensuring the #", "not supported by TPU for now. Since we have done", "4) conv_lstm_out_shape = tf.shape(conv_lstm_out) new_shape = tf.concat([conv_lstm_out_shape[:2], [-1]], 0) conv_lstm_out", "is expected to be of shape [batch, time, feature_dim, channels].", "template for the conv layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs template for", "# Move time dimension to be the first. conv_lstm_in =", "from lingvo.core import rnn_cell from lingvo.core import rnn_layers from lingvo.core", "= tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps), paddings.dtype) inputs = tf.concat([inputs, inputs_pad],", "tensorflow.python.ops import inplace_ops from lingvo.core import base_encoder from lingvo.core import", "def FProp(self, theta, batch, state0=None): \"\"\"Encodes source as represented by", "with rank 4.') p.Define('lstm_cell_size', 256, 'LSTM cell size for the", "= conv_lstm_out_padding cnn_out, cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding) conv_lstm_out, conv_lstm_out_padding", "# NOTE(yonghui): Fortunately, variational noise logic is currently not #", "be the first. rnn_in = tf.transpose(conv_lstm_out, [1, 0, 2]) rnn_padding", "children layers. batch: A NestedMap with fields: src_inputs - The", "' 'native_cudnn: BidirectionalNativeCuDNNLSTM.') # TODO(yonghui): Maybe move those configs to", "params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p = p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name = 'conv_lstm_cnn_%d' % (i) cnn_p.filter_shape[2]", "< p.num_lstm_layers - 1): # Projection layers. rnn_out = self.proj[i].FProp(theta.proj[i],", "2), (2, 2)] p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational", "the lstm input dims is multiple of 16 (alignment #", "Unless required by applicable law or agreed to in writing,", "rnn_out) num_skips += 1 else: # Residual skip connection. rnn_out", "[-1, -1, self._first_lstm_input_dim]) # Transpose to move the time dimension", "from lingvo.core import base_layer from lingvo.core import layers from lingvo.core", "the specific language governing permissions and # limitations under the", "conv-layers at the edges. if p.pad_steps > 0: # inplace_update()", "self.cluster.add_summary: fig = plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8, len(plots) * 3.5)) #", "[(3, 3, 3, 32), (3, 3, 32, 32)] p.conv_filter_strides =", "16 (alignment # requirement from FRNN). first_lstm_input_dim_unpadded = lstm_input_shape[2] *", "proj_p.input_dim = 2 * p.lstm_cell_size proj_p.output_dim = 2 * p.lstm_cell_size", "proj_p.name = 'proj_L%d' % (i) proj_p.is_eval = p.is_eval params_proj_layers.append(proj_p) #", "highway_skip = p.highway_skip_tpl.Copy() highway_skip.name = 'enc_hwskip_%d' % len(params_highway_skip_layers) highway_skip.input_dim =", "# NOTE(yonghui): We assume that output from ConvLSTMBlock has the", "[1, 0, 2]) t_shape_new = tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]], 0) return", "and # limitations under the License. \"\"\"Encoders for the speech", "def FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16): lstm_input_shape = conv_output_shape # Makes sure", "- The paddings tensor. It is expected to be of", "= 'proj_L%d' % (i) proj_p.is_eval = p.is_eval params_proj_layers.append(proj_p) # add", "logic is currently not # implemented for ProjectionLayer yet (as", "for i in range(p.num_lstm_layers): rnn_out = self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding) residual_index", "import print_function import collections from six.moves import range from six.moves", "_, width, in_channel = conv_output_shape f_conv_lstm_p = p.conv_lstm_tpl.Copy() f_conv_lstm_p.name =", "'fwd_rnn_L%d' % (i) forward_p.num_input_nodes = input_dim forward_p.num_output_nodes = p.lstm_cell_size backward_p", "4 # batch, height, width, channel. params_conv_lstm_rnn = [] params_conv_lstm_cnn", "AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder version 1.\"\"\" @classmethod def Params(cls): \"\"\"Configs for", "inputs_pad = tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps), inputs.dtype) paddings_pad = tf.ones(", "third into the third. batch_size = tf.shape(tensor)[0] max_len = tf.shape(tensor)[1]", "Now the conv-lstm part. conv_lstm_out = conv_out conv_lstm_out_padding = out_padding", "to add to the input sequence. ') p.Define( 'residual_start', 0,", "to the input sequence. ') p.Define( 'residual_start', 0, 'Start residual", "rnn_out += py_utils.HasShape(residual_in, tf.shape(rnn_out)) if p.project_lstm_output and (i < p.num_lstm_layers", "backward_p.name = 'bak_rnn_L%d' % (i) rnn_p = self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name", "ReshapeForPlot(tensor, padding, name): \"\"\"Transposes and flattens channels to [batch, dim,", "return p @base_layer.initializer def __init__(self, params): super(AsrEncoder, self).__init__(params) p =", "= [None, 1, width, in_channel] f_conv_lstm_p.cell_shape = [None, 1, width,", "highway_skip.input_dim = 2 * p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj', params_proj_layers)", "in range(p.num_lstm_layers): if i == 0: input_dim = self._first_lstm_input_dim else:", "= conv_output_shape # Makes sure the lstm input dims is", "and its children layers. batch: A NestedMap with fields: src_inputs", "in_channel] f_conv_lstm_p.cell_shape = [None, 1, width, in_channel] b_conv_lstm_p = f_conv_lstm_p.Copy()", "layers to skip per residual connection.') p.Define( 'bidi_rnn_type', 'func', 'Options:", "cnn/batch-norm/relu -> # bidirectional conv-lstm -> # cnn/batch-norm/relu # bidirectional", "backward_p) def CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16): lstm_input_shape", "and flattens channels to [batch, dim, seq_len] shape.\"\"\" # Flatten", "= 2 * p.lstm_cell_size proj_p.output_dim = 2 * p.lstm_cell_size proj_p.name", "int( (first_lstm_input_dim_unpadded + pad_to_multiple - 1) / pad_to_multiple) * pad_to_multiple", "noise logic is currently not # implemented for ConvLayer yet", "== 0: residual_in = rnn_in if residual_index % p.residual_stride ==", "p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name = 'conv_lstm_cnn_%d' % (i) cnn_p.filter_shape[2] = 2 *", "'Disabled if 0 or greater than num_lstm_layers.') p.Define('residual_stride', 1, 'Number", "self.CreateChildren('highway_skip', params_highway_skip_layers) @property def _use_functional(self): return True def CreateBidirectionalRNNParams(self, forward_p,", "% (i) cnn_p.filter_shape[2] = 2 * in_channel cnn_p.filter_shape[3] = in_channel", "move the time dimension to be the first. rnn_in =", "tensor. It is expected to be of shape [batch, time,", "p.residual_start + 1 if p.residual_start > 0 and residual_index >=", "the first. rnn_in = tf.transpose(conv_lstm_out, [1, 0, 2]) rnn_padding =", "'Options: func, native_cudnn. ' 'func: BidirectionalFRNN, ' 'native_cudnn: BidirectionalNativeCuDNNLSTM.') #", "2]), 'rnn_%d_out' % i)) rnn_in = rnn_out final_out = rnn_in", "p.Define('input_shape', [None, None, None, None], 'Shape of the input. This", "0, 2]), tf.transpose(rnn_padding, [1, 0, 2]), 'rnn_%d_out' % i)) rnn_in", "layers. batch: A NestedMap with fields: src_inputs - The inputs", "inplace_update() is not supported by TPU for now. Since we", "absolute_import from __future__ import division from __future__ import print_function import", "is of the shape [time, batch] \"\"\" p = self.params", "+ 1 if p.residual_start > 0 and residual_index >= 0:", "input. This should a TensorShape with rank 4.') p.Define('lstm_cell_size', 256,", "0 and residual_index >= 0 and p.highway_skip: highway_skip = p.highway_skip_tpl.Copy()", "p.pad_steps > 0: # inplace_update() is not supported by TPU", "conv_lstm_rnn_p.bak = b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p = p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name = 'conv_lstm_cnn_%d'", "projection layers. # TODO(yonghui): take care of device placement. params_rnn_layers", "(i) conv_lstm_rnn_p = self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name = 'conv_lstm_rnn' conv_lstm_rnn_p.fwd = f_conv_lstm_p", "that output from ConvLSTMBlock has the same # shape as", "plots.append( ReshapeForPlot( tf.transpose(conv_out, [0, 1, 3, 2]), out_padding, 'conv_%d_out' %", "rnn_in = rnn_out final_out = rnn_in if self.cluster.add_summary: fig =", "py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride = [1, 1] return p @base_layer.initializer def __init__(self,", "for the cnn layer immediately follow the' ' convlstm layer.')", "You may obtain a copy of the License at #", "p.num_cnn_layers == len(p.conv_filter_strides) params_conv_layers = [] for i in range(p.num_cnn_layers):", "conv_lstm_out_padding cnn_out, cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding) conv_lstm_out, conv_lstm_out_padding =", "placement. params_rnn_layers = [] params_proj_layers = [] params_highway_skip_layers = []", "few extra padded timesteps at the end. This is for", "top. plots.reverse() for tensor, seq_len in plots: fig.AddSubplot( [tensor, seq_len],", "cnn_in_padding) conv_lstm_out, conv_lstm_out_padding = cnn_out, cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out'", "# Makes sure the lstm input dims is multiple of", "rnn_padding) plots.append( ReshapeForPlot( tf.transpose(rnn_out, [1, 0, 2]), tf.transpose(rnn_padding, [1, 0,", "if i == 0: input_dim = self._first_lstm_input_dim else: input_dim =", "pad_to_multiple) * pad_to_multiple else: first_lstm_input_dim = first_lstm_input_dim_unpadded first_lstm_input_dim_padding = (", "assert p.num_cnn_layers == len(p.conv_filter_strides) params_conv_layers = [] for i in", "inputs_pad], 1, name='inputs') paddings = tf.concat([paddings, paddings_pad], 1) def ReshapeForPlot(tensor,", "License. \"\"\"Encoders for the speech model.\"\"\" from __future__ import absolute_import", "edges. if p.pad_steps > 0: # inplace_update() is not supported", "tf.reshape(t_new, t_shape_new) # Now the conv-lstm part. conv_lstm_out = conv_out", "'residual_start', 0, 'Start residual connections from this lstm layer. '", "with tf.name_scope(p.name): # Add a few extra padded timesteps at", "p.Define('lstm_cell_size', 256, 'LSTM cell size for the RNN layer.') p.Define('num_cnn_layers',", "cnn_p.name = 'conv_lstm_cnn_%d' % (i) cnn_p.filter_shape[2] = 2 * in_channel", "conv_out conv_lstm_out_padding = out_padding for i, (rnn, cnn) in enumerate(", "p.conv_lstm_tpl.filter_shape = [1, 3] # height (time), width (frequency) p.conv_lstm_tpl.inputs_shape", "self.params inputs, paddings = batch.src_inputs, batch.paddings with tf.name_scope(p.name): # Add", "has the same # shape as its input. _, _,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name = 'conv_lstm_cnn_%d' % (i) cnn_p.filter_shape[2] = 2", "the end. This is for ensuring the # correctness of", "# projection/batch-norm/relu -> # bidirectional lstm # # Default config", "base_layer from lingvo.core import layers from lingvo.core import plot from", "tf.name_scope(p.name): # Add a few extra padded timesteps at the", "layers. num_skips = 0 for i in range(p.num_lstm_layers): rnn_out =", "import zip import tensorflow as tf from tensorflow.python.ops import inplace_ops", "for i in range(p.num_conv_lstm_layers): # NOTE(yonghui): We assume that output", "[(2, 2), (2, 2)] p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable", "input. _, _, width, in_channel = conv_output_shape f_conv_lstm_p = p.conv_lstm_tpl.Copy()", "= tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding = tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2) lstm_out =", "the rnn layers and projection layers. # TODO(yonghui): take care", "len(params_highway_skip_layers) highway_skip.input_dim = 2 * p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj',", "2, 'Number of conv layers to create.') p.Define('num_conv_lstm_layers', 1, 'Number", "this lstm layer. ' 'Disabled if 0 or greater than", "to be of shape [batch, time]. state0: Recurrent input state.", "# TODO(yonghui): take care of device placement. params_rnn_layers = []", "conv_lstm_out = conv_out conv_lstm_out_padding = out_padding for i, (rnn, cnn)", "self.conv[i].OutShape(conv_output_shape) conv_output_shape = conv_output_shape.as_list() assert len(conv_output_shape) == 4 # batch,", "# batch, height, width, channel. params_conv_lstm_rnn = [] params_conv_lstm_cnn =", "the RNN layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the conv", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "not yet supported for ' 'AsrEncoder.') name = p.name with", "conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in = tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding = tf.expand_dims(", "License. # You may obtain a copy of the License", "@base_layer.initializer def __init__(self, params): super(AsrEncoder, self).__init__(params) p = self.params assert", "% (i) conv_p.filter_shape = p.conv_filter_shapes[i] conv_p.filter_stride = p.conv_filter_strides[i] conv_p.is_eval =", "on the input_generator, we may avoid this additional padding. assert", "for ' 'AsrEncoder.') name = p.name with tf.variable_scope(name): # First", "Now create all the rnn layers and projection layers. #", "= 'bak_rnn_L%d' % (i) rnn_p = self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name =", "supported by TPU for now. Since we have done #", "def TransposeFirstTwoDims(t): first_dim = tf.shape(t)[0] second_dim = tf.shape(t)[1] t_new =", "theta: A NestedMap object containing weights' values of this layer", "[None, 1, width, in_channel] b_conv_lstm_p = f_conv_lstm_p.Copy() b_conv_lstm_p.name = 'b_conv_lstm_%d'", "projection/batch-norm/relu -> # bidirectional lstm # # Default config for", "p.project_lstm_output and (i < p.num_lstm_layers - 1): proj_p = p.proj_tpl.Copy()", "def ReshapeForPlot(tensor, padding, name): \"\"\"Transposes and flattens channels to [batch,", "are not yet supported for ' 'AsrEncoder.') name = p.name", "p.pad_steps), inputs.dtype) paddings_pad = tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps), paddings.dtype) inputs", "(time), width (frequency) p.conv_lstm_tpl.inputs_shape = [None, None, None, None] p.conv_lstm_tpl.cell_shape", "input_dim forward_p.num_output_nodes = p.lstm_cell_size backward_p = forward_p.Copy() backward_p.name = 'bak_rnn_L%d'", "move those configs to a separate file. # Set some", "(self._first_lstm_input_dim, self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16) # Now create all", "currently not # implemented for ProjectionLayer yet (as of sep", "in_channel params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui): Refactor ConvLSTMBlock into a layer. self.CreateChildren('conv_lstm_rnn',", "A NestedMap with fields: src_inputs - The inputs tensor. It", "TensorFlow Authors. All Rights Reserved. # # Licensed under the", "# height (time), width (frequency) p.conv_lstm_tpl.inputs_shape = [None, None, None,", "p.residual_stride == 0: residual_in = rnn_in if residual_index % p.residual_stride", "i, (rnn, cnn) in enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in = conv_lstm_out", "assert len(conv_output_shape) == 4 # batch, height, width, channel. params_conv_lstm_rnn", "flattens channels to [batch, dim, seq_len] shape.\"\"\" # Flatten any", "[None, None, 80, 3] p.conv_filter_shapes = [(3, 3, 3, 32),", "/ pad_to_multiple) * pad_to_multiple else: first_lstm_input_dim = first_lstm_input_dim_unpadded first_lstm_input_dim_padding =", "# padding on the input_generator, we may avoid this additional", "yet supported for ' 'AsrEncoder.') name = p.name with tf.variable_scope(name):", "p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise logic. #", "range(p.num_conv_lstm_layers): # NOTE(yonghui): We assume that output from ConvLSTMBlock has", "[1, 1] return p @base_layer.initializer def __init__(self, params): super(AsrEncoder, self).__init__(params)", "= input_dim forward_p.num_output_nodes = p.lstm_cell_size backward_p = forward_p.Copy() backward_p.name =", "conv_layer in enumerate(self.conv): conv_out, out_padding = conv_layer.FProp(theta.conv[i], conv_out, out_padding) plots.append(", "forward_p, backward_p): return model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p) def CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params()", "tf.transpose(conv_lstm_out_padding), 2) lstm_out = rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding) # Move time", "p = super(AsrEncoder, cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs template for the", "the following encoder # architecture: # # cnn/batch-norm/relu -> #", "= TransposeFirstTwoDims(lstm_out) cnn_in = tf.squeeze(cnn_in, 2) cnn_in_padding = conv_lstm_out_padding cnn_out,", "p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1) # Default config for the convolution layer.", "# First create the conv layers. assert p.num_cnn_layers == len(p.conv_filter_shapes)", "(i) cnn_p.filter_shape[2] = 2 * in_channel cnn_p.filter_shape[3] = in_channel params_conv_lstm_cnn.append(cnn_p)", "create.') p.Define('num_lstm_layers', 3, 'Number of rnn layers to create') p.Define('project_lstm_output',", "conv_p.filter_shape = p.conv_filter_shapes[i] conv_p.filter_stride = p.conv_filter_strides[i] conv_p.is_eval = p.is_eval params_conv_layers.append(conv_p)", "the conv-layers at the edges. if p.pad_steps > 0: #", "( first_lstm_input_dim - first_lstm_input_dim_unpadded) return first_lstm_input_dim, first_lstm_input_dim_padding @property def supports_streaming(self):", "from __future__ import division from __future__ import print_function import collections", "= cnn_out, cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out' % i)) #", "ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the cnn layer", "is expected to be of shape [batch, time]. state0: Recurrent", "1) def ReshapeForPlot(tensor, padding, name): \"\"\"Transposes and flattens channels to", "'inputs' and 'paddings'. Args: theta: A NestedMap object containing weights'", "(as of sep 22, 2016). # Default config for the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "i - p.residual_start + 1 if p.residual_start > 0 and", "the rnn layers. conv_lstm_out = py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape = tf.shape(conv_lstm_out)", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "[3, 3, None, None] p.after_conv_lstm_cnn_tpl.params_init = ( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride =", "None, 'Filter shapes for each conv layer.') p.Define('conv_filter_strides', None, 'Filter", "' 'AsrEncoder.') name = p.name with tf.variable_scope(name): # First create", "batch.paddings with tf.name_scope(p.name): # Add a few extra padded timesteps", "Default config for the rnn layer. p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1) #", "* in_channel cnn_p.filter_shape[3] = in_channel params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui): Refactor ConvLSTMBlock", "cnn_in_padding = conv_lstm_out_padding cnn_out, cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding) conv_lstm_out,", "= [None, None, 80, 3] p.conv_filter_shapes = [(3, 3, 3,", "from six.moves import zip import tensorflow as tf from tensorflow.python.ops", "p.after_conv_lstm_cnn_tpl.filter_stride = [1, 1] return p @base_layer.initializer def __init__(self, params):", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "a TensorShape with rank 4.') p.Define('lstm_cell_size', 256, 'LSTM cell size", "speech model.\"\"\" from __future__ import absolute_import from __future__ import division", "seq_len in plots: fig.AddSubplot( [tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time') fig.Finalize()", "range(p.num_cnn_layers): conv_output_shape = self.conv[i].OutShape(conv_output_shape) conv_output_shape = conv_output_shape.as_list() assert len(conv_output_shape) ==", "Args: theta: A NestedMap object containing weights' values of this", "[1, 0, 2]), 'rnn_%d_out' % i)) rnn_in = rnn_out final_out", "_use_functional(self): return True def CreateBidirectionalRNNParams(self, forward_p, backward_p): return model_helper.CreateBidirectionalRNNParams(self.params, forward_p,", "1, p.pad_steps), inputs.dtype) paddings_pad = tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps), paddings.dtype)", "template for the RNN layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs template for", "rnn_p.name = 'brnn_L%d' % (i) params_rnn_layers.append(rnn_p) if p.project_lstm_output and (i", "agreed to in writing, software # distributed under the License", "rnn_layers from lingvo.core import summary_utils from lingvo.core import model_helper ConvLSTMBlock", "residual_start is enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs template for the highway", "distributed under the License is distributed on an \"AS IS\"", "(3, 3, 32, 32)] p.conv_filter_strides = [(2, 2), (2, 2)]", "# # cnn/batch-norm/relu -> # cnn/batch-norm/relu -> # bidirectional conv-lstm", "under the License. \"\"\"Encoders for the speech model.\"\"\" from __future__", "= ( first_lstm_input_dim - first_lstm_input_dim_unpadded) return first_lstm_input_dim, first_lstm_input_dim_padding @property def", "return True def CreateBidirectionalRNNParams(self, forward_p, backward_p): return model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p)", "len(p.conv_filter_strides) params_conv_layers = [] for i in range(p.num_cnn_layers): conv_p =", "lingvo.core import plot from lingvo.core import py_utils from lingvo.core import", "= ( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride = [1, 1] return p @base_layer.initializer", "num_skips += 1 else: # Residual skip connection. rnn_out +=", "32), (3, 3, 32, 32)] p.conv_filter_strides = [(2, 2), (2,", "import summary_utils from lingvo.core import model_helper ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock', ('rnn',", "'func: BidirectionalFRNN, ' 'native_cudnn: BidirectionalNativeCuDNNLSTM.') # TODO(yonghui): Maybe move those", "from ConvLSTMBlock has the same # shape as its input.", "pad_to_multiple=16) # Now create all the rnn layers and projection", "< p.num_lstm_layers - 1): proj_p = p.proj_tpl.Copy() proj_p.input_dim = 2", "containing weights' values of this layer and its children layers.", "[] for i in range(p.num_cnn_layers): conv_p = p.cnn_tpl.Copy() conv_p.name =", "(first_lstm_input_dim_unpadded + pad_to_multiple - 1) / pad_to_multiple) * pad_to_multiple else:", "dims is multiple of 16 (alignment # requirement from FRNN).", "None], 'Shape of the input. This should a TensorShape with", "we may avoid this additional padding. assert not py_utils.use_tpu() inputs_pad", "and p.highway_skip: highway_skip = p.highway_skip_tpl.Copy() highway_skip.name = 'enc_hwskip_%d' % len(params_highway_skip_layers)", "self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name = 'brnn_L%d' % (i) params_rnn_layers.append(rnn_p) if p.project_lstm_output", "The inputs tensor. It is expected to be of shape", "= self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in, rnn_out) num_skips += 1 else: #", "of the conv-layers at the edges. if p.pad_steps > 0:", "immediately follow the' ' convlstm layer.') p.Define('conv_filter_shapes', None, 'Filter shapes", "= 'fwd_rnn_L%d' % (i) forward_p.num_input_nodes = input_dim forward_p.num_output_nodes = p.lstm_cell_size", "the input_generator, we may avoid this additional padding. assert not", "tf.variable_scope(name): # First create the conv layers. assert p.num_cnn_layers ==", "from lingvo.core import plot from lingvo.core import py_utils from lingvo.core", "- rnn_padding) plots.append( ReshapeForPlot( tf.transpose(rnn_out, [1, 0, 2]), tf.transpose(rnn_padding, [1,", "p.lstm_cell_size proj_p.name = 'proj_L%d' % (i) proj_p.is_eval = p.is_eval params_proj_layers.append(proj_p)", "This is for ensuring the # correctness of the conv-layers", "bidirectional conv-lstm -> # cnn/batch-norm/relu # bidirectional lstm -> #", "f_conv_lstm_p.inputs_shape = [None, 1, width, in_channel] f_conv_lstm_p.cell_shape = [None, 1,", "conv_lstm_in_padding = tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2) lstm_out = rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding)", "self._first_lstm_input_dim else: input_dim = 2 * p.lstm_cell_size forward_p = p.lstm_tpl.Copy()", "- 1: rnn_out *= (1.0 - rnn_padding) plots.append( ReshapeForPlot( tf.transpose(rnn_out,", "CreateBidirectionalRNNParams(self, forward_p, backward_p): return model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p) def CreateConvLstmLayerParams(self): return", "t_shape_new) # Now the conv-lstm part. conv_lstm_out = conv_out conv_lstm_out_padding", "height (time), width (frequency) p.conv_lstm_tpl.inputs_shape = [None, None, None, None]", "the RNN layer.') p.Define('num_cnn_layers', 2, 'Number of conv layers to", "= self.conv[i].OutShape(conv_output_shape) conv_output_shape = conv_output_shape.as_list() assert len(conv_output_shape) == 4 #", "yet (as of sep 22, 2016). p.conv_lstm_tpl.filter_shape = [1, 3]", "params_rnn_layers.append(rnn_p) if p.project_lstm_output and (i < p.num_lstm_layers - 1): proj_p", "= tf.shape(conv_lstm_out) new_shape = tf.concat([conv_lstm_out_shape[:2], [-1]], 0) conv_lstm_out = tf.reshape(conv_lstm_out,", "residual_index >= 0: if residual_index % p.residual_stride == 0: residual_in", "1, 3, 2]), out_padding, 'conv_%d_out' % i)) def TransposeFirstTwoDims(t): first_dim", "ConvLayer yet (as of sep 22, 2016). # Default config", "rnn_padding) residual_index = i - p.residual_start + 1 if p.residual_start", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# add the skip layers residual_index = i - p.residual_start", "conv_p.filter_stride = p.conv_filter_strides[i] conv_p.is_eval = p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers) conv_output_shape", "the License is distributed on an \"AS IS\" BASIS, #", "timesteps to add to the input sequence. ') p.Define( 'residual_start',", "plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8, len(plots) * 3.5)) # Order layers from", "FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16): lstm_input_shape = conv_output_shape # Makes sure the", "create.') p.Define('num_conv_lstm_layers', 1, 'Number of conv lstm layers to create.')", "paddings, 'inputs') ] conv_out = inputs out_padding = paddings for", "[] params_proj_layers = [] params_highway_skip_layers = [] for i in", "py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise logic. # NOTE(yonghui): Fortunately,", "variational noise logic. # NOTE(yonghui): Fortunately, variational noise logic is", "from lingvo.core import rnn_layers from lingvo.core import summary_utils from lingvo.core", "'f_conv_lstm_%d' % (i) f_conv_lstm_p.inputs_shape = [None, 1, width, in_channel] f_conv_lstm_p.cell_shape", "pad_to_multiple=16): lstm_input_shape = conv_output_shape # Makes sure the lstm input", "0: residual_in = rnn_in if residual_index % p.residual_stride == p.residual_stride", "= 2 * p.lstm_cell_size proj_p.name = 'proj_L%d' % (i) proj_p.is_eval", "be the first. conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in = tf.expand_dims(conv_lstm_in, 2)", "second_dim = tf.shape(t)[1] t_new = tf.transpose( tf.reshape(t, [first_dim, second_dim, -1]),", "the skip layers residual_index = i - p.residual_start + 1", "super(AsrEncoder, cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs template for the RNN layer.')", "law or agreed to in writing, software # distributed under", "to create.') p.Define('num_lstm_layers', 3, 'Number of rnn layers to create')", "p.residual_stride - 1: # Highway skip connection. if p.highway_skip: rnn_out", "the cnn layer immediately follow the' ' convlstm layer.') p.Define('conv_filter_shapes',", "ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out' % i)) # Need to do a", "plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out' % i)) # Need to do", "paddings - The paddings tensor. It is expected to be", "figsize=(8, len(plots) * 3.5)) # Order layers from bottom to", "') p.Define( 'residual_start', 0, 'Start residual connections from this lstm", "for the projection layer. p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable", "# Flatten any dimensions beyond the third into the third.", "to be of shape [batch, time, feature_dim, channels]. paddings -", "= [(3, 3, 3, 32), (3, 3, 32, 32)] p.conv_filter_strides", "= [None, None, None, None] p.conv_lstm_tpl.cell_shape = [None, None, None,", "> 0 and residual_index >= 0: if residual_index % p.residual_stride", ">= 0: if residual_index % p.residual_stride == 0: residual_in =", "Residual skip connection. rnn_out += py_utils.HasShape(residual_in, tf.shape(rnn_out)) if p.project_lstm_output and", "# implemented for ConvLayer yet (as of sep 22, 2016).", "] conv_out = inputs out_padding = paddings for i, conv_layer", "may obtain a copy of the License at # #", "'Configs template for the highway skip layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs", "= 'brnn_L%d' % (i) params_rnn_layers.append(rnn_p) if p.project_lstm_output and (i <", "of the shape [time, batch] \"\"\" p = self.params inputs,", "batch] \"\"\" p = self.params inputs, paddings = batch.src_inputs, batch.paddings", "rnn layers. num_skips = 0 for i in range(p.num_lstm_layers): rnn_out", "summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time') fig.Finalize() rnn_padding = tf.squeeze(rnn_padding, [2]) return final_out,", "= tf.squeeze(cnn_in, 2) cnn_in_padding = conv_lstm_out_padding cnn_out, cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i],", "= tf.shape(tensor)[1] plot_tensor = tf.reshape(tensor, [batch_size, max_len, -1]) plot_tensor =", "1] # Now the rnn layers. num_skips = 0 for", "may not use this file except in compliance with the", "RNN layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the conv layer.')", "the third. batch_size = tf.shape(tensor)[0] max_len = tf.shape(tensor)[1] plot_tensor =", "if residual_start is enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs template for the", "(2, 2)] p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise", "-> # projection/batch-norm/relu -> # bidirectional lstm # # Default", "i, conv_layer in enumerate(self.conv): conv_out, out_padding = conv_layer.FProp(theta.conv[i], conv_out, out_padding)", "this file except in compliance with the License. # You", "for ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the cnn", "= self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name = 'conv_lstm_rnn' conv_lstm_rnn_p.fwd = f_conv_lstm_p conv_lstm_rnn_p.bak =", "= [ ReshapeForPlot( tf.transpose(inputs, [0, 1, 3, 2]), paddings, 'inputs')", "Need to do a reshape before starting the rnn layers.", "py_utils.NestedMap() def FProp(self, theta, batch, state0=None): \"\"\"Encodes source as represented", "conv layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs template for the projection layer.')", "* p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers) @property", "care of device placement. params_rnn_layers = [] params_proj_layers = []", "tensorflow as tf from tensorflow.python.ops import inplace_ops from lingvo.core import", "# # Licensed under the Apache License, Version 2.0 (the", "# cnn/batch-norm/relu -> # cnn/batch-norm/relu -> # bidirectional conv-lstm ->", "plots.append( ReshapeForPlot( tf.transpose(rnn_out, [1, 0, 2]), tf.transpose(rnn_padding, [1, 0, 2]),", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "a layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding(", "-> # projection/batch-norm/relu -> # bidirectional lstm -> # projection/batch-norm/relu", "first_lstm_input_dim_unpadded first_lstm_input_dim_padding = ( first_lstm_input_dim - first_lstm_input_dim_unpadded) return first_lstm_input_dim, first_lstm_input_dim_padding", "= tf.shape(tensor)[0] max_len = tf.shape(tensor)[1] plot_tensor = tf.reshape(tensor, [batch_size, max_len,", "p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape = [3, 3, None, None] p.after_conv_lstm_cnn_tpl.params_init", "its input. _, _, width, in_channel = conv_output_shape f_conv_lstm_p =", "FProp(self, theta, batch, state0=None): \"\"\"Encodes source as represented by 'inputs'", "not # implemented for ConvLayer yet (as of sep 22,", "[tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time') fig.Finalize() rnn_padding = tf.squeeze(rnn_padding, [2])", "layers residual_index = i - p.residual_start + 1 if p.residual_start", "is False, ('Packed inputs are not yet supported for '", "residual_index >= 0 and p.highway_skip: highway_skip = p.highway_skip_tpl.Copy() highway_skip.name =", "( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride = [1, 1] return p @base_layer.initializer def", "[ ReshapeForPlot( tf.transpose(inputs, [0, 1, 3, 2]), paddings, 'inputs') ]", "None] p.conv_lstm_tpl.cell_shape = [None, None, None, None] p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1)", "It is expected to be of shape [batch, time, feature_dim,", "add to the input sequence. ') p.Define( 'residual_start', 0, 'Start", "[batch, time, feature_dim, channels]. paddings - The paddings tensor. It", "of sep 22, 2016). p.conv_lstm_tpl.filter_shape = [1, 3] # height", "# Residual skip connection. rnn_out += py_utils.HasShape(residual_in, tf.shape(rnn_out)) if p.project_lstm_output", "= 2 * in_channel cnn_p.filter_shape[3] = in_channel params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui):", "2, 1], name=name) return (plot_tensor, summary_utils.SequenceLength(padding)) plots = [ ReshapeForPlot(", "conv_output_shape, pad_to_multiple=16) # Now create all the rnn layers and", "= f_conv_lstm_p.Copy() b_conv_lstm_p.name = 'b_conv_lstm_%d' % (i) conv_lstm_rnn_p = self.CreateConvLstmLayerParams()", "[batch_size, max_len, -1]) plot_tensor = tf.transpose(plot_tensor, [0, 2, 1], name=name)", "layers. # TODO(yonghui): take care of device placement. params_rnn_layers =", "for the RNN layer.') p.Define('num_cnn_layers', 2, 'Number of conv layers", "0 or greater than num_lstm_layers.') p.Define('residual_stride', 1, 'Number of lstm", "# TODO(yonghui): Disable variational noise logic. # NOTE(yonghui): Fortunately, variational", "1] return p @base_layer.initializer def __init__(self, params): super(AsrEncoder, self).__init__(params) p", "[batch, time]. state0: Recurrent input state. Not supported/ignored by this", "TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in = tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding = tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2)", "shape as its input. _, _, width, in_channel = conv_output_shape", "or implied. # See the License for the specific language", "range(p.num_lstm_layers): rnn_out = self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding) residual_index = i -", "if p.highway_skip: rnn_out = self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in, rnn_out) num_skips +=", "architecture: # # cnn/batch-norm/relu -> # cnn/batch-norm/relu -> # bidirectional", "cnn_out, cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out' % i)) # Need", "= [] params_proj_layers = [] params_highway_skip_layers = [] for i", "self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in, rnn_out) num_skips += 1 else: # Residual", "expected to be of shape [batch, time]. state0: Recurrent input", "multiple of 16 (alignment # requirement from FRNN). first_lstm_input_dim_unpadded =", "== len(p.conv_filter_shapes) assert p.num_cnn_layers == len(p.conv_filter_strides) params_conv_layers = [] for", "def supports_streaming(self): return False def zero_state(self, batch_size): return py_utils.NestedMap() def", "configs to a separate file. # Set some reasonable default", "add the skip layers residual_index = i - p.residual_start +", "== 0: input_dim = self._first_lstm_input_dim else: input_dim = 2 *", "* p.lstm_cell_size proj_p.name = 'proj_L%d' % (i) proj_p.is_eval = p.is_eval", "'conv_lstm_cnn_%d' % (i) cnn_p.filter_shape[2] = 2 * in_channel cnn_p.filter_shape[3] =", "(plot_tensor, summary_utils.SequenceLength(padding)) plots = [ ReshapeForPlot( tf.transpose(inputs, [0, 1, 3,", "first_dim = tf.shape(t)[0] second_dim = tf.shape(t)[1] t_new = tf.transpose( tf.reshape(t,", "len(plots) * 3.5)) # Order layers from bottom to top.", "width, in_channel = conv_output_shape f_conv_lstm_p = p.conv_lstm_tpl.Copy() f_conv_lstm_p.name = 'f_conv_lstm_%d'", "self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers) @property def _use_functional(self): return", "= tf.transpose(conv_lstm_out, [1, 0, 2]) rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) #", "= cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding) conv_lstm_out, conv_lstm_out_padding = cnn_out, cnn_out_padding plots.append(", "inputs tensor. It is expected to be of shape [batch,", "state. Not supported/ignored by this encoder. Returns: (outputs, out_paddings, state1)", "all the rnn layers and projection layers. # TODO(yonghui): take", "0) return tf.reshape(t_new, t_shape_new) # Now the conv-lstm part. conv_lstm_out", "lingvo.core import rnn_layers from lingvo.core import summary_utils from lingvo.core import", "inputs.dtype) paddings_pad = tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps), paddings.dtype) inputs =", "first_lstm_input_dim - first_lstm_input_dim_unpadded) return first_lstm_input_dim, first_lstm_input_dim_padding @property def supports_streaming(self): return", "TransposeFirstTwoDims(lstm_out) cnn_in = tf.squeeze(cnn_in, 2) cnn_in_padding = conv_lstm_out_padding cnn_out, cnn_out_padding", "seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time') fig.Finalize() rnn_padding = tf.squeeze(rnn_padding, [2]) return", "p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers) conv_output_shape = tf.TensorShape(p.input_shape) for i in", "skip layers residual_index = i - p.residual_start + 1 if", "None, None, None] p.conv_lstm_tpl.cell_shape = [None, None, None, None] p.conv_lstm_tpl.params_init", "fields: src_inputs - The inputs tensor. It is expected to", "tf.concat([paddings, paddings_pad], 1) def ReshapeForPlot(tensor, padding, name): \"\"\"Transposes and flattens", "if self.cluster.add_summary: fig = plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8, len(plots) * 3.5))", "state0: Recurrent input state. Not supported/ignored by this encoder. Returns:", "rnn_cell.LSTMCellSimple.Params(), 'Configs template for the RNN layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs", "inplace_ops from lingvo.core import base_encoder from lingvo.core import base_layer from", "'Filter shapes for each conv layer.') p.Define('conv_filter_strides', None, 'Filter strides", "create') p.Define('project_lstm_output', True, 'Include projection layer after each encoder LSTM", "conv_lstm_out, conv_lstm_out_padding = cnn_out, cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out' %", "self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16) # Now create all the rnn layers", "if i == p.num_lstm_layers - 1: rnn_out *= (1.0 -", "lstm_input_shape[2] * lstm_input_shape[3] if self._use_functional and (first_lstm_input_dim_unpadded % pad_to_multiple !=", "model_helper ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn')) class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder", "# Order layers from bottom to top. plots.reverse() for tensor,", "for the RNN layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the", "residual connections from this lstm layer. ' 'Disabled if 0", "# implemented for ProjectionLayer yet (as of sep 22, 2016).", "shape [time, batch] \"\"\" p = self.params inputs, paddings =", "'AsrEncoder.') name = p.name with tf.variable_scope(name): # First create the", "batch.src_inputs, batch.paddings with tf.name_scope(p.name): # Add a few extra padded", "division from __future__ import print_function import collections from six.moves import", "return first_lstm_input_dim, first_lstm_input_dim_padding @property def supports_streaming(self): return False def zero_state(self,", "4.') p.Define('lstm_cell_size', 256, 'LSTM cell size for the RNN layer.')", "* 3.5)) # Order layers from bottom to top. plots.reverse()", "[batch, dim, seq_len] shape.\"\"\" # Flatten any dimensions beyond the", "in enumerate(self.conv): conv_out, out_padding = conv_layer.FProp(theta.conv[i], conv_out, out_padding) plots.append( ReshapeForPlot(", "1, p.pad_steps), paddings.dtype) inputs = tf.concat([inputs, inputs_pad], 1, name='inputs') paddings", "BidirectionalNativeCuDNNLSTM.') # TODO(yonghui): Maybe move those configs to a separate", "pad_to_multiple else: first_lstm_input_dim = first_lstm_input_dim_unpadded first_lstm_input_dim_padding = ( first_lstm_input_dim -", "RNN layer.') p.Define('num_cnn_layers', 2, 'Number of conv layers to create.')", "__future__ import print_function import collections from six.moves import range from", "def __init__(self, params): super(AsrEncoder, self).__init__(params) p = self.params assert p.packed_input", "[-1]], 0) conv_lstm_out = tf.reshape(conv_lstm_out, new_shape) if self._first_lstm_input_dim_pad: conv_lstm_out =", "correctness of the conv-layers at the edges. if p.pad_steps >", "cnn_in = TransposeFirstTwoDims(lstm_out) cnn_in = tf.squeeze(cnn_in, 2) cnn_in_padding = conv_lstm_out_padding", "rank 4.') p.Define('lstm_cell_size', 256, 'LSTM cell size for the RNN", "p.Define( 'bidi_rnn_type', 'func', 'Options: func, native_cudnn. ' 'func: BidirectionalFRNN, '", "tf.shape(rnn_out)) if p.project_lstm_output and (i < p.num_lstm_layers - 1): #", "'Include projection layer after each encoder LSTM layer.') p.Define('pad_steps', 6,", "p.residual_start > 0 and residual_index >= 0: if residual_index %", "for each conv layer.') p.Define('input_shape', [None, None, None, None], 'Shape", "and out_paddings is of the shape [time, batch] \"\"\" p", "do a reshape before starting the rnn layers. conv_lstm_out =", "default config below assumes the following encoder # architecture: #", "cnn) in enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in = conv_lstm_out # Move", "channel. params_conv_lstm_rnn = [] params_conv_lstm_cnn = [] for i in", "# Now the conv-lstm part. conv_lstm_out = conv_out conv_lstm_out_padding =", "weights' values of this layer and its children layers. batch:", "skip layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs template for ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl',", "for i, (rnn, cnn) in enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in =", "layer. p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1) # Default config for the convolution", "in writing, software # distributed under the License is distributed", "-> # bidirectional lstm # # Default config for the", "= tf.reshape(tensor, [batch_size, max_len, -1]) plot_tensor = tf.transpose(plot_tensor, [0, 2,", "conv_output_shape, pad_to_multiple=16): lstm_input_shape = conv_output_shape # Makes sure the lstm", "0) conv_lstm_out = tf.reshape(conv_lstm_out, new_shape) if self._first_lstm_input_dim_pad: conv_lstm_out = tf.pad(", "from different layers are gated. ' 'Will only be used", "a reshape before starting the rnn layers. conv_lstm_out = py_utils.HasRank(conv_lstm_out,", "p.after_conv_lstm_cnn_tpl.filter_shape = [3, 3, None, None] p.after_conv_lstm_cnn_tpl.params_init = ( py_utils.WeightInit.TruncatedGaussian(0.1))", "by TPU for now. Since we have done # padding", "Outputs is of the shape [time, batch, depth], and out_paddings", "assert p.packed_input is False, ('Packed inputs are not yet supported", "cnn_p.filter_shape[3] = in_channel params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui): Refactor ConvLSTMBlock into a", "len(p.conv_filter_shapes) assert p.num_cnn_layers == len(p.conv_filter_strides) params_conv_layers = [] for i", "conv_lstm_out_shape = tf.shape(conv_lstm_out) new_shape = tf.concat([conv_lstm_out_shape[:2], [-1]], 0) conv_lstm_out =", "shapes for each conv layer.') p.Define('conv_filter_strides', None, 'Filter strides for", "may avoid this additional padding. assert not py_utils.use_tpu() inputs_pad =", "expected to be of shape [batch, time, feature_dim, channels]. paddings", "(as of sep 22, 2016). p.conv_lstm_tpl.filter_shape = [1, 3] #", "6, 'Extra zero-padded timesteps to add to the input sequence.", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "as represented by 'inputs' and 'paddings'. Args: theta: A NestedMap", "paddings_pad = tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps), paddings.dtype) inputs = tf.concat([inputs,", "= conv_output_shape f_conv_lstm_p = p.conv_lstm_tpl.Copy() f_conv_lstm_p.name = 'f_conv_lstm_%d' % (i)", "second. cnn_in = TransposeFirstTwoDims(lstm_out) cnn_in = tf.squeeze(cnn_in, 2) cnn_in_padding =", "2016). p.conv_lstm_tpl.filter_shape = [1, 3] # height (time), width (frequency)", "dimension to be the first. rnn_in = tf.transpose(conv_lstm_out, [1, 0,", "lingvo.core import summary_utils from lingvo.core import model_helper ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock',", "Highway skip connection. if p.highway_skip: rnn_out = self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in,", "conv_lstm_out, [[0, 0], [0, 0], [0, self._first_lstm_input_dim_pad]]) conv_lstm_out = py_utils.HasShape(conv_lstm_out,", "the License for the specific language governing permissions and #", "2 * in_channel cnn_p.filter_shape[3] = in_channel params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui): Refactor", "(i < p.num_lstm_layers - 1): # Projection layers. rnn_out =", "connection. rnn_out += py_utils.HasShape(residual_in, tf.shape(rnn_out)) if p.project_lstm_output and (i <", "params): super(AsrEncoder, self).__init__(params) p = self.params assert p.packed_input is False,", "rnn_out = self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in, rnn_out) num_skips += 1 else:", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "Maybe move those configs to a separate file. # Set", "# Projection layers. rnn_out = self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding) if i", "bidirectional lstm # # Default config for the rnn layer.", "rnn_cell.ConvLSTMCell.Params(), 'Configs template for ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs template", "False, ('Packed inputs are not yet supported for ' 'AsrEncoder.')", "name=name) return (plot_tensor, summary_utils.SequenceLength(padding)) plots = [ ReshapeForPlot( tf.transpose(inputs, [0,", "ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn')) class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder version", "'Shape of the input. This should a TensorShape with rank", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "2]), tf.transpose(rnn_padding, [1, 0, 2]), 'rnn_%d_out' % i)) rnn_in =", "p.Define('residual_stride', 1, 'Number of lstm layers to skip per residual", "('Packed inputs are not yet supported for ' 'AsrEncoder.') name", "= tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps), inputs.dtype) paddings_pad = tf.ones( inplace_ops.inplace_update(tf.shape(paddings),", "the convolution layer. p.input_shape = [None, None, 80, 3] p.conv_filter_shapes", "layer and its children layers. batch: A NestedMap with fields:", "for ensuring the # correctness of the conv-layers at the", "skip connection. rnn_out += py_utils.HasShape(residual_in, tf.shape(rnn_out)) if p.project_lstm_output and (i", "collections from six.moves import range from six.moves import zip import", "= 'conv_lstm_cnn_%d' % (i) cnn_p.filter_shape[2] = 2 * in_channel cnn_p.filter_shape[3]", "in_channel = conv_output_shape f_conv_lstm_p = p.conv_lstm_tpl.Copy() f_conv_lstm_p.name = 'f_conv_lstm_%d' %", "def CreateBidirectionalRNNParams(self, forward_p, backward_p): return model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p) def CreateConvLstmLayerParams(self):", "# distributed under the License is distributed on an \"AS", "for the highway skip layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs template for", "channels to [batch, dim, seq_len] shape.\"\"\" # Flatten any dimensions", "# Unless required by applicable law or agreed to in", "rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding) # Move time dimension to be the", "= rnn_in if residual_index % p.residual_stride == p.residual_stride - 1:", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "\"\"\" p = self.params inputs, paddings = batch.src_inputs, batch.paddings with", "= self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding) if i == p.num_lstm_layers - 1:", "= tf.TensorShape(p.input_shape) for i in range(p.num_cnn_layers): conv_output_shape = self.conv[i].OutShape(conv_output_shape) conv_output_shape", "@property def supports_streaming(self): return False def zero_state(self, batch_size): return py_utils.NestedMap()", "22, 2016). p.conv_lstm_tpl.filter_shape = [1, 3] # height (time), width", "% i)) # Need to do a reshape before starting", "conv_lstm_rnn_p = self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name = 'conv_lstm_rnn' conv_lstm_rnn_p.fwd = f_conv_lstm_p conv_lstm_rnn_p.bak", "currently not # implemented for ConvLayer yet (as of sep", "the Apache License, Version 2.0 (the \"License\"); # you may", "size for the RNN layer.') p.Define('num_cnn_layers', 2, 'Number of conv", "A NestedMap object containing weights' values of this layer and", "= rnn_out final_out = rnn_in if self.cluster.add_summary: fig = plot.MatplotlibFigureSummary(", "conv_p.is_eval = p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers) conv_output_shape = tf.TensorShape(p.input_shape) for", "tensor. It is expected to be of shape [batch, time].", "(rnn, cnn) in enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in = conv_lstm_out #", "inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps), paddings.dtype) inputs = tf.concat([inputs, inputs_pad], 1, name='inputs')", "= p.lstm_tpl.Copy() forward_p.name = 'fwd_rnn_L%d' % (i) forward_p.num_input_nodes = input_dim", "# inplace_update() is not supported by TPU for now. Since", "[] for i in range(p.num_lstm_layers): if i == 0: input_dim", "lstm layer. ' 'Disabled if 0 or greater than num_lstm_layers.')", "enumerate(self.conv): conv_out, out_padding = conv_layer.FProp(theta.conv[i], conv_out, out_padding) plots.append( ReshapeForPlot( tf.transpose(conv_out,", "to [batch, dim, seq_len] shape.\"\"\" # Flatten any dimensions beyond", "not py_utils.use_tpu() inputs_pad = tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps), inputs.dtype) paddings_pad", "Recurrent input state. Not supported/ignored by this encoder. Returns: (outputs,", "[] params_highway_skip_layers = [] for i in range(p.num_lstm_layers): if i", "and projection layers. # TODO(yonghui): take care of device placement.", "TODO(yonghui): Refactor ConvLSTMBlock into a layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn)", "= plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8, len(plots) * 3.5)) # Order layers", "2]) t_shape_new = tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]], 0) return tf.reshape(t_new, t_shape_new)", "b_conv_lstm_p.name = 'b_conv_lstm_%d' % (i) conv_lstm_rnn_p = self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name =", "(first_lstm_input_dim_unpadded % pad_to_multiple != 0): first_lstm_input_dim = int( (first_lstm_input_dim_unpadded +", "for the convolution layer. p.input_shape = [None, None, 80, 3]", "0): first_lstm_input_dim = int( (first_lstm_input_dim_unpadded + pad_to_multiple - 1) /", "conv_lstm_out = py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape = tf.shape(conv_lstm_out) new_shape = tf.concat([conv_lstm_out_shape[:2],", "'b_conv_lstm_%d' % (i) conv_lstm_rnn_p = self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name = 'conv_lstm_rnn' conv_lstm_rnn_p.fwd", "inputs out_padding = paddings for i, conv_layer in enumerate(self.conv): conv_out,", "*= (1.0 - rnn_padding) plots.append( ReshapeForPlot( tf.transpose(rnn_out, [1, 0, 2]),", "'brnn_L%d' % (i) params_rnn_layers.append(rnn_p) if p.project_lstm_output and (i < p.num_lstm_layers", "conv_lstm_in_padding) # Move time dimension to be the second. cnn_in", "layers from lingvo.core import plot from lingvo.core import py_utils from", "be of shape [batch, time, feature_dim, channels]. paddings - The", "under the License is distributed on an \"AS IS\" BASIS,", "'inputs') ] conv_out = inputs out_padding = paddings for i,", "3, 32, 32)] p.conv_filter_strides = [(2, 2), (2, 2)] p.cnn_tpl.params_init", "+ pad_to_multiple - 1) / pad_to_multiple) * pad_to_multiple else: first_lstm_input_dim", "= [None, None, None, None] p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape =", "None, None] p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape = [3, 3, None,", "The default config below assumes the following encoder # architecture:", "paddings = batch.src_inputs, batch.paddings with tf.name_scope(p.name): # Add a few", "this layer and its children layers. batch: A NestedMap with", "reshape before starting the rnn layers. conv_lstm_out = py_utils.HasRank(conv_lstm_out, 4)", ">= 0 and p.highway_skip: highway_skip = p.highway_skip_tpl.Copy() highway_skip.name = 'enc_hwskip_%d'", "lstm # # Default config for the rnn layer. p.lstm_tpl.params_init", "conv layers. assert p.num_cnn_layers == len(p.conv_filter_shapes) assert p.num_cnn_layers == len(p.conv_filter_strides)", "padding, name): \"\"\"Transposes and flattens channels to [batch, dim, seq_len]", "False, 'If set, residual connections from different layers are gated.", "Move time dimension to be the second. cnn_in = TransposeFirstTwoDims(lstm_out)", "== 4 # batch, height, width, channel. params_conv_lstm_rnn = []", "shape [time, batch, depth] # rnn_padding is of shape [time,", "p @base_layer.initializer def __init__(self, params): super(AsrEncoder, self).__init__(params) p = self.params", "layers.ConvLayer.Params(), 'Configs template for the cnn layer immediately follow the'", "'conv_lstm_rnn' conv_lstm_rnn_p.fwd = f_conv_lstm_p conv_lstm_rnn_p.bak = b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p =", "rnn layers. conv_lstm_out = py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape = tf.shape(conv_lstm_out) new_shape", "p.lstm_cell_size forward_p = p.lstm_tpl.Copy() forward_p.name = 'fwd_rnn_L%d' % (i) forward_p.num_input_nodes", "[time, batch, 1] # Now the rnn layers. num_skips =", "ReshapeForPlot( tf.transpose(rnn_out, [1, 0, 2]), tf.transpose(rnn_padding, [1, 0, 2]), 'rnn_%d_out'", "from __future__ import absolute_import from __future__ import division from __future__", "- 1): proj_p = p.proj_tpl.Copy() proj_p.input_dim = 2 * p.lstm_cell_size", "0], [0, self._first_lstm_input_dim_pad]]) conv_lstm_out = py_utils.HasShape(conv_lstm_out, [-1, -1, self._first_lstm_input_dim]) #", "-> # bidirectional lstm -> # projection/batch-norm/relu -> # bidirectional", "t_shape_new = tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]], 0) return tf.reshape(t_new, t_shape_new) #", "rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16): lstm_input_shape = conv_output_shape # Makes", "some reasonable default values. # # NOTE(yonghui): The default config", "the rnn layers. num_skips = 0 for i in range(p.num_lstm_layers):", "layer.') p.Define('num_cnn_layers', 2, 'Number of conv layers to create.') p.Define('num_conv_lstm_layers',", "summary_utils.SequenceLength(padding)) plots = [ ReshapeForPlot( tf.transpose(inputs, [0, 1, 3, 2]),", "strides for each conv layer.') p.Define('input_shape', [None, None, None, None],", "% p.residual_stride == 0: residual_in = rnn_in if residual_index %", "# Set some reasonable default values. # # NOTE(yonghui): The", "> 0: # inplace_update() is not supported by TPU for", "= [1, 1] return p @base_layer.initializer def __init__(self, params): super(AsrEncoder,", "TODO(yonghui): Maybe move those configs to a separate file. #", "before starting the rnn layers. conv_lstm_out = py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape", "follow the' ' convlstm layer.') p.Define('conv_filter_shapes', None, 'Filter shapes for", "for i in range(p.num_cnn_layers): conv_output_shape = self.conv[i].OutShape(conv_output_shape) conv_output_shape = conv_output_shape.as_list()", "3, 3, 32), (3, 3, 32, 32)] p.conv_filter_strides = [(2,", "conv_output_shape f_conv_lstm_p = p.conv_lstm_tpl.Copy() f_conv_lstm_p.name = 'f_conv_lstm_%d' % (i) f_conv_lstm_p.inputs_shape", "p.Define('num_lstm_layers', 3, 'Number of rnn layers to create') p.Define('project_lstm_output', True,", "logic. # NOTE(yonghui): Fortunately, variational noise logic is currently not", "p.Define( 'residual_start', 0, 'Start residual connections from this lstm layer.", "p = self.params inputs, paddings = batch.src_inputs, batch.paddings with tf.name_scope(p.name):", "'Configs template for ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs template for", "ANY KIND, either express or implied. # See the License", "range from six.moves import zip import tensorflow as tf from", "(i) rnn_p = self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name = 'brnn_L%d' % (i)", "the License. # You may obtain a copy of the", "file. # Set some reasonable default values. # # NOTE(yonghui):", "[None, None, None, None], 'Shape of the input. This should", "self.params assert p.packed_input is False, ('Packed inputs are not yet", "# See the License for the specific language governing permissions", "'Number of lstm layers to skip per residual connection.') p.Define(", "Set some reasonable default values. # # NOTE(yonghui): The default", "params_highway_skip_layers = [] for i in range(p.num_lstm_layers): if i ==", "- 1) / pad_to_multiple) * pad_to_multiple else: first_lstm_input_dim = first_lstm_input_dim_unpadded", "if 0 or greater than num_lstm_layers.') p.Define('residual_stride', 1, 'Number of", "layers. rnn_out = self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding) if i == p.num_lstm_layers", "additional padding. assert not py_utils.use_tpu() inputs_pad = tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1,", "-1, self._first_lstm_input_dim]) # Transpose to move the time dimension to", "only be used if residual_start is enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs", "tf.concat([inputs, inputs_pad], 1, name='inputs') paddings = tf.concat([paddings, paddings_pad], 1) def", "in range(p.num_lstm_layers): rnn_out = self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding) residual_index = i", "self._use_functional and (first_lstm_input_dim_unpadded % pad_to_multiple != 0): first_lstm_input_dim = int(", "first_lstm_input_dim_unpadded) return first_lstm_input_dim, first_lstm_input_dim_padding @property def supports_streaming(self): return False def", "[0, 1, 3, 2]), out_padding, 'conv_%d_out' % i)) def TransposeFirstTwoDims(t):", "from lingvo.core import base_encoder from lingvo.core import base_layer from lingvo.core", "separate file. # Set some reasonable default values. # #", "% (i) conv_lstm_rnn_p = self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name = 'conv_lstm_rnn' conv_lstm_rnn_p.fwd =", "end. This is for ensuring the # correctness of the", "to create') p.Define('project_lstm_output', True, 'Include projection layer after each encoder", "i in range(p.num_cnn_layers): conv_output_shape = self.conv[i].OutShape(conv_output_shape) conv_output_shape = conv_output_shape.as_list() assert", "lstm_input_shape[3] if self._use_functional and (first_lstm_input_dim_unpadded % pad_to_multiple != 0): first_lstm_input_dim", "import tensorflow as tf from tensorflow.python.ops import inplace_ops from lingvo.core", "p.Define('num_conv_lstm_layers', 1, 'Number of conv lstm layers to create.') p.Define('num_lstm_layers',", "dimension to be the second. cnn_in = TransposeFirstTwoDims(lstm_out) cnn_in =", "tf.shape(t)[1] t_new = tf.transpose( tf.reshape(t, [first_dim, second_dim, -1]), [1, 0,", "template for the projection layer.') p.Define( 'highway_skip', False, 'If set,", "# correctness of the conv-layers at the edges. if p.pad_steps", "than num_lstm_layers.') p.Define('residual_stride', 1, 'Number of lstm layers to skip", "tf.shape(tensor)[0] max_len = tf.shape(tensor)[1] plot_tensor = tf.reshape(tensor, [batch_size, max_len, -1])", "self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers) @property def _use_functional(self): return True def", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "limitations under the License. \"\"\"Encoders for the speech model.\"\"\" from", "params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers) conv_output_shape = tf.TensorShape(p.input_shape) for i in range(p.num_cnn_layers):", "p.lstm_cell_size backward_p = forward_p.Copy() backward_p.name = 'bak_rnn_L%d' % (i) rnn_p", "inputs, paddings = batch.src_inputs, batch.paddings with tf.name_scope(p.name): # Add a", "writing, software # distributed under the License is distributed on", "assert not py_utils.use_tpu() inputs_pad = tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps), inputs.dtype)", "Order layers from bottom to top. plots.reverse() for tensor, seq_len", "in enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in = conv_lstm_out # Move time", "object containing weights' values of this layer and its children", "(i) forward_p.num_input_nodes = input_dim forward_p.num_output_nodes = p.lstm_cell_size backward_p = forward_p.Copy()", "for the conv layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs template for the", "params_rnn_layers = [] params_proj_layers = [] params_highway_skip_layers = [] for", "conv_output_shape = self.conv[i].OutShape(conv_output_shape) conv_output_shape = conv_output_shape.as_list() assert len(conv_output_shape) == 4", "residual_in, rnn_out) num_skips += 1 else: # Residual skip connection.", "xlabel='Time') fig.Finalize() rnn_padding = tf.squeeze(rnn_padding, [2]) return final_out, rnn_padding, py_utils.NestedMap()", "= 'conv_lstm_rnn' conv_lstm_rnn_p.fwd = f_conv_lstm_p conv_lstm_rnn_p.bak = b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p", "len(conv_output_shape) == 4 # batch, height, width, channel. params_conv_lstm_rnn =", "-1]) plot_tensor = tf.transpose(plot_tensor, [0, 2, 1], name=name) return (plot_tensor,", "= tf.transpose( tf.reshape(t, [first_dim, second_dim, -1]), [1, 0, 2]) t_shape_new", "= py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape = tf.shape(conv_lstm_out) new_shape = tf.concat([conv_lstm_out_shape[:2], [-1]],", "AsrEncoder.\"\"\" p = super(AsrEncoder, cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs template for", "avoid this additional padding. assert not py_utils.use_tpu() inputs_pad = tf.zeros(", "3.5)) # Order layers from bottom to top. plots.reverse() for", "\"\"\"Encoders for the speech model.\"\"\" from __future__ import absolute_import from", "= self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding) residual_index = i - p.residual_start +", "% len(params_highway_skip_layers) highway_skip.input_dim = 2 * p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers)", "rnn layers and projection layers. # TODO(yonghui): take care of", "p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise logic. #", "= self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name = 'brnn_L%d' % (i) params_rnn_layers.append(rnn_p) if", "cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out' % i)) # Need to", "final_out = rnn_in if self.cluster.add_summary: fig = plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8,", "self._first_lstm_input_dim_pad]]) conv_lstm_out = py_utils.HasShape(conv_lstm_out, [-1, -1, self._first_lstm_input_dim]) # Transpose to", "cnn/batch-norm/relu # bidirectional lstm -> # projection/batch-norm/relu -> # bidirectional", "None, None, None] p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape = [3, 3,", "bottom to top. plots.reverse() for tensor, seq_len in plots: fig.AddSubplot(", "in_channel] b_conv_lstm_p = f_conv_lstm_p.Copy() b_conv_lstm_p.name = 'b_conv_lstm_%d' % (i) conv_lstm_rnn_p", "residual connections from different layers are gated. ' 'Will only", "= conv_lstm_out # Move time dimension to be the first.", "p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the cnn layer immediately", "Default config for the convolution layer. p.input_shape = [None, None,", "lingvo.core import model_helper ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn')) class AsrEncoder(base_encoder.BaseEncoder):", "the same # shape as its input. _, _, width,", "layers. assert p.num_cnn_layers == len(p.conv_filter_shapes) assert p.num_cnn_layers == len(p.conv_filter_strides) params_conv_layers", "the conv-lstm part. conv_lstm_out = conv_out conv_lstm_out_padding = out_padding for", "params_conv_layers) conv_output_shape = tf.TensorShape(p.input_shape) for i in range(p.num_cnn_layers): conv_output_shape =", "max_len, -1]) plot_tensor = tf.transpose(plot_tensor, [0, 2, 1], name=name) return", "[] for i in range(p.num_conv_lstm_layers): # NOTE(yonghui): We assume that", "default values. # # NOTE(yonghui): The default config below assumes", "tf.reshape(conv_lstm_out, new_shape) if self._first_lstm_input_dim_pad: conv_lstm_out = tf.pad( conv_lstm_out, [[0, 0],", "Since we have done # padding on the input_generator, we", "template for the highway skip layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs template", "proj_p = p.proj_tpl.Copy() proj_p.input_dim = 2 * p.lstm_cell_size proj_p.output_dim =", "shape.\"\"\" # Flatten any dimensions beyond the third into the", "layers. conv_lstm_out = py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape = tf.shape(conv_lstm_out) new_shape =", "the time dimension to be the first. rnn_in = tf.transpose(conv_lstm_out,", "This should a TensorShape with rank 4.') p.Define('lstm_cell_size', 256, 'LSTM", "_, _, width, in_channel = conv_output_shape f_conv_lstm_p = p.conv_lstm_tpl.Copy() f_conv_lstm_p.name", "rnn_in, rnn_padding) residual_index = i - p.residual_start + 1 if", "# bidirectional lstm # # Default config for the rnn", "p.num_cnn_layers == len(p.conv_filter_shapes) assert p.num_cnn_layers == len(p.conv_filter_strides) params_conv_layers = []", "'cnn')) class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder version 1.\"\"\" @classmethod def Params(cls):", "sequence. ') p.Define( 'residual_start', 0, 'Start residual connections from this", "and residual_index >= 0 and p.highway_skip: highway_skip = p.highway_skip_tpl.Copy() highway_skip.name", "lingvo.core import py_utils from lingvo.core import rnn_cell from lingvo.core import", "'Number of rnn layers to create') p.Define('project_lstm_output', True, 'Include projection", "rnn_padding is of shape [time, batch, 1] # Now the", "= p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers) conv_output_shape = tf.TensorShape(p.input_shape) for i", "= tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) # rnn_in is of shape [time, batch,", "backward_p): return model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p) def CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params() def", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the conv layer.') p.Define('proj_tpl',", "= first_lstm_input_dim_unpadded first_lstm_input_dim_padding = ( first_lstm_input_dim - first_lstm_input_dim_unpadded) return first_lstm_input_dim,", "'rnn_%d_out' % i)) rnn_in = rnn_out final_out = rnn_in if", "[first_dim], tf.shape(t)[2:]], 0) return tf.reshape(t_new, t_shape_new) # Now the conv-lstm", "% i)) rnn_in = rnn_out final_out = rnn_in if self.cluster.add_summary:", "forward_p.name = 'fwd_rnn_L%d' % (i) forward_p.num_input_nodes = input_dim forward_p.num_output_nodes =", "is not supported by TPU for now. Since we have", "source as represented by 'inputs' and 'paddings'. Args: theta: A", "rnn_in is of shape [time, batch, depth] # rnn_padding is", "lstm -> # projection/batch-norm/relu -> # bidirectional lstm # #", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "cell size for the RNN layer.') p.Define('num_cnn_layers', 2, 'Number of", "input sequence. ') p.Define( 'residual_start', 0, 'Start residual connections from", "cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding) conv_lstm_out, conv_lstm_out_padding = cnn_out, cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out,", "conv layers to create.') p.Define('num_conv_lstm_layers', 1, 'Number of conv lstm", "to a separate file. # Set some reasonable default values.", "The paddings tensor. It is expected to be of shape", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "lingvo.core import base_encoder from lingvo.core import base_layer from lingvo.core import", "into the third. batch_size = tf.shape(tensor)[0] max_len = tf.shape(tensor)[1] plot_tensor", "= self.params assert p.packed_input is False, ('Packed inputs are not", "b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p = p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name = 'conv_lstm_cnn_%d' % (i)", "name): \"\"\"Transposes and flattens channels to [batch, dim, seq_len] shape.\"\"\"", "lstm layers to skip per residual connection.') p.Define( 'bidi_rnn_type', 'func',", "import rnn_cell from lingvo.core import rnn_layers from lingvo.core import summary_utils", "p.input_shape = [None, None, 80, 3] p.conv_filter_shapes = [(3, 3,", "conv lstm layers to create.') p.Define('num_lstm_layers', 3, 'Number of rnn", "# projection/batch-norm/relu -> # bidirectional lstm -> # projection/batch-norm/relu ->", "out_padding) plots.append( ReshapeForPlot( tf.transpose(conv_out, [0, 1, 3, 2]), out_padding, 'conv_%d_out'", "p.highway_skip: highway_skip = p.highway_skip_tpl.Copy() highway_skip.name = 'enc_hwskip_%d' % len(params_highway_skip_layers) highway_skip.input_dim", "from __future__ import print_function import collections from six.moves import range", "rnn_cell from lingvo.core import rnn_layers from lingvo.core import summary_utils from", "governing permissions and # limitations under the License. \"\"\"Encoders for", "2 * p.lstm_cell_size proj_p.output_dim = 2 * p.lstm_cell_size proj_p.name =", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "[time, batch] \"\"\" p = self.params inputs, paddings = batch.src_inputs,", "t_new = tf.transpose( tf.reshape(t, [first_dim, second_dim, -1]), [1, 0, 2])", "TPU for now. Since we have done # padding on", "None, None, None], 'Shape of the input. This should a", "= forward_p.Copy() backward_p.name = 'bak_rnn_L%d' % (i) rnn_p = self.CreateBidirectionalRNNParams(forward_p,", "Rights Reserved. # # Licensed under the Apache License, Version", "% p.residual_stride == p.residual_stride - 1: # Highway skip connection.", "lstm -> # projection/batch-norm/relu -> # bidirectional lstm -> #", "specific language governing permissions and # limitations under the License.", "after each encoder LSTM layer.') p.Define('pad_steps', 6, 'Extra zero-padded timesteps", "padded timesteps at the end. This is for ensuring the", "py_utils.use_tpu() inputs_pad = tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps), inputs.dtype) paddings_pad =", "create all the rnn layers and projection layers. # TODO(yonghui):", "version 1.\"\"\" @classmethod def Params(cls): \"\"\"Configs for AsrEncoder.\"\"\" p =", "shape [batch, time]. state0: Recurrent input state. Not supported/ignored by", "TODO(yonghui): Disable variational noise logic. # NOTE(yonghui): Fortunately, variational noise", "p.highway_skip: rnn_out = self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in, rnn_out) num_skips += 1", "f_conv_lstm_p = p.conv_lstm_tpl.Copy() f_conv_lstm_p.name = 'f_conv_lstm_%d' % (i) f_conv_lstm_p.inputs_shape =", "be the second. cnn_in = TransposeFirstTwoDims(lstm_out) cnn_in = tf.squeeze(cnn_in, 2)", "from six.moves import range from six.moves import zip import tensorflow", "# you may not use this file except in compliance", "of shape [batch, time, feature_dim, channels]. paddings - The paddings", "into a layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad) =", "the conv layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs template for the projection", "def zero_state(self, batch_size): return py_utils.NestedMap() def FProp(self, theta, batch, state0=None):", "= tf.pad( conv_lstm_out, [[0, 0], [0, 0], [0, self._first_lstm_input_dim_pad]]) conv_lstm_out", "lingvo.core import rnn_cell from lingvo.core import rnn_layers from lingvo.core import", "tf.transpose( tf.reshape(t, [first_dim, second_dim, -1]), [1, 0, 2]) t_shape_new =", "starting the rnn layers. conv_lstm_out = py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape =", "def Params(cls): \"\"\"Configs for AsrEncoder.\"\"\" p = super(AsrEncoder, cls).Params() p.Define('lstm_tpl',", "# shape as its input. _, _, width, in_channel =", "% (i) params_rnn_layers.append(rnn_p) if p.project_lstm_output and (i < p.num_lstm_layers -", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "backward_p) rnn_p.name = 'brnn_L%d' % (i) params_rnn_layers.append(rnn_p) if p.project_lstm_output and", "= self.params inputs, paddings = batch.src_inputs, batch.paddings with tf.name_scope(p.name): #", "are gated. ' 'Will only be used if residual_start is", "lstm_out = rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding) # Move time dimension to", "= p.name with tf.variable_scope(name): # First create the conv layers.", "cnn_p.filter_shape[2] = 2 * in_channel cnn_p.filter_shape[3] = in_channel params_conv_lstm_cnn.append(cnn_p) #", "shape [time, batch, 1] # Now the rnn layers. num_skips", "padding. assert not py_utils.use_tpu() inputs_pad = tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps),", "f_conv_lstm_p.Copy() b_conv_lstm_p.name = 'b_conv_lstm_%d' % (i) conv_lstm_rnn_p = self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name", "self.conv_lstm_cnn)): conv_lstm_in = conv_lstm_out # Move time dimension to be", "None, 'Filter strides for each conv layer.') p.Define('input_shape', [None, None,", "in plots: fig.AddSubplot( [tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time') fig.Finalize() rnn_padding", "= b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p = p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name = 'conv_lstm_cnn_%d' %", "out_paddings is of the shape [time, batch] \"\"\" p =", "under the Apache License, Version 2.0 (the \"License\"); # you", "the input sequence. ') p.Define( 'residual_start', 0, 'Start residual connections", "0, 'Start residual connections from this lstm layer. ' 'Disabled", "permissions and # limitations under the License. \"\"\"Encoders for the", "input_generator, we may avoid this additional padding. assert not py_utils.use_tpu()", "p.lstm_tpl.Copy() forward_p.name = 'fwd_rnn_L%d' % (i) forward_p.num_input_nodes = input_dim forward_p.num_output_nodes", "f_conv_lstm_p conv_lstm_rnn_p.bak = b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p = p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name =", "import rnn_layers from lingvo.core import summary_utils from lingvo.core import model_helper", "the speech model.\"\"\" from __future__ import absolute_import from __future__ import", "in_channel cnn_p.filter_shape[3] = in_channel params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui): Refactor ConvLSTMBlock into", "paddings for i, conv_layer in enumerate(self.conv): conv_out, out_padding = conv_layer.FProp(theta.conv[i],", "ConvLSTMBlock into a layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad)", "'Configs template for the cnn layer immediately follow the' '", "2016). # Default config for the projection layer. p.proj_tpl.params_init =", "= [] for i in range(p.num_cnn_layers): conv_p = p.cnn_tpl.Copy() conv_p.name", "'paddings'. Args: theta: A NestedMap object containing weights' values of", "conv_lstm_in, conv_lstm_in_padding) # Move time dimension to be the second.", "# cnn/batch-norm/relu -> # bidirectional conv-lstm -> # cnn/batch-norm/relu #", "batch, 1] # Now the rnn layers. num_skips = 0", "[0, self._first_lstm_input_dim_pad]]) conv_lstm_out = py_utils.HasShape(conv_lstm_out, [-1, -1, self._first_lstm_input_dim]) # Transpose", "p.cnn_tpl.Copy() conv_p.name = 'conv_L%d' % (i) conv_p.filter_shape = p.conv_filter_shapes[i] conv_p.filter_stride", "theta, batch, state0=None): \"\"\"Encodes source as represented by 'inputs' and", "= 'enc_hwskip_%d' % len(params_highway_skip_layers) highway_skip.input_dim = 2 * p.lstm_cell_size params_highway_skip_layers.append(highway_skip)", "ReshapeForPlot( tf.transpose(inputs, [0, 1, 3, 2]), paddings, 'inputs') ] conv_out", "i in range(p.num_conv_lstm_layers): # NOTE(yonghui): We assume that output from", "input dims is multiple of 16 (alignment # requirement from", "'conv_%d_out' % i)) def TransposeFirstTwoDims(t): first_dim = tf.shape(t)[0] second_dim =", "proj_p.output_dim = 2 * p.lstm_cell_size proj_p.name = 'proj_L%d' % (i)", "tf.transpose(conv_lstm_out, [1, 0, 2]) rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) # rnn_in", "# rnn_in is of shape [time, batch, depth] # rnn_padding", "forward_p, backward_p) def CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16):", "p.conv_filter_shapes = [(3, 3, 3, 32), (3, 3, 32, 32)]", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "input_dim = self._first_lstm_input_dim else: input_dim = 2 * p.lstm_cell_size forward_p", "0 for i in range(p.num_lstm_layers): rnn_out = self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding)", "conv_lstm_rnn_p.fwd = f_conv_lstm_p conv_lstm_rnn_p.bak = b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p = p.after_conv_lstm_cnn_tpl.Copy()", "self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16)", "(outputs, out_paddings, state1) tuple. Outputs is of the shape [time,", "return tf.reshape(t_new, t_shape_new) # Now the conv-lstm part. conv_lstm_out =", "# TODO(yonghui): Refactor ConvLSTMBlock into a layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn',", "the License. \"\"\"Encoders for the speech model.\"\"\" from __future__ import", "[None, None, None, None] p.conv_lstm_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape = [3,", "= [(2, 2), (2, 2)] p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui):", "tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]], 0) return tf.reshape(t_new, t_shape_new) # Now the", "bidirectional lstm -> # projection/batch-norm/relu -> # bidirectional lstm #", "conv_output_shape # Makes sure the lstm input dims is multiple", "params_highway_skip_layers) @property def _use_functional(self): return True def CreateBidirectionalRNNParams(self, forward_p, backward_p):", "import range from six.moves import zip import tensorflow as tf", "params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16) # Now create", "time dimension to be the first. rnn_in = tf.transpose(conv_lstm_out, [1,", "import layers from lingvo.core import plot from lingvo.core import py_utils", "'Filter strides for each conv layer.') p.Define('input_shape', [None, None, None,", "same # shape as its input. _, _, width, in_channel", "# Now the rnn layers. num_skips = 0 for i", "# architecture: # # cnn/batch-norm/relu -> # cnn/batch-norm/relu -> #", "else: first_lstm_input_dim = first_lstm_input_dim_unpadded first_lstm_input_dim_padding = ( first_lstm_input_dim - first_lstm_input_dim_unpadded)", "plot_tensor = tf.transpose(plot_tensor, [0, 2, 1], name=name) return (plot_tensor, summary_utils.SequenceLength(padding))", "1, 3, 2]), paddings, 'inputs') ] conv_out = inputs out_padding", "enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs template for the highway skip layer.')", "= conv_layer.FProp(theta.conv[i], conv_out, out_padding) plots.append( ReshapeForPlot( tf.transpose(conv_out, [0, 1, 3,", "# Default config for the projection layer. p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1)", "layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs template for the projection layer.') p.Define(", "self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding) if i == p.num_lstm_layers - 1: rnn_out", "# NOTE(yonghui): The default config below assumes the following encoder", "the shape [time, batch] \"\"\" p = self.params inputs, paddings", "= 0 for i in range(p.num_lstm_layers): rnn_out = self.rnn[i].FProp(theta.rnn[i], rnn_in,", "[time, batch, depth] # rnn_padding is of shape [time, batch,", "for ProjectionLayer yet (as of sep 22, 2016). p.conv_lstm_tpl.filter_shape =", "layer.') p.Define( 'highway_skip', False, 'If set, residual connections from different", "layers to create.') p.Define('num_lstm_layers', 3, 'Number of rnn layers to", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "lingvo.core import base_layer from lingvo.core import layers from lingvo.core import", "layers.HighwaySkipLayer.Params(), 'Configs template for the highway skip layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(),", "Authors. All Rights Reserved. # # Licensed under the Apache", "p.proj_tpl.Copy() proj_p.input_dim = 2 * p.lstm_cell_size proj_p.output_dim = 2 *", "layer after each encoder LSTM layer.') p.Define('pad_steps', 6, 'Extra zero-padded", "cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs template for the RNN layer.') p.Define('cnn_tpl',", "variational noise logic is currently not # implemented for ProjectionLayer", "yet (as of sep 22, 2016). # Default config for", "batch, depth] # rnn_padding is of shape [time, batch, 1]", "reasonable default values. # # NOTE(yonghui): The default config below", "self._first_lstm_input_dim_pad: conv_lstm_out = tf.pad( conv_lstm_out, [[0, 0], [0, 0], [0,", "cnn/batch-norm/relu -> # cnn/batch-norm/relu -> # bidirectional conv-lstm -> #", "= p.is_eval params_proj_layers.append(proj_p) # add the skip layers residual_index =", "= [] for i in range(p.num_lstm_layers): if i == 0:", "layers.ProjectionLayer.Params(), 'Configs template for the projection layer.') p.Define( 'highway_skip', False,", "'highway_skip', False, 'If set, residual connections from different layers are", "# Default config for the convolution layer. p.input_shape = [None,", "lstm layers to create.') p.Define('num_lstm_layers', 3, 'Number of rnn layers", "Apache License, Version 2.0 (the \"License\"); # you may not", "' 'Will only be used if residual_start is enabled.') p.Define('highway_skip_tpl',", "either express or implied. # See the License for the", "ConvLSTMBlock has the same # shape as its input. _,", "Returns: (outputs, out_paddings, state1) tuple. Outputs is of the shape", "= [] for i in range(p.num_conv_lstm_layers): # NOTE(yonghui): We assume", "self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16) # Now create all the", "import division from __future__ import print_function import collections from six.moves", "= p.conv_filter_shapes[i] conv_p.filter_stride = p.conv_filter_strides[i] conv_p.is_eval = p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv',", "num_skips = 0 for i in range(p.num_lstm_layers): rnn_out = self.rnn[i].FProp(theta.rnn[i],", "convolution layer. p.input_shape = [None, None, 80, 3] p.conv_filter_shapes =", "NOTE(yonghui): The default config below assumes the following encoder #", "state1) tuple. Outputs is of the shape [time, batch, depth],", "# requirement from FRNN). first_lstm_input_dim_unpadded = lstm_input_shape[2] * lstm_input_shape[3] if", "of shape [time, batch, 1] # Now the rnn layers.", "import plot from lingvo.core import py_utils from lingvo.core import rnn_cell", "import collections from six.moves import range from six.moves import zip", "logic is currently not # implemented for ConvLayer yet (as", "py_utils.HasShape(residual_in, tf.shape(rnn_out)) if p.project_lstm_output and (i < p.num_lstm_layers - 1):", "be of shape [batch, time]. state0: Recurrent input state. Not", "# Default config for the rnn layer. p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1)", "is currently not # implemented for ConvLayer yet (as of", "residual_index % p.residual_stride == 0: residual_in = rnn_in if residual_index", "this encoder. Returns: (outputs, out_paddings, state1) tuple. Outputs is of", "cnn_in, cnn_in_padding) conv_lstm_out, conv_lstm_out_padding = cnn_out, cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding,", "and residual_index >= 0: if residual_index % p.residual_stride == 0:", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "skip per residual connection.') p.Define( 'bidi_rnn_type', 'func', 'Options: func, native_cudnn.", "= tf.concat([inputs, inputs_pad], 1, name='inputs') paddings = tf.concat([paddings, paddings_pad], 1)", "is of the shape [time, batch, depth], and out_paddings is", "to top. plots.reverse() for tensor, seq_len in plots: fig.AddSubplot( [tensor,", "layers to create.') p.Define('num_conv_lstm_layers', 1, 'Number of conv lstm layers", "= p.highway_skip_tpl.Copy() highway_skip.name = 'enc_hwskip_%d' % len(params_highway_skip_layers) highway_skip.input_dim = 2", "is for ensuring the # correctness of the conv-layers at", "num_lstm_layers.') p.Define('residual_stride', 1, 'Number of lstm layers to skip per", "super(AsrEncoder, self).__init__(params) p = self.params assert p.packed_input is False, ('Packed", "rnn_out = self.rnn[i].FProp(theta.rnn[i], rnn_in, rnn_padding) residual_index = i - p.residual_start", "% (i) proj_p.is_eval = p.is_eval params_proj_layers.append(proj_p) # add the skip", "== p.residual_stride - 1: # Highway skip connection. if p.highway_skip:", "sep 22, 2016). # Default config for the projection layer.", "conv_lstm_out_padding = cnn_out, cnn_out_padding plots.append( ReshapeForPlot(conv_lstm_out, conv_lstm_out_padding, 'conv_lstm_%d_out' % i))", "the' ' convlstm layer.') p.Define('conv_filter_shapes', None, 'Filter shapes for each", "conv layer.') p.Define('input_shape', [None, None, None, None], 'Shape of the", "= self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16) # Now create all the rnn", "i == 0: input_dim = self._first_lstm_input_dim else: input_dim = 2", "params_conv_layers = [] for i in range(p.num_cnn_layers): conv_p = p.cnn_tpl.Copy()", "rnn_out final_out = rnn_in if self.cluster.add_summary: fig = plot.MatplotlibFigureSummary( 'encoder_example',", "py_utils.HasShape(conv_lstm_out, [-1, -1, self._first_lstm_input_dim]) # Transpose to move the time", "py_utils.HasRank(conv_lstm_out, 4) conv_lstm_out_shape = tf.shape(conv_lstm_out) new_shape = tf.concat([conv_lstm_out_shape[:2], [-1]], 0)", "NOTE(yonghui): We assume that output from ConvLSTMBlock has the same", "p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers) @property def", "p.conv_lstm_tpl.Copy() f_conv_lstm_p.name = 'f_conv_lstm_%d' % (i) f_conv_lstm_p.inputs_shape = [None, 1,", "p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(), 'Configs template for the RNN layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(),", "the input. This should a TensorShape with rank 4.') p.Define('lstm_cell_size',", "max_len = tf.shape(tensor)[1] plot_tensor = tf.reshape(tensor, [batch_size, max_len, -1]) plot_tensor", "tf.zeros( inplace_ops.inplace_update(tf.shape(inputs), 1, p.pad_steps), inputs.dtype) paddings_pad = tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1,", "layers and projection layers. # TODO(yonghui): take care of device", "3, None, None] p.after_conv_lstm_cnn_tpl.params_init = ( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride = [1,", "to move the time dimension to be the first. rnn_in", "tf.TensorShape(p.input_shape) for i in range(p.num_cnn_layers): conv_output_shape = self.conv[i].OutShape(conv_output_shape) conv_output_shape =", "shape [time, batch, depth], and out_paddings is of the shape", "Disable variational noise logic. # NOTE(yonghui): Fortunately, variational noise logic", "first_lstm_input_dim_padding = ( first_lstm_input_dim - first_lstm_input_dim_unpadded) return first_lstm_input_dim, first_lstm_input_dim_padding @property", "of rnn layers to create') p.Define('project_lstm_output', True, 'Include projection layer", "highway skip layer.') p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs template for ConvLSTMCell.') p.Define(", "i)) rnn_in = rnn_out final_out = rnn_in if self.cluster.add_summary: fig", "and (i < p.num_lstm_layers - 1): # Projection layers. rnn_out", "= py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape = [3, 3, None, None] p.after_conv_lstm_cnn_tpl.params_init =", "implemented for ConvLayer yet (as of sep 22, 2016). #", "None, None], 'Shape of the input. This should a TensorShape", "% (i) forward_p.num_input_nodes = input_dim forward_p.num_output_nodes = p.lstm_cell_size backward_p =", "conv_out, out_padding = conv_layer.FProp(theta.conv[i], conv_out, out_padding) plots.append( ReshapeForPlot( tf.transpose(conv_out, [0,", "layer.') p.Define('input_shape', [None, None, None, None], 'Shape of the input.", "params_conv_lstm_rnn = [] params_conv_lstm_cnn = [] for i in range(p.num_conv_lstm_layers):", "template for the cnn layer immediately follow the' ' convlstm", "out_padding = paddings for i, conv_layer in enumerate(self.conv): conv_out, out_padding", "1): # Projection layers. rnn_out = self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding) if", "TransposeFirstTwoDims(t): first_dim = tf.shape(t)[0] second_dim = tf.shape(t)[1] t_new = tf.transpose(", "= tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2) lstm_out = rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding) #", "0, 2]), 'rnn_%d_out' % i)) rnn_in = rnn_out final_out =", "p.Define('conv_lstm_tpl', rnn_cell.ConvLSTMCell.Params(), 'Configs template for ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs", "tf.concat([conv_lstm_out_shape[:2], [-1]], 0) conv_lstm_out = tf.reshape(conv_lstm_out, new_shape) if self._first_lstm_input_dim_pad: conv_lstm_out", "enumerate( zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in = conv_lstm_out # Move time dimension", "= py_utils.HasShape(conv_lstm_out, [-1, -1, self._first_lstm_input_dim]) # Transpose to move the", "use this file except in compliance with the License. #", "and (i < p.num_lstm_layers - 1): proj_p = p.proj_tpl.Copy() proj_p.input_dim", "p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs template for the highway skip layer.') p.Define('conv_lstm_tpl',", "p.project_lstm_output and (i < p.num_lstm_layers - 1): # Projection layers.", "3, 32), (3, 3, 32, 32)] p.conv_filter_strides = [(2, 2),", "= p.conv_filter_strides[i] conv_p.is_eval = p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers) conv_output_shape =", "tf.transpose(rnn_out, [1, 0, 2]), tf.transpose(rnn_padding, [1, 0, 2]), 'rnn_%d_out' %", "= int( (first_lstm_input_dim_unpadded + pad_to_multiple - 1) / pad_to_multiple) *", "The TensorFlow Authors. All Rights Reserved. # # Licensed under", "lingvo.core import layers from lingvo.core import plot from lingvo.core import", "'conv_lstm_%d_out' % i)) # Need to do a reshape before", "at the end. This is for ensuring the # correctness", "tuple. Outputs is of the shape [time, batch, depth], and", "= [] params_conv_lstm_cnn = [] for i in range(p.num_conv_lstm_layers): #", "batch, depth], and out_paddings is of the shape [time, batch]", "Now the rnn layers. num_skips = 0 for i in", "collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn')) class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder version 1.\"\"\" @classmethod", "requirement from FRNN). first_lstm_input_dim_unpadded = lstm_input_shape[2] * lstm_input_shape[3] if self._use_functional", "if self._use_functional and (first_lstm_input_dim_unpadded % pad_to_multiple != 0): first_lstm_input_dim =", "* p.lstm_cell_size forward_p = p.lstm_tpl.Copy() forward_p.name = 'fwd_rnn_L%d' % (i)", "= 'conv_L%d' % (i) conv_p.filter_shape = p.conv_filter_shapes[i] conv_p.filter_stride = p.conv_filter_strides[i]", "forward_p.Copy() backward_p.name = 'bak_rnn_L%d' % (i) rnn_p = self.CreateBidirectionalRNNParams(forward_p, backward_p)", "of the input. This should a TensorShape with rank 4.')", "device placement. params_rnn_layers = [] params_proj_layers = [] params_highway_skip_layers =", "1 if p.residual_start > 0 and residual_index >= 0: if", "residual_in = rnn_in if residual_index % p.residual_stride == p.residual_stride -", "as its input. _, _, width, in_channel = conv_output_shape f_conv_lstm_p", "0], [0, 0], [0, self._first_lstm_input_dim_pad]]) conv_lstm_out = py_utils.HasShape(conv_lstm_out, [-1, -1,", "= tf.reshape(conv_lstm_out, new_shape) if self._first_lstm_input_dim_pad: conv_lstm_out = tf.pad( conv_lstm_out, [[0,", "layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding( conv_output_shape,", "of conv lstm layers to create.') p.Define('num_lstm_layers', 3, 'Number of", "and 'paddings'. Args: theta: A NestedMap object containing weights' values", "conv_lstm_out = tf.pad( conv_lstm_out, [[0, 0], [0, 0], [0, self._first_lstm_input_dim_pad]])", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "for ConvLayer yet (as of sep 22, 2016). # Default", "3, 2]), paddings, 'inputs') ] conv_out = inputs out_padding =", "= rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding) # Move time dimension to be", "be used if residual_start is enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs template", "template for ConvLSTMCell.') p.Define( 'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the", "'Configs template for the projection layer.') p.Define( 'highway_skip', False, 'If", "32, 32)] p.conv_filter_strides = [(2, 2), (2, 2)] p.cnn_tpl.params_init =", "@property def _use_functional(self): return True def CreateBidirectionalRNNParams(self, forward_p, backward_p): return", "'after_conv_lstm_cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the cnn layer immediately follow", "conv_layer.FProp(theta.conv[i], conv_out, out_padding) plots.append( ReshapeForPlot( tf.transpose(conv_out, [0, 1, 3, 2]),", "used if residual_start is enabled.') p.Define('highway_skip_tpl', layers.HighwaySkipLayer.Params(), 'Configs template for", "the rnn layer. p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1) # Default config for", "return rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self, conv_output_shape, pad_to_multiple=16): lstm_input_shape = conv_output_shape #", "out_padding = conv_layer.FProp(theta.conv[i], conv_out, out_padding) plots.append( ReshapeForPlot( tf.transpose(conv_out, [0, 1,", "p.pad_steps), paddings.dtype) inputs = tf.concat([inputs, inputs_pad], 1, name='inputs') paddings =", "the second. cnn_in = TransposeFirstTwoDims(lstm_out) cnn_in = tf.squeeze(cnn_in, 2) cnn_in_padding", "layer. p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise logic.", "the # correctness of the conv-layers at the edges. if", "of sep 22, 2016). # Default config for the projection", "(i) f_conv_lstm_p.inputs_shape = [None, 1, width, in_channel] f_conv_lstm_p.cell_shape = [None,", "extra padded timesteps at the end. This is for ensuring", "2 * p.lstm_cell_size forward_p = p.lstm_tpl.Copy() forward_p.name = 'fwd_rnn_L%d' %", "projection layer.') p.Define( 'highway_skip', False, 'If set, residual connections from", "tf.squeeze(cnn_in, 2) cnn_in_padding = conv_lstm_out_padding cnn_out, cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i], cnn_in,", "p.Define('conv_filter_shapes', None, 'Filter shapes for each conv layer.') p.Define('conv_filter_strides', None,", "create the conv layers. assert p.num_cnn_layers == len(p.conv_filter_shapes) assert p.num_cnn_layers", "self._first_lstm_input_dim]) # Transpose to move the time dimension to be", "projection/batch-norm/relu -> # bidirectional lstm -> # projection/batch-norm/relu -> #", "input_dim = 2 * p.lstm_cell_size forward_p = p.lstm_tpl.Copy() forward_p.name =", "* p.lstm_cell_size proj_p.output_dim = 2 * p.lstm_cell_size proj_p.name = 'proj_L%d'", "return False def zero_state(self, batch_size): return py_utils.NestedMap() def FProp(self, theta,", "cnn_in = tf.squeeze(cnn_in, 2) cnn_in_padding = conv_lstm_out_padding cnn_out, cnn_out_padding =", "output from ConvLSTMBlock has the same # shape as its", "3] # height (time), width (frequency) p.conv_lstm_tpl.inputs_shape = [None, None,", "tf.pad( conv_lstm_out, [[0, 0], [0, 0], [0, self._first_lstm_input_dim_pad]]) conv_lstm_out =", "else: input_dim = 2 * p.lstm_cell_size forward_p = p.lstm_tpl.Copy() forward_p.name", "with the License. # You may obtain a copy of", "> 0 and residual_index >= 0 and p.highway_skip: highway_skip =", "depth], and out_paddings is of the shape [time, batch] \"\"\"", "- first_lstm_input_dim_unpadded) return first_lstm_input_dim, first_lstm_input_dim_padding @property def supports_streaming(self): return False", "None, None] p.after_conv_lstm_cnn_tpl.params_init = ( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride = [1, 1]", "import inplace_ops from lingvo.core import base_encoder from lingvo.core import base_layer", "conv_lstm_out # Move time dimension to be the first. conv_lstm_in", "Projection layers. rnn_out = self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding) if i ==", "third. batch_size = tf.shape(tensor)[0] max_len = tf.shape(tensor)[1] plot_tensor = tf.reshape(tensor,", "# limitations under the License. \"\"\"Encoders for the speech model.\"\"\"", "of conv layers to create.') p.Define('num_conv_lstm_layers', 1, 'Number of conv", "import model_helper ConvLSTMBlock = collections.namedtuple('ConvLSTMBlock', ('rnn', 'cnn')) class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech", "for tensor, seq_len in plots: fig.AddSubplot( [tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name,", "'Configs template for the RNN layer.') p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs template", "layer.') p.Define('conv_filter_strides', None, 'Filter strides for each conv layer.') p.Define('input_shape',", "layers from bottom to top. plots.reverse() for tensor, seq_len in", "we have done # padding on the input_generator, we may", "# Move time dimension to be the second. cnn_in =", "== len(p.conv_filter_strides) params_conv_layers = [] for i in range(p.num_cnn_layers): conv_p", "express or implied. # See the License for the specific", "native_cudnn. ' 'func: BidirectionalFRNN, ' 'native_cudnn: BidirectionalNativeCuDNNLSTM.') # TODO(yonghui): Maybe", "except in compliance with the License. # You may obtain", "class AsrEncoder(base_encoder.BaseEncoder): \"\"\"Speech encoder version 1.\"\"\" @classmethod def Params(cls): \"\"\"Configs", "from lingvo.core import py_utils from lingvo.core import rnn_cell from lingvo.core", "p.residual_start > 0 and residual_index >= 0 and p.highway_skip: highway_skip", "tf from tensorflow.python.ops import inplace_ops from lingvo.core import base_encoder from", "layer. p.input_shape = [None, None, 80, 3] p.conv_filter_shapes = [(3,", "Params(cls): \"\"\"Configs for AsrEncoder.\"\"\" p = super(AsrEncoder, cls).Params() p.Define('lstm_tpl', rnn_cell.LSTMCellSimple.Params(),", "# # NOTE(yonghui): The default config below assumes the following", "and (first_lstm_input_dim_unpadded % pad_to_multiple != 0): first_lstm_input_dim = int( (first_lstm_input_dim_unpadded", "= tf.shape(t)[1] t_new = tf.transpose( tf.reshape(t, [first_dim, second_dim, -1]), [1,", "\"\"\"Speech encoder version 1.\"\"\" @classmethod def Params(cls): \"\"\"Configs for AsrEncoder.\"\"\"", "of 16 (alignment # requirement from FRNN). first_lstm_input_dim_unpadded = lstm_input_shape[2]", "% (i) rnn_p = self.CreateBidirectionalRNNParams(forward_p, backward_p) rnn_p.name = 'brnn_L%d' %", "!= 0): first_lstm_input_dim = int( (first_lstm_input_dim_unpadded + pad_to_multiple - 1)", "2) lstm_out = rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding) # Move time dimension", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "paddings_pad], 1) def ReshapeForPlot(tensor, padding, name): \"\"\"Transposes and flattens channels", "ProjectionLayer yet (as of sep 22, 2016). p.conv_lstm_tpl.filter_shape = [1,", "cnn_p = p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name = 'conv_lstm_cnn_%d' % (i) cnn_p.filter_shape[2] =", "Fortunately, variational noise logic is currently not # implemented for", "32)] p.conv_filter_strides = [(2, 2), (2, 2)] p.cnn_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1)", "import base_layer from lingvo.core import layers from lingvo.core import plot", "' 'Disabled if 0 or greater than num_lstm_layers.') p.Define('residual_stride', 1,", "CONDITIONS OF ANY KIND, either express or implied. # See", "= tf.concat([[second_dim], [first_dim], tf.shape(t)[2:]], 0) return tf.reshape(t_new, t_shape_new) # Now", "layers to create') p.Define('project_lstm_output', True, 'Include projection layer after each", "'native_cudnn: BidirectionalNativeCuDNNLSTM.') # TODO(yonghui): Maybe move those configs to a", "of shape [batch, time]. state0: Recurrent input state. Not supported/ignored", "[None, 1, width, in_channel] f_conv_lstm_p.cell_shape = [None, 1, width, in_channel]", "-> # cnn/batch-norm/relu -> # bidirectional conv-lstm -> # cnn/batch-norm/relu", "NestedMap with fields: src_inputs - The inputs tensor. It is", "cnn_out, cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding) conv_lstm_out, conv_lstm_out_padding = cnn_out,", "layers are gated. ' 'Will only be used if residual_start", "assert p.num_cnn_layers == len(p.conv_filter_shapes) assert p.num_cnn_layers == len(p.conv_filter_strides) params_conv_layers =", "conv_lstm_in = conv_lstm_out # Move time dimension to be the", "1 else: # Residual skip connection. rnn_out += py_utils.HasShape(residual_in, tf.shape(rnn_out))", "None, None] p.conv_lstm_tpl.cell_shape = [None, None, None, None] p.conv_lstm_tpl.params_init =", "= f_conv_lstm_p conv_lstm_rnn_p.bak = b_conv_lstm_p params_conv_lstm_rnn.append(conv_lstm_rnn_p) cnn_p = p.after_conv_lstm_cnn_tpl.Copy() cnn_p.name", "by this encoder. Returns: (outputs, out_paddings, state1) tuple. Outputs is", "1): proj_p = p.proj_tpl.Copy() proj_p.input_dim = 2 * p.lstm_cell_size proj_p.output_dim", "[] params_conv_lstm_cnn = [] for i in range(p.num_conv_lstm_layers): # NOTE(yonghui):", "is currently not # implemented for ProjectionLayer yet (as of", "= [] params_highway_skip_layers = [] for i in range(p.num_lstm_layers): if", "i)) def TransposeFirstTwoDims(t): first_dim = tf.shape(t)[0] second_dim = tf.shape(t)[1] t_new", "TODO(yonghui): take care of device placement. params_rnn_layers = [] params_proj_layers", "1, 'Number of lstm layers to skip per residual connection.')", "return py_utils.NestedMap() def FProp(self, theta, batch, state0=None): \"\"\"Encodes source as", "p.conv_filter_strides[i] conv_p.is_eval = p.is_eval params_conv_layers.append(conv_p) self.CreateChildren('conv', params_conv_layers) conv_output_shape = tf.TensorShape(p.input_shape)", "to be the first. rnn_in = tf.transpose(conv_lstm_out, [1, 0, 2])", "backward_p = forward_p.Copy() backward_p.name = 'bak_rnn_L%d' % (i) rnn_p =", "__init__(self, params): super(AsrEncoder, self).__init__(params) p = self.params assert p.packed_input is", "those configs to a separate file. # Set some reasonable", "assumes the following encoder # architecture: # # cnn/batch-norm/relu ->", "dimensions beyond the third into the third. batch_size = tf.shape(tensor)[0]", "pad_to_multiple != 0): first_lstm_input_dim = int( (first_lstm_input_dim_unpadded + pad_to_multiple -", "True, 'Include projection layer after each encoder LSTM layer.') p.Define('pad_steps',", "FRNN). first_lstm_input_dim_unpadded = lstm_input_shape[2] * lstm_input_shape[3] if self._use_functional and (first_lstm_input_dim_unpadded", "'Number of conv lstm layers to create.') p.Define('num_lstm_layers', 3, 'Number", "256, 'LSTM cell size for the RNN layer.') p.Define('num_cnn_layers', 2,", "beyond the third into the third. batch_size = tf.shape(tensor)[0] max_len", "3] p.conv_filter_shapes = [(3, 3, 3, 32), (3, 3, 32,", "- 1): # Projection layers. rnn_out = self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding)", "# # Default config for the rnn layer. p.lstm_tpl.params_init =", "values. # # NOTE(yonghui): The default config below assumes the", "of the shape [time, batch, depth], and out_paddings is of", "'Number of conv layers to create.') p.Define('num_conv_lstm_layers', 1, 'Number of", "connections from different layers are gated. ' 'Will only be", "'proj_L%d' % (i) proj_p.is_eval = p.is_eval params_proj_layers.append(proj_p) # add the", "if p.pad_steps > 0: # inplace_update() is not supported by", "i == p.num_lstm_layers - 1: rnn_out *= (1.0 - rnn_padding)", "the projection layer.') p.Define( 'highway_skip', False, 'If set, residual connections", "TensorShape with rank 4.') p.Define('lstm_cell_size', 256, 'LSTM cell size for", "p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs template for the projection layer.') p.Define( 'highway_skip',", "connections from this lstm layer. ' 'Disabled if 0 or", "Refactor ConvLSTMBlock into a layer. self.CreateChildren('conv_lstm_rnn', params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim,", "'enc_hwskip_%d' % len(params_highway_skip_layers) highway_skip.input_dim = 2 * p.lstm_cell_size params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn',", "lstm input dims is multiple of 16 (alignment # requirement", "Transpose to move the time dimension to be the first.", "p = self.params assert p.packed_input is False, ('Packed inputs are", "for i in range(p.num_lstm_layers): if i == 0: input_dim =", "if residual_index % p.residual_stride == 0: residual_in = rnn_in if", "for the rnn layer. p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1) # Default config", "plots: fig.AddSubplot( [tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time') fig.Finalize() rnn_padding =", "LSTM layer.') p.Define('pad_steps', 6, 'Extra zero-padded timesteps to add to", "[0, 1, 3, 2]), paddings, 'inputs') ] conv_out = inputs", "1, name='inputs') paddings = tf.concat([paddings, paddings_pad], 1) def ReshapeForPlot(tensor, padding,", "below assumes the following encoder # architecture: # # cnn/batch-norm/relu", "residual connection.') p.Define( 'bidi_rnn_type', 'func', 'Options: func, native_cudnn. ' 'func:", "the conv layers. assert p.num_cnn_layers == len(p.conv_filter_shapes) assert p.num_cnn_layers ==", "tf.transpose(inputs, [0, 1, 3, 2]), paddings, 'inputs') ] conv_out =", "fig.AddSubplot( [tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence, title=tensor.name, xlabel='Time') fig.Finalize() rnn_padding = tf.squeeze(rnn_padding,", "= p.lstm_cell_size backward_p = forward_p.Copy() backward_p.name = 'bak_rnn_L%d' % (i)", "' convlstm layer.') p.Define('conv_filter_shapes', None, 'Filter shapes for each conv", "not # implemented for ProjectionLayer yet (as of sep 22,", "'Extra zero-padded timesteps to add to the input sequence. ')", "[[0, 0], [0, 0], [0, self._first_lstm_input_dim_pad]]) conv_lstm_out = py_utils.HasShape(conv_lstm_out, [-1,", "per residual connection.') p.Define( 'bidi_rnn_type', 'func', 'Options: func, native_cudnn. '", "residual_index = i - p.residual_start + 1 if p.residual_start >", "= in_channel params_conv_lstm_cnn.append(cnn_p) # TODO(yonghui): Refactor ConvLSTMBlock into a layer.", "the first. conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in = tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding", "* pad_to_multiple else: first_lstm_input_dim = first_lstm_input_dim_unpadded first_lstm_input_dim_padding = ( first_lstm_input_dim", "encoder. Returns: (outputs, out_paddings, state1) tuple. Outputs is of the", "to be the first. conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in = tf.expand_dims(conv_lstm_in,", "batch: A NestedMap with fields: src_inputs - The inputs tensor.", "sep 22, 2016). p.conv_lstm_tpl.filter_shape = [1, 3] # height (time),", "time, feature_dim, channels]. paddings - The paddings tensor. It is", "layer.') p.Define('conv_filter_shapes', None, 'Filter shapes for each conv layer.') p.Define('conv_filter_strides',", "'encoder_example', figsize=(8, len(plots) * 3.5)) # Order layers from bottom", "as tf from tensorflow.python.ops import inplace_ops from lingvo.core import base_encoder", "this additional padding. assert not py_utils.use_tpu() inputs_pad = tf.zeros( inplace_ops.inplace_update(tf.shape(inputs),", "2018 The TensorFlow Authors. All Rights Reserved. # # Licensed", "or greater than num_lstm_layers.') p.Define('residual_stride', 1, 'Number of lstm layers", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "i in range(p.num_cnn_layers): conv_p = p.cnn_tpl.Copy() conv_p.name = 'conv_L%d' %", "assume that output from ConvLSTMBlock has the same # shape", "to create.') p.Define('num_conv_lstm_layers', 1, 'Number of conv lstm layers to", "= i - p.residual_start + 1 if p.residual_start > 0", "connection. if p.highway_skip: rnn_out = self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips], residual_in, rnn_out) num_skips", "Default config for the projection layer. p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) #", "if p.project_lstm_output and (i < p.num_lstm_layers - 1): proj_p =", "p.Define('conv_filter_strides', None, 'Filter strides for each conv layer.') p.Define('input_shape', [None,", "inputs = tf.concat([inputs, inputs_pad], 1, name='inputs') paddings = tf.concat([paddings, paddings_pad],", "self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16) # Now", "p.Define('cnn_tpl', layers.ConvLayer.Params(), 'Configs template for the conv layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(),", "plot from lingvo.core import py_utils from lingvo.core import rnn_cell from", "cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding) conv_lstm_out, conv_lstm_out_padding = cnn_out, cnn_out_padding", "paddings tensor. It is expected to be of shape [batch,", "rnn_out = self.proj[i].FProp(theta.proj[i], rnn_out, rnn_padding) if i == p.num_lstm_layers -", "now. Since we have done # padding on the input_generator,", "layer immediately follow the' ' convlstm layer.') p.Define('conv_filter_shapes', None, 'Filter", "Flatten any dimensions beyond the third into the third. batch_size", "0 and p.highway_skip: highway_skip = p.highway_skip_tpl.Copy() highway_skip.name = 'enc_hwskip_%d' %", "of lstm layers to skip per residual connection.') p.Define( 'bidi_rnn_type',", "0: # inplace_update() is not supported by TPU for now.", "have done # padding on the input_generator, we may avoid", "noise logic. # NOTE(yonghui): Fortunately, variational noise logic is currently", "each encoder LSTM layer.') p.Define('pad_steps', 6, 'Extra zero-padded timesteps to", "p.Define('num_cnn_layers', 2, 'Number of conv layers to create.') p.Define('num_conv_lstm_layers', 1,", "conv_p.name = 'conv_L%d' % (i) conv_p.filter_shape = p.conv_filter_shapes[i] conv_p.filter_stride =", "self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name = 'conv_lstm_rnn' conv_lstm_rnn_p.fwd = f_conv_lstm_p conv_lstm_rnn_p.bak = b_conv_lstm_p", "__future__ import division from __future__ import print_function import collections from", "[1, 0, 2]) rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2) # rnn_in is", "Version 2.0 (the \"License\"); # you may not use this", "% pad_to_multiple != 0): first_lstm_input_dim = int( (first_lstm_input_dim_unpadded + pad_to_multiple", "channels]. paddings - The paddings tensor. It is expected to", "p.is_eval params_proj_layers.append(proj_p) # add the skip layers residual_index = i", "2) conv_lstm_in_padding = tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2) lstm_out = rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in,", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved. #", "config for the projection layer. p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui):", "% i)) def TransposeFirstTwoDims(t): first_dim = tf.shape(t)[0] second_dim = tf.shape(t)[1]", "# Now create all the rnn layers and projection layers.", "__future__ import absolute_import from __future__ import division from __future__ import", "import base_encoder from lingvo.core import base_layer from lingvo.core import layers", "1, width, in_channel] b_conv_lstm_p = f_conv_lstm_p.Copy() b_conv_lstm_p.name = 'b_conv_lstm_%d' %", "by 'inputs' and 'paddings'. Args: theta: A NestedMap object containing", "conv_out = inputs out_padding = paddings for i, conv_layer in", "[time, batch, depth], and out_paddings is of the shape [time,", "state0=None): \"\"\"Encodes source as represented by 'inputs' and 'paddings'. Args:", "by applicable law or agreed to in writing, software #", "tf.transpose(conv_out, [0, 1, 3, 2]), out_padding, 'conv_%d_out' % i)) def", "plots.reverse() for tensor, seq_len in plots: fig.AddSubplot( [tensor, seq_len], summary_utils.TrimPaddingAndPlotSequence,", "= py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational noise logic. # NOTE(yonghui):", "width (frequency) p.conv_lstm_tpl.inputs_shape = [None, None, None, None] p.conv_lstm_tpl.cell_shape =", "return model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p) def CreateConvLstmLayerParams(self): return rnn_layers.BidirectionalFRNN.Params() def FirstLstmLayerInputDimAndPadding(self,", "the edges. if p.pad_steps > 0: # inplace_update() is not", "for each conv layer.') p.Define('conv_filter_strides', None, 'Filter strides for each", "2]), out_padding, 'conv_%d_out' % i)) def TransposeFirstTwoDims(t): first_dim = tf.shape(t)[0]", "variational noise logic is currently not # implemented for ConvLayer", "(i) conv_p.filter_shape = p.conv_filter_shapes[i] conv_p.filter_stride = p.conv_filter_strides[i] conv_p.is_eval = p.is_eval", "-> # cnn/batch-norm/relu # bidirectional lstm -> # projection/batch-norm/relu ->", "supported for ' 'AsrEncoder.') name = p.name with tf.variable_scope(name): #", "layer. ' 'Disabled if 0 or greater than num_lstm_layers.') p.Define('residual_stride',", "'conv_L%d' % (i) conv_p.filter_shape = p.conv_filter_shapes[i] conv_p.filter_stride = p.conv_filter_strides[i] conv_p.is_eval", "supports_streaming(self): return False def zero_state(self, batch_size): return py_utils.NestedMap() def FProp(self,", "# Add a few extra padded timesteps at the end.", "py_utils.WeightInit.TruncatedGaussian(0.1) p.after_conv_lstm_cnn_tpl.filter_shape = [3, 3, None, None] p.after_conv_lstm_cnn_tpl.params_init = (", "True def CreateBidirectionalRNNParams(self, forward_p, backward_p): return model_helper.CreateBidirectionalRNNParams(self.params, forward_p, backward_p) def", "Add a few extra padded timesteps at the end. This", "bidirectional lstm -> # projection/batch-norm/relu -> # bidirectional lstm ->", "batch_size = tf.shape(tensor)[0] max_len = tf.shape(tensor)[1] plot_tensor = tf.reshape(tensor, [batch_size,", "six.moves import range from six.moves import zip import tensorflow as", "rnn layers to create') p.Define('project_lstm_output', True, 'Include projection layer after", "= paddings for i, conv_layer in enumerate(self.conv): conv_out, out_padding =", "applicable law or agreed to in writing, software # distributed", "conv_lstm_in = tf.expand_dims(conv_lstm_in, 2) conv_lstm_in_padding = tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2) lstm_out", "func, native_cudnn. ' 'func: BidirectionalFRNN, ' 'native_cudnn: BidirectionalNativeCuDNNLSTM.') # TODO(yonghui):", "p.conv_lstm_tpl.inputs_shape = [None, None, None, None] p.conv_lstm_tpl.cell_shape = [None, None,", "a few extra padded timesteps at the end. This is", "rnn_in if residual_index % p.residual_stride == p.residual_stride - 1: #", "batch, state0=None): \"\"\"Encodes source as represented by 'inputs' and 'paddings'.", "six.moves import zip import tensorflow as tf from tensorflow.python.ops import", "first_lstm_input_dim = int( (first_lstm_input_dim_unpadded + pad_to_multiple - 1) / pad_to_multiple)", "zero-padded timesteps to add to the input sequence. ') p.Define(", "forward_p = p.lstm_tpl.Copy() forward_p.name = 'fwd_rnn_L%d' % (i) forward_p.num_input_nodes =", "proj_p.is_eval = p.is_eval params_proj_layers.append(proj_p) # add the skip layers residual_index", "for i, conv_layer in enumerate(self.conv): conv_out, out_padding = conv_layer.FProp(theta.conv[i], conv_out,", "None] p.after_conv_lstm_cnn_tpl.params_init = ( py_utils.WeightInit.TruncatedGaussian(0.1)) p.after_conv_lstm_cnn_tpl.filter_stride = [1, 1] return", "= 'b_conv_lstm_%d' % (i) conv_lstm_rnn_p = self.CreateConvLstmLayerParams() conv_lstm_rnn_p.name = 'conv_lstm_rnn'", "rnn_in = tf.transpose(conv_lstm_out, [1, 0, 2]) rnn_padding = tf.expand_dims(tf.transpose(conv_lstm_out_padding), 2)", "= tf.transpose(plot_tensor, [0, 2, 1], name=name) return (plot_tensor, summary_utils.SequenceLength(padding)) plots", "(i) proj_p.is_eval = p.is_eval params_proj_layers.append(proj_p) # add the skip layers", "first_lstm_input_dim = first_lstm_input_dim_unpadded first_lstm_input_dim_padding = ( first_lstm_input_dim - first_lstm_input_dim_unpadded) return", "tf.reshape(t, [first_dim, second_dim, -1]), [1, 0, 2]) t_shape_new = tf.concat([[second_dim],", "params_highway_skip_layers.append(highway_skip) self.CreateChildren('rnn', params_rnn_layers) self.CreateChildren('proj', params_proj_layers) self.CreateChildren('highway_skip', params_highway_skip_layers) @property def _use_functional(self):", "# You may obtain a copy of the License at", "conv_p = p.cnn_tpl.Copy() conv_p.name = 'conv_L%d' % (i) conv_p.filter_shape =", "It is expected to be of shape [batch, time]. state0:", "# TODO(yonghui): Maybe move those configs to a separate file.", "theta.highway_skip[num_skips], residual_in, rnn_out) num_skips += 1 else: # Residual skip", "conv_lstm_out = tf.reshape(conv_lstm_out, new_shape) if self._first_lstm_input_dim_pad: conv_lstm_out = tf.pad( conv_lstm_out,", "from tensorflow.python.ops import inplace_ops from lingvo.core import base_encoder from lingvo.core", "0: if residual_index % p.residual_stride == 0: residual_in = rnn_in", "params_proj_layers = [] params_highway_skip_layers = [] for i in range(p.num_lstm_layers):", "BidirectionalFRNN, ' 'native_cudnn: BidirectionalNativeCuDNNLSTM.') # TODO(yonghui): Maybe move those configs", "zip(self.conv_lstm_rnn, self.conv_lstm_cnn)): conv_lstm_in = conv_lstm_out # Move time dimension to", "for the projection layer.') p.Define( 'highway_skip', False, 'If set, residual", "dimension to be the first. conv_lstm_in = TransposeFirstTwoDims(conv_lstm_in) conv_lstm_in =", "the projection layer. p.proj_tpl.params_init = py_utils.WeightInit.TruncatedGaussian(0.1) # TODO(yonghui): Disable variational", "rnn layer. p.lstm_tpl.params_init = py_utils.WeightInit.Uniform(0.1) # Default config for the", "p.residual_stride == p.residual_stride - 1: # Highway skip connection. if", "# cnn/batch-norm/relu # bidirectional lstm -> # projection/batch-norm/relu -> #", "take care of device placement. params_rnn_layers = [] params_proj_layers =", "80, 3] p.conv_filter_shapes = [(3, 3, 3, 32), (3, 3,", "= 'f_conv_lstm_%d' % (i) f_conv_lstm_p.inputs_shape = [None, 1, width, in_channel]", "conv_output_shape.as_list() assert len(conv_output_shape) == 4 # batch, height, width, channel.", "p.num_lstm_layers - 1: rnn_out *= (1.0 - rnn_padding) plots.append( ReshapeForPlot(", "+= 1 else: # Residual skip connection. rnn_out += py_utils.HasShape(residual_in,", "params_conv_lstm_rnn) self.CreateChildren('conv_lstm_cnn', params_conv_lstm_cnn) (self._first_lstm_input_dim, self._first_lstm_input_dim_pad) = self.FirstLstmLayerInputDimAndPadding( conv_output_shape, pad_to_multiple=16) #", "tf.expand_dims( tf.transpose(conv_lstm_out_padding), 2) lstm_out = rnn.FProp(theta.conv_lstm_rnn[i], conv_lstm_in, conv_lstm_in_padding) # Move", "False def zero_state(self, batch_size): return py_utils.NestedMap() def FProp(self, theta, batch,", "def _use_functional(self): return True def CreateBidirectionalRNNParams(self, forward_p, backward_p): return model_helper.CreateBidirectionalRNNParams(self.params,", "new_shape = tf.concat([conv_lstm_out_shape[:2], [-1]], 0) conv_lstm_out = tf.reshape(conv_lstm_out, new_shape) if", "\"\"\"Encodes source as represented by 'inputs' and 'paddings'. Args: theta:", "\"License\"); # you may not use this file except in", "tf.ones( inplace_ops.inplace_update(tf.shape(paddings), 1, p.pad_steps), paddings.dtype) inputs = tf.concat([inputs, inputs_pad], 1,", "for the speech model.\"\"\" from __future__ import absolute_import from __future__", "-> # bidirectional conv-lstm -> # cnn/batch-norm/relu # bidirectional lstm", "rnn_padding) if i == p.num_lstm_layers - 1: rnn_out *= (1.0", "rnn_out, rnn_padding) if i == p.num_lstm_layers - 1: rnn_out *=", "plots = [ ReshapeForPlot( tf.transpose(inputs, [0, 1, 3, 2]), paddings,", "2) cnn_in_padding = conv_lstm_out_padding cnn_out, cnn_out_padding = cnn.FProp(theta.conv_lstm_cnn[i], cnn_in, cnn_in_padding)", "b_conv_lstm_p = f_conv_lstm_p.Copy() b_conv_lstm_p.name = 'b_conv_lstm_%d' % (i) conv_lstm_rnn_p =", "encoder # architecture: # # cnn/batch-norm/relu -> # cnn/batch-norm/relu ->", "(alignment # requirement from FRNN). first_lstm_input_dim_unpadded = lstm_input_shape[2] * lstm_input_shape[3]", "[0, 0], [0, self._first_lstm_input_dim_pad]]) conv_lstm_out = py_utils.HasShape(conv_lstm_out, [-1, -1, self._first_lstm_input_dim])", "# Highway skip connection. if p.highway_skip: rnn_out = self.highway_skip[num_skips].FProp( theta.highway_skip[num_skips],", "layers.ConvLayer.Params(), 'Configs template for the conv layer.') p.Define('proj_tpl', layers.ProjectionLayer.Params(), 'Configs", "range(p.num_lstm_layers): if i == 0: input_dim = self._first_lstm_input_dim else: input_dim", "fig = plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8, len(plots) * 3.5)) # Order", "params_proj_layers.append(proj_p) # add the skip layers residual_index = i -", "its children layers. batch: A NestedMap with fields: src_inputs -", "= rnn_in if self.cluster.add_summary: fig = plot.MatplotlibFigureSummary( 'encoder_example', figsize=(8, len(plots)", "= tf.concat([conv_lstm_out_shape[:2], [-1]], 0) conv_lstm_out = tf.reshape(conv_lstm_out, new_shape) if self._first_lstm_input_dim_pad:", "is of shape [time, batch, 1] # Now the rnn", "= p.cnn_tpl.Copy() conv_p.name = 'conv_L%d' % (i) conv_p.filter_shape = p.conv_filter_shapes[i]", "from FRNN). first_lstm_input_dim_unpadded = lstm_input_shape[2] * lstm_input_shape[3] if self._use_functional and" ]
[ "fig.add_subplot() ## 프레임 생성 pie = ax.pie(c, ## 파이차트 출력", "((r + 0.5) / 2) * np.cos(np.pi / 180 *", "한글이 적용이 안됨!!! c = b['score'].value_counts().sort_index() ## 빈도 print(c) print(labelss)", "빈도수 총합 sum_pct = 0 ## 백분율 초기값 for i,", "## 백분율 텍스트 표시 else: ## 총합을 100으로 맞추기위해 마지막", "f'{100 - sum_pct:.2f}%', ha='center', va='center',size=22,color='white', weight='bold') # pie.rc('font', family=font_name) #", "enumerate(labelss): ang1, ang2 = pie[0][i].theta1, pie[0][i].theta2 ## 각1, 각2 r", "## 총합을 100으로 맞추기위해 마지막 백분율은 100에서 백분율 누적값을 빼준다.", "colors = ['yellowgreen', 'orange'], labels = labelss, textprops={'fontsize': 22} )", "마지막 백분율은 100에서 백분율 누적값을 빼준다. ax.text(x, y, f'{100 -", "numpy as np font_location = './wordcloud_file/malgun.ttf' # For Windows font_name", "plt.rc('font', family=font_name) def percent_graph2(movie_review) : b = movie_review labelss =", "시작점을 90도(degree)로 지정 counterclock=False, ## 시계 방향으로 그린다. # autopct=lambda", "백분율은 100에서 백분율 누적값을 빼준다. ax.text(x, y, f'{100 - sum_pct:.2f}%',", "/ 2) * np.cos(np.pi / 180 * ((ang1 + ang2)", "['yellowgreen', 'orange'], labels = labelss, textprops={'fontsize': 22} ) total =", "np.cos(np.pi / 180 * ((ang1 + ang2) / 2)) ##", "+ ang2) / 2)) ## 정중앙 y좌표 if i <", "/ total * 100:.2f}') ## 백분율을 누적한다. ax.text(x, y, f'{c[i]", "pie[0][i].theta2 ## 각1, 각2 r = pie[0][i].r ## 원의 반지름", "total * 100:.2f}%', ha='center', va='center', size=22, color='white', weight='bold') ## 백분율", "ang2) / 2)) ## 정중앙 y좌표 if i < len(labelss)", "적용이 안됨!!! c = b['score'].value_counts().sort_index() ## 빈도 print(c) print(labelss) fig", "y좌표 if i < len(labelss) - 1: sum_pct += float(f'{c[i]", "- sum_pct:.2f}%', ha='center', va='center',size=22,color='white', weight='bold') # pie.rc('font', family=font_name) # plt.legend(pie[0],", "autopct=lambda p : '{:.2f}%'.format(p), ## 퍼센티지 출력 wedgeprops=dict(width=0.5), colors =", "= movie_review labelss = sorted(b['score'].unique())## 라벨설정함. 한글이 적용이 안됨!!! c", "b['score'].value_counts().sort_index() ## 빈도 print(c) print(labelss) fig = plt.figure(figsize=(8,8)) ## 캔버스", "## 캔버스 배경색을 하얀색으로 설정 ax = fig.add_subplot() ## 프레임", "family=font_name) def percent_graph2(movie_review) : b = movie_review labelss = sorted(b['score'].unique())##", "as fm import matplotlib.pyplot as plt import numpy as np", "* 100:.2f}') ## 백분율을 누적한다. ax.text(x, y, f'{c[i] / total", "textprops={'fontsize': 22} ) total = np.sum(c) ## 빈도수 총합 sum_pct", "np font_location = './wordcloud_file/malgun.ttf' # For Windows font_name = fm.FontProperties(fname=font_location).get_name()", "family=font_name) # plt.legend(pie[0], labelss) ## 범례 표시 plt.savefig('./static/images/pos_neg_ratio.png') # 경로", "ax.text(x, y, f'{c[i] / total * 100:.2f}%', ha='center', va='center', size=22,", "## 각1, 각2 r = pie[0][i].r ## 원의 반지름 x", "color='white', weight='bold') ## 백분율 텍스트 표시 else: ## 총합을 100으로", "## 정중앙 x좌표 y = ((r + 0.5) / 2)", "하얀색으로 설정 ax = fig.add_subplot() ## 프레임 생성 pie =", "생성 fig.set_facecolor('white') ## 캔버스 배경색을 하얀색으로 설정 ax = fig.add_subplot()", "weight='bold') ## 백분율 텍스트 표시 else: ## 총합을 100으로 맞추기위해", "/ 180 * ((ang1 + ang2) / 2)) ## 정중앙", "## 정중앙 y좌표 if i < len(labelss) - 1: sum_pct", "프레임 생성 pie = ax.pie(c, ## 파이차트 출력 startangle=90, ##", "va='center', size=22, color='white', weight='bold') ## 백분율 텍스트 표시 else: ##", "as np font_location = './wordcloud_file/malgun.ttf' # For Windows font_name =", "import matplotlib.font_manager as fm import matplotlib.pyplot as plt import numpy", "fig.set_facecolor('white') ## 캔버스 배경색을 하얀색으로 설정 ax = fig.add_subplot() ##", "그린다. # autopct=lambda p : '{:.2f}%'.format(p), ## 퍼센티지 출력 wedgeprops=dict(width=0.5),", "labels = labelss, textprops={'fontsize': 22} ) total = np.sum(c) ##", "## 백분율을 누적한다. ax.text(x, y, f'{c[i] / total * 100:.2f}%',", "l in enumerate(labelss): ang1, ang2 = pie[0][i].theta1, pie[0][i].theta2 ## 각1,", "def percent_graph2(movie_review) : b = movie_review labelss = sorted(b['score'].unique())## 라벨설정함.", "else: ## 총합을 100으로 맞추기위해 마지막 백분율은 100에서 백분율 누적값을", "font_name = fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name) def percent_graph2(movie_review) : b =", "반지름 x = ((r + 0.5) / 2) * np.cos(np.pi", "in enumerate(labelss): ang1, ang2 = pie[0][i].theta1, pie[0][i].theta2 ## 각1, 각2", "ax = fig.add_subplot() ## 프레임 생성 pie = ax.pie(c, ##", "'orange'], labels = labelss, textprops={'fontsize': 22} ) total = np.sum(c)", "# pie.rc('font', family=font_name) # plt.legend(pie[0], labelss) ## 범례 표시 plt.savefig('./static/images/pos_neg_ratio.png')", "2) * np.sin(np.pi / 180 * ((ang1 + ang2) /", "pie.rc('font', family=font_name) # plt.legend(pie[0], labelss) ## 범례 표시 plt.savefig('./static/images/pos_neg_ratio.png') #", "total = np.sum(c) ## 빈도수 총합 sum_pct = 0 ##", "/ 2) * np.sin(np.pi / 180 * ((ang1 + ang2)", "파이차트 출력 startangle=90, ## 시작점을 90도(degree)로 지정 counterclock=False, ## 시계", "총합 sum_pct = 0 ## 백분율 초기값 for i, l", "0.5) / 2) * np.cos(np.pi / 180 * ((ang1 +", "안됨!!! c = b['score'].value_counts().sort_index() ## 빈도 print(c) print(labelss) fig =", "= labelss, textprops={'fontsize': 22} ) total = np.sum(c) ## 빈도수", "pie = ax.pie(c, ## 파이차트 출력 startangle=90, ## 시작점을 90도(degree)로", "labelss = sorted(b['score'].unique())## 라벨설정함. 한글이 적용이 안됨!!! c = b['score'].value_counts().sort_index()", "sum_pct = 0 ## 백분율 초기값 for i, l in", "= ((r + 0.5) / 2) * np.sin(np.pi / 180", "설정 ax = fig.add_subplot() ## 프레임 생성 pie = ax.pie(c,", "fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name) def percent_graph2(movie_review) : b = movie_review labelss", "0 ## 백분율 초기값 for i, l in enumerate(labelss): ang1,", "백분율 누적값을 빼준다. ax.text(x, y, f'{100 - sum_pct:.2f}%', ha='center', va='center',size=22,color='white',", "len(labelss) - 1: sum_pct += float(f'{c[i] / total * 100:.2f}')", "sorted(b['score'].unique())## 라벨설정함. 한글이 적용이 안됨!!! c = b['score'].value_counts().sort_index() ## 빈도", "fig = plt.figure(figsize=(8,8)) ## 캔버스 생성 fig.set_facecolor('white') ## 캔버스 배경색을", "정중앙 y좌표 if i < len(labelss) - 1: sum_pct +=", "'./wordcloud_file/malgun.ttf' # For Windows font_name = fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name) def", "sum_pct:.2f}%', ha='center', va='center',size=22,color='white', weight='bold') # pie.rc('font', family=font_name) # plt.legend(pie[0], labelss)", "- 1: sum_pct += float(f'{c[i] / total * 100:.2f}') ##", "퍼센티지 출력 wedgeprops=dict(width=0.5), colors = ['yellowgreen', 'orange'], labels = labelss,", "초기값 for i, l in enumerate(labelss): ang1, ang2 = pie[0][i].theta1,", "## 백분율 초기값 for i, l in enumerate(labelss): ang1, ang2", "'{:.2f}%'.format(p), ## 퍼센티지 출력 wedgeprops=dict(width=0.5), colors = ['yellowgreen', 'orange'], labels", "총합을 100으로 맞추기위해 마지막 백분율은 100에서 백분율 누적값을 빼준다. ax.text(x,", "표시 else: ## 총합을 100으로 맞추기위해 마지막 백분율은 100에서 백분율", "= plt.figure(figsize=(8,8)) ## 캔버스 생성 fig.set_facecolor('white') ## 캔버스 배경색을 하얀색으로", "지정 counterclock=False, ## 시계 방향으로 그린다. # autopct=lambda p :", "y, f'{c[i] / total * 100:.2f}%', ha='center', va='center', size=22, color='white',", "빼준다. ax.text(x, y, f'{100 - sum_pct:.2f}%', ha='center', va='center',size=22,color='white', weight='bold') #", "각1, 각2 r = pie[0][i].r ## 원의 반지름 x =", "matplotlib.font_manager as fm import matplotlib.pyplot as plt import numpy as", "startangle=90, ## 시작점을 90도(degree)로 지정 counterclock=False, ## 시계 방향으로 그린다.", "weight='bold') # pie.rc('font', family=font_name) # plt.legend(pie[0], labelss) ## 범례 표시", "백분율 텍스트 표시 else: ## 총합을 100으로 맞추기위해 마지막 백분율은", "2) * np.cos(np.pi / 180 * ((ang1 + ang2) /", "/ total * 100:.2f}%', ha='center', va='center', size=22, color='white', weight='bold') ##", "i < len(labelss) - 1: sum_pct += float(f'{c[i] / total", "정중앙 x좌표 y = ((r + 0.5) / 2) *", "캔버스 배경색을 하얀색으로 설정 ax = fig.add_subplot() ## 프레임 생성", "2)) ## 정중앙 y좌표 if i < len(labelss) - 1:", "22} ) total = np.sum(c) ## 빈도수 총합 sum_pct =", "ang2 = pie[0][i].theta1, pie[0][i].theta2 ## 각1, 각2 r = pie[0][i].r", "va='center',size=22,color='white', weight='bold') # pie.rc('font', family=font_name) # plt.legend(pie[0], labelss) ## 범례", "+ 0.5) / 2) * np.sin(np.pi / 180 * ((ang1", "= sorted(b['score'].unique())## 라벨설정함. 한글이 적용이 안됨!!! c = b['score'].value_counts().sort_index() ##", "p : '{:.2f}%'.format(p), ## 퍼센티지 출력 wedgeprops=dict(width=0.5), colors = ['yellowgreen',", "* np.cos(np.pi / 180 * ((ang1 + ang2) / 2))", "백분율 초기값 for i, l in enumerate(labelss): ang1, ang2 =", "import numpy as np font_location = './wordcloud_file/malgun.ttf' # For Windows", "누적한다. ax.text(x, y, f'{c[i] / total * 100:.2f}%', ha='center', va='center',", "print(labelss) fig = plt.figure(figsize=(8,8)) ## 캔버스 생성 fig.set_facecolor('white') ## 캔버스", "ax.text(x, y, f'{100 - sum_pct:.2f}%', ha='center', va='center',size=22,color='white', weight='bold') # pie.rc('font',", "y, f'{100 - sum_pct:.2f}%', ha='center', va='center',size=22,color='white', weight='bold') # pie.rc('font', family=font_name)", "import matplotlib.pyplot as plt import numpy as np font_location =", "/ 2)) ## 정중앙 x좌표 y = ((r + 0.5)", "y = ((r + 0.5) / 2) * np.sin(np.pi /", "matplotlib.pyplot as plt import numpy as np font_location = './wordcloud_file/malgun.ttf'", "plt import numpy as np font_location = './wordcloud_file/malgun.ttf' # For", "캔버스 생성 fig.set_facecolor('white') ## 캔버스 배경색을 하얀색으로 설정 ax =", "= ((r + 0.5) / 2) * np.cos(np.pi / 180", "x = ((r + 0.5) / 2) * np.cos(np.pi /", ": '{:.2f}%'.format(p), ## 퍼센티지 출력 wedgeprops=dict(width=0.5), colors = ['yellowgreen', 'orange'],", "as plt import numpy as np font_location = './wordcloud_file/malgun.ttf' #", "r = pie[0][i].r ## 원의 반지름 x = ((r +", "ha='center', va='center',size=22,color='white', weight='bold') # pie.rc('font', family=font_name) # plt.legend(pie[0], labelss) ##", "2)) ## 정중앙 x좌표 y = ((r + 0.5) /", "100:.2f}%', ha='center', va='center', size=22, color='white', weight='bold') ## 백분율 텍스트 표시", "텍스트 표시 else: ## 총합을 100으로 맞추기위해 마지막 백분율은 100에서", "fm import matplotlib.pyplot as plt import numpy as np font_location", "= pie[0][i].r ## 원의 반지름 x = ((r + 0.5)", "= fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name) def percent_graph2(movie_review) : b = movie_review", "## 시작점을 90도(degree)로 지정 counterclock=False, ## 시계 방향으로 그린다. #", "100으로 맞추기위해 마지막 백분율은 100에서 백분율 누적값을 빼준다. ax.text(x, y,", "* ((ang1 + ang2) / 2)) ## 정중앙 x좌표 y", "if i < len(labelss) - 1: sum_pct += float(f'{c[i] /", "+ ang2) / 2)) ## 정중앙 x좌표 y = ((r", "c = b['score'].value_counts().sort_index() ## 빈도 print(c) print(labelss) fig = plt.figure(figsize=(8,8))", "< len(labelss) - 1: sum_pct += float(f'{c[i] / total *", "= ax.pie(c, ## 파이차트 출력 startangle=90, ## 시작점을 90도(degree)로 지정", "movie_review labelss = sorted(b['score'].unique())## 라벨설정함. 한글이 적용이 안됨!!! c =", "percent_graph2(movie_review) : b = movie_review labelss = sorted(b['score'].unique())## 라벨설정함. 한글이", "ang1, ang2 = pie[0][i].theta1, pie[0][i].theta2 ## 각1, 각2 r =", "np.sin(np.pi / 180 * ((ang1 + ang2) / 2)) ##", "생성 pie = ax.pie(c, ## 파이차트 출력 startangle=90, ## 시작점을", "* np.sin(np.pi / 180 * ((ang1 + ang2) / 2))", "180 * ((ang1 + ang2) / 2)) ## 정중앙 y좌표", "* ((ang1 + ang2) / 2)) ## 정중앙 y좌표 if", "## 캔버스 생성 fig.set_facecolor('white') ## 캔버스 배경색을 하얀색으로 설정 ax", "counterclock=False, ## 시계 방향으로 그린다. # autopct=lambda p : '{:.2f}%'.format(p),", "0.5) / 2) * np.sin(np.pi / 180 * ((ang1 +", "total * 100:.2f}') ## 백분율을 누적한다. ax.text(x, y, f'{c[i] /", "np.sum(c) ## 빈도수 총합 sum_pct = 0 ## 백분율 초기값", "font_location = './wordcloud_file/malgun.ttf' # For Windows font_name = fm.FontProperties(fname=font_location).get_name() plt.rc('font',", "size=22, color='white', weight='bold') ## 백분율 텍스트 표시 else: ## 총합을", "## 퍼센티지 출력 wedgeprops=dict(width=0.5), colors = ['yellowgreen', 'orange'], labels =", "= './wordcloud_file/malgun.ttf' # For Windows font_name = fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name)", "= fig.add_subplot() ## 프레임 생성 pie = ax.pie(c, ## 파이차트", "((r + 0.5) / 2) * np.sin(np.pi / 180 *", "## 빈도 print(c) print(labelss) fig = plt.figure(figsize=(8,8)) ## 캔버스 생성", "## 시계 방향으로 그린다. # autopct=lambda p : '{:.2f}%'.format(p), ##", "wedgeprops=dict(width=0.5), colors = ['yellowgreen', 'orange'], labels = labelss, textprops={'fontsize': 22}", "print(c) print(labelss) fig = plt.figure(figsize=(8,8)) ## 캔버스 생성 fig.set_facecolor('white') ##", "= ['yellowgreen', 'orange'], labels = labelss, textprops={'fontsize': 22} ) total", "# For Windows font_name = fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name) def percent_graph2(movie_review)", "1: sum_pct += float(f'{c[i] / total * 100:.2f}') ## 백분율을", "ax.pie(c, ## 파이차트 출력 startangle=90, ## 시작점을 90도(degree)로 지정 counterclock=False,", "출력 startangle=90, ## 시작점을 90도(degree)로 지정 counterclock=False, ## 시계 방향으로", "## 프레임 생성 pie = ax.pie(c, ## 파이차트 출력 startangle=90,", "= 0 ## 백분율 초기값 for i, l in enumerate(labelss):", "100:.2f}') ## 백분율을 누적한다. ax.text(x, y, f'{c[i] / total *", "180 * ((ang1 + ang2) / 2)) ## 정중앙 x좌표", "+= float(f'{c[i] / total * 100:.2f}') ## 백분율을 누적한다. ax.text(x,", "빈도 print(c) print(labelss) fig = plt.figure(figsize=(8,8)) ## 캔버스 생성 fig.set_facecolor('white')", "pie[0][i].theta1, pie[0][i].theta2 ## 각1, 각2 r = pie[0][i].r ## 원의", "## 원의 반지름 x = ((r + 0.5) / 2)", "pie[0][i].r ## 원의 반지름 x = ((r + 0.5) /", "labelss, textprops={'fontsize': 22} ) total = np.sum(c) ## 빈도수 총합", "라벨설정함. 한글이 적용이 안됨!!! c = b['score'].value_counts().sort_index() ## 빈도 print(c)", "i, l in enumerate(labelss): ang1, ang2 = pie[0][i].theta1, pie[0][i].theta2 ##", "## 빈도수 총합 sum_pct = 0 ## 백분율 초기값 for", "for i, l in enumerate(labelss): ang1, ang2 = pie[0][i].theta1, pie[0][i].theta2", "각2 r = pie[0][i].r ## 원의 반지름 x = ((r", "누적값을 빼준다. ax.text(x, y, f'{100 - sum_pct:.2f}%', ha='center', va='center',size=22,color='white', weight='bold')", "90도(degree)로 지정 counterclock=False, ## 시계 방향으로 그린다. # autopct=lambda p", "ang2) / 2)) ## 정중앙 x좌표 y = ((r +", "배경색을 하얀색으로 설정 ax = fig.add_subplot() ## 프레임 생성 pie", "+ 0.5) / 2) * np.cos(np.pi / 180 * ((ang1", "백분율을 누적한다. ax.text(x, y, f'{c[i] / total * 100:.2f}%', ha='center',", "((ang1 + ang2) / 2)) ## 정중앙 y좌표 if i", ") total = np.sum(c) ## 빈도수 총합 sum_pct = 0", "plt.figure(figsize=(8,8)) ## 캔버스 생성 fig.set_facecolor('white') ## 캔버스 배경색을 하얀색으로 설정", "출력 wedgeprops=dict(width=0.5), colors = ['yellowgreen', 'orange'], labels = labelss, textprops={'fontsize':", "((ang1 + ang2) / 2)) ## 정중앙 x좌표 y =", "시계 방향으로 그린다. # autopct=lambda p : '{:.2f}%'.format(p), ## 퍼센티지", "/ 2)) ## 정중앙 y좌표 if i < len(labelss) -", "sum_pct += float(f'{c[i] / total * 100:.2f}') ## 백분율을 누적한다.", "맞추기위해 마지막 백분율은 100에서 백분율 누적값을 빼준다. ax.text(x, y, f'{100", "b = movie_review labelss = sorted(b['score'].unique())## 라벨설정함. 한글이 적용이 안됨!!!", "100에서 백분율 누적값을 빼준다. ax.text(x, y, f'{100 - sum_pct:.2f}%', ha='center',", "= pie[0][i].theta1, pie[0][i].theta2 ## 각1, 각2 r = pie[0][i].r ##", "f'{c[i] / total * 100:.2f}%', ha='center', va='center', size=22, color='white', weight='bold')", "= b['score'].value_counts().sort_index() ## 빈도 print(c) print(labelss) fig = plt.figure(figsize=(8,8)) ##", "# autopct=lambda p : '{:.2f}%'.format(p), ## 퍼센티지 출력 wedgeprops=dict(width=0.5), colors", ": b = movie_review labelss = sorted(b['score'].unique())## 라벨설정함. 한글이 적용이", "Windows font_name = fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name) def percent_graph2(movie_review) : b", "ha='center', va='center', size=22, color='white', weight='bold') ## 백분율 텍스트 표시 else:", "* 100:.2f}%', ha='center', va='center', size=22, color='white', weight='bold') ## 백분율 텍스트", "원의 반지름 x = ((r + 0.5) / 2) *", "= np.sum(c) ## 빈도수 총합 sum_pct = 0 ## 백분율", "## 파이차트 출력 startangle=90, ## 시작점을 90도(degree)로 지정 counterclock=False, ##", "For Windows font_name = fm.FontProperties(fname=font_location).get_name() plt.rc('font', family=font_name) def percent_graph2(movie_review) :", "x좌표 y = ((r + 0.5) / 2) * np.sin(np.pi", "방향으로 그린다. # autopct=lambda p : '{:.2f}%'.format(p), ## 퍼센티지 출력", "float(f'{c[i] / total * 100:.2f}') ## 백분율을 누적한다. ax.text(x, y," ]
[ "<reponame>kbilak/City-portal from django.shortcuts import render from django.views.generic import TemplateView def", "import render from django.views.generic import TemplateView def index(request): return render(request,", "render from django.views.generic import TemplateView def index(request): return render(request, 'index.html')", "from django.shortcuts import render from django.views.generic import TemplateView def index(request):", "django.shortcuts import render from django.views.generic import TemplateView def index(request): return" ]
[ ". models import * from django.views import generic @login_required(login_url='/accounts/login/') def", "generic @login_required(login_url='/accounts/login/') def home(request): mylocs = Myloc.objects.all() return render(request, 'home.html',{\"mylocs\":mylocs,})", "* from django.shortcuts import redirect,get_object_or_404 from django.contrib.auth.decorators import login_required from", "else: form = MylocForm() return render(request, 'addmy_area.html', {\"form\": form}) def", "= current_user image.save() return redirect('home') else: form = MylocForm() return", "request.GET.get(\"project_name\") searched_project = Myloc.search_by_location(search_term) message = f\"{search_term}\" return render(request, \"search.html\",{\"message\":message,\"project\":", "else: form = NewProfileForm() return render(request, 'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/') def", "post.save() return redirect('detail', myloc_id=myloc.id) else: post_form = NewPostForm() return render(request,", "render from .forms import * from django.shortcuts import redirect,get_object_or_404 from", "my_my_area = Myloc.objects.filter(user = current_user) my_profile = Profile.objects.filter(user = current_user).first", "NewPostForm(request.POST, request.FILES) if post_form.is_valid(): post = post_form.save(commit=False) post.user = current_user", ".forms import * from django.shortcuts import redirect,get_object_or_404 from django.contrib.auth.decorators import", "'POST': form = NewProfileForm(request.POST, request.FILES) if form.is_valid(): caption = form.save(commit=False)", "== 'POST': form = MylocForm(request.POST, request.FILES) if form.is_valid(): image =", "def home(request): mylocs = Myloc.objects.all() return render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def", "= NewPostForm(request.POST, request.FILES) if post_form.is_valid(): post = post_form.save(commit=False) post.user =", "= form.save(commit=False) caption.user = current_user caption.save() return redirect('myprofile') else: form", "'new_post.html', {\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def search_project(request): if 'project_name' in request.GET", "= Myloc.search_by_location(search_term) message = f\"{search_term}\" return render(request, \"search.html\",{\"message\":message,\"project\": searched_project}) else:", "from django.shortcuts import render from .forms import * from django.shortcuts", "current_user) my_profile = Profile.objects.filter(user = current_user).first return render(request, 'profile.html', {\"my_my_areas\":my_my_areas,", "current_user).first return render(request, 'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def addmy_area(request): current_user", "= get_object_or_404(Myloc,pk=pk) if request.method == 'POST': activity_form = NewActivityForm(request.POST, request.FILES)", "= NewActivityForm(request.POST, request.FILES) if activity_form.is_valid(): activity = activity_form.save(commit=False) activity.user =", "NewPostForm() return render(request, 'new_post.html', {\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def search_project(request): if", "= Profile.objects.filter(user = current_user).first return render(request, 'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/')", "else: post_form = NewPostForm() return render(request, 'new_post.html', {\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/')", "request.user if request.method == 'POST': form = MylocForm(request.POST, request.FILES) if", "current_user activity.myloc=myloc activity.save() return redirect('detail', myloc_id=myloc.id) else: activity_form = NewActivityForm()", "if form.is_valid(): caption = form.save(commit=False) caption.user = current_user caption.save() return", "request.user my_my_area = Myloc.objects.filter(user = current_user) my_profile = Profile.objects.filter(user =", "current_user = request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method == 'POST':", "request.method == 'POST': form = NewProfileForm(request.POST, request.FILES) if form.is_valid(): caption", "MylocForm(request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False) image.user = current_user", "django.contrib.auth.decorators import login_required from . models import * from django.views", "NewActivityForm(request.POST, request.FILES) if activity_form.is_valid(): activity = activity_form.save(commit=False) activity.user = current_user", "activity = activity_form.save(commit=False) activity.user = current_user activity.myloc=myloc activity.save() return redirect('detail',", "form = MylocForm(request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False) image.user", "caption.save() return redirect('myprofile') else: form = NewProfileForm() return render(request, 'edit.html',", "\"search.html\",{\"message\":message,\"project\": searched_project}) else: message = \"No search history\" return render(request,", "def new_post(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method", "@login_required(login_url='/accounts/login/') def addmy_area(request): current_user = request.user if request.method == 'POST':", "render(request, 'addmy_area.html', {\"form\": form}) def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return", "request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method == 'POST': post_form =", "* from django.views import generic @login_required(login_url='/accounts/login/') def home(request): mylocs =", "activity_form.save(commit=False) activity.user = current_user activity.myloc=myloc activity.save() return redirect('detail', myloc_id=myloc.id) else:", "@login_required(login_url='accounts/login/') def my_profile(request): current_user = request.user my_my_area = Myloc.objects.filter(user =", "form.is_valid(): caption = form.save(commit=False) caption.user = current_user caption.save() return redirect('myprofile')", "redirect,get_object_or_404 from django.contrib.auth.decorators import login_required from . models import *", "request.FILES) if form.is_valid(): image = form.save(commit=False) image.user = current_user image.save()", "post.user = current_user post.myloc=myloc post.save() return redirect('detail', myloc_id=myloc.id) else: post_form", "activity_form = NewActivityForm() return render(request, 'new_activity.html', {\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def", "form.save(commit=False) image.user = current_user image.save() return redirect('home') else: form =", "= current_user activity.myloc=myloc activity.save() return redirect('detail', myloc_id=myloc.id) else: activity_form =", "return redirect('detail', myloc_id=myloc.id) else: activity_form = NewActivityForm() return render(request, 'new_activity.html',", "redirect('myprofile') else: form = NewProfileForm() return render(request, 'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/')", "== 'POST': form = NewProfileForm(request.POST, request.FILES) if form.is_valid(): caption =", "search_project(request): if 'project_name' in request.GET and request.GET[\"project_name\"]: search_term = request.GET.get(\"project_name\")", "request.method == 'POST': form = MylocForm(request.POST, request.FILES) if form.is_valid(): image", "import login_required from . models import * from django.views import", "redirect('home') else: form = MylocForm() return render(request, 'addmy_area.html', {\"form\": form})", "my_profile = Profile.objects.filter(user = current_user).first return render(request, 'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile})", "django.shortcuts import redirect,get_object_or_404 from django.contrib.auth.decorators import login_required from . models", "Profile.objects.filter(user = current_user).first return render(request, 'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def", "myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def new_activity(request,pk): current_user = request.user myloc", "import render from .forms import * from django.shortcuts import redirect,get_object_or_404", "{\"form\":form}) @login_required(login_url='accounts/login/') def my_profile(request): current_user = request.user my_my_area = Myloc.objects.filter(user", "request.FILES) if activity_form.is_valid(): activity = activity_form.save(commit=False) activity.user = current_user activity.myloc=myloc", "if request.method == 'POST': form = NewProfileForm(request.POST, request.FILES) if form.is_valid():", "'POST': form = MylocForm(request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False)", "render(request, 'new_post.html', {\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def search_project(request): if 'project_name' in", "= NewProfileForm(request.POST, request.FILES) if form.is_valid(): caption = form.save(commit=False) caption.user =", "'POST': post_form = NewPostForm(request.POST, request.FILES) if post_form.is_valid(): post = post_form.save(commit=False)", "import * from django.shortcuts import redirect,get_object_or_404 from django.contrib.auth.decorators import login_required", "post = post_form.save(commit=False) post.user = current_user post.myloc=myloc post.save() return redirect('detail',", "= MylocForm(request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False) image.user =", "and request.GET[\"project_name\"]: search_term = request.GET.get(\"project_name\") searched_project = Myloc.search_by_location(search_term) message =", "= current_user.id) if request.method == 'POST': form = NewProfileForm(request.POST, request.FILES)", "= current_user) my_profile = Profile.objects.filter(user = current_user).first return render(request, 'profile.html',", "models import * from django.views import generic @login_required(login_url='/accounts/login/') def home(request):", "request.method == 'POST': post_form = NewPostForm(request.POST, request.FILES) if post_form.is_valid(): post", "{\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def new_post(request,pk): current_user = request.user myloc =", "django.views import generic @login_required(login_url='/accounts/login/') def home(request): mylocs = Myloc.objects.all() return", "= request.user if request.method == 'POST': form = MylocForm(request.POST, request.FILES)", "current_user image.save() return redirect('home') else: form = MylocForm() return render(request,", "if request.method == 'POST': form = MylocForm(request.POST, request.FILES) if form.is_valid():", "return render(request, 'new_activity.html', {\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def new_post(request,pk): current_user =", "'new_activity.html', {\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def new_post(request,pk): current_user = request.user myloc", "from .forms import * from django.shortcuts import redirect,get_object_or_404 from django.contrib.auth.decorators", "NewProfileForm() return render(request, 'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/') def my_profile(request): current_user =", "return render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def add_profile(request): current_user = request.user profile", "current_user caption.save() return redirect('myprofile') else: form = NewProfileForm() return render(request,", "image = form.save(commit=False) image.user = current_user image.save() return redirect('home') else:", "'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def add_profile(request): current_user = request.user profile = Profile.objects.filter(id", "current_user = request.user if request.method == 'POST': form = MylocForm(request.POST,", "from django.shortcuts import redirect,get_object_or_404 from django.contrib.auth.decorators import login_required from .", "image.save() return redirect('home') else: form = MylocForm() return render(request, 'addmy_area.html',", "== 'POST': post_form = NewPostForm(request.POST, request.FILES) if post_form.is_valid(): post =", "if 'project_name' in request.GET and request.GET[\"project_name\"]: search_term = request.GET.get(\"project_name\") searched_project", "= current_user caption.save() return redirect('myprofile') else: form = NewProfileForm() return", "'addmy_area.html', {\"form\": form}) def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts})", "post_form.save(commit=False) post.user = current_user post.myloc=myloc post.save() return redirect('detail', myloc_id=myloc.id) else:", "login_required from . models import * from django.views import generic", "def add_profile(request): current_user = request.user profile = Profile.objects.filter(id = current_user.id)", "current_user = request.user profile = Profile.objects.filter(id = current_user.id) if request.method", "'project_name' in request.GET and request.GET[\"project_name\"]: search_term = request.GET.get(\"project_name\") searched_project =", "return render(request, \"search.html\",{\"message\":message,\"project\": searched_project}) else: message = \"No search history\"", "= NewProfileForm() return render(request, 'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/') def my_profile(request): current_user", "form = NewProfileForm() return render(request, 'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/') def my_profile(request):", "= NewPostForm() return render(request, 'new_post.html', {\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def search_project(request):", "home(request): mylocs = Myloc.objects.all() return render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def add_profile(request):", "return redirect('detail', myloc_id=myloc.id) else: post_form = NewPostForm() return render(request, 'new_post.html',", "from django.views import generic @login_required(login_url='/accounts/login/') def home(request): mylocs = Myloc.objects.all()", "post_form = NewPostForm() return render(request, 'new_post.html', {\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def", "if post_form.is_valid(): post = post_form.save(commit=False) post.user = current_user post.myloc=myloc post.save()", "message = f\"{search_term}\" return render(request, \"search.html\",{\"message\":message,\"project\": searched_project}) else: message =", "import redirect,get_object_or_404 from django.contrib.auth.decorators import login_required from . models import", "myloc = get_object_or_404(Myloc,pk=pk) if request.method == 'POST': post_form = NewPostForm(request.POST,", "Myloc.search_by_location(search_term) message = f\"{search_term}\" return render(request, \"search.html\",{\"message\":message,\"project\": searched_project}) else: message", "redirect('detail', myloc_id=myloc.id) else: post_form = NewPostForm() return render(request, 'new_post.html', {\"form\":", "profile = Profile.objects.filter(id = current_user.id) if request.method == 'POST': form", "= MylocForm() return render(request, 'addmy_area.html', {\"form\": form}) def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id)", "\"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def addmy_area(request): current_user = request.user if request.method ==", "get_object_or_404(Myloc,pk=pk) if request.method == 'POST': activity_form = NewActivityForm(request.POST, request.FILES) if", "post_form.is_valid(): post = post_form.save(commit=False) post.user = current_user post.myloc=myloc post.save() return", "{\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def addmy_area(request): current_user = request.user if request.method", "request.GET[\"project_name\"]: search_term = request.GET.get(\"project_name\") searched_project = Myloc.search_by_location(search_term) message = f\"{search_term}\"", "myloc_id=myloc.id) else: activity_form = NewActivityForm() return render(request, 'new_activity.html', {\"form\": activity_form,'myloc':myloc})", "= Myloc.objects.filter(user = current_user) my_profile = Profile.objects.filter(user = current_user).first return", "f\"{search_term}\" return render(request, \"search.html\",{\"message\":message,\"project\": searched_project}) else: message = \"No search", "redirect('detail', myloc_id=myloc.id) else: activity_form = NewActivityForm() return render(request, 'new_activity.html', {\"form\":", "def search_project(request): if 'project_name' in request.GET and request.GET[\"project_name\"]: search_term =", "search_term = request.GET.get(\"project_name\") searched_project = Myloc.search_by_location(search_term) message = f\"{search_term}\" return", "posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def new_activity(request,pk): current_user = request.user", "= activity_form.save(commit=False) activity.user = current_user activity.myloc=myloc activity.save() return redirect('detail', myloc_id=myloc.id)", "Myloc.objects.filter(user = current_user) my_profile = Profile.objects.filter(user = current_user).first return render(request,", "def new_activity(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method", "request.method == 'POST': activity_form = NewActivityForm(request.POST, request.FILES) if activity_form.is_valid(): activity", "if form.is_valid(): image = form.save(commit=False) image.user = current_user image.save() return", "myloc_id=myloc.id) else: post_form = NewPostForm() return render(request, 'new_post.html', {\"form\": post_form,'myloc':myloc})", "NewActivityForm() return render(request, 'new_activity.html', {\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def new_post(request,pk): current_user", "activity.user = current_user activity.myloc=myloc activity.save() return redirect('detail', myloc_id=myloc.id) else: activity_form", "def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def new_activity(request,pk):", "caption = form.save(commit=False) caption.user = current_user caption.save() return redirect('myprofile') else:", "add_profile(request): current_user = request.user profile = Profile.objects.filter(id = current_user.id) if", "= Profile.objects.filter(id = current_user.id) if request.method == 'POST': form =", "myloc = get_object_or_404(Myloc,pk=pk) if request.method == 'POST': activity_form = NewActivityForm(request.POST,", "activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def new_activity(request,pk): current_user =", "from django.contrib.auth.decorators import login_required from . models import * from", "== 'POST': activity_form = NewActivityForm(request.POST, request.FILES) if activity_form.is_valid(): activity =", "= NewActivityForm() return render(request, 'new_activity.html', {\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def new_post(request,pk):", "else: activity_form = NewActivityForm() return render(request, 'new_activity.html', {\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\")", "{\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def search_project(request): if 'project_name' in request.GET and", "render(request, 'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def addmy_area(request): current_user = request.user", "form.is_valid(): image = form.save(commit=False) image.user = current_user image.save() return redirect('home')", "return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def new_activity(request,pk): current_user = request.user myloc =", "NewProfileForm(request.POST, request.FILES) if form.is_valid(): caption = form.save(commit=False) caption.user = current_user", "form = MylocForm() return render(request, 'addmy_area.html', {\"form\": form}) def myloc_details(request,myloc_id):", "render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def new_activity(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk)", "if request.method == 'POST': activity_form = NewActivityForm(request.POST, request.FILES) if activity_form.is_valid():", "mylocs = Myloc.objects.all() return render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def add_profile(request): current_user", "= current_user post.myloc=myloc post.save() return redirect('detail', myloc_id=myloc.id) else: post_form =", "= request.GET.get(\"project_name\") searched_project = Myloc.search_by_location(search_term) message = f\"{search_term}\" return render(request,", "= request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method == 'POST': activity_form", "def my_profile(request): current_user = request.user my_my_area = Myloc.objects.filter(user = current_user)", "'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def addmy_area(request): current_user = request.user if", "addmy_area(request): current_user = request.user if request.method == 'POST': form =", "request.user profile = Profile.objects.filter(id = current_user.id) if request.method == 'POST':", "activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def new_post(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk)", "@login_required(login_url=\"/accounts/login/\") def new_post(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk) if", "get_object_or_404(Myloc,pk=pk) if request.method == 'POST': post_form = NewPostForm(request.POST, request.FILES) if", "current_user post.myloc=myloc post.save() return redirect('detail', myloc_id=myloc.id) else: post_form = NewPostForm()", "request.GET and request.GET[\"project_name\"]: search_term = request.GET.get(\"project_name\") searched_project = Myloc.search_by_location(search_term) message", "return render(request, 'new_post.html', {\"form\": post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def search_project(request): if 'project_name'", "@login_required(login_url='accounts/login/') def add_profile(request): current_user = request.user profile = Profile.objects.filter(id =", "searched_project}) else: message = \"No search history\" return render(request, 'search.html',{\"message\":message})", "{\"form\": form}) def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\")", "activity_form.is_valid(): activity = activity_form.save(commit=False) activity.user = current_user activity.myloc=myloc activity.save() return", "return redirect('home') else: form = MylocForm() return render(request, 'addmy_area.html', {\"form\":", "new_activity(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method ==", "import generic @login_required(login_url='/accounts/login/') def home(request): mylocs = Myloc.objects.all() return render(request,", "Profile.objects.filter(id = current_user.id) if request.method == 'POST': form = NewProfileForm(request.POST,", "return render(request, 'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/') def my_profile(request): current_user = request.user", "return render(request, 'addmy_area.html', {\"form\": form}) def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id)", "activity.save() return redirect('detail', myloc_id=myloc.id) else: activity_form = NewActivityForm() return render(request,", "render(request, 'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/') def my_profile(request): current_user = request.user my_my_area", "render(request, 'new_activity.html', {\"form\": activity_form,'myloc':myloc}) @login_required(login_url=\"/accounts/login/\") def new_post(request,pk): current_user = request.user", "@login_required(login_url='/accounts/login/') def search_project(request): if 'project_name' in request.GET and request.GET[\"project_name\"]: search_term", "render(request, \"search.html\",{\"message\":message,\"project\": searched_project}) else: message = \"No search history\" return", "return redirect('myprofile') else: form = NewProfileForm() return render(request, 'edit.html', {\"form\":form})", "form = NewProfileForm(request.POST, request.FILES) if form.is_valid(): caption = form.save(commit=False) caption.user", "= Myloc.objects.all() return render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def add_profile(request): current_user =", "if activity_form.is_valid(): activity = activity_form.save(commit=False) activity.user = current_user activity.myloc=myloc activity.save()", "= form.save(commit=False) image.user = current_user image.save() return redirect('home') else: form", "django.shortcuts import render from .forms import * from django.shortcuts import", "request.FILES) if form.is_valid(): caption = form.save(commit=False) caption.user = current_user caption.save()", "request.FILES) if post_form.is_valid(): post = post_form.save(commit=False) post.user = current_user post.myloc=myloc", "from . models import * from django.views import generic @login_required(login_url='/accounts/login/')", "form.save(commit=False) caption.user = current_user caption.save() return redirect('myprofile') else: form =", "in request.GET and request.GET[\"project_name\"]: search_term = request.GET.get(\"project_name\") searched_project = Myloc.search_by_location(search_term)", "current_user.id) if request.method == 'POST': form = NewProfileForm(request.POST, request.FILES) if", "new_post(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method ==", "post.myloc=myloc post.save() return redirect('detail', myloc_id=myloc.id) else: post_form = NewPostForm() return", "form}) def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def", "= f\"{search_term}\" return render(request, \"search.html\",{\"message\":message,\"project\": searched_project}) else: message = \"No", "myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id) myloc=Myloc.objects.get(pk=myloc_id) return render(request,'details.html',{'myloc':myloc,'activities':activities,'posts':posts}) @login_required(login_url=\"/accounts/login/\") def new_activity(request,pk): current_user", "= request.user profile = Profile.objects.filter(id = current_user.id) if request.method ==", "MylocForm() return render(request, 'addmy_area.html', {\"form\": form}) def myloc_details(request,myloc_id): activities=Activity.objects.filter(myloc=myloc_id) posts=Post.objects.filter(myloc=myloc_id)", "Myloc.objects.all() return render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def add_profile(request): current_user = request.user", "if request.method == 'POST': post_form = NewPostForm(request.POST, request.FILES) if post_form.is_valid():", "= request.user my_my_area = Myloc.objects.filter(user = current_user) my_profile = Profile.objects.filter(user", "post_form = NewPostForm(request.POST, request.FILES) if post_form.is_valid(): post = post_form.save(commit=False) post.user", "= request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method == 'POST': post_form", "@login_required(login_url=\"/accounts/login/\") def new_activity(request,pk): current_user = request.user myloc = get_object_or_404(Myloc,pk=pk) if", "def addmy_area(request): current_user = request.user if request.method == 'POST': form", "request.user myloc = get_object_or_404(Myloc,pk=pk) if request.method == 'POST': activity_form =", "= get_object_or_404(Myloc,pk=pk) if request.method == 'POST': post_form = NewPostForm(request.POST, request.FILES)", "'edit.html', {\"form\":form}) @login_required(login_url='accounts/login/') def my_profile(request): current_user = request.user my_my_area =", "'POST': activity_form = NewActivityForm(request.POST, request.FILES) if activity_form.is_valid(): activity = activity_form.save(commit=False)", "return render(request, 'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def addmy_area(request): current_user =", "activity_form = NewActivityForm(request.POST, request.FILES) if activity_form.is_valid(): activity = activity_form.save(commit=False) activity.user", "searched_project = Myloc.search_by_location(search_term) message = f\"{search_term}\" return render(request, \"search.html\",{\"message\":message,\"project\": searched_project})", "caption.user = current_user caption.save() return redirect('myprofile') else: form = NewProfileForm()", "current_user = request.user my_my_area = Myloc.objects.filter(user = current_user) my_profile =", "import * from django.views import generic @login_required(login_url='/accounts/login/') def home(request): mylocs", "activity.myloc=myloc activity.save() return redirect('detail', myloc_id=myloc.id) else: activity_form = NewActivityForm() return", "= post_form.save(commit=False) post.user = current_user post.myloc=myloc post.save() return redirect('detail', myloc_id=myloc.id)", "render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/') def add_profile(request): current_user = request.user profile =", "@login_required(login_url='/accounts/login/') def home(request): mylocs = Myloc.objects.all() return render(request, 'home.html',{\"mylocs\":mylocs,}) @login_required(login_url='accounts/login/')", "= current_user).first return render(request, 'profile.html', {\"my_my_areas\":my_my_areas, \"my_profile\":my_profile}) @login_required(login_url='/accounts/login/') def addmy_area(request):", "image.user = current_user image.save() return redirect('home') else: form = MylocForm()", "post_form,'myloc':myloc}) @login_required(login_url='/accounts/login/') def search_project(request): if 'project_name' in request.GET and request.GET[\"project_name\"]:", "my_profile(request): current_user = request.user my_my_area = Myloc.objects.filter(user = current_user) my_profile" ]
[ "part1, part2 if __name__ == \"__main__\": # trying out the", "Module \"\"\" from day01 import parse_input, part1, part2 if __name__", "if __name__ == \"__main__\": # trying out the new walrus[:=]", "part2 if __name__ == \"__main__\": # trying out the new", "import parse_input, part1, part2 if __name__ == \"__main__\": # trying", "walrus[:=] oprtr in python if (part := int(input(\"Enter Part: \")))", "Main Module \"\"\" from day01 import parse_input, part1, part2 if", "# trying out the new walrus[:=] oprtr in python if", "python if (part := int(input(\"Enter Part: \"))) == 1: print(part1(parse_input(\"input.txt\")))", "__name__ == \"__main__\": # trying out the new walrus[:=] oprtr", "parse_input, part1, part2 if __name__ == \"__main__\": # trying out", "\"))) == 1: print(part1(parse_input(\"input.txt\"))) elif part == 2: print(part2(parse_input(\"input.txt\"))) else:", "\"\"\" Day 1 Main Module \"\"\" from day01 import parse_input,", "== \"__main__\": # trying out the new walrus[:=] oprtr in", "in python if (part := int(input(\"Enter Part: \"))) == 1:", "out the new walrus[:=] oprtr in python if (part :=", "new walrus[:=] oprtr in python if (part := int(input(\"Enter Part:", "day01 import parse_input, part1, part2 if __name__ == \"__main__\": #", "if (part := int(input(\"Enter Part: \"))) == 1: print(part1(parse_input(\"input.txt\"))) elif", "Day 1 Main Module \"\"\" from day01 import parse_input, part1,", "Part: \"))) == 1: print(part1(parse_input(\"input.txt\"))) elif part == 2: print(part2(parse_input(\"input.txt\")))", "from day01 import parse_input, part1, part2 if __name__ == \"__main__\":", "the new walrus[:=] oprtr in python if (part := int(input(\"Enter", "(part := int(input(\"Enter Part: \"))) == 1: print(part1(parse_input(\"input.txt\"))) elif part", "trying out the new walrus[:=] oprtr in python if (part", "== 1: print(part1(parse_input(\"input.txt\"))) elif part == 2: print(part2(parse_input(\"input.txt\"))) else: print(\"Wrong", "oprtr in python if (part := int(input(\"Enter Part: \"))) ==", "1 Main Module \"\"\" from day01 import parse_input, part1, part2", "1: print(part1(parse_input(\"input.txt\"))) elif part == 2: print(part2(parse_input(\"input.txt\"))) else: print(\"Wrong choice", ":= int(input(\"Enter Part: \"))) == 1: print(part1(parse_input(\"input.txt\"))) elif part ==", "\"\"\" from day01 import parse_input, part1, part2 if __name__ ==", "\"__main__\": # trying out the new walrus[:=] oprtr in python", "print(part1(parse_input(\"input.txt\"))) elif part == 2: print(part2(parse_input(\"input.txt\"))) else: print(\"Wrong choice [1|2]\")", "int(input(\"Enter Part: \"))) == 1: print(part1(parse_input(\"input.txt\"))) elif part == 2:" ]
[ "STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION", "= True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/", "http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000',", "- unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING:", "'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization #", "['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites',", "# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key", "] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',", "the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #", "ROOT_URLCONF = 'quiz_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':", "os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings -", "os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on", "paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =", "AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE =", "https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID = 1 import os import dj_database_url #", "# 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),", "validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },", "1 import os import dj_database_url # Build paths inside the", "STATIC_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL", "dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR,", "like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development", "}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]", "] WSGI_APPLICATION = 'quiz_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES", "= \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL =", "project. Generated by 'django-admin startproject' using Django 2.1.2. For more", "GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\")", "}, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {", "For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the", "= 'quiz_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = {", "inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))", "{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE", "WSGI_APPLICATION = 'quiz_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES =", "WARNING: keep the secret key used in production secret! SECRET_KEY", "'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'quiz', 'multichoice',", "production! DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application", "Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' # STATIC_ROOT = 'staticfiles'", "'staticfiles' STATICFILES_DIRS= ( os.path.join(BASE_DIR, \"static\"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media')", "settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID = 1", "'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'quiz_app.wsgi.application' #", "'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)", "STATIC_ROOT = 'staticfiles' STATICFILES_DIRS= ( os.path.join(BASE_DIR, \"static\"), ) MEDIA_ROOT =", "'/media/' DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS = { #", "this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings", "'essay', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',", "'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF =", "run with debug turned on in production! DEBUG = os.environ.get('DEBUG',", "startproject' using Django 2.1.2. For more information on this file,", "'quiz_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS':", "'UTC' USE_I18N = True USE_L10N = True USE_TZ = True", "MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DATABASES = {'default':", "production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run", "= 'media' MEDIA_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE =", "= 'UTC' USE_I18N = True USE_L10N = True USE_TZ =", "'storages', 'quiz', 'multichoice', 'true_false', 'essay', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware',", "definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',", "see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID = 1 import os import dj_database_url", "'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE =", "2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For", "import os import dj_database_url # Build paths inside the project", "# https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { # 'default': { #", "LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N", "= '/media/' DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS = {", "BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for", "'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), #", "os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST = 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION", "secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with", "'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'quiz_app.urls' TEMPLATES =", "{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], },", "= [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },", "more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full", "# Build paths inside the project like this: os.path.join(BASE_DIR, ...)", "'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',", "'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'quiz_app.wsgi.application'", "used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING:", "using Django 2.1.2. For more information on this file, see", "'quiz_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { #", "see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their", "[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {", "os.path.join(BASE_DIR, 'db.sqlite3'), # } # } # Password validation #", "= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production", "'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },", "# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL =", "https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' # STATIC_ROOT = 'staticfiles' STATICFILES_DIRS= (", "\"\"\" SITE_ID = 1 import os import dj_database_url # Build", "production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret", "MEDIA_URL = '/media/' DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS =", "# Quick-start development settings - unsuitable for production # See", "}, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE", "this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings", "see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control':", "AWS_S3_HOST = 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION =", "with debug turned on in production! DEBUG = os.environ.get('DEBUG', False)", "os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production #", "{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':", "in production! DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] #", "= '/static/' # STATIC_ROOT = 'staticfiles' STATICFILES_DIRS= ( os.path.join(BASE_DIR, \"static\"),", "= os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST = 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME", "values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID = 1 import os import", "'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'quiz', 'multichoice', 'true_false', 'essay', ] MIDDLEWARE_CLASSES =", "} # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {", "\"static\"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DATABASES", "= [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]", "unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep", "Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',", "# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } # Password", "\"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = \"https://%s/%s/\"", "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',", "'django.contrib.staticfiles', 'storages', 'quiz', 'multichoice', 'true_false', 'essay', ] MIDDLEWARE_CLASSES = [", "# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {", "{ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] #", "20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID =", "= os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST = 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN =", "'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'quiz', 'multichoice', 'true_false', 'essay', ] MIDDLEWARE_CLASSES", "list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID", "# } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [", "'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'quiz', 'multichoice', 'true_false',", "settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY", "See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used", "'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # }", "WARNING: don't run with debug turned on in production! DEBUG", "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes',", "https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values,", "# } # } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS", "...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable", "{ # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # }", "True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL", "DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS = { # see", "'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, },", "'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ],", "and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID = 1 import", "quiz_app project. Generated by 'django-admin startproject' using Django 2.1.2. For", "[], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',", "[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'quiz',", "for quiz_app project. Generated by 'django-admin startproject' using Django 2.1.2.", "'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION", "'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us'", "'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'quiz_app.urls' TEMPLATES = [ {", "AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec", "'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'quiz_app.wsgi.application' # Database", "} # } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS =", "secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') #", "}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/", "# Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME':", "https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE':", "the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY')", "= True USE_TZ = True # Static files (CSS, JavaScript,", "os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) }", "{ # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00", "% (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = \"https://%s/%s/\" %", "by 'django-admin startproject' using Django 2.1.2. For more information on", "os.path.join(BASE_DIR, \"static\"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'", "AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST = 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN", "'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'quiz', 'multichoice', 'true_false', 'essay',", "AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',", "'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',", "Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/", "= 'quiz_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [],", "31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME =", "Django settings for quiz_app project. Generated by 'django-admin startproject' using", "information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list", "os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS =", "'media' MEDIA_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'", "'/static/' # STATIC_ROOT = 'staticfiles' STATICFILES_DIRS= ( os.path.join(BASE_DIR, \"static\"), )", "(AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN,", "'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'quiz_app.urls' TEMPLATES = [ { 'BACKEND':", "the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/", "SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug", "True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media',", "[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {", "SECURITY WARNING: don't run with debug turned on in production!", "'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization", "] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE =", "'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME", "= 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N =", "2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID", "'true_false', 'essay', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',", "= 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN,", "project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start", "in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't", "# SECURITY WARNING: don't run with debug turned on in", "ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin',", "= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS':", "'custom_storages.StaticStorage' STATIC_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media'", "# https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' # STATIC_ROOT = 'staticfiles' STATICFILES_DIRS=", "}, ] WSGI_APPLICATION = 'quiz_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases #", "'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',", "= ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',", "'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',", "'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True", "= os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))", "JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' # STATIC_ROOT =", "'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'quiz_app.urls' TEMPLATES", "https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME':", "'s3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE", "their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID = 1 import os", "# SECURITY WARNING: keep the secret key used in production", "= { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099", "USE_TZ = True # Static files (CSS, JavaScript, Images) #", "= 1 import os import dj_database_url # Build paths inside", "= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages',", "full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\"", "don't run with debug turned on in production! DEBUG =", "DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application definition", "'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION =", "# DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3',", "= '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage'", "= 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static'", "# Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC'", "TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ", "https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in", "# Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { # 'default':", "} AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31", "'django-admin startproject' using Django 2.1.2. For more information on this", "development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ #", "{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':", "Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { # 'default': {", "of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" SITE_ID =", "STATIC_URL = '/static/' # STATIC_ROOT = 'staticfiles' STATICFILES_DIRS= ( os.path.join(BASE_DIR,", "= os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned", "= {'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires", "= 'staticfiles' STATICFILES_DIRS= ( os.path.join(BASE_DIR, \"static\"), ) MEDIA_ROOT = os.path.join(BASE_DIR,", "# 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } #", "os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST = 's3-eu-west-1.amazonaws.com'", "Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\")", "key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY", "'db.sqlite3'), # } # } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators", "'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [", "# see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',", "'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },", "Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR", "\"\"\" Django settings for quiz_app project. Generated by 'django-admin startproject'", "files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' #", "settings for quiz_app project. Generated by 'django-admin startproject' using Django", "DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', #", "# STATIC_ROOT = 'staticfiles' STATICFILES_DIRS= ( os.path.join(BASE_DIR, \"static\"), ) MEDIA_ROOT", "STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)", "'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'quiz', 'multichoice', 'true_false', 'essay', ]", "Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'", "'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', }", "turned on in production! DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS =", "SITE_ID = 1 import os import dj_database_url # Build paths", "} AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\")", "USE_I18N = True USE_L10N = True USE_TZ = True #", "'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY", "Generated by 'django-admin startproject' using Django 2.1.2. For more information", "[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF", "% AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL =", "True USE_L10N = True USE_TZ = True # Static files", "'media') MEDIA_URL = '/media/' DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS", "for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the", "True USE_TZ = True # Static files (CSS, JavaScript, Images)", "[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ]", "= 'custom_storages.StaticStorage' STATIC_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION =", "Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions',", "'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',", "'%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL", "AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = \"https://%s/%s/\"", "SECURITY WARNING: keep the secret key used in production secret!", "(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' # STATIC_ROOT", "debug turned on in production! DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS", "{ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME':", "For the full list of settings and their values, see", "on in production! DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1']", "'multichoice', 'true_false', 'essay', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',", "'quiz', 'multichoice', 'true_false', 'essay', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',", "= os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST =", "on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of", "MEDIAFILES_LOCATION = 'media' MEDIA_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE", "dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu,", "= os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS", "# https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N =", "https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True", "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True,", "STATICFILES_DIRS= ( os.path.join(BASE_DIR, \"static\"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL", "MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',", "], }, }, ] WSGI_APPLICATION = 'quiz_app.wsgi.application' # Database #", "{ # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR,", "'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY =", "False) ALLOWED_HOSTS = ['ignas-quiz.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS = [", "'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'quiz_app.urls'", "'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } # Password validation", "AWS_STORAGE_BUCKET_NAME = os.environ.get(\"AWS_STORAGE_BUCKET_NAME\") AWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST", "{'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires':", "keep the secret key used in production secret! SECRET_KEY =", "Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N", "( os.path.join(BASE_DIR, \"static\"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL =", "os.environ.get(\"AWS_ACCESS_KEY_ID\") AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST = 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com'", "'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } #", "USE_L10N = True USE_TZ = True # Static files (CSS,", "Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/", "= True USE_L10N = True USE_TZ = True # Static", "}, }, ] WSGI_APPLICATION = 'quiz_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases", "STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = \"https://%s/%s/\" %", "= { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME':", "file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and", "'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'quiz_app.urls' TEMPLATES = [", "] ROOT_URLCONF = 'quiz_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',", "os import dj_database_url # Build paths inside the project like", "import dj_database_url # Build paths inside the project like this:", ") MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DATABASES =", "AWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\") AWS_S3_HOST = 's3-eu-west-1.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' %" ]
[ "ToppleDataset(object): ''' Loads toppling data and provides batches for training", "norm_info.inertia_max try: self.friction_offset = norm_info.friction_offset self.friction_max = norm_info.friction_max except: #", "self.mass_offset = norm_info.mass_offset self.mass_max = norm_info.mass_max self.inertia_offset = norm_info.inertia_offset self.inertia_max", "pc_inds = np.random.choice(pc.shape[0], self.num_pts, replace=False) pc = pc[pc_inds, :] #", "self.use_delta_quat: delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa: delta_rot_out", "np.zeros((num_steps), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0: if", "not find dataset at ' + root) return data_loader =", "'max_delta_rot' : self.max_delta_rot, 'force_vec_max' : self.force_vec_max, 'pc_max' : self.pc_max, \\", "rot if self.use_delta_quat: batch.delta_quat[i] = delta_quat if self.use_aa: batch.delta_rot[i] =", "1] data.point_cloud /= norm_info.pc_max # force pos -> [-1, 1]", "' + str(count)) topple_data.reset() count = 0 while topple_data.has_next_batch(): batch", "delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx: topple_label_out = np.zeros((num_steps), dtype=int) seq_topple_idx", "before topple idx, 1 if after self.topple_label = np.zeros((self.size, self.num_steps),", "# density -> [0, 1] data.density = (data.density - norm_info.density_offset)", "data.force_pos /= norm_info.pc_max # force vec -> [-1, 1] data.force_vec", "0: self.use_aa = True if len(self.data.delta_rot_split) > 0: self.use_aa_split =", "def copy_from(self, norm_info): ''' Takes values from the given normalization", "pos) self.pc_max = None # normalization values for shape-related stuff", "self.max_delta_rot = norm_info.max_delta_rot except: # old versions of data doesn't", "= None self.mass_max = None self.inertia_offset = None self.inertia_max =", "of rotation between two steps for axis-angle representation self.max_delta_rot =", "= batch.delta_rot_split[i] if self.use_topple_idx: batch.topple_label[batch_size + i] = batch.topple_label[i] if", "3)) # cummulative euler angles self.rot = np.zeros((self.size, self.num_steps, 3))", "\\ self.get_seq(self.iter_inds[start_idx + i], self.steps_per_seq, random_window, focus_toppling) batch.point_cloud[i] = pc", "f: pickle.dump(self, f) def load_from(self, pkl_file): ''' Load normalization info", "> 0: self.use_aa_split = True if len(self.data.topple_idx) > 0: self.use_topple_idx", "= None # max angle of rotation between two steps", "= None # normalization values for shape-related stuff self.density_offset =", "= False self.use_delta_quat = False if len(self.data.delta_rot) > 0: self.use_aa", "norm_info.max_delta_rot) for x in delta_rot_split_steps] def reset(self): ''' Prepares to", "data for root in roots: if not exists(root): print('Could not", "data for i in range(self.batch_size - batch_size): batch.point_cloud[batch_size + i]", "window around the index where it topples topple_idx = self.data.topple_idx[idx]", "+ [delta_quat_list[-1]]*pad_len) euler_rot_list = self.data.rot_euler[idx] euler_rot_out = np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len)", "delta_rot_out = None if not self.use_aa_split: delta_rot_split_out = None if", "end of the data start_idx = self.batch_idx * self.batch_size end_idx", "shuffle : randomly shuffles the returned sequence ordering - num_pts", "np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx: topple_label_out = np.zeros((num_steps), dtype=int) seq_topple_idx = self.data.topple_idx[idx]", "# print(batch.delta_rot[0]) # print(batch.topple_label[0]) # print(batch.pos) # print(batch.body_friction) # print(batch.delta_quat[0])", "# scale accordingly pc *= np.reshape(scale, (1, -1)) # randomly", "perturbation is performed. - ''' # settings self.batch_size = batch_size", "num_steps : number of timesteps to return in each sequence", "= np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale = self.data.scale[idx] # scale accordingly pc *=", ") self.num_batches = (self.data.size + self.batch_size - 1) // self.batch_size", "count = 0 while topple_data.has_next_batch(): batch = topple_data.next_batch() count +=", "hold a single batch of data. ''' def __init__(self, size,", "if self.use_aa_split: delta_rot_split_list = self.data.delta_rot_split[idx] delta_rot_split_out = np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len)", "rot_steps in enumerate(data.total_rot): data.total_rot[i] = [(x / norm_info.max_rot) for x", "dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0: if seq_topple_idx", "self.pc_max = norm_info.pc_max self.density_offset = norm_info.density_offset self.density_max = norm_info.density_max self.mass_offset", "+= np.random.normal(0.0, self.perturb_std, pc.shape) # randomly draw a subset of", "np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa: delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split: delta_rot_split_out =", "'mass_max' : self.mass_max, 'inertia_off' : self.inertia_offset, 'inertia_max' : self.inertia_max, \\", "self.rot = np.zeros((self.size, self.num_steps, 3)) # change in rotation in", "all points in the data. - perturb_pts : the stdev", "+ i], self.steps_per_seq, random_window, focus_toppling) batch.point_cloud[i] = pc batch.lin_vel[i] =", "enumerate(data.delta_rot_split): data.delta_rot_split[i] = [np.append(x[:3] / np.linalg.norm(x[:3]), x[3] / norm_info.max_delta_rot) for", "self.num_batches def next_batch(self, random_window=True, focus_toppling=False): ''' Returns the next batch", "= np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len) pos_list = self.data.pos[idx] pos_out = np.array(pos_list", "= np.array(self.data.pos[idx][start_step:end_step]) rot_out = np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat: delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step])", "seq_topple_idx > 0: if seq_topple_idx <= start_step: topple_label_out[:] = 1", "in axis-angle rep (scaled 3 vec) self.delta_rot = np.zeros((self.size, self.num_steps,", "batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size + i] = batch.scale[i] batch.rot_euler[batch_size +", "-> [-1, 1] for i, pos_steps in enumerate(data.pos): data.pos[i] =", "batch def get_seq(self, idx, num_steps, random_window=True, focus_toppling=False): ''' Returns a", "just pick the max index start_step = max_start_step else: #", "= norm_info.inertia_offset self.inertia_max = norm_info.inertia_max try: self.friction_offset = norm_info.friction_offset self.friction_max", "sequence ordering - num_pts : the number of points to", "= [(x / norm_info.max_rot) for x in rot_steps] # delta", "ToppleNormalizationInfo. ''' # point clouds -> [-1, 1] data.point_cloud /=", "if self.use_aa: delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split: delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step])", "idx and length num_steps. If num_steps > sim_length the final", "# velocities -> [-1, 1] for i, lin_vel_steps in enumerate(data.lin_vel):", "import exists, realpath import sys import math from topple_data_loader import", "between two contiguous timesteps (for euler rot) self.max_rot = None", "''' # get the normalized canonical point cloud for this", "around any axis between two contiguous timesteps (for euler rot)", "is shorter than desired sequence length pad_len = abs(max_start_step) lin_vel_list", "-> [0, 1] if norm_info.friction_offset is not None: data.body_friction =", "start_step: topple_label_out[:] = 1 elif seq_topple_idx < end_step: topple_label_out[seq_topple_idx-start_step:] =", "the given idx and length num_steps. If num_steps > sim_length", "self.max_rot = None # max angle of rotation between two", "self.inertia_max, \\ 'friction_off' : self.friction_offset, 'friction_max' : self.friction_max }) def", "if random_window=True will get a random sequence of correct length", "'density_max' : self.density_max, 'mass_off' : self.mass_offset, \\ 'mass_max' : self.mass_max,", "rot) self.max_rot = None # max angle of rotation between", "start_step = max_start_step else: # our window is guaranteed to", "if not exists(norm_info_file): print('Could not find normalization info at '", "self.use_aa_split: delta_rot_split_out = None if not self.use_topple_idx: topple_label_out = None", "0 def has_next_batch(self): ''' Returns false if done with the", "rotation -> [-1, 1] for i, rot_steps in enumerate(data.total_rot): data.total_rot[i]", "''' Prepares to iterate through dataset. ''' if self.shuffle: np.random.shuffle(self.iter_inds)", "print({'max_lin_vel' : self.max_lin_vel, 'max_ang_vel' : self.max_ang_vel, 'max_pos' : self.max_pos, \\", "Returns the next batch of data. if random_window=True will get", "# get batch data batch = ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts) for", "rot, delta_quat, delta_rot, delta_rot_split, topple_label, meta_info = \\ self.get_seq(self.iter_inds[start_idx +", "i, rot_steps in enumerate(data.total_rot): data.total_rot[i] = [(x / norm_info.max_rot) for", "= range(0, self.data.size) # prepare to iterate through self.reset() def", "of correct length (otherwise starts at 0). If focus_toppling=True, will", "[-1, 1] for i, lin_vel_steps in enumerate(data.lin_vel): data.lin_vel[i] = [(x", "return pc, lin_vel_out, ang_vel_out, pos_out, rot_out, delta_quat_out, delta_rot_out, delta_rot_split_out, topple_label_out,", "1) * self.batch_size, self.data.size) batch_size = end_idx - start_idx #", "representation self.max_delta_rot = None # max 2-norm of applied impulse", "from os.path import exists, realpath import sys import math from", "self.use_body_friction: batch.body_friction[batch_size + i] = batch.body_friction[i] self.batch_idx += 1 return", "two contiguous timesteps self.max_pos = None # max change in", "delta_rot_split_out, topple_label_out, meta_info def get_norm_info(self): return self.norm_info if __name__=='__main__': #", "points in the point cloud self.num_pts = self.data.point_cloud.shape[1] # load", "self.mass_max = norm_info.mass_max self.inertia_offset = norm_info.inertia_offset self.inertia_max = norm_info.inertia_max try:", "self.num_steps, 3)) # cummulative euler angles self.rot = np.zeros((self.size, self.num_steps,", "delta_rot if self.use_aa_split: batch.delta_rot_split[i] = delta_rot_split if self.use_topple_idx: batch.topple_label[i] =", "end_step)) lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out = np.array(self.data.pos[idx][start_step:end_step])", "[(x / norm_info.max_pos) for x in pos_steps] # delta rotation", "self.friction_max = norm_info.friction_max except: # old version doesn't have this", "'friction_max' : self.friction_max }) def save(self, pkl_file): ''' Saves normalization", "vec) self.delta_rot = np.zeros((self.size, self.num_steps, 3)) # change in rotation", "if not self.use_aa_split: delta_rot_split_out = None if not self.use_topple_idx: topple_label_out", "1 # print(batch.lin_vel[0]) # print(batch.toppled[0]) # print(batch.delta_rot_split[0]) # print(batch.delta_rot[0]) #", "np.zeros((self.size)) self.mass = np.zeros((self.size)) self.scale = np.zeros((self.size, 3)) self.rot_euler =", "np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len) euler_rot_list = self.data.rot_euler[idx] euler_rot_out = np.array(euler_rot_list +", "sequence length pad_len = abs(max_start_step) lin_vel_list = self.data.lin_vel[idx] lin_vel_out =", "realpath import sys import math from topple_data_loader import ToppleData, ToppleDataLoader", "a single batch of data. ''' def __init__(self, size, seq_len,", "if seq_topple_idx > 0: topple_label_out[seq_topple_idx:] = 1 else: start_step =", "self.num_pts < pc.shape[0]: pc_inds = np.random.choice(pc.shape[0], self.num_pts, replace=False) pc =", "open(pkl_file, 'rb') as f: norm_info = pickle.load(f) self.copy_from(norm_info) def copy_from(self,", "in range(self.batch_size - batch_size): batch.point_cloud[batch_size + i] = batch.point_cloud[i] batch.lin_vel[batch_size", "= max([topple_idx - num_steps + 1, 0]) if min_idx >=", "self.lin_vel = np.zeros((self.size, self.num_steps, 3)) self.ang_vel = np.zeros((self.size, self.num_steps, 3))", "self.use_aa: delta_rot_list = self.data.delta_rot[idx] delta_rot_out = np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len) if", "simulation at the given idx and length num_steps. If num_steps", "not find normalization info at ' + norm_info_file) return self.norm_info", "if desired if self.num_pts < pc.shape[0]: pc_inds = np.random.choice(pc.shape[0], self.num_pts,", "for axis-angle representation self.max_delta_rot = None # max 2-norm of", "if we have axis-angle info (for backwards compat) self.use_aa =", "= pos batch.rot[i] = rot if self.use_delta_quat: batch.delta_quat[i] = delta_quat", "If None uses all points in the data. - perturb_pts", "points if desired if self.num_pts < pc.shape[0]: pc_inds = np.random.choice(pc.shape[0],", "yrot, axes='szxy') # unity applies euler angles in z, x,", "np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len) if self.use_aa_split: delta_rot_split_list = self.data.delta_rot_split[idx] delta_rot_split_out =", "= np.zeros((total_steps + pad_len), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx", "data start_idx = self.batch_idx * self.batch_size end_idx = min((self.batch_idx +", "z) self.delta_quat = np.zeros((self.size, self.num_steps, 4)) # change in rotation", "x, y, z) self.delta_quat = np.zeros((self.size, self.num_steps, 4)) # change", "+ i] = batch.delta_rot_split[i] if self.use_topple_idx: batch.topple_label[batch_size + i] =", "an epoch as returning one sequence from every single simulation", "normalized canonical point cloud for this simulation pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]])", "# max element of any linear vel vector self.max_lin_vel =", "all the points in the point cloud self.num_pts = self.data.point_cloud.shape[1]", "enumerate(data.pos): data.pos[i] = [(x / norm_info.max_pos) for x in pos_steps]", "- perturb_pts : the stdev to randomly perturb point clouds", "sequence of correct length (otherwise starts at 0). If focus_toppling=True,", "= np.dot(pc, R.T) toppled = self.data.toppled[idx] shape_name = self.data.shape_name[idx] mass", "self.shape_name = [] self.body_friction = np.zeros((self.size)) self.mass = np.zeros((self.size)) self.scale", "training and model evaluation. ''' def __init__(self, roots, norm_info_file, batch_size=32,", "= None return pc, lin_vel_out, ang_vel_out, pos_out, rot_out, delta_quat_out, delta_rot_out,", "+ i] = batch.scale[i] batch.rot_euler[batch_size + i] = batch.rot_euler[i] batch.mass[batch_size", "Takes values from the given normalization info object and copies", "range(batch_size): pc, lin_vel, ang_vel, pos, rot, delta_quat, delta_rot, delta_rot_split, topple_label,", "= self.data.toppled[idx] shape_name = self.data.shape_name[idx] mass = self.data.mass[idx] body_fric =", "information for a dataset. ''' def __init__(self): # max element", "number of timesteps to return in each sequence - shuffle", "length is shorter than sim length the unique sequences contained", "data and provides batches for training and model evaluation. '''", "None: data.body_friction = (data.body_friction - norm_info.friction_offset) / norm_info.friction_max # now", "when returning batches (in order by default) self.iter_inds = range(0,", "+ self.batch_size - 1) // self.batch_size self.batch_idx = 0 def", "''' Normalizes (in place) the given ToppleData using the ToppleNormalizationInfo.", "shorter than sim length the unique sequences contained # in", "-> [0, 1] data.mass = (data.mass - norm_info.mass_offset) / norm_info.mass_max", "delta_quat_out = np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len) euler_rot_list = self.data.rot_euler[idx] euler_rot_out =", "shuffle=True, num_pts=None, perturb_pts=0.01) count = 0 while topple_data.has_next_batch(): batch =", "self.batch_idx < self.num_batches def next_batch(self, random_window=True, focus_toppling=False): ''' Returns the", "focus_toppling=False): ''' Returns the next batch of data. if random_window=True", "randomly draw a subset of points if desired if self.num_pts", "some part of toppling start_step = np.random.randint(min_idx, max_start_step+1) else: start_step", "# norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out() topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5,", "> 0: self.use_topple_idx = True if len(self.data.body_friction) > 0: self.use_body_friction", "self.use_topple_idx = False self.use_delta_quat = False if len(self.data.delta_rot) > 0:", "- ''' # settings self.batch_size = batch_size self.steps_per_seq = num_steps", "Saves normalization info object to a specified .pkl file. '''", "seq_topple_idx > 0: topple_label_out[seq_topple_idx:] = 1 else: start_step = 0", "applied impulse vector self.force_vec_max = None # max 2-norm of", "lin_vel batch.ang_vel[i] = ang_vel batch.pos[i] = pos batch.rot[i] = rot", "ordering pc = np.dot(pc, R.T) toppled = self.data.toppled[idx] shape_name =", "''' Structure to hold a single batch of data. '''", "a dataset. ''' def __init__(self): # max element of any", "print('Range: %d, %d' % (start_step, end_step)) lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out", "y ordering pc = np.dot(pc, R.T) toppled = self.data.toppled[idx] shape_name", "sure this sequence includes the part of the sequence where", "print(batch.lin_vel[0]) # print(batch.toppled[0]) # print(batch.delta_rot_split[0]) # print(batch.delta_rot[0]) # print(batch.topple_label[0]) #", "\"epoch\" (seen each sim once). ''' return self.batch_idx < self.num_batches", "self.use_aa = True if len(self.data.delta_rot_split) > 0: self.use_aa_split = True", "max delta rot pass self.force_vec_max = norm_info.force_vec_max self.pc_max = norm_info.pc_max", "data # velocities -> [-1, 1] for i, lin_vel_steps in", "# randomly choose a size num_steps sequence from the simulation", "self.batch_size, self.data.size) batch_size = end_idx - start_idx # get batch", "self.reset() def normalize_data(self, data, norm_info): ''' Normalizes (in place) the", "delta position -> [-1, 1] for i, pos_steps in enumerate(data.pos):", "and normalize angle -> [-1, 1] if self.use_aa_split: for i,", "= np.radians(init_rot) R = transforms3d.euler.euler2mat(zrot, xrot, yrot, axes='szxy') # unity", "= total_steps - num_steps start_step = 0 if max_start_step <", "self.point_cloud = np.zeros((self.size, self.num_pts, 3)) self.lin_vel = np.zeros((self.size, self.num_steps, 3))", "self.norm_info = ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded normalization info!') # see if", "batch.topple_label[i] if self.use_body_friction: batch.body_friction[batch_size + i] = batch.body_friction[i] self.batch_idx +=", ": self.max_pos, \\ 'max_rot' : self.max_rot, 'max_delta_rot' : self.max_delta_rot, 'force_vec_max'", "None if not self.use_aa_split: delta_rot_split_out = None if not self.use_topple_idx:", "roots: if not exists(root): print('Could not find dataset at '", "= meta_info[3] if self.use_body_friction: batch.body_friction[i] = meta_info[4] batch.mass[i] = meta_info[5]", "self.data.delta_rot[idx] delta_rot_out = np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len) if self.use_aa_split: delta_rot_split_list =", "delta_rot_split, topple_label, meta_info = \\ self.get_seq(self.iter_inds[start_idx + i], self.steps_per_seq, random_window,", "exists(root): print('Could not find dataset at ' + root) return", "i], self.steps_per_seq, random_window, focus_toppling) batch.point_cloud[i] = pc batch.lin_vel[i] = lin_vel", "sequence from the simulation at the given idx and length", "init_rot = self.data.rot_euler[idx][start_step] xrot, yrot, zrot = np.radians(init_rot) R =", "vector self.max_lin_vel = None # max element of any angular", "# settings self.batch_size = batch_size self.steps_per_seq = num_steps self.shuffle =", "/ norm_info.max_delta_rot) for x in delta_rot_split_steps] def reset(self): ''' Prepares", "''' Structure to hold all the normalization information for a", "clouds with. If None no perturbation is performed. - '''", "(for backwards compat) self.use_aa = False self.use_aa_split = False self.use_topple_idx", "> sim_length the final (sim_length-num_steps) steps are padded with the", "now time sequence data # velocities -> [-1, 1] for", "batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size + i] = batch.scale[i] batch.rot_euler[batch_size + i] =", "element of any linear vel vector self.max_lin_vel = None #", "data...') self.normalize_data(self.data, self.norm_info) print('Finished normalizing!') # order to iterate through", "= 0 while topple_data.has_next_batch(): batch = topple_data.next_batch() count += 1", "for i, delta_rot_split_steps in enumerate(data.delta_rot_split): data.delta_rot_split[i] = [np.append(x[:3] / np.linalg.norm(x[:3]),", "topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5, num_steps=10, shuffle=True, num_pts=None, perturb_pts=0.01)", "lin_vel_list = self.data.lin_vel[idx] lin_vel_out = np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len) ang_vel_list =", "rot_out = np.array(rot_list + [rot_list[-1]]*pad_len) if self.use_delta_quat: delta_quat_list = self.data.delta_quat[idx]", "data.lin_vel[i] = [(x / norm_info.max_lin_vel) for x in lin_vel_steps] for", "# randomly perturb point cloud pc += np.random.normal(0.0, self.perturb_std, pc.shape)", "pad_len), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0: topple_label_out[seq_topple_idx:]", "0 if max_start_step < 0: # simulation is shorter than", "the data print('Normalizing data...') self.normalize_data(self.data, self.norm_info) print('Finished normalizing!') # order", "def __init__(self, roots, norm_info_file, batch_size=32, num_steps=15, shuffle=False, num_pts=None, perturb_pts=0.0): '''", "1] if self.use_aa_split: for i, delta_rot_split_steps in enumerate(data.delta_rot_split): data.delta_rot_split[i] =", "= False if len(self.data.delta_rot) > 0: self.use_aa = True if", "= None self.inertia_offset = None self.inertia_max = None self.friction_offset =", "self.steps_per_seq, self.num_pts) for i in range(batch_size): pc, lin_vel, ang_vel, pos,", "scale, euler_rot_out, body_fric, mass) if not self.use_aa: delta_rot_out = None", "them to this one ''' self.max_lin_vel = norm_info.max_lin_vel self.max_ang_vel =", "meta_info[2] batch.rot_euler[i] = meta_info[3] if self.use_body_friction: batch.body_friction[i] = meta_info[4] batch.mass[i]", "= ang_vel batch.pos[i] = pos batch.rot[i] = rot if self.use_delta_quat:", "from the given normalization info object and copies them to", "pickle.load(f) self.copy_from(norm_info) def copy_from(self, norm_info): ''' Takes values from the", "if self.shuffle: np.random.shuffle(self.iter_inds) # we consider an epoch as returning", "+ i] = batch.delta_rot[i] if self.use_aa_split: batch.delta_rot_split[batch_size + i] =", "= transforms3d.euler.euler2mat(zrot, xrot, yrot, axes='szxy') # unity applies euler angles", "for x in rot_steps] # delta rot axis-angle -> [-1,", "= norm_info.max_rot try: self.max_delta_rot = norm_info.max_delta_rot except: # old versions", "if self.use_topple_idx: topple_label_out = np.zeros((num_steps), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if", "pass self.force_vec_max = norm_info.force_vec_max self.pc_max = norm_info.pc_max self.density_offset = norm_info.density_offset", "(in order by default) self.iter_inds = range(0, self.data.size) # prepare", "in lin_vel_steps] for i, ang_vel_steps in enumerate(data.ang_vel): data.ang_vel[i] = [(x", "batch.mass[i] if self.use_aa: batch.delta_rot[batch_size + i] = batch.delta_rot[i] if self.use_aa_split:", "element of any angular vel vector self.max_ang_vel = None #", "simulation pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale = self.data.scale[idx] # scale accordingly", "np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale = self.data.scale[idx] # scale accordingly pc *= np.reshape(scale,", "= norm_info.max_delta_rot except: # old versions of data doesn't have", "np.zeros((self.size, self.num_steps, 3)) self.pos = np.zeros((self.size, self.num_steps, 3)) # cummulative", "end with repeat of data for i in range(self.batch_size -", "= (data.inertia - norm_info.inertia_offset) / norm_info.inertia_max # friction -> [0,", "pos_list = self.data.pos[idx] pos_out = np.array(pos_list + [pos_list[-1]]*pad_len) rot_list =", "random_window=True will get a random sequence of correct length (otherwise", "single batch of data. ''' def __init__(self, size, seq_len, num_pts):", "data.ang_vel[i] = [(x / norm_info.max_ang_vel) for x in ang_vel_steps] #", "steps in split axis-angle rep (4-vec) self.delta_rot_split = np.zeros((self.size, self.num_steps,", "not self.use_aa_split: delta_rot_split_out = None if not self.use_topple_idx: topple_label_out =", "self.density_offset, 'density_max' : self.density_max, 'mass_off' : self.mass_offset, \\ 'mass_max' :", "np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len) pos_list = self.data.pos[idx] pos_out = np.array(pos_list +", "cummulative euler angles self.rot = np.zeros((self.size, self.num_steps, 3)) # change", "pos_steps in enumerate(data.pos): data.pos[i] = [(x / norm_info.max_pos) for x", "2-norm of applied impulse vector self.force_vec_max = None # max", "given idx and length num_steps. If num_steps > sim_length the", "pos_out, rot_out, delta_quat_out, delta_rot_out, delta_rot_split_out, topple_label_out, meta_info def get_norm_info(self): return", "'max_pos' : self.max_pos, \\ 'max_rot' : self.max_rot, 'max_delta_rot' : self.max_delta_rot,", "i, ang_vel_steps in enumerate(data.ang_vel): data.ang_vel[i] = [(x / norm_info.max_ang_vel) for", "file containing normalization information - batch_size : number of sequences", "= batch.topple_label[i] if self.use_body_friction: batch.body_friction[batch_size + i] = batch.body_friction[i] self.batch_idx", "= None self.mass_offset = None self.mass_max = None self.inertia_offset =", "data.delta_rot_split[i] = [np.append(x[:3] / np.linalg.norm(x[:3]), x[3] / norm_info.max_delta_rot) for x", "object and copies them to this one ''' self.max_lin_vel =", "self.perturb_std, pc.shape) # randomly draw a subset of points if", "rep (scaled 3 vec) self.delta_rot = np.zeros((self.size, self.num_steps, 3)) #", "load_from(self, pkl_file): ''' Load normalization info into this object from", "np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx: topple_label_out = np.zeros((total_steps + pad_len),", "delta_rot_split_out = np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx: topple_label_out = np.zeros((total_steps", "end_step: topple_label_out[seq_topple_idx-start_step:] = 1 # rotate point cloud to align", "axis-angle rep (scaled 3 vec) self.delta_rot = np.zeros((self.size, self.num_steps, 3))", "file. ''' with open(pkl_file, 'rb') as f: norm_info = pickle.load(f)", "= norm_info.friction_offset self.friction_max = norm_info.friction_max except: # old version doesn't", "batch = ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts) for i in range(batch_size): pc,", "to hold all the normalization information for a dataset. '''", "0 while topple_data.has_next_batch(): batch = topple_data.next_batch() count += 1 print(batch.size)", "specified .pkl file. ''' with open(pkl_file, 'rb') as f: norm_info", ": list of directories containing data to load for this", "[delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx: topple_label_out = np.zeros((total_steps + pad_len), dtype=int) seq_topple_idx", "''' Loads toppling data and provides batches for training and", "self.delta_rot = np.zeros((self.size, self.num_steps, 3)) # change in rotation between", "self.mass_offset = None self.mass_max = None self.inertia_offset = None self.inertia_max", "- num_steps + 1, 0]) if min_idx >= max_start_step: #", "1 return batch def get_seq(self, idx, num_steps, random_window=True, focus_toppling=False): '''", "-> [-1, 1] data.point_cloud /= norm_info.pc_max # force pos ->", "0: self.use_topple_idx = True if len(self.data.body_friction) > 0: self.use_body_friction =", "steps in axis-angle rep (scaled 3 vec) self.delta_rot = np.zeros((self.size,", "= None # max change in rotation around any axis", "self.max_ang_vel, 'max_pos' : self.max_pos, \\ 'max_rot' : self.max_rot, 'max_delta_rot' :", "sequence length is shorter than sim length the unique sequences", "if we're at the end of the data start_idx =", "delta_quat if self.use_aa: batch.delta_rot[i] = delta_rot if self.use_aa_split: batch.delta_rot_split[i] =", "None return pc, lin_vel_out, ang_vel_out, pos_out, rot_out, delta_quat_out, delta_rot_out, delta_rot_split_out,", "< 0: # simulation is shorter than desired sequence length", "delta rot axis-angle -> [-1, 1] norm if self.use_aa: for", "= num_pts self.point_cloud = np.zeros((self.size, self.num_pts, 3)) self.lin_vel = np.zeros((self.size,", "1] data.inertia = (data.inertia - norm_info.inertia_offset) / norm_info.inertia_max # friction", "the stdev to randomly perturb point clouds with. If None", "length num_steps. If num_steps > sim_length the final (sim_length-num_steps) steps", "data.force_vec /= norm_info.force_vec_max # density -> [0, 1] data.density =", "norm_info.mass_offset) / norm_info.mass_max # inertia -> [0, 1] data.inertia =", "num_steps start_step = 0 if max_start_step < 0: # simulation", "None self.friction_offset = None self.friction_max = None def print_out(self): print({'max_lin_vel'", "= ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts) for i in range(batch_size): pc, lin_vel,", "start_step + num_steps # print('Range: %d, %d' % (start_step, end_step))", "will make sure this sequence includes the part of the", "batch.delta_rot[batch_size + i] = batch.delta_rot[i] if self.use_aa_split: batch.delta_rot_split[batch_size + i]", "- norm_info.friction_offset) / norm_info.friction_max # now time sequence data #", "self.pc_max = None # normalization values for shape-related stuff self.density_offset", "zrot = np.radians(init_rot) R = transforms3d.euler.euler2mat(zrot, xrot, yrot, axes='szxy') #", "batch.topple_label[i] = topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i] = meta_info[2] batch.rot_euler[i] =", "self.copy_from(norm_info) def copy_from(self, norm_info): ''' Takes values from the given", "rotation between steps in split axis-angle rep (4-vec) self.delta_rot_split =", "exists(norm_info_file): print('Could not find normalization info at ' + norm_info_file)", "if before topple idx, 1 if after self.topple_label = np.zeros((self.size,", "norm_info.friction_offset) / norm_info.friction_max # now time sequence data # velocities", "''' def __init__(self, size, seq_len, num_pts): self.size = size self.num_steps", "batch_size, or shorter if we're at the end of the", "# normalization values for shape-related stuff self.density_offset = None self.density_max", "ang_vel_steps] # delta position -> [-1, 1] for i, pos_steps", "batch_size = end_idx - start_idx # get batch data batch", "self.data.body_friction[idx] meta_info = (toppled, shape_name, scale, euler_rot_out, body_fric, mass) if", "data, norm_info): ''' Normalizes (in place) the given ToppleData using", "rot pass self.force_vec_max = norm_info.force_vec_max self.pc_max = norm_info.pc_max self.density_offset =", "+ [pos_list[-1]]*pad_len) rot_list = self.data.total_rot[idx] rot_out = np.array(rot_list + [rot_list[-1]]*pad_len)", "axes unit and and normalize angle -> [-1, 1] if", "= self.data.point_cloud.shape[1] # load in normalization info if not exists(norm_info_file):", "correct length (otherwise starts at 0). If focus_toppling=True, will make", "# see if we have axis-angle info (for backwards compat)", "any angular vel vector self.max_ang_vel = None # max distance", "True if len(self.data.topple_idx) > 0: self.use_topple_idx = True if len(self.data.body_friction)", "np.zeros((self.size, self.num_steps), dtype=int) # other meta-data not directly used in", "(1, -1)) # randomly perturb point cloud pc += np.random.normal(0.0,", "= ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out() topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl',", "as f: pickle.dump(self, f) def load_from(self, pkl_file): ''' Load normalization", "+ [euler_rot_list[-1]]*pad_len) if self.use_aa: delta_rot_list = self.data.delta_rot[idx] delta_rot_out = np.array(delta_rot_list", "to see some part of toppling start_step = np.random.randint(min_idx, max_start_step+1)", "len(self.data.delta_quat) > 0: self.use_delta_quat = True # normalize the data", "elif seq_topple_idx < end_step: topple_label_out[seq_topple_idx-start_step:] = 1 # rotate point", "self.batch_size - 1) // self.batch_size self.batch_idx = 0 def has_next_batch(self):", "pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale = self.data.scale[idx] # scale accordingly pc", "occurs. ''' # size is either batch_size, or shorter if", "3)) self.lin_vel = np.zeros((self.size, self.num_steps, 3)) self.ang_vel = np.zeros((self.size, self.num_steps,", "self.inertia_offset = None self.inertia_max = None self.friction_offset = None self.friction_max", "self.num_pts = self.data.point_cloud.shape[1] # load in normalization info if not", "of toppling start_step = np.random.randint(min_idx, max_start_step+1) else: start_step = np.random.randint(0,", "two contiguous timesteps (for euler rot) self.max_rot = None #", "ang_vel_steps in enumerate(data.ang_vel): data.ang_vel[i] = [(x / norm_info.max_ang_vel) for x", "/ np.linalg.norm(x[:3]), x[3] / norm_info.max_delta_rot) for x in delta_rot_split_steps] def", "3)) self.ang_vel = np.zeros((self.size, self.num_steps, 3)) self.pos = np.zeros((self.size, self.num_steps,", "with repeat of data for i in range(self.batch_size - batch_size):", "self.delta_quat = np.zeros((self.size, self.num_steps, 4)) # change in rotation between", "specified .pkl file. ''' with open(pkl_file, 'wb') as f: pickle.dump(self,", "self.size = size self.num_steps = seq_len self.num_pts = num_pts self.point_cloud", "= self.data.scale[idx] # scale accordingly pc *= np.reshape(scale, (1, -1))", "# order to iterate through data when returning batches (in", "perturb_pts self.num_pts = num_pts # load in data for root", "have max delta rot pass self.force_vec_max = norm_info.force_vec_max self.pc_max =", "index where it topples topple_idx = self.data.topple_idx[idx] min_idx = max([topple_idx", "= norm_info.max_pos self.max_rot = norm_info.max_rot try: self.max_delta_rot = norm_info.max_delta_rot except:", "next batch of data. if random_window=True will get a random", "self.data.topple_idx[idx] if seq_topple_idx > 0: topple_label_out[seq_topple_idx:] = 1 else: start_step", "size self.num_steps = seq_len self.num_pts = num_pts self.point_cloud = np.zeros((self.size,", "[-1, 1] if self.use_aa_split: for i, delta_rot_split_steps in enumerate(data.delta_rot_split): data.delta_rot_split[i]", "= None self.density_max = None self.mass_offset = None self.mass_max =", "# old version doesn't have this pass class ToppleBatch(object): '''", "'wb') as f: pickle.dump(self, f) def load_from(self, pkl_file): ''' Load", "simulation # ( though if the sequence length is shorter", "+ str(count)) topple_data.reset() count = 0 while topple_data.has_next_batch(): batch =", ": self.mass_max, 'inertia_off' : self.inertia_offset, 'inertia_max' : self.inertia_max, \\ 'friction_off'", "1) // self.batch_size self.batch_idx = 0 def has_next_batch(self): ''' Returns", "cloud for this simulation pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale = self.data.scale[idx]", ": self.friction_offset, 'friction_max' : self.friction_max }) def save(self, pkl_file): '''", "self.num_steps = seq_len self.num_pts = num_pts self.point_cloud = np.zeros((self.size, self.num_pts,", "delta_rot_out, delta_rot_split_out, topple_label_out, meta_info def get_norm_info(self): return self.norm_info if __name__=='__main__':", "1, 0]) if min_idx >= max_start_step: # just pick the", "len(self.data.topple_idx) > 0: self.use_topple_idx = True if len(self.data.body_friction) > 0:", "self.data.pos[idx] pos_out = np.array(pos_list + [pos_list[-1]]*pad_len) rot_list = self.data.total_rot[idx] rot_out", "self.mass_max, 'inertia_off' : self.inertia_offset, 'inertia_max' : self.inertia_max, \\ 'friction_off' :", "= norm_info.pc_max self.density_offset = norm_info.density_offset self.density_max = norm_info.density_max self.mass_offset =", "self.friction_offset, 'friction_max' : self.friction_max }) def save(self, pkl_file): ''' Saves", "rot_list = self.data.total_rot[idx] rot_out = np.array(rot_list + [rot_list[-1]]*pad_len) if self.use_delta_quat:", "R = transforms3d.euler.euler2mat(zrot, xrot, yrot, axes='szxy') # unity applies euler", "self.density_offset = norm_info.density_offset self.density_max = norm_info.density_max self.mass_offset = norm_info.mass_offset self.mass_max", "see if we have axis-angle info (for backwards compat) self.use_aa", "None self.mass_offset = None self.mass_max = None self.inertia_offset = None", "self.toppled = [] self.shape_name = [] self.body_friction = np.zeros((self.size)) self.mass", "if random_window: if focus_toppling and self.data.toppled[idx]: # choose window around", "f) def load_from(self, pkl_file): ''' Load normalization info into this", "network self.toppled = [] self.shape_name = [] self.body_friction = np.zeros((self.size))", "self.max_pos, \\ 'max_rot' : self.max_rot, 'max_delta_rot' : self.max_delta_rot, 'force_vec_max' :", "= 1 elif seq_topple_idx < end_step: topple_label_out[seq_topple_idx-start_step:] = 1 #", "dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0: topple_label_out[seq_topple_idx:] =", "frame of sequence init_rot = self.data.rot_euler[idx][start_step] xrot, yrot, zrot =", "and provides batches for training and model evaluation. ''' def", "after self.topple_label = np.zeros((self.size, self.num_steps), dtype=int) # other meta-data not", "at the given idx and length num_steps. If num_steps >", "batch of data. ''' def __init__(self, size, seq_len, num_pts): self.size", ": self.max_rot, 'max_delta_rot' : self.max_delta_rot, 'force_vec_max' : self.force_vec_max, 'pc_max' :", "seq_topple_idx < end_step: topple_label_out[seq_topple_idx-start_step:] = 1 # rotate point cloud", "a specified .pkl file. ''' with open(pkl_file, 'rb') as f:", "''' Takes values from the given normalization info object and", "batch.point_cloud[i] batch.lin_vel[batch_size + i] = batch.lin_vel[i] batch.ang_vel[batch_size + i] =", "# old versions of data doesn't have max delta rot", "if self.use_delta_quat: batch.delta_quat[i] = delta_quat if self.use_aa: batch.delta_rot[i] = delta_rot", "for i, pos_steps in enumerate(data.pos): data.pos[i] = [(x / norm_info.max_pos)", "timesteps (for euler rot) self.max_rot = None # max angle", "padded with the value at sim[sim_length]. ''' # get the", "roots : list of directories containing data to load for", "start_step = 0 if max_start_step < 0: # simulation is", "= np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split: delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx: topple_label_out", "0: self.use_body_friction = True if len(self.data.delta_quat) > 0: self.use_delta_quat =", "0 if before topple idx, 1 if after self.topple_label =", "is not None: data.body_friction = (data.body_friction - norm_info.friction_offset) / norm_info.friction_max", "batches: ' + str(count)) topple_data.reset() count = 0 while topple_data.has_next_batch():", "-> [-1, 1] data.force_pos /= norm_info.pc_max # force vec ->", "data_loader.load_data(roots) if num_pts is None: # use all the points", ": number of sequences to return in each batch -", "self.shuffle = shuffle self.perturb_std = perturb_pts self.num_pts = num_pts #", "# norm_info.print_out() topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5, num_steps=10, shuffle=True,", "the unique sequences contained # in the dataset will be", "seq_topple_idx <= start_step: topple_label_out[:] = 1 elif seq_topple_idx < end_step:", "3 vec) self.delta_rot = np.zeros((self.size, self.num_steps, 3)) # change in", "each batch - num_steps : number of timesteps to return", "point in an object point cloud (used for point cloud", "range(self.batch_size - batch_size): batch.point_cloud[batch_size + i] = batch.point_cloud[i] batch.lin_vel[batch_size +", "batch.pos[i] batch.rot[batch_size + i] = batch.rot[i] if self.use_delta_quat: batch.delta_quat[batch_size +", "get_norm_info(self): return self.norm_info if __name__=='__main__': # norm_info = ToppleNormalizationInfo() #", "and and normalize angle -> [-1, 1] if self.use_aa_split: for", "load in data for root in roots: if not exists(root):", "= np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len) euler_rot_list = self.data.rot_euler[idx] euler_rot_out = np.array(euler_rot_list", "self.use_delta_quat: delta_quat_list = self.data.delta_quat[idx] delta_quat_out = np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len) euler_rot_list", "random_window: if focus_toppling and self.data.toppled[idx]: # choose window around the", "print('Finished normalizing!') # order to iterate through data when returning", "= np.zeros((self.size, self.num_steps, 3)) # change in rotation in quaternion", "def reset(self): ''' Prepares to iterate through dataset. ''' if", "self.use_aa_split: delta_rot_split_list = self.data.delta_rot_split[idx] delta_rot_split_out = np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len) if", "provides batches for training and model evaluation. ''' def __init__(self,", "batch.rot[i] if self.use_delta_quat: batch.delta_quat[batch_size + i] = batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i])", "ToppleDataLoader import transforms3d class ToppleNormalizationInfo(): ''' Structure to hold all", "''' def __init__(self): # max element of any linear vel", "xrot, yrot, zrot = np.radians(init_rot) R = transforms3d.euler.euler2mat(zrot, xrot, yrot,", "of points if desired if self.num_pts < pc.shape[0]: pc_inds =", "[(x / norm_info.max_delta_rot) for x in delta_rot_steps] # make axes", "applies euler angles in z, x, y ordering pc =", "self.data.scale[idx] # scale accordingly pc *= np.reshape(scale, (1, -1)) #", "[0, 1] data.mass = (data.mass - norm_info.mass_offset) / norm_info.mass_max #", "else: # our window is guaranteed to see some part", "norm_info_file) return self.norm_info = ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded normalization info!') #", "if self.use_aa_split: for i, delta_rot_split_steps in enumerate(data.delta_rot_split): data.delta_rot_split[i] = [np.append(x[:3]", "[(x / norm_info.max_lin_vel) for x in lin_vel_steps] for i, ang_vel_steps", "used in network self.toppled = [] self.shape_name = [] self.body_friction", "= batch.pos[i] batch.rot[batch_size + i] = batch.rot[i] if self.use_delta_quat: batch.delta_quat[batch_size", "numpy as np import pickle from os.path import exists, realpath", "+ i] = batch.lin_vel[i] batch.ang_vel[batch_size + i] = batch.ang_vel[i] batch.pos[batch_size", "load for this dataset - norm_info_file : .pkl file containing", "distance between positions in two contiguous timesteps self.max_pos = None", "[0, 1] data.density = (data.density - norm_info.density_offset) / norm_info.density_max #", "/= norm_info.pc_max # force pos -> [-1, 1] data.force_pos /=", "# print(batch.pos) # print(batch.body_friction) # print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0])))", "norm_info.max_delta_rot except: # old versions of data doesn't have max", "# max distance between positions in two contiguous timesteps self.max_pos", "pad_len = abs(max_start_step) lin_vel_list = self.data.lin_vel[idx] lin_vel_out = np.array(lin_vel_list +", "angle of rotation between two steps for axis-angle representation self.max_delta_rot", "# change in rotation in quaternion rep (w, x, y,", "evaluation. ''' def __init__(self, roots, norm_info_file, batch_size=32, num_steps=15, shuffle=False, num_pts=None,", "rot_steps] # delta rot axis-angle -> [-1, 1] norm if", "norm_info.density_max # mass -> [0, 1] data.mass = (data.mass -", "not None: data.body_friction = (data.body_friction - norm_info.friction_offset) / norm_info.friction_max #", "3)) # change in rotation between steps in split axis-angle", "= np.zeros((self.size, self.num_steps, 3)) class ToppleDataset(object): ''' Loads toppling data", "try: self.max_delta_rot = norm_info.max_delta_rot except: # old versions of data", "shuffle self.perturb_std = perturb_pts self.num_pts = num_pts # load in", "0 if random_window: if focus_toppling and self.data.toppled[idx]: # choose window", "norm_info_file : .pkl file containing normalization information - batch_size :", "= np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx: topple_label_out = np.zeros((total_steps +", ".pkl file. ''' with open(pkl_file, 'rb') as f: norm_info =", "norm_info.pc_max self.density_offset = norm_info.density_offset self.density_max = norm_info.density_max self.mass_offset = norm_info.mass_offset", "if self.use_topple_idx: batch.topple_label[batch_size + i] = batch.topple_label[i] if self.use_body_friction: batch.body_friction[batch_size", "def has_next_batch(self): ''' Returns false if done with the current", "contiguous sequence from the simulation at the given idx and", "dataset will be much more than an epoch length )", "np import pickle from os.path import exists, realpath import sys", "None uses all points in the data. - perturb_pts :", "batches (in order by default) self.iter_inds = range(0, self.data.size) #", "ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out() topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\", "values for shape-related stuff self.density_offset = None self.density_max = None", "to return in each sequence - shuffle : randomly shuffles", "in enumerate(data.delta_rot): data.delta_rot[i] = [(x / norm_info.max_delta_rot) for x in", "in split axis-angle rep (4-vec) self.delta_rot_split = np.zeros((self.size, self.num_steps, 4))", "if the sequence length is shorter than sim length the", "self.use_aa_split = False self.use_topple_idx = False self.use_delta_quat = False if", "the max index start_step = max_start_step else: # our window", "= 1 # rotate point cloud to align with first", "norm_info): ''' Takes values from the given normalization info object", "self.use_aa: for i, delta_rot_steps in enumerate(data.delta_rot): data.delta_rot[i] = [(x /", "= np.zeros((self.size)) self.mass = np.zeros((self.size)) self.scale = np.zeros((self.size, 3)) self.rot_euler", "= self.data.rot_euler[idx] euler_rot_out = np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len) if self.use_aa: delta_rot_list", ": self.friction_max }) def save(self, pkl_file): ''' Saves normalization info", "while topple_data.has_next_batch(): batch = topple_data.next_batch(random_window=True, focus_toppling=False) count += 1 #", "or shorter if we're at the end of the data", "topple_data.next_batch(random_window=True, focus_toppling=False) count += 1 # print(batch.lin_vel[0]) # print(batch.toppled[0]) #", "to iterate through dataset. ''' if self.shuffle: np.random.shuffle(self.iter_inds) # we", "num_pts # load in data for root in roots: if", "of data doesn't have max delta rot pass self.force_vec_max =", "self.inertia_max = norm_info.inertia_max try: self.friction_offset = norm_info.friction_offset self.friction_max = norm_info.friction_max", "''' # size is either batch_size, or shorter if we're", "force pos) self.pc_max = None # normalization values for shape-related", "def save(self, pkl_file): ''' Saves normalization info object to a", "= norm_info.friction_max except: # old version doesn't have this pass", "transforms3d.euler.euler2mat(zrot, xrot, yrot, axes='szxy') # unity applies euler angles in", "data total_steps = len(self.data.lin_vel[idx]) max_start_step = total_steps - num_steps start_step", "num_pts): self.size = size self.num_steps = seq_len self.num_pts = num_pts", "= None # max distance between positions in two contiguous", "enumerate(data.lin_vel): data.lin_vel[i] = [(x / norm_info.max_lin_vel) for x in lin_vel_steps]", "= 0 if random_window: if focus_toppling and self.data.toppled[idx]: # choose", "this simulation pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale = self.data.scale[idx] # scale", "None: # use all the points in the point cloud", "linear vel vector self.max_lin_vel = None # max element of", "max 2-norm of a point in an object point cloud", "i in range(self.batch_size - batch_size): batch.point_cloud[batch_size + i] = batch.point_cloud[i]", "shape_name, scale, euler_rot_out, body_fric, mass) if not self.use_aa: delta_rot_out =", "= [(x / norm_info.max_pos) for x in pos_steps] # delta", "= np.random.randint(min_idx, max_start_step+1) else: start_step = np.random.randint(0, max_start_step+1) end_step =", "batch_size=5, num_steps=10, shuffle=True, num_pts=None, perturb_pts=0.01) count = 0 while topple_data.has_next_batch():", "get batch data batch = ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts) for i", "-> [-1, 1] data.force_vec /= norm_info.force_vec_max # density -> [0,", "timesteps to return in each sequence - shuffle : randomly", "= np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa: delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step])", "with open(pkl_file, 'wb') as f: pickle.dump(self, f) def load_from(self, pkl_file):", "# prepare to iterate through self.reset() def normalize_data(self, data, norm_info):", "i, pos_steps in enumerate(data.pos): data.pos[i] = [(x / norm_info.max_pos) for", "= batch.rot[i] if self.use_delta_quat: batch.delta_quat[batch_size + i] = batch.delta_quat[i] batch.toppled.append(batch.toppled[i])", "version doesn't have this pass class ToppleBatch(object): ''' Structure to", "self.scale = np.zeros((self.size, 3)) self.rot_euler = np.zeros((self.size, self.num_steps, 3)) class", "at ' + root) return data_loader = ToppleDataLoader() self.data =", "''' self.max_lin_vel = norm_info.max_lin_vel self.max_ang_vel = norm_info.max_ang_vel self.max_pos = norm_info.max_pos", "data print('Normalizing data...') self.normalize_data(self.data, self.norm_info) print('Finished normalizing!') # order to", "if len(self.data.delta_quat) > 0: self.use_delta_quat = True # normalize the", "from every single simulation # ( though if the sequence", "+ num_steps # print('Range: %d, %d' % (start_step, end_step)) lin_vel_out", "enumerate(data.ang_vel): data.ang_vel[i] = [(x / norm_info.max_ang_vel) for x in ang_vel_steps]", "# in the dataset will be much more than an", "= True if len(self.data.delta_quat) > 0: self.use_delta_quat = True #", "batch.mass[i] = meta_info[5] if batch_size != self.batch_size: # need to", "(sim_length-num_steps) steps are padded with the value at sim[sim_length]. '''", "Returns a random contiguous sequence from the simulation at the", "topple_data_loader import ToppleData, ToppleDataLoader import transforms3d class ToppleNormalizationInfo(): ''' Structure", "for shape-related stuff self.density_offset = None self.density_max = None self.mass_offset", "norm_info.max_rot) for x in rot_steps] # delta rot axis-angle ->", "delta_rot_split_list = self.data.delta_rot_split[idx] delta_rot_split_out = np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx:", "self.pc_max, \\ 'density_off' : self.density_offset, 'density_max' : self.density_max, 'mass_off' :", "= False self.use_aa_split = False self.use_topple_idx = False self.use_delta_quat =", "values from the given normalization info object and copies them", "the sequence length is shorter than sim length the unique", "between two steps for axis-angle representation self.max_delta_rot = None #", "= ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded normalization info!') # see if we", "import math from topple_data_loader import ToppleData, ToppleDataLoader import transforms3d class", "to iterate through data when returning batches (in order by", "data.density = (data.density - norm_info.density_offset) / norm_info.density_max # mass ->", "= np.zeros((self.size, self.num_steps, 3)) # cummulative euler angles self.rot =", "self.max_ang_vel = norm_info.max_ang_vel self.max_pos = norm_info.max_pos self.max_rot = norm_info.max_rot try:", "= True if len(self.data.body_friction) > 0: self.use_body_friction = True if", "self.batch_size self.batch_idx = 0 def has_next_batch(self): ''' Returns false if", "''' with open(pkl_file, 'wb') as f: pickle.dump(self, f) def load_from(self,", "norm_info.pc_max # force vec -> [-1, 1] data.force_vec /= norm_info.force_vec_max", "None self.friction_max = None def print_out(self): print({'max_lin_vel' : self.max_lin_vel, 'max_ang_vel'", "self.use_topple_idx: batch.topple_label[batch_size + i] = batch.topple_label[i] if self.use_body_friction: batch.body_friction[batch_size +", "focus_toppling=False) count += 1 # print(batch.lin_vel[0]) # print(batch.toppled[0]) # print(batch.delta_rot_split[0])", "'max_rot' : self.max_rot, 'max_delta_rot' : self.max_delta_rot, 'force_vec_max' : self.force_vec_max, 'pc_max'", "= norm_info.max_lin_vel self.max_ang_vel = norm_info.max_ang_vel self.max_pos = norm_info.max_pos self.max_rot =", "True if len(self.data.delta_quat) > 0: self.use_delta_quat = True # normalize", "self.use_aa: batch.delta_rot[i] = delta_rot if self.use_aa_split: batch.delta_rot_split[i] = delta_rot_split if", "Loads toppling data and provides batches for training and model", "- 1) // self.batch_size self.batch_idx = 0 def has_next_batch(self): '''", "axis-angle info (for backwards compat) self.use_aa = False self.use_aa_split =", "np.zeros((self.size, self.num_steps, 3)) # change in rotation between steps in", ":, 0]))) print('Total num batches: ' + str(count)) topple_data.reset() count", "+ i] = batch.pos[i] batch.rot[batch_size + i] = batch.rot[i] if", "focus_toppling and self.data.toppled[idx]: # choose window around the index where", "- num_steps start_step = 0 if max_start_step < 0: #", "self.num_steps, 4)) # 0 if before topple idx, 1 if", "= num_pts # load in data for root in roots:", "len(self.data.delta_rot_split) > 0: self.use_aa_split = True if len(self.data.topple_idx) > 0:", "norm_info.pc_max # force pos -> [-1, 1] data.force_pos /= norm_info.pc_max", "// self.batch_size self.batch_idx = 0 def has_next_batch(self): ''' Returns false", "[(x / norm_info.max_rot) for x in rot_steps] # delta rot", "''' with open(pkl_file, 'rb') as f: norm_info = pickle.load(f) self.copy_from(norm_info)", "ordering - num_pts : the number of points to use", "next_batch(self, random_window=True, focus_toppling=False): ''' Returns the next batch of data.", "random_window=True, focus_toppling=False): ''' Returns a random contiguous sequence from the", "randomly choose a size num_steps sequence from the simulation to", "If focus_toppling=True, will make sure this sequence includes the part", "self.data.lin_vel[idx] lin_vel_out = np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len) ang_vel_list = self.data.ang_vel[idx] ang_vel_out", "-> [-1, 1] if self.use_aa_split: for i, delta_rot_split_steps in enumerate(data.delta_rot_split):", "are padded with the value at sim[sim_length]. ''' # get", "in enumerate(data.lin_vel): data.lin_vel[i] = [(x / norm_info.max_lin_vel) for x in", "if norm_info.friction_offset is not None: data.body_friction = (data.body_friction - norm_info.friction_offset)", "the value at sim[sim_length]. ''' # get the normalized canonical", "the simulation at the given idx and length num_steps. If", "(self.data.size + self.batch_size - 1) // self.batch_size self.batch_idx = 0", "lin_vel_out, ang_vel_out, pos_out, rot_out, delta_quat_out, delta_rot_out, delta_rot_split_out, topple_label_out, meta_info def", "ang_vel, pos, rot, delta_quat, delta_rot, delta_rot_split, topple_label, meta_info = \\", "from the simulation at the given idx and length num_steps.", "= np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len) if self.use_aa_split: delta_rot_split_list = self.data.delta_rot_split[idx] delta_rot_split_out", "> 0: if seq_topple_idx <= start_step: topple_label_out[:] = 1 elif", "replace=False) pc = pc[pc_inds, :] # randomly choose a size", "def load_from(self, pkl_file): ''' Load normalization info into this object", "meta_info[4] batch.mass[i] = meta_info[5] if batch_size != self.batch_size: # need", "# delta position -> [-1, 1] for i, pos_steps in", "(in place) the given ToppleData using the ToppleNormalizationInfo. ''' #", "the data. - perturb_pts : the stdev to randomly perturb", "angle -> [-1, 1] if self.use_aa_split: for i, delta_rot_split_steps in", "if self.use_body_friction: body_fric = self.data.body_friction[idx] meta_info = (toppled, shape_name, scale,", "the current \"epoch\" (seen each sim once). ''' return self.batch_idx", "= (data.body_friction - norm_info.friction_offset) / norm_info.friction_max # now time sequence", ": .pkl file containing normalization information - batch_size : number", "meta-data not directly used in network self.toppled = [] self.shape_name", "meta_info[5] if batch_size != self.batch_size: # need to pad the", "end_step = start_step + num_steps # print('Range: %d, %d' %", "# other meta-data not directly used in network self.toppled =", "np.reshape(scale, (1, -1)) # randomly perturb point cloud pc +=", "idx, 1 if after self.topple_label = np.zeros((self.size, self.num_steps), dtype=int) #", "pos_out = np.array(pos_list + [pos_list[-1]]*pad_len) rot_list = self.data.total_rot[idx] rot_out =", "for x in delta_rot_steps] # make axes unit and and", "is guaranteed to see some part of toppling start_step =", "transforms3d class ToppleNormalizationInfo(): ''' Structure to hold all the normalization", "batch.mass[batch_size + i] = batch.mass[i] if self.use_aa: batch.delta_rot[batch_size + i]", "to hold a single batch of data. ''' def __init__(self,", "in each sequence - shuffle : randomly shuffles the returned", "delta_quat, delta_rot, delta_rot_split, topple_label, meta_info = \\ self.get_seq(self.iter_inds[start_idx + i],", "once). ''' return self.batch_idx < self.num_batches def next_batch(self, random_window=True, focus_toppling=False):", "= len(self.data.lin_vel[idx]) max_start_step = total_steps - num_steps start_step = 0", "get a random sequence of correct length (otherwise starts at", "= norm_info.mass_max self.inertia_offset = norm_info.inertia_offset self.inertia_max = norm_info.inertia_max try: self.friction_offset", "num batches: ' + str(count)) topple_data.reset() count = 0 while", "backwards compat) self.use_aa = False self.use_aa_split = False self.use_topple_idx =", "if done with the current \"epoch\" (seen each sim once).", "the simulation to return time-series data total_steps = len(self.data.lin_vel[idx]) max_start_step", "= norm_info.max_ang_vel self.max_pos = norm_info.max_pos self.max_rot = norm_info.max_rot try: self.max_delta_rot", "perturb point clouds with. If None no perturbation is performed.", "= [(x / norm_info.max_lin_vel) for x in lin_vel_steps] for i,", "if self.use_delta_quat: batch.delta_quat[batch_size + i] = batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size", "# cummulative euler angles self.rot = np.zeros((self.size, self.num_steps, 3)) #", "ToppleBatch(object): ''' Structure to hold a single batch of data.", "= np.array(rot_list + [rot_list[-1]]*pad_len) if self.use_delta_quat: delta_quat_list = self.data.delta_quat[idx] delta_quat_out", "= self.data.rot_euler[idx][start_step] xrot, yrot, zrot = np.radians(init_rot) R = transforms3d.euler.euler2mat(zrot,", "'rb') as f: norm_info = pickle.load(f) self.copy_from(norm_info) def copy_from(self, norm_info):", "max distance between positions in two contiguous timesteps self.max_pos =", "= None self.inertia_max = None self.friction_offset = None self.friction_max =", "focus_toppling) batch.point_cloud[i] = pc batch.lin_vel[i] = lin_vel batch.ang_vel[i] = ang_vel", "# rotate point cloud to align with first frame of", "return in each sequence - shuffle : randomly shuffles the", "self.use_delta_quat = False if len(self.data.delta_rot) > 0: self.use_aa = True", "data.mass = (data.mass - norm_info.mass_offset) / norm_info.mass_max # inertia ->", "/ norm_info.max_pos) for x in pos_steps] # delta rotation ->", "delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa: delta_rot_out =", "try: self.friction_offset = norm_info.friction_offset self.friction_max = norm_info.friction_max except: # old", "ToppleData, ToppleDataLoader import transforms3d class ToppleNormalizationInfo(): ''' Structure to hold", "where toppling occurs. ''' # size is either batch_size, or", "for root in roots: if not exists(root): print('Could not find", "a point in an object point cloud (used for point", "len(self.data.body_friction) > 0: self.use_body_friction = True if len(self.data.delta_quat) > 0:", "as returning one sequence from every single simulation # (", "compat) self.use_aa = False self.use_aa_split = False self.use_topple_idx = False", "info!') # see if we have axis-angle info (for backwards", "topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i] = meta_info[2] batch.rot_euler[i] = meta_info[3] if", "x in lin_vel_steps] for i, ang_vel_steps in enumerate(data.ang_vel): data.ang_vel[i] =", "to load for this dataset - norm_info_file : .pkl file", "self.max_rot = norm_info.max_rot try: self.max_delta_rot = norm_info.max_delta_rot except: # old", "for a dataset. ''' def __init__(self): # max element of", "one ''' self.max_lin_vel = norm_info.max_lin_vel self.max_ang_vel = norm_info.max_ang_vel self.max_pos =", "between steps in axis-angle rep (scaled 3 vec) self.delta_rot =", "norm_info): ''' Normalizes (in place) the given ToppleData using the", "np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out = np.array(self.data.pos[idx][start_step:end_step]) rot_out = np.array(self.data.total_rot[idx][start_step:end_step])", "> 0: self.use_delta_quat = True # normalize the data print('Normalizing", "np.zeros((self.size, self.num_steps, 3)) # change in rotation in quaternion rep", "= self.data.topple_idx[idx] if seq_topple_idx > 0: if seq_topple_idx <= start_step:", "data.pos[i] = [(x / norm_info.max_pos) for x in pos_steps] #", "iterate through data when returning batches (in order by default)", "point cloud (used for point cloud and force pos) self.pc_max", "= rot if self.use_delta_quat: batch.delta_quat[i] = delta_quat if self.use_aa: batch.delta_rot[i]", "= self.data.topple_idx[idx] min_idx = max([topple_idx - num_steps + 1, 0])", "sequence data # velocities -> [-1, 1] for i, lin_vel_steps", "topple_data.has_next_batch(): batch = topple_data.next_batch() count += 1 print(batch.size) print('Total num", "sequence from every single simulation # ( though if the", "count = 0 while topple_data.has_next_batch(): batch = topple_data.next_batch(random_window=True, focus_toppling=False) count", "norm_info = pickle.load(f) self.copy_from(norm_info) def copy_from(self, norm_info): ''' Takes values", "returned point cloud. If None uses all points in the", "ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts) for i in range(batch_size): pc, lin_vel, ang_vel,", "= norm_info.inertia_max try: self.friction_offset = norm_info.friction_offset self.friction_max = norm_info.friction_max except:", "''' def __init__(self, roots, norm_info_file, batch_size=32, num_steps=15, shuffle=False, num_pts=None, perturb_pts=0.0):", "rotate point cloud to align with first frame of sequence", "[lin_vel_list[-1]]*pad_len) ang_vel_list = self.data.ang_vel[idx] ang_vel_out = np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len) pos_list", "norm_info = ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out() topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'],", "np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split: delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx: topple_label_out =", "batch.body_friction[i] = meta_info[4] batch.mass[i] = meta_info[5] if batch_size != self.batch_size:", "self.num_steps, 3)) # change in rotation in quaternion rep (w,", "Structure to hold all the normalization information for a dataset.", "norm_info.mass_offset self.mass_max = norm_info.mass_max self.inertia_offset = norm_info.inertia_offset self.inertia_max = norm_info.inertia_max", "x in delta_rot_split_steps] def reset(self): ''' Prepares to iterate through", "part of the sequence where toppling occurs. ''' # size", "rotation between steps in axis-angle rep (scaled 3 vec) self.delta_rot", "repeat of data for i in range(self.batch_size - batch_size): batch.point_cloud[batch_size", "= False self.use_topple_idx = False self.use_delta_quat = False if len(self.data.delta_rot)", "- norm_info.inertia_offset) / norm_info.inertia_max # friction -> [0, 1] if", "i, delta_rot_split_steps in enumerate(data.delta_rot_split): data.delta_rot_split[i] = [np.append(x[:3] / np.linalg.norm(x[:3]), x[3]", "%d' % (start_step, end_step)) lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step])", "pkl_file): ''' Load normalization info into this object from a", "[(x / norm_info.max_ang_vel) for x in ang_vel_steps] # delta position", "if self.use_aa: for i, delta_rot_steps in enumerate(data.delta_rot): data.delta_rot[i] = [(x", "= self.data.body_friction[idx] meta_info = (toppled, shape_name, scale, euler_rot_out, body_fric, mass)", "< end_step: topple_label_out[seq_topple_idx-start_step:] = 1 # rotate point cloud to", "norm_info.mass_max self.inertia_offset = norm_info.inertia_offset self.inertia_max = norm_info.inertia_max try: self.friction_offset =", "of timesteps to return in each sequence - shuffle :", "= np.random.randint(0, max_start_step+1) end_step = start_step + num_steps # print('Range:", "batch of data. if random_window=True will get a random sequence", "this one ''' self.max_lin_vel = norm_info.max_lin_vel self.max_ang_vel = norm_info.max_ang_vel self.max_pos", "+ root) return data_loader = ToppleDataLoader() self.data = data_loader.load_data(roots) if", "str(count)) topple_data.reset() count = 0 while topple_data.has_next_batch(): batch = topple_data.next_batch()", "use in the returned point cloud. If None uses all", "1] for i, lin_vel_steps in enumerate(data.lin_vel): data.lin_vel[i] = [(x /", "norm_info.inertia_offset) / norm_info.inertia_max # friction -> [0, 1] if norm_info.friction_offset", "= np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx: topple_label_out = np.zeros((num_steps), dtype=int) seq_topple_idx =", "Returns false if done with the current \"epoch\" (seen each", "in rotation between steps in split axis-angle rep (4-vec) self.delta_rot_split", "length (otherwise starts at 0). If focus_toppling=True, will make sure", "self.density_offset = None self.density_max = None self.mass_offset = None self.mass_max", "to return time-series data total_steps = len(self.data.lin_vel[idx]) max_start_step = total_steps", "max_start_step+1) else: start_step = np.random.randint(0, max_start_step+1) end_step = start_step +", "for i, ang_vel_steps in enumerate(data.ang_vel): data.ang_vel[i] = [(x / norm_info.max_ang_vel)", "0: topple_label_out[seq_topple_idx:] = 1 else: start_step = 0 if random_window:", "topples topple_idx = self.data.topple_idx[idx] min_idx = max([topple_idx - num_steps +", "if not exists(root): print('Could not find dataset at ' +", "self.normalize_data(self.data, self.norm_info) print('Finished normalizing!') # order to iterate through data", "= batch_size self.steps_per_seq = num_steps self.shuffle = shuffle self.perturb_std =", "self.num_pts = num_pts # load in data for root in", "/ norm_info.friction_max # now time sequence data # velocities ->", "euler_rot_out, body_fric, mass) if not self.use_aa: delta_rot_out = None if", "seq_len, num_pts): self.size = size self.num_steps = seq_len self.num_pts =", "= [] self.body_friction = np.zeros((self.size)) self.mass = np.zeros((self.size)) self.scale =", "self.delta_rot_split = np.zeros((self.size, self.num_steps, 4)) # 0 if before topple", ": self.inertia_max, \\ 'friction_off' : self.friction_offset, 'friction_max' : self.friction_max })", "info object and copies them to this one ''' self.max_lin_vel", "= np.zeros((self.size, self.num_pts, 3)) self.lin_vel = np.zeros((self.size, self.num_steps, 3)) self.ang_vel", "toppling start_step = np.random.randint(min_idx, max_start_step+1) else: start_step = np.random.randint(0, max_start_step+1)", "batch.ang_vel[i] = ang_vel batch.pos[i] = pos batch.rot[i] = rot if", "(seen each sim once). ''' return self.batch_idx < self.num_batches def", "root in roots: if not exists(root): print('Could not find dataset", "end_idx = min((self.batch_idx + 1) * self.batch_size, self.data.size) batch_size =", "rot_out, delta_quat_out, delta_rot_out, delta_rot_split_out, topple_label_out, meta_info def get_norm_info(self): return self.norm_info", ": self.max_ang_vel, 'max_pos' : self.max_pos, \\ 'max_rot' : self.max_rot, 'max_delta_rot'", "batch.scale[i] batch.rot_euler[batch_size + i] = batch.rot_euler[i] batch.mass[batch_size + i] =", "self.friction_offset = None self.friction_max = None def print_out(self): print({'max_lin_vel' :", "the final (sim_length-num_steps) steps are padded with the value at", "toppled = self.data.toppled[idx] shape_name = self.data.shape_name[idx] mass = self.data.mass[idx] body_fric", "norm_info.force_vec_max # density -> [0, 1] data.density = (data.density -", "\\ batch_size=5, num_steps=10, shuffle=True, num_pts=None, perturb_pts=0.01) count = 0 while", "exists, realpath import sys import math from topple_data_loader import ToppleData,", "as f: norm_info = pickle.load(f) self.copy_from(norm_info) def copy_from(self, norm_info): '''", "topple_label_out[seq_topple_idx-start_step:] = 1 # rotate point cloud to align with", "np.random.normal(0.0, self.perturb_std, pc.shape) # randomly draw a subset of points", "self.data.ang_vel[idx] ang_vel_out = np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len) pos_list = self.data.pos[idx] pos_out", "either batch_size, or shorter if we're at the end of", "sim once). ''' return self.batch_idx < self.num_batches def next_batch(self, random_window=True,", "[0, 1] if norm_info.friction_offset is not None: data.body_friction = (data.body_friction", "# normalize the data print('Normalizing data...') self.normalize_data(self.data, self.norm_info) print('Finished normalizing!')", "size is either batch_size, or shorter if we're at the", "if focus_toppling and self.data.toppled[idx]: # choose window around the index", "change in rotation in quaternion rep (w, x, y, z)", "for i in range(batch_size): pc, lin_vel, ang_vel, pos, rot, delta_quat,", "num_pts=None, perturb_pts=0.01) count = 0 while topple_data.has_next_batch(): batch = topple_data.next_batch(random_window=True,", "length the unique sequences contained # in the dataset will", "start_step = np.random.randint(min_idx, max_start_step+1) else: start_step = np.random.randint(0, max_start_step+1) end_step", "data batch = ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts) for i in range(batch_size):", "print(batch.delta_rot_split[0]) # print(batch.delta_rot[0]) # print(batch.topple_label[0]) # print(batch.pos) # print(batch.body_friction) #", "dataset. ''' if self.shuffle: np.random.shuffle(self.iter_inds) # we consider an epoch", "= ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5, num_steps=10, shuffle=True, num_pts=None, perturb_pts=0.01) count", "z, x, y ordering pc = np.dot(pc, R.T) toppled =", "this object from a specified .pkl file. ''' with open(pkl_file,", "sim_length the final (sim_length-num_steps) steps are padded with the value", "the returned point cloud. If None uses all points in", "x in pos_steps] # delta rotation -> [-1, 1] for", "(data.mass - norm_info.mass_offset) / norm_info.mass_max # inertia -> [0, 1]", "except: # old versions of data doesn't have max delta", "max_start_step < 0: # simulation is shorter than desired sequence", "idx, num_steps, random_window=True, focus_toppling=False): ''' Returns a random contiguous sequence", "done with the current \"epoch\" (seen each sim once). '''", "data. if random_window=True will get a random sequence of correct", "i] = batch.lin_vel[i] batch.ang_vel[batch_size + i] = batch.ang_vel[i] batch.pos[batch_size +", "cloud (used for point cloud and force pos) self.pc_max =", "np.zeros((self.size, self.num_steps, 3)) # cummulative euler angles self.rot = np.zeros((self.size,", "and model evaluation. ''' def __init__(self, roots, norm_info_file, batch_size=32, num_steps=15,", "= (data.mass - norm_info.mass_offset) / norm_info.mass_max # inertia -> [0,", "batch.scale[batch_size + i] = batch.scale[i] batch.rot_euler[batch_size + i] = batch.rot_euler[i]", "1 elif seq_topple_idx < end_step: topple_label_out[seq_topple_idx-start_step:] = 1 # rotate", "if __name__=='__main__': # norm_info = ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out()", "object from a specified .pkl file. ''' with open(pkl_file, 'rb')", "# use all the points in the point cloud self.num_pts", "if seq_topple_idx > 0: if seq_topple_idx <= start_step: topple_label_out[:] =", "print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0]))) print('Total num batches: ' +", "to this one ''' self.max_lin_vel = norm_info.max_lin_vel self.max_ang_vel = norm_info.max_ang_vel", "shorter than desired sequence length pad_len = abs(max_start_step) lin_vel_list =", "of the data start_idx = self.batch_idx * self.batch_size end_idx =", "change in rotation between steps in split axis-angle rep (4-vec)", "self.max_lin_vel = norm_info.max_lin_vel self.max_ang_vel = norm_info.max_ang_vel self.max_pos = norm_info.max_pos self.max_rot", "total_steps - num_steps start_step = 0 if max_start_step < 0:", "the normalized canonical point cloud for this simulation pc =", "self.max_pos = norm_info.max_pos self.max_rot = norm_info.max_rot try: self.max_delta_rot = norm_info.max_delta_rot", ": randomly shuffles the returned sequence ordering - num_pts :", "0 while topple_data.has_next_batch(): batch = topple_data.next_batch(random_window=True, focus_toppling=False) count += 1", "False self.use_topple_idx = False self.use_delta_quat = False if len(self.data.delta_rot) >", "the index where it topples topple_idx = self.data.topple_idx[idx] min_idx =", "norm_info.friction_max # now time sequence data # velocities -> [-1,", "this sequence includes the part of the sequence where toppling", "-> [-1, 1] norm if self.use_aa: for i, delta_rot_steps in", "between steps in split axis-angle rep (4-vec) self.delta_rot_split = np.zeros((self.size,", "num_steps sequence from the simulation to return time-series data total_steps", "0]))) print('Total num batches: ' + str(count)) topple_data.reset() count =", "have axis-angle info (for backwards compat) self.use_aa = False self.use_aa_split", "}) def save(self, pkl_file): ''' Saves normalization info object to", "one sequence from every single simulation # ( though if", "batch.lin_vel[i] batch.ang_vel[batch_size + i] = batch.ang_vel[i] batch.pos[batch_size + i] =", "rot axis-angle -> [-1, 1] norm if self.use_aa: for i,", "batch.delta_rot_split[i] = delta_rot_split if self.use_topple_idx: batch.topple_label[i] = topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1])", "pc *= np.reshape(scale, (1, -1)) # randomly perturb point cloud", "class ToppleBatch(object): ''' Structure to hold a single batch of", "norm_info.max_rot try: self.max_delta_rot = norm_info.max_delta_rot except: # old versions of", "1] data.force_vec /= norm_info.force_vec_max # density -> [0, 1] data.density", "iterate through self.reset() def normalize_data(self, data, norm_info): ''' Normalizes (in", "''' Load normalization info into this object from a specified", "1 if after self.topple_label = np.zeros((self.size, self.num_steps), dtype=int) # other", "# print(batch.lin_vel[0]) # print(batch.toppled[0]) # print(batch.delta_rot_split[0]) # print(batch.delta_rot[0]) # print(batch.topple_label[0])", "axis-angle rep (4-vec) self.delta_rot_split = np.zeros((self.size, self.num_steps, 4)) # 0", "every single simulation # ( though if the sequence length", "norm_info.inertia_offset self.inertia_max = norm_info.inertia_max try: self.friction_offset = norm_info.friction_offset self.friction_max =", "has_next_batch(self): ''' Returns false if done with the current \"epoch\"", "than sim length the unique sequences contained # in the", "focus_toppling=False): ''' Returns a random contiguous sequence from the simulation", "- num_pts : the number of points to use in", "using the ToppleNormalizationInfo. ''' # point clouds -> [-1, 1]", "= norm_info.density_max self.mass_offset = norm_info.mass_offset self.mass_max = norm_info.mass_max self.inertia_offset =", "self.use_delta_quat: batch.delta_quat[batch_size + i] = batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size +", "for this simulation pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale = self.data.scale[idx] #", "max([topple_idx - num_steps + 1, 0]) if min_idx >= max_start_step:", "our window is guaranteed to see some part of toppling", "desired sequence length pad_len = abs(max_start_step) lin_vel_list = self.data.lin_vel[idx] lin_vel_out", "if seq_topple_idx <= start_step: topple_label_out[:] = 1 elif seq_topple_idx <", "randomly perturb point clouds with. If None no perturbation is", "# now time sequence data # velocities -> [-1, 1]", "norm_info.inertia_max # friction -> [0, 1] if norm_info.friction_offset is not", "need to pad the end with repeat of data for", "= None # max 2-norm of a point in an", "topple_label_out = np.zeros((num_steps), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx >", "self.num_steps, 3)) self.ang_vel = np.zeros((self.size, self.num_steps, 3)) self.pos = np.zeros((self.size,", "> 0: topple_label_out[seq_topple_idx:] = 1 else: start_step = 0 if", "self.density_max = None self.mass_offset = None self.mass_max = None self.inertia_offset", "sequences contained # in the dataset will be much more", "np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa: delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step]) if", "ToppleNormalizationInfo(): ''' Structure to hold all the normalization information for", "the point cloud self.num_pts = self.data.point_cloud.shape[1] # load in normalization", "max element of any angular vel vector self.max_ang_vel = None", "norm_info.max_ang_vel) for x in ang_vel_steps] # delta position -> [-1,", "size num_steps sequence from the simulation to return time-series data", "if self.use_aa_split: delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx: topple_label_out = np.zeros((num_steps),", "= np.zeros((self.size)) self.scale = np.zeros((self.size, 3)) self.rot_euler = np.zeros((self.size, self.num_steps,", "scale accordingly pc *= np.reshape(scale, (1, -1)) # randomly perturb", "= ToppleDataLoader() self.data = data_loader.load_data(roots) if num_pts is None: #", "shuffles the returned sequence ordering - num_pts : the number", "meta_info def get_norm_info(self): return self.norm_info if __name__=='__main__': # norm_info =", "def print_out(self): print({'max_lin_vel' : self.max_lin_vel, 'max_ang_vel' : self.max_ang_vel, 'max_pos' :", "# ( though if the sequence length is shorter than", "doesn't have max delta rot pass self.force_vec_max = norm_info.force_vec_max self.pc_max", "np.zeros((self.size, 3)) self.rot_euler = np.zeros((self.size, self.num_steps, 3)) class ToppleDataset(object): '''", "seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0: topple_label_out[seq_topple_idx:] = 1", "- num_steps : number of timesteps to return in each", "False if len(self.data.delta_rot) > 0: self.use_aa = True if len(self.data.delta_rot_split)", "data.body_friction = (data.body_friction - norm_info.friction_offset) / norm_info.friction_max # now time", "except: # old version doesn't have this pass class ToppleBatch(object):", "perturb_pts : the stdev to randomly perturb point clouds with.", "None # max angle of rotation between two steps for", "vel vector self.max_lin_vel = None # max element of any", "self.use_aa: delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split: delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step]) if", "pos batch.rot[i] = rot if self.use_delta_quat: batch.delta_quat[i] = delta_quat if", "delta rotation -> [-1, 1] for i, rot_steps in enumerate(data.total_rot):", "impulse vector self.force_vec_max = None # max 2-norm of a", "# force pos -> [-1, 1] data.force_pos /= norm_info.pc_max #", "object point cloud (used for point cloud and force pos)", "xrot, yrot, axes='szxy') # unity applies euler angles in z,", "+ [ang_vel_list[-1]]*pad_len) pos_list = self.data.pos[idx] pos_out = np.array(pos_list + [pos_list[-1]]*pad_len)", "of a point in an object point cloud (used for", "batch.rot_euler[i] batch.mass[batch_size + i] = batch.mass[i] if self.use_aa: batch.delta_rot[batch_size +", "guaranteed to see some part of toppling start_step = np.random.randint(min_idx,", "randomly shuffles the returned sequence ordering - num_pts : the", "self.use_topple_idx: topple_label_out = np.zeros((total_steps + pad_len), dtype=int) seq_topple_idx = self.data.topple_idx[idx]", "info object to a specified .pkl file. ''' with open(pkl_file,", "- norm_info_file : .pkl file containing normalization information - batch_size", "= np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len) if self.use_aa: delta_rot_list = self.data.delta_rot[idx] delta_rot_out", "lin_vel, ang_vel, pos, rot, delta_quat, delta_rot, delta_rot_split, topple_label, meta_info =", "sequence - shuffle : randomly shuffles the returned sequence ordering", "hold all the normalization information for a dataset. ''' def", "ang_vel_out, pos_out, rot_out, delta_quat_out, delta_rot_out, delta_rot_split_out, topple_label_out, meta_info def get_norm_info(self):", "cloud self.num_pts = self.data.point_cloud.shape[1] # load in normalization info if", "True if len(self.data.delta_rot_split) > 0: self.use_aa_split = True if len(self.data.topple_idx)", "of data for i in range(self.batch_size - batch_size): batch.point_cloud[batch_size +", "of data. if random_window=True will get a random sequence of", "if self.use_aa: batch.delta_rot[batch_size + i] = batch.delta_rot[i] if self.use_aa_split: batch.delta_rot_split[batch_size", "# max angle of rotation between two steps for axis-angle", "delta_rot_steps] # make axes unit and and normalize angle ->", "False self.use_delta_quat = False if len(self.data.delta_rot) > 0: self.use_aa =", "density -> [0, 1] data.density = (data.density - norm_info.density_offset) /", "i] = batch.delta_rot[i] if self.use_aa_split: batch.delta_rot_split[batch_size + i] = batch.delta_rot_split[i]", "directories containing data to load for this dataset - norm_info_file", "= batch.scale[i] batch.rot_euler[batch_size + i] = batch.rot_euler[i] batch.mass[batch_size + i]", "seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0: if seq_topple_idx <=", "self.use_delta_quat: delta_quat_out = None return pc, lin_vel_out, ang_vel_out, pos_out, rot_out,", "the sequence where toppling occurs. ''' # size is either", ": self.mass_offset, \\ 'mass_max' : self.mass_max, 'inertia_off' : self.inertia_offset, 'inertia_max'", "pc = np.dot(pc, R.T) toppled = self.data.toppled[idx] shape_name = self.data.shape_name[idx]", "point cloud to align with first frame of sequence init_rot", "cloud pc += np.random.normal(0.0, self.perturb_std, pc.shape) # randomly draw a", "x in ang_vel_steps] # delta position -> [-1, 1] for", "accordingly pc *= np.reshape(scale, (1, -1)) # randomly perturb point", "self.use_body_friction: body_fric = self.data.body_friction[idx] meta_info = (toppled, shape_name, scale, euler_rot_out,", "topple idx, 1 if after self.topple_label = np.zeros((self.size, self.num_steps), dtype=int)", "to pad the end with repeat of data for i", "for training and model evaluation. ''' def __init__(self, roots, norm_info_file,", "normalizing!') # order to iterate through data when returning batches", "current \"epoch\" (seen each sim once). ''' return self.batch_idx <", "batch_size): batch.point_cloud[batch_size + i] = batch.point_cloud[i] batch.lin_vel[batch_size + i] =", "+ i] = batch.ang_vel[i] batch.pos[batch_size + i] = batch.pos[i] batch.rot[batch_size", "/ norm_info.max_rot) for x in rot_steps] # delta rot axis-angle", "a subset of points if desired if self.num_pts < pc.shape[0]:", "!= self.batch_size: # need to pad the end with repeat", "= None if not self.use_aa_split: delta_rot_split_out = None if not", "euler_rot_list = self.data.rot_euler[idx] euler_rot_out = np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len) if self.use_aa:", "at the end of the data start_idx = self.batch_idx *", "change in rotation between steps in axis-angle rep (scaled 3", "None self.density_max = None self.mass_offset = None self.mass_max = None", "will be much more than an epoch length ) self.num_batches", "with. If None no perturbation is performed. - ''' #", "dataset - norm_info_file : .pkl file containing normalization information -", "Structure to hold a single batch of data. ''' def", "''' Returns a random contiguous sequence from the simulation at", "self.rot_euler = np.zeros((self.size, self.num_steps, 3)) class ToppleDataset(object): ''' Loads toppling", "not exists(root): print('Could not find dataset at ' + root)", "in an object point cloud (used for point cloud and", "# print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0]))) print('Total num batches: ' + str(count))", "points in the data. - perturb_pts : the stdev to", "= -1.0 if self.use_body_friction: body_fric = self.data.body_friction[idx] meta_info = (toppled,", "( though if the sequence length is shorter than sim", "data.inertia = (data.inertia - norm_info.inertia_offset) / norm_info.inertia_max # friction ->", "root) return data_loader = ToppleDataLoader() self.data = data_loader.load_data(roots) if num_pts", "print_out(self): print({'max_lin_vel' : self.max_lin_vel, 'max_ang_vel' : self.max_ang_vel, 'max_pos' : self.max_pos,", "= np.zeros((self.size, 3)) self.rot_euler = np.zeros((self.size, self.num_steps, 3)) class ToppleDataset(object):", "self.data.delta_rot_split[idx] delta_rot_split_out = np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx: topple_label_out =", "the dataset will be much more than an epoch length", "batch = topple_data.next_batch(random_window=True, focus_toppling=False) count += 1 # print(batch.lin_vel[0]) #", "of any angular vel vector self.max_ang_vel = None # max", "self.steps_per_seq = num_steps self.shuffle = shuffle self.perturb_std = perturb_pts self.num_pts", "size, seq_len, num_pts): self.size = size self.num_steps = seq_len self.num_pts", "delta_rot_steps in enumerate(data.delta_rot): data.delta_rot[i] = [(x / norm_info.max_delta_rot) for x", "i] = batch.mass[i] if self.use_aa: batch.delta_rot[batch_size + i] = batch.delta_rot[i]", "count += 1 # print(batch.lin_vel[0]) # print(batch.toppled[0]) # print(batch.delta_rot_split[0]) #", "lin_vel_out = np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len) ang_vel_list = self.data.ang_vel[idx] ang_vel_out =", "cloud to align with first frame of sequence init_rot =", "the points in the point cloud self.num_pts = self.data.point_cloud.shape[1] #", "= topple_data.next_batch(random_window=True, focus_toppling=False) count += 1 # print(batch.lin_vel[0]) # print(batch.toppled[0])", "not directly used in network self.toppled = [] self.shape_name =", "[-1, 1] for i, pos_steps in enumerate(data.pos): data.pos[i] = [(x", "+ i] = batch.rot_euler[i] batch.mass[batch_size + i] = batch.mass[i] if", "''' Saves normalization info object to a specified .pkl file.", "If num_steps > sim_length the final (sim_length-num_steps) steps are padded", "self.max_rot, 'max_delta_rot' : self.max_delta_rot, 'force_vec_max' : self.force_vec_max, 'pc_max' : self.pc_max,", "self.steps_per_seq, random_window, focus_toppling) batch.point_cloud[i] = pc batch.lin_vel[i] = lin_vel batch.ang_vel[i]", "= self.data.topple_idx[idx] if seq_topple_idx > 0: topple_label_out[seq_topple_idx:] = 1 else:", "= [np.append(x[:3] / np.linalg.norm(x[:3]), x[3] / norm_info.max_delta_rot) for x in", "self.batch_idx = 0 def has_next_batch(self): ''' Returns false if done", "# randomly draw a subset of points if desired if", "normalization info object and copies them to this one '''", "count += 1 print(batch.size) print('Total num batches: ' + str(count))", "mass -> [0, 1] data.mass = (data.mass - norm_info.mass_offset) /", "= end_idx - start_idx # get batch data batch =", "import sys import math from topple_data_loader import ToppleData, ToppleDataLoader import", "1] if norm_info.friction_offset is not None: data.body_friction = (data.body_friction -", "of any linear vel vector self.max_lin_vel = None # max", "ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded normalization info!') # see if we have", "import transforms3d class ToppleNormalizationInfo(): ''' Structure to hold all the", "is shorter than sim length the unique sequences contained #", "if self.use_topple_idx: topple_label_out = np.zeros((total_steps + pad_len), dtype=int) seq_topple_idx =", "''' # settings self.batch_size = batch_size self.steps_per_seq = num_steps self.shuffle", "np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len) if self.use_aa: delta_rot_list = self.data.delta_rot[idx] delta_rot_out =", "batch.rot[batch_size + i] = batch.rot[i] if self.use_delta_quat: batch.delta_quat[batch_size + i]", "i] = batch.body_friction[i] self.batch_idx += 1 return batch def get_seq(self,", "= abs(max_start_step) lin_vel_list = self.data.lin_vel[idx] lin_vel_out = np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len)", "directly used in network self.toppled = [] self.shape_name = []", "angular vel vector self.max_ang_vel = None # max distance between", "= True if len(self.data.delta_rot_split) > 0: self.use_aa_split = True if", "canonical point cloud for this simulation pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale", "[ang_vel_list[-1]]*pad_len) pos_list = self.data.pos[idx] pos_out = np.array(pos_list + [pos_list[-1]]*pad_len) rot_list", "of sequences to return in each batch - num_steps :", "batch.body_friction[i] self.batch_idx += 1 return batch def get_seq(self, idx, num_steps,", "[np.append(x[:3] / np.linalg.norm(x[:3]), x[3] / norm_info.max_delta_rot) for x in delta_rot_split_steps]", "to align with first frame of sequence init_rot = self.data.rot_euler[idx][start_step]", "more than an epoch length ) self.num_batches = (self.data.size +", "self.mass = np.zeros((self.size)) self.scale = np.zeros((self.size, 3)) self.rot_euler = np.zeros((self.size,", "normalization values for shape-related stuff self.density_offset = None self.density_max =", "in rot_steps] # delta rot axis-angle -> [-1, 1] norm", "toppling data and provides batches for training and model evaluation.", "simulation is shorter than desired sequence length pad_len = abs(max_start_step)", "cloud. If None uses all points in the data. -", "rotation between two steps for axis-angle representation self.max_delta_rot = None", "for x in pos_steps] # delta rotation -> [-1, 1]", "i] = batch.pos[i] batch.rot[batch_size + i] = batch.rot[i] if self.use_delta_quat:", "batch.delta_rot[i] = delta_rot if self.use_aa_split: batch.delta_rot_split[i] = delta_rot_split if self.use_topple_idx:", "# unity applies euler angles in z, x, y ordering", "num_pts is None: # use all the points in the", "norm_info.max_ang_vel self.max_pos = norm_info.max_pos self.max_rot = norm_info.max_rot try: self.max_delta_rot =", "= np.zeros((self.size, self.num_steps, 3)) # change in rotation between steps", "the part of the sequence where toppling occurs. ''' #", "= batch.mass[i] if self.use_aa: batch.delta_rot[batch_size + i] = batch.delta_rot[i] if", "pos_steps] # delta rotation -> [-1, 1] for i, rot_steps", "self.data.toppled[idx]: # choose window around the index where it topples", "= 1 else: start_step = 0 if random_window: if focus_toppling", "perturb_pts=0.0): ''' - roots : list of directories containing data", "'inertia_max' : self.inertia_max, \\ 'friction_off' : self.friction_offset, 'friction_max' : self.friction_max", "range(0, self.data.size) # prepare to iterate through self.reset() def normalize_data(self,", "with first frame of sequence init_rot = self.data.rot_euler[idx][start_step] xrot, yrot,", "# get the normalized canonical point cloud for this simulation", "''' return self.batch_idx < self.num_batches def next_batch(self, random_window=True, focus_toppling=False): '''", "= (self.data.size + self.batch_size - 1) // self.batch_size self.batch_idx =", "pick the max index start_step = max_start_step else: # our", "in the data. - perturb_pts : the stdev to randomly", "any linear vel vector self.max_lin_vel = None # max element", "% (start_step, end_step)) lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out", "self.batch_idx += 1 return batch def get_seq(self, idx, num_steps, random_window=True,", "is performed. - ''' # settings self.batch_size = batch_size self.steps_per_seq", "by default) self.iter_inds = range(0, self.data.size) # prepare to iterate", "normalization info into this object from a specified .pkl file.", "self.body_friction = np.zeros((self.size)) self.mass = np.zeros((self.size)) self.scale = np.zeros((self.size, 3))", "in the dataset will be much more than an epoch", "lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out = np.array(self.data.pos[idx][start_step:end_step]) rot_out", "of applied impulse vector self.force_vec_max = None # max 2-norm", "import numpy as np import pickle from os.path import exists,", "self.max_lin_vel = None # max element of any angular vel", "info into this object from a specified .pkl file. '''", "[-1, 1] for i, rot_steps in enumerate(data.total_rot): data.total_rot[i] = [(x", "cloud and force pos) self.pc_max = None # normalization values", "i] = batch.delta_rot_split[i] if self.use_topple_idx: batch.topple_label[batch_size + i] = batch.topple_label[i]", "num_steps. If num_steps > sim_length the final (sim_length-num_steps) steps are", "self.num_pts, replace=False) pc = pc[pc_inds, :] # randomly choose a", "through dataset. ''' if self.shuffle: np.random.shuffle(self.iter_inds) # we consider an", "info at ' + norm_info_file) return self.norm_info = ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file)", "= (toppled, shape_name, scale, euler_rot_out, body_fric, mass) if not self.use_aa:", "''' Returns the next batch of data. if random_window=True will", "object to a specified .pkl file. ''' with open(pkl_file, 'wb')", "a specified .pkl file. ''' with open(pkl_file, 'wb') as f:", "np.zeros((self.size, self.num_steps, 4)) # 0 if before topple idx, 1", "# norm_info = ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out() topple_data =", "# we consider an epoch as returning one sequence from", "self.max_delta_rot = None # max 2-norm of applied impulse vector", "if num_pts is None: # use all the points in", "ToppleDataLoader() self.data = data_loader.load_data(roots) if num_pts is None: # use", "epoch length ) self.num_batches = (self.data.size + self.batch_size - 1)", "%d, %d' % (start_step, end_step)) lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out =", "# size is either batch_size, or shorter if we're at", "= self.data.delta_rot_split[idx] delta_rot_split_out = np.array(delta_rot_split_list + [delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx: topple_label_out", "if self.use_aa: batch.delta_rot[i] = delta_rot if self.use_aa_split: batch.delta_rot_split[i] = delta_rot_split", "from a specified .pkl file. ''' with open(pkl_file, 'rb') as", "reset(self): ''' Prepares to iterate through dataset. ''' if self.shuffle:", "# force vec -> [-1, 1] data.force_vec /= norm_info.force_vec_max #", "= np.zeros((self.size, self.num_steps), dtype=int) # other meta-data not directly used", "end_idx - start_idx # get batch data batch = ToppleBatch(self.batch_size,", "toppling occurs. ''' # size is either batch_size, or shorter", "= self.data.shape_name[idx] mass = self.data.mass[idx] body_fric = -1.0 if self.use_body_friction:", "uses all points in the data. - perturb_pts : the", "dataset. ''' def __init__(self): # max element of any linear", "self.get_seq(self.iter_inds[start_idx + i], self.steps_per_seq, random_window, focus_toppling) batch.point_cloud[i] = pc batch.lin_vel[i]", "topple_data.has_next_batch(): batch = topple_data.next_batch(random_window=True, focus_toppling=False) count += 1 # print(batch.lin_vel[0])", "batch.shape_name.append(meta_info[1]) batch.scale[i] = meta_info[2] batch.rot_euler[i] = meta_info[3] if self.use_body_friction: batch.body_friction[i]", "angles self.rot = np.zeros((self.size, self.num_steps, 3)) # change in rotation", "an epoch length ) self.num_batches = (self.data.size + self.batch_size -", "normalization info if not exists(norm_info_file): print('Could not find normalization info", "print('Loaded normalization info!') # see if we have axis-angle info", "''' - roots : list of directories containing data to", "(data.body_friction - norm_info.friction_offset) / norm_info.friction_max # now time sequence data", "batch.lin_vel[i] = lin_vel batch.ang_vel[i] = ang_vel batch.pos[i] = pos batch.rot[i]", "+ i] = batch.body_friction[i] self.batch_idx += 1 return batch def", "if self.use_body_friction: batch.body_friction[batch_size + i] = batch.body_friction[i] self.batch_idx += 1", "if not self.use_aa: delta_rot_out = None if not self.use_aa_split: delta_rot_split_out", "in range(batch_size): pc, lin_vel, ang_vel, pos, rot, delta_quat, delta_rot, delta_rot_split,", "= 0 while topple_data.has_next_batch(): batch = topple_data.next_batch(random_window=True, focus_toppling=False) count +=", "first frame of sequence init_rot = self.data.rot_euler[idx][start_step] xrot, yrot, zrot", "part of toppling start_step = np.random.randint(min_idx, max_start_step+1) else: start_step =", "norm_info.friction_max except: # old version doesn't have this pass class", "will get a random sequence of correct length (otherwise starts", "batch.pos[batch_size + i] = batch.pos[i] batch.rot[batch_size + i] = batch.rot[i]", "and force pos) self.pc_max = None # normalization values for", "self.batch_size: # need to pad the end with repeat of", "topple_label_out, meta_info def get_norm_info(self): return self.norm_info if __name__=='__main__': # norm_info", "norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out() topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5, num_steps=10,", "pickle.dump(self, f) def load_from(self, pkl_file): ''' Load normalization info into", "topple_data.next_batch() count += 1 print(batch.size) print('Total num batches: ' +", "if self.use_delta_quat: delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa:", "+ 1) * self.batch_size, self.data.size) batch_size = end_idx - start_idx", "- shuffle : randomly shuffles the returned sequence ordering -", "3)) # change in rotation in quaternion rep (w, x,", "= topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i] = meta_info[2] batch.rot_euler[i] = meta_info[3]", "list of directories containing data to load for this dataset", "pass class ToppleBatch(object): ''' Structure to hold a single batch", "get the normalized canonical point cloud for this simulation pc", "it topples topple_idx = self.data.topple_idx[idx] min_idx = max([topple_idx - num_steps", "norm_info.max_delta_rot) for x in delta_rot_steps] # make axes unit and", "None # max element of any angular vel vector self.max_ang_vel", "sim[sim_length]. ''' # get the normalized canonical point cloud for", "ang_vel_list = self.data.ang_vel[idx] ang_vel_out = np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len) pos_list =", "doesn't have this pass class ToppleBatch(object): ''' Structure to hold", "split axis-angle rep (4-vec) self.delta_rot_split = np.zeros((self.size, self.num_steps, 4)) #", "= self.data.total_rot[idx] rot_out = np.array(rot_list + [rot_list[-1]]*pad_len) if self.use_delta_quat: delta_quat_list", "to return in each batch - num_steps : number of", "if self.num_pts < pc.shape[0]: pc_inds = np.random.choice(pc.shape[0], self.num_pts, replace=False) pc", "# choose window around the index where it topples topple_idx", "all the normalization information for a dataset. ''' def __init__(self):", "batch.topple_label[batch_size + i] = batch.topple_label[i] if self.use_body_friction: batch.body_friction[batch_size + i]", "x, y ordering pc = np.dot(pc, R.T) toppled = self.data.toppled[idx]", "to use in the returned point cloud. If None uses", ": the stdev to randomly perturb point clouds with. If", "batch.delta_rot_split[i] if self.use_topple_idx: batch.topple_label[batch_size + i] = batch.topple_label[i] if self.use_body_friction:", "make axes unit and and normalize angle -> [-1, 1]", "in pos_steps] # delta rotation -> [-1, 1] for i,", "self.data = data_loader.load_data(roots) if num_pts is None: # use all", "self.data.total_rot[idx] rot_out = np.array(rot_list + [rot_list[-1]]*pad_len) if self.use_delta_quat: delta_quat_list =", "pc.shape[0]: pc_inds = np.random.choice(pc.shape[0], self.num_pts, replace=False) pc = pc[pc_inds, :]", "[-1, 1] data.force_pos /= norm_info.pc_max # force vec -> [-1,", "if not self.use_topple_idx: topple_label_out = None if not self.use_delta_quat: delta_quat_out", "def get_norm_info(self): return self.norm_info if __name__=='__main__': # norm_info = ToppleNormalizationInfo()", "of points to use in the returned point cloud. If", "norm_info.density_max self.mass_offset = norm_info.mass_offset self.mass_max = norm_info.mass_max self.inertia_offset = norm_info.inertia_offset", "* self.batch_size end_idx = min((self.batch_idx + 1) * self.batch_size, self.data.size)", "ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5, num_steps=10, shuffle=True, num_pts=None, perturb_pts=0.01) count =", "batch.scale[i] = meta_info[2] batch.rot_euler[i] = meta_info[3] if self.use_body_friction: batch.body_friction[i] =", "= (data.density - norm_info.density_offset) / norm_info.density_max # mass -> [0,", "< pc.shape[0]: pc_inds = np.random.choice(pc.shape[0], self.num_pts, replace=False) pc = pc[pc_inds,", "batch.pos[i] = pos batch.rot[i] = rot if self.use_delta_quat: batch.delta_quat[i] =", "self.data.point_cloud.shape[1] # load in normalization info if not exists(norm_info_file): print('Could", "each sequence - shuffle : randomly shuffles the returned sequence", "len(self.data.lin_vel[idx]) max_start_step = total_steps - num_steps start_step = 0 if", "\\ 'max_rot' : self.max_rot, 'max_delta_rot' : self.max_delta_rot, 'force_vec_max' : self.force_vec_max,", "# delta rot axis-angle -> [-1, 1] norm if self.use_aa:", ": self.density_offset, 'density_max' : self.density_max, 'mass_off' : self.mass_offset, \\ 'mass_max'", "ToppleData using the ToppleNormalizationInfo. ''' # point clouds -> [-1,", "# max element of any angular vel vector self.max_ang_vel =", "versions of data doesn't have max delta rot pass self.force_vec_max", "vector self.max_ang_vel = None # max distance between positions in", "2-norm of a point in an object point cloud (used", "self.inertia_offset, 'inertia_max' : self.inertia_max, \\ 'friction_off' : self.friction_offset, 'friction_max' :", "i] = batch.scale[i] batch.rot_euler[batch_size + i] = batch.rot_euler[i] batch.mass[batch_size +", "norm_info.friction_offset self.friction_max = norm_info.friction_max except: # old version doesn't have", "normalization info at ' + norm_info_file) return self.norm_info = ToppleNormalizationInfo()", "self.use_aa_split: for i, delta_rot_split_steps in enumerate(data.delta_rot_split): data.delta_rot_split[i] = [np.append(x[:3] /", "# need to pad the end with repeat of data", "pos -> [-1, 1] data.force_pos /= norm_info.pc_max # force vec", "= self.data.pos[idx] pos_out = np.array(pos_list + [pos_list[-1]]*pad_len) rot_list = self.data.total_rot[idx]", "in rotation around any axis between two contiguous timesteps (for", "the data start_idx = self.batch_idx * self.batch_size end_idx = min((self.batch_idx", "i] = batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size + i] = batch.scale[i]", "max_start_step: # just pick the max index start_step = max_start_step", "norm_info.max_pos) for x in pos_steps] # delta rotation -> [-1,", "ang_vel batch.pos[i] = pos batch.rot[i] = rot if self.use_delta_quat: batch.delta_quat[i]", "while topple_data.has_next_batch(): batch = topple_data.next_batch() count += 1 print(batch.size) print('Total", "print(batch.pos) # print(batch.body_friction) # print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0]))) print('Total", "self.mass_offset, \\ 'mass_max' : self.mass_max, 'inertia_off' : self.inertia_offset, 'inertia_max' :", "+ [lin_vel_list[-1]]*pad_len) ang_vel_list = self.data.ang_vel[idx] ang_vel_out = np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len)", "__init__(self): # max element of any linear vel vector self.max_lin_vel", "not self.use_topple_idx: topple_label_out = None if not self.use_delta_quat: delta_quat_out =", "normalize_data(self, data, norm_info): ''' Normalizes (in place) the given ToppleData", "normalization info object to a specified .pkl file. ''' with", "\\ 'density_off' : self.density_offset, 'density_max' : self.density_max, 'mass_off' : self.mass_offset,", "other meta-data not directly used in network self.toppled = []", "i in range(batch_size): pc, lin_vel, ang_vel, pos, rot, delta_quat, delta_rot,", "self.data.size) # prepare to iterate through self.reset() def normalize_data(self, data,", "np.zeros((total_steps + pad_len), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx >", "self.data.shape_name[idx] mass = self.data.mass[idx] body_fric = -1.0 if self.use_body_friction: body_fric", "math from topple_data_loader import ToppleData, ToppleDataLoader import transforms3d class ToppleNormalizationInfo():", "euler angles self.rot = np.zeros((self.size, self.num_steps, 3)) # change in", "if max_start_step < 0: # simulation is shorter than desired", "file. ''' with open(pkl_file, 'wb') as f: pickle.dump(self, f) def", ":] # randomly choose a size num_steps sequence from the", "' + root) return data_loader = ToppleDataLoader() self.data = data_loader.load_data(roots)", "sim length the unique sequences contained # in the dataset", "shape-related stuff self.density_offset = None self.density_max = None self.mass_offset =", "data when returning batches (in order by default) self.iter_inds =", "steps are padded with the value at sim[sim_length]. ''' #", "1] norm if self.use_aa: for i, delta_rot_steps in enumerate(data.delta_rot): data.delta_rot[i]", "topple_data.reset() count = 0 while topple_data.has_next_batch(): batch = topple_data.next_batch() count", "None no perturbation is performed. - ''' # settings self.batch_size", "sequence init_rot = self.data.rot_euler[idx][start_step] xrot, yrot, zrot = np.radians(init_rot) R", "pkl_file): ''' Saves normalization info object to a specified .pkl", "None self.inertia_max = None self.friction_offset = None self.friction_max = None", "f: norm_info = pickle.load(f) self.copy_from(norm_info) def copy_from(self, norm_info): ''' Takes", "with open(pkl_file, 'rb') as f: norm_info = pickle.load(f) self.copy_from(norm_info) def", "= None if not self.use_topple_idx: topple_label_out = None if not", "if len(self.data.body_friction) > 0: self.use_body_friction = True if len(self.data.delta_quat) >", "self.friction_offset = norm_info.friction_offset self.friction_max = norm_info.friction_max except: # old version", "batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i] = meta_info[2] batch.rot_euler[i] = meta_info[3] if self.use_body_friction:", "batch.delta_quat[batch_size + i] = batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size + i]", "self.data.delta_quat[idx] delta_quat_out = np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len) euler_rot_list = self.data.rot_euler[idx] euler_rot_out", "sequences to return in each batch - num_steps : number", "in enumerate(data.total_rot): data.total_rot[i] = [(x / norm_info.max_rot) for x in", "(4-vec) self.delta_rot_split = np.zeros((self.size, self.num_steps, 4)) # 0 if before", "rep (4-vec) self.delta_rot_split = np.zeros((self.size, self.num_steps, 4)) # 0 if", "at sim[sim_length]. ''' # get the normalized canonical point cloud", "axes='szxy') # unity applies euler angles in z, x, y", "max index start_step = max_start_step else: # our window is", "norm_info.print_out() topple_data = ToppleDataset(roots=['./data/sim/Cube/Cube30k_ObjSplit/Cube30kVal'], norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5, num_steps=10, shuffle=True, num_pts=None,", "not self.use_delta_quat: delta_quat_out = None return pc, lin_vel_out, ang_vel_out, pos_out,", "[delta_rot_list[-1]]*pad_len) if self.use_aa_split: delta_rot_split_list = self.data.delta_rot_split[idx] delta_rot_split_out = np.array(delta_rot_split_list +", "= self.data.ang_vel[idx] ang_vel_out = np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len) pos_list = self.data.pos[idx]", "(data.density - norm_info.density_offset) / norm_info.density_max # mass -> [0, 1]", "min((self.batch_idx + 1) * self.batch_size, self.data.size) batch_size = end_idx -", "subset of points if desired if self.num_pts < pc.shape[0]: pc_inds", "self.data.rot_euler[idx] euler_rot_out = np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len) if self.use_aa: delta_rot_list =", "np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out = np.array(self.data.pos[idx][start_step:end_step]) rot_out = np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat: delta_quat_out", "self.max_delta_rot, 'force_vec_max' : self.force_vec_max, 'pc_max' : self.pc_max, \\ 'density_off' :", "None # max 2-norm of applied impulse vector self.force_vec_max =", "print(batch.toppled[0]) # print(batch.delta_rot_split[0]) # print(batch.delta_rot[0]) # print(batch.topple_label[0]) # print(batch.pos) #", ": self.density_max, 'mass_off' : self.mass_offset, \\ 'mass_max' : self.mass_max, 'inertia_off'", "np.zeros((self.size, self.num_steps, 4)) # change in rotation between steps in", "0: # simulation is shorter than desired sequence length pad_len", "__init__(self, size, seq_len, num_pts): self.size = size self.num_steps = seq_len", "much more than an epoch length ) self.num_batches = (self.data.size", "pad the end with repeat of data for i in", "''' if self.shuffle: np.random.shuffle(self.iter_inds) # we consider an epoch as", "returning batches (in order by default) self.iter_inds = range(0, self.data.size)", "max 2-norm of applied impulse vector self.force_vec_max = None #", "shuffle=False, num_pts=None, perturb_pts=0.0): ''' - roots : list of directories", "self.use_topple_idx: topple_label_out = np.zeros((num_steps), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx", "= delta_quat if self.use_aa: batch.delta_rot[i] = delta_rot if self.use_aa_split: batch.delta_rot_split[i]", "print('Could not find dataset at ' + root) return data_loader", "# print(batch.delta_rot_split[0]) # print(batch.delta_rot[0]) # print(batch.topple_label[0]) # print(batch.pos) # print(batch.body_friction)", "num_pts : the number of points to use in the", "'friction_off' : self.friction_offset, 'friction_max' : self.friction_max }) def save(self, pkl_file):", "axis between two contiguous timesteps (for euler rot) self.max_rot =", "# friction -> [0, 1] if norm_info.friction_offset is not None:", "self.mass_max = None self.inertia_offset = None self.inertia_max = None self.friction_offset", "inertia -> [0, 1] data.inertia = (data.inertia - norm_info.inertia_offset) /", "self.density_max = norm_info.density_max self.mass_offset = norm_info.mass_offset self.mass_max = norm_info.mass_max self.inertia_offset", "data. - perturb_pts : the stdev to randomly perturb point", "= meta_info[5] if batch_size != self.batch_size: # need to pad", "< self.num_batches def next_batch(self, random_window=True, focus_toppling=False): ''' Returns the next", "(data.inertia - norm_info.inertia_offset) / norm_info.inertia_max # friction -> [0, 1]", "# print(batch.topple_label[0]) # print(batch.pos) # print(batch.body_friction) # print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0,", "in the returned point cloud. If None uses all points", "starts at 0). If focus_toppling=True, will make sure this sequence", "batch.delta_rot_split[batch_size + i] = batch.delta_rot_split[i] if self.use_topple_idx: batch.topple_label[batch_size + i]", "scale = self.data.scale[idx] # scale accordingly pc *= np.reshape(scale, (1,", "self.norm_info) print('Finished normalizing!') # order to iterate through data when", "= None def print_out(self): print({'max_lin_vel' : self.max_lin_vel, 'max_ang_vel' : self.max_ang_vel,", "/ norm_info.max_lin_vel) for x in lin_vel_steps] for i, ang_vel_steps in", "self.force_vec_max = None # max 2-norm of a point in", "None # max distance between positions in two contiguous timesteps", "start_idx = self.batch_idx * self.batch_size end_idx = min((self.batch_idx + 1)", "start_step = np.random.randint(0, max_start_step+1) end_step = start_step + num_steps #", "false if done with the current \"epoch\" (seen each sim", "self.force_vec_max = norm_info.force_vec_max self.pc_max = norm_info.pc_max self.density_offset = norm_info.density_offset self.density_max", "old versions of data doesn't have max delta rot pass", "4)) # 0 if before topple idx, 1 if after", "euler rot) self.max_rot = None # max angle of rotation", "max element of any linear vel vector self.max_lin_vel = None", "- norm_info.density_offset) / norm_info.density_max # mass -> [0, 1] data.mass", "(scaled 3 vec) self.delta_rot = np.zeros((self.size, self.num_steps, 3)) # change", "given ToppleData using the ToppleNormalizationInfo. ''' # point clouds ->", "num_pts self.point_cloud = np.zeros((self.size, self.num_pts, 3)) self.lin_vel = np.zeros((self.size, self.num_steps,", "# max 2-norm of a point in an object point", "'force_vec_max' : self.force_vec_max, 'pc_max' : self.pc_max, \\ 'density_off' : self.density_offset,", "num_steps # print('Range: %d, %d' % (start_step, end_step)) lin_vel_out =", "an object point cloud (used for point cloud and force", "pc, lin_vel, ang_vel, pos, rot, delta_quat, delta_rot, delta_rot_split, topple_label, meta_info", "for this dataset - norm_info_file : .pkl file containing normalization", "data.point_cloud /= norm_info.pc_max # force pos -> [-1, 1] data.force_pos", "where it topples topple_idx = self.data.topple_idx[idx] min_idx = max([topple_idx -", "np.zeros((self.size, self.num_pts, 3)) self.lin_vel = np.zeros((self.size, self.num_steps, 3)) self.ang_vel =", "for x in lin_vel_steps] for i, ang_vel_steps in enumerate(data.ang_vel): data.ang_vel[i]", "''' Returns false if done with the current \"epoch\" (seen", "else: start_step = np.random.randint(0, max_start_step+1) end_step = start_step + num_steps", "than desired sequence length pad_len = abs(max_start_step) lin_vel_list = self.data.lin_vel[idx]", "= None if not self.use_delta_quat: delta_quat_out = None return pc,", "point clouds -> [-1, 1] data.point_cloud /= norm_info.pc_max # force", "angles in z, x, y ordering pc = np.dot(pc, R.T)", "0). If focus_toppling=True, will make sure this sequence includes the", "contiguous timesteps (for euler rot) self.max_rot = None # max", "start_idx # get batch data batch = ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts)", "num_steps=10, shuffle=True, num_pts=None, perturb_pts=0.01) count = 0 while topple_data.has_next_batch(): batch", "self.use_aa_split: delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx: topple_label_out = np.zeros((num_steps), dtype=int)", "norm if self.use_aa: for i, delta_rot_steps in enumerate(data.delta_rot): data.delta_rot[i] =", "0]) if min_idx >= max_start_step: # just pick the max", "delta_rot, delta_rot_split, topple_label, meta_info = \\ self.get_seq(self.iter_inds[start_idx + i], self.steps_per_seq,", "copy_from(self, norm_info): ''' Takes values from the given normalization info", ": self.max_delta_rot, 'force_vec_max' : self.force_vec_max, 'pc_max' : self.pc_max, \\ 'density_off'", "if not self.use_delta_quat: delta_quat_out = None return pc, lin_vel_out, ang_vel_out,", "= batch.lin_vel[i] batch.ang_vel[batch_size + i] = batch.ang_vel[i] batch.pos[batch_size + i]", "a random contiguous sequence from the simulation at the given", "+ i] = batch.rot[i] if self.use_delta_quat: batch.delta_quat[batch_size + i] =", "info if not exists(norm_info_file): print('Could not find normalization info at", "in each batch - num_steps : number of timesteps to", "start_step = 0 if random_window: if focus_toppling and self.data.toppled[idx]: #", "in enumerate(data.delta_rot_split): data.delta_rot_split[i] = [np.append(x[:3] / np.linalg.norm(x[:3]), x[3] / norm_info.max_delta_rot)", "= lin_vel batch.ang_vel[i] = ang_vel batch.pos[i] = pos batch.rot[i] =", "+ [delta_rot_list[-1]]*pad_len) if self.use_aa_split: delta_rot_split_list = self.data.delta_rot_split[idx] delta_rot_split_out = np.array(delta_rot_split_list", "= delta_rot_split if self.use_topple_idx: batch.topple_label[i] = topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i]", "ang_vel_out = np.array(ang_vel_list + [ang_vel_list[-1]]*pad_len) pos_list = self.data.pos[idx] pos_out =", "meta_info = (toppled, shape_name, scale, euler_rot_out, body_fric, mass) if not", "num_steps > sim_length the final (sim_length-num_steps) steps are padded with", "+ [delta_rot_split_list[-1]]*pad_len) if self.use_topple_idx: topple_label_out = np.zeros((total_steps + pad_len), dtype=int)", "pc.shape) # randomly draw a subset of points if desired", "- start_idx # get batch data batch = ToppleBatch(self.batch_size, self.steps_per_seq,", "self.data.size) batch_size = end_idx - start_idx # get batch data", "import ToppleData, ToppleDataLoader import transforms3d class ToppleNormalizationInfo(): ''' Structure to", "'density_off' : self.density_offset, 'density_max' : self.density_max, 'mass_off' : self.mass_offset, \\", "None self.mass_max = None self.inertia_offset = None self.inertia_max = None", "data doesn't have max delta rot pass self.force_vec_max = norm_info.force_vec_max", "= np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out = np.array(self.data.pos[idx][start_step:end_step]) rot_out = np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat:", "if batch_size != self.batch_size: # need to pad the end", "' + norm_info_file) return self.norm_info = ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded normalization", "self.num_pts, 3)) self.lin_vel = np.zeros((self.size, self.num_steps, 3)) self.ang_vel = np.zeros((self.size,", "'max_ang_vel' : self.max_ang_vel, 'max_pos' : self.max_pos, \\ 'max_rot' : self.max_rot,", "load in normalization info if not exists(norm_info_file): print('Could not find", "point cloud and force pos) self.pc_max = None # normalization", "self.data.toppled[idx] shape_name = self.data.shape_name[idx] mass = self.data.mass[idx] body_fric = -1.0", "prepare to iterate through self.reset() def normalize_data(self, data, norm_info): '''", "time-series data total_steps = len(self.data.lin_vel[idx]) max_start_step = total_steps - num_steps", "if len(self.data.topple_idx) > 0: self.use_topple_idx = True if len(self.data.body_friction) >", "# just pick the max index start_step = max_start_step else:", "mass) if not self.use_aa: delta_rot_out = None if not self.use_aa_split:", "euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa: delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split:", "length pad_len = abs(max_start_step) lin_vel_list = self.data.lin_vel[idx] lin_vel_out = np.array(lin_vel_list", "if after self.topple_label = np.zeros((self.size, self.num_steps), dtype=int) # other meta-data", "stdev to randomly perturb point clouds with. If None no", "0: self.use_aa_split = True if len(self.data.topple_idx) > 0: self.use_topple_idx =", "enumerate(data.total_rot): data.total_rot[i] = [(x / norm_info.max_rot) for x in rot_steps]", "max angle of rotation between two steps for axis-angle representation", "self.use_topple_idx = True if len(self.data.body_friction) > 0: self.use_body_friction = True", "= perturb_pts self.num_pts = num_pts # load in data for", "self.num_pts) for i in range(batch_size): pc, lin_vel, ang_vel, pos, rot,", "[-1, 1] data.force_vec /= norm_info.force_vec_max # density -> [0, 1]", "around the index where it topples topple_idx = self.data.topple_idx[idx] min_idx", "have this pass class ToppleBatch(object): ''' Structure to hold a", "print('Normalizing data...') self.normalize_data(self.data, self.norm_info) print('Finished normalizing!') # order to iterate", ".pkl file. ''' with open(pkl_file, 'wb') as f: pickle.dump(self, f)", "# print(batch.body_friction) # print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0]))) print('Total num", "steps for axis-angle representation self.max_delta_rot = None # max 2-norm", "lin_vel_steps in enumerate(data.lin_vel): data.lin_vel[i] = [(x / norm_info.max_lin_vel) for x", "-1)) # randomly perturb point cloud pc += np.random.normal(0.0, self.perturb_std,", "batch_size=32, num_steps=15, shuffle=False, num_pts=None, perturb_pts=0.0): ''' - roots : list", "of directories containing data to load for this dataset -", "[rot_list[-1]]*pad_len) if self.use_delta_quat: delta_quat_list = self.data.delta_quat[idx] delta_quat_out = np.array(delta_quat_list +", "delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split: delta_rot_split_out = np.array(self.data.delta_rot_split[idx][start_step:end_step]) if self.use_topple_idx:", "self.friction_max }) def save(self, pkl_file): ''' Saves normalization info object", "self.num_steps, 3)) # change in rotation between steps in split", "min_idx = max([topple_idx - num_steps + 1, 0]) if min_idx", "find dataset at ' + root) return data_loader = ToppleDataLoader()", "= np.zeros((num_steps), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0:", "class ToppleDataset(object): ''' Loads toppling data and provides batches for", "batch data batch = ToppleBatch(self.batch_size, self.steps_per_seq, self.num_pts) for i in", "max change in rotation around any axis between two contiguous", "[pos_list[-1]]*pad_len) rot_list = self.data.total_rot[idx] rot_out = np.array(rot_list + [rot_list[-1]]*pad_len) if", "ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out = np.array(self.data.pos[idx][start_step:end_step]) rot_out = np.array(self.data.total_rot[idx][start_step:end_step]) if", "roots, norm_info_file, batch_size=32, num_steps=15, shuffle=False, num_pts=None, perturb_pts=0.0): ''' - roots", "in quaternion rep (w, x, y, z) self.delta_quat = np.zeros((self.size,", "from topple_data_loader import ToppleData, ToppleDataLoader import transforms3d class ToppleNormalizationInfo(): '''", "return self.batch_idx < self.num_batches def next_batch(self, random_window=True, focus_toppling=False): ''' Returns", ".pkl file containing normalization information - batch_size : number of", "number of sequences to return in each batch - num_steps", "# load in normalization info if not exists(norm_info_file): print('Could not", "+ i] = batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size + i] =", "in enumerate(data.pos): data.pos[i] = [(x / norm_info.max_pos) for x in", "= self.data.lin_vel[idx] lin_vel_out = np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len) ang_vel_list = self.data.ang_vel[idx]", "batch.rot[i] = rot if self.use_delta_quat: batch.delta_quat[i] = delta_quat if self.use_aa:", "__init__(self, roots, norm_info_file, batch_size=32, num_steps=15, shuffle=False, num_pts=None, perturb_pts=0.0): ''' -", "batch.body_friction[batch_size + i] = batch.body_friction[i] self.batch_idx += 1 return batch", "# simulation is shorter than desired sequence length pad_len =", "performed. - ''' # settings self.batch_size = batch_size self.steps_per_seq =", "np.zeros((self.size)) self.scale = np.zeros((self.size, 3)) self.rot_euler = np.zeros((self.size, self.num_steps, 3))", "= min((self.batch_idx + 1) * self.batch_size, self.data.size) batch_size = end_idx", "= norm_info.force_vec_max self.pc_max = norm_info.pc_max self.density_offset = norm_info.density_offset self.density_max =", "be much more than an epoch length ) self.num_batches =", "self.batch_size = batch_size self.steps_per_seq = num_steps self.shuffle = shuffle self.perturb_std", "os.path import exists, realpath import sys import math from topple_data_loader", "the given ToppleData using the ToppleNormalizationInfo. ''' # point clouds", "if len(self.data.delta_rot_split) > 0: self.use_aa_split = True if len(self.data.topple_idx) >", "\\ 'mass_max' : self.mass_max, 'inertia_off' : self.inertia_offset, 'inertia_max' : self.inertia_max,", "+ i] = batch.mass[i] if self.use_aa: batch.delta_rot[batch_size + i] =", "self.data.topple_idx[idx] if seq_topple_idx > 0: if seq_topple_idx <= start_step: topple_label_out[:]", "random contiguous sequence from the simulation at the given idx", "= True # normalize the data print('Normalizing data...') self.normalize_data(self.data, self.norm_info)", "self.use_aa_split: batch.delta_rot_split[i] = delta_rot_split if self.use_topple_idx: batch.topple_label[i] = topple_label batch.toppled.append(meta_info[0])", "# max change in rotation around any axis between two", "= np.array(pos_list + [pos_list[-1]]*pad_len) rot_list = self.data.total_rot[idx] rot_out = np.array(rot_list", "see some part of toppling start_step = np.random.randint(min_idx, max_start_step+1) else:", "/ norm_info.mass_max # inertia -> [0, 1] data.inertia = (data.inertia", "False self.use_aa_split = False self.use_topple_idx = False self.use_delta_quat = False", "return data_loader = ToppleDataLoader() self.data = data_loader.load_data(roots) if num_pts is", "info (for backwards compat) self.use_aa = False self.use_aa_split = False", "of sequence init_rot = self.data.rot_euler[idx][start_step] xrot, yrot, zrot = np.radians(init_rot)", "iterate through dataset. ''' if self.shuffle: np.random.shuffle(self.iter_inds) # we consider", "self.use_topple_idx: topple_label_out = None if not self.use_delta_quat: delta_quat_out = None", "random_window, focus_toppling) batch.point_cloud[i] = pc batch.lin_vel[i] = lin_vel batch.ang_vel[i] =", "= [(x / norm_info.max_delta_rot) for x in delta_rot_steps] # make", "print(batch.delta_rot[0]) # print(batch.topple_label[0]) # print(batch.pos) # print(batch.body_friction) # print(batch.delta_quat[0]) #", "> 0: self.use_body_friction = True if len(self.data.delta_quat) > 0: self.use_delta_quat", "= max_start_step else: # our window is guaranteed to see", "if min_idx >= max_start_step: # just pick the max index", "= np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat: delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step])", "information - batch_size : number of sequences to return in", "the next batch of data. if random_window=True will get a", "= self.data.delta_quat[idx] delta_quat_out = np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len) euler_rot_list = self.data.rot_euler[idx]", "None # max 2-norm of a point in an object", "norm_info.max_lin_vel self.max_ang_vel = norm_info.max_ang_vel self.max_pos = norm_info.max_pos self.max_rot = norm_info.max_rot", "[] self.body_friction = np.zeros((self.size)) self.mass = np.zeros((self.size)) self.scale = np.zeros((self.size,", "np.random.choice(pc.shape[0], self.num_pts, replace=False) pc = pc[pc_inds, :] # randomly choose", "normalize angle -> [-1, 1] if self.use_aa_split: for i, delta_rot_split_steps", "= np.random.choice(pc.shape[0], self.num_pts, replace=False) pc = pc[pc_inds, :] # randomly", "pc[pc_inds, :] # randomly choose a size num_steps sequence from", "pickle from os.path import exists, realpath import sys import math", "change in rotation around any axis between two contiguous timesteps", "+ i] = batch.point_cloud[i] batch.lin_vel[batch_size + i] = batch.lin_vel[i] batch.ang_vel[batch_size", "topple_label_out[:] = 1 elif seq_topple_idx < end_step: topple_label_out[seq_topple_idx-start_step:] = 1", "position -> [-1, 1] for i, pos_steps in enumerate(data.pos): data.pos[i]", "self.max_lin_vel, 'max_ang_vel' : self.max_ang_vel, 'max_pos' : self.max_pos, \\ 'max_rot' :", "get_seq(self, idx, num_steps, random_window=True, focus_toppling=False): ''' Returns a random contiguous", "copies them to this one ''' self.max_lin_vel = norm_info.max_lin_vel self.max_ang_vel", "rep (w, x, y, z) self.delta_quat = np.zeros((self.size, self.num_steps, 4))", "self.pos = np.zeros((self.size, self.num_steps, 3)) # cummulative euler angles self.rot", "[] self.shape_name = [] self.body_friction = np.zeros((self.size)) self.mass = np.zeros((self.size))", "i, lin_vel_steps in enumerate(data.lin_vel): data.lin_vel[i] = [(x / norm_info.max_lin_vel) for", "Normalizes (in place) the given ToppleData using the ToppleNormalizationInfo. '''", "through self.reset() def normalize_data(self, data, norm_info): ''' Normalizes (in place)", ": self.pc_max, \\ 'density_off' : self.density_offset, 'density_max' : self.density_max, 'mass_off'", "i] = batch.rot_euler[i] batch.mass[batch_size + i] = batch.mass[i] if self.use_aa:", "/= norm_info.pc_max # force vec -> [-1, 1] data.force_vec /=", "at 0). If focus_toppling=True, will make sure this sequence includes", "# print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0]))) print('Total num batches: '", "# change in rotation between steps in split axis-angle rep", "norm_info.density_offset) / norm_info.density_max # mass -> [0, 1] data.mass =", "delta_quat_out, delta_rot_out, delta_rot_split_out, topple_label_out, meta_info def get_norm_info(self): return self.norm_info if", "norm_info.density_offset self.density_max = norm_info.density_max self.mass_offset = norm_info.mass_offset self.mass_max = norm_info.mass_max", "batch_size != self.batch_size: # need to pad the end with", "= [] self.shape_name = [] self.body_friction = np.zeros((self.size)) self.mass =", "pc = pc[pc_inds, :] # randomly choose a size num_steps", "= self.data.mass[idx] body_fric = -1.0 if self.use_body_friction: body_fric = self.data.body_friction[idx]", "the normalization information for a dataset. ''' def __init__(self): #", "positions in two contiguous timesteps self.max_pos = None # max", "num_steps=15, shuffle=False, num_pts=None, perturb_pts=0.0): ''' - roots : list of", "(w, x, y, z) self.delta_quat = np.zeros((self.size, self.num_steps, 4)) #", "batch.rot_euler[batch_size + i] = batch.rot_euler[i] batch.mass[batch_size + i] = batch.mass[i]", "Load normalization info into this object from a specified .pkl", "single simulation # ( though if the sequence length is", "focus_toppling=True, will make sure this sequence includes the part of", "pc, lin_vel_out, ang_vel_out, pos_out, rot_out, delta_quat_out, delta_rot_out, delta_rot_split_out, topple_label_out, meta_info", "a random sequence of correct length (otherwise starts at 0).", "abs(max_start_step) lin_vel_list = self.data.lin_vel[idx] lin_vel_out = np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len) ang_vel_list", "-> [0, 1] data.density = (data.density - norm_info.density_offset) / norm_info.density_max", "/= norm_info.force_vec_max # density -> [0, 1] data.density = (data.density", "data to load for this dataset - norm_info_file : .pkl", "the given normalization info object and copies them to this", "the returned sequence ordering - num_pts : the number of", "not exists(norm_info_file): print('Could not find normalization info at ' +", "i] = batch.ang_vel[i] batch.pos[batch_size + i] = batch.pos[i] batch.rot[batch_size +", "np.dot(pc, R.T) toppled = self.data.toppled[idx] shape_name = self.data.shape_name[idx] mass =", "no perturbation is performed. - ''' # settings self.batch_size =", "print(batch.body_friction) # print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0]))) print('Total num batches:", "return batch def get_seq(self, idx, num_steps, random_window=True, focus_toppling=False): ''' Returns", "topple_label_out = None if not self.use_delta_quat: delta_quat_out = None return", "and copies them to this one ''' self.max_lin_vel = norm_info.max_lin_vel", "= np.zeros((self.size, self.num_steps, 4)) # 0 if before topple idx,", "in network self.toppled = [] self.shape_name = [] self.body_friction =", "= np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out = np.array(self.data.pos[idx][start_step:end_step]) rot_out =", "self.use_aa: batch.delta_rot[batch_size + i] = batch.delta_rot[i] if self.use_aa_split: batch.delta_rot_split[batch_size +", "as np import pickle from os.path import exists, realpath import", "i] = batch.point_cloud[i] batch.lin_vel[batch_size + i] = batch.lin_vel[i] batch.ang_vel[batch_size +", "= None # max element of any angular vel vector", "self.friction_max = None def print_out(self): print({'max_lin_vel' : self.max_lin_vel, 'max_ang_vel' :", "old version doesn't have this pass class ToppleBatch(object): ''' Structure", "3)) self.rot_euler = np.zeros((self.size, self.num_steps, 3)) class ToppleDataset(object): ''' Loads", "num_steps, random_window=True, focus_toppling=False): ''' Returns a random contiguous sequence from", "self.data.mass[idx] body_fric = -1.0 if self.use_body_friction: body_fric = self.data.body_friction[idx] meta_info", "+ pad_len), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if seq_topple_idx > 0:", "order to iterate through data when returning batches (in order", "norm_info.mass_max # inertia -> [0, 1] data.inertia = (data.inertia -", "= \\ self.get_seq(self.iter_inds[start_idx + i], self.steps_per_seq, random_window, focus_toppling) batch.point_cloud[i] =", "choose a size num_steps sequence from the simulation to return", "print(batch.topple_label[0]) # print(batch.pos) # print(batch.body_friction) # print(batch.delta_quat[0]) # print(np.degrees(2*np.arccos(batch.delta_quat[0, :,", "3)) class ToppleDataset(object): ''' Loads toppling data and provides batches", "norm_info.max_pos self.max_rot = norm_info.max_rot try: self.max_delta_rot = norm_info.max_delta_rot except: #", "delta_rot_out = np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len) if self.use_aa_split: delta_rot_split_list = self.data.delta_rot_split[idx]", "0: if seq_topple_idx <= start_step: topple_label_out[:] = 1 elif seq_topple_idx", "self.num_steps), dtype=int) # other meta-data not directly used in network", "> 0: self.use_aa = True if len(self.data.delta_rot_split) > 0: self.use_aa_split", "make sure this sequence includes the part of the sequence", "min_idx >= max_start_step: # just pick the max index start_step", "1] data.density = (data.density - norm_info.density_offset) / norm_info.density_max # mass", "body_fric = self.data.body_friction[idx] meta_info = (toppled, shape_name, scale, euler_rot_out, body_fric,", "[0, 1] data.inertia = (data.inertia - norm_info.inertia_offset) / norm_info.inertia_max #", "self.data.topple_idx[idx] min_idx = max([topple_idx - num_steps + 1, 0]) if", "np.linalg.norm(x[:3]), x[3] / norm_info.max_delta_rot) for x in delta_rot_split_steps] def reset(self):", "x[3] / norm_info.max_delta_rot) for x in delta_rot_split_steps] def reset(self): '''", "# change in rotation between steps in axis-angle rep (scaled", "batch.lin_vel[batch_size + i] = batch.lin_vel[i] batch.ang_vel[batch_size + i] = batch.ang_vel[i]", "num_pts=None, perturb_pts=0.0): ''' - roots : list of directories containing", "unity applies euler angles in z, x, y ordering pc", "the end with repeat of data for i in range(self.batch_size", "i] = batch.topple_label[i] if self.use_body_friction: batch.body_friction[batch_size + i] = batch.body_friction[i]", "point clouds with. If None no perturbation is performed. -", "seq_len self.num_pts = num_pts self.point_cloud = np.zeros((self.size, self.num_pts, 3)) self.lin_vel", "= 0 def has_next_batch(self): ''' Returns false if done with", "norm_info.max_lin_vel) for x in lin_vel_steps] for i, ang_vel_steps in enumerate(data.ang_vel):", "__name__=='__main__': # norm_info = ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') # norm_info.print_out() topple_data", "= norm_info.density_offset self.density_max = norm_info.density_max self.mass_offset = norm_info.mass_offset self.mass_max =", "vel vector self.max_ang_vel = None # max distance between positions", "self.max_ang_vel = None # max distance between positions in two", "self.data.rot_euler[idx][start_step] xrot, yrot, zrot = np.radians(init_rot) R = transforms3d.euler.euler2mat(zrot, xrot,", "self.num_batches = (self.data.size + self.batch_size - 1) // self.batch_size self.batch_idx", "# max 2-norm of applied impulse vector self.force_vec_max = None", "contained # in the dataset will be much more than", "each sim once). ''' return self.batch_idx < self.num_batches def next_batch(self,", "force vec -> [-1, 1] data.force_vec /= norm_info.force_vec_max # density", "we consider an epoch as returning one sequence from every", "= seq_len self.num_pts = num_pts self.point_cloud = np.zeros((self.size, self.num_pts, 3))", "at ' + norm_info_file) return self.norm_info = ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded", "of the sequence where toppling occurs. ''' # size is", "return time-series data total_steps = len(self.data.lin_vel[idx]) max_start_step = total_steps -", "for i in range(self.batch_size - batch_size): batch.point_cloud[batch_size + i] =", "vec -> [-1, 1] data.force_vec /= norm_info.force_vec_max # density ->", "containing data to load for this dataset - norm_info_file :", "simulation to return time-series data total_steps = len(self.data.lin_vel[idx]) max_start_step =", "+ 1, 0]) if min_idx >= max_start_step: # just pick", "1] for i, pos_steps in enumerate(data.pos): data.pos[i] = [(x /", "+ [rot_list[-1]]*pad_len) if self.use_delta_quat: delta_quat_list = self.data.delta_quat[idx] delta_quat_out = np.array(delta_quat_list", "-> [0, 1] data.inertia = (data.inertia - norm_info.inertia_offset) / norm_info.inertia_max", "stuff self.density_offset = None self.density_max = None self.mass_offset = None", "if self.use_aa_split: batch.delta_rot_split[i] = delta_rot_split if self.use_topple_idx: batch.topple_label[i] = topple_label", "mass = self.data.mass[idx] body_fric = -1.0 if self.use_body_friction: body_fric =", "= norm_info.mass_offset self.mass_max = norm_info.mass_max self.inertia_offset = norm_info.inertia_offset self.inertia_max =", "x in rot_steps] # delta rot axis-angle -> [-1, 1]", "self.norm_info if __name__=='__main__': # norm_info = ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl') #", "= data_loader.load_data(roots) if num_pts is None: # use all the", "batch.point_cloud[i] = pc batch.lin_vel[i] = lin_vel batch.ang_vel[i] = ang_vel batch.pos[i]", "self.use_aa: delta_rot_out = None if not self.use_aa_split: delta_rot_split_out = None", "= np.zeros((self.size, self.num_steps, 4)) # change in rotation between steps", "pos, rot, delta_quat, delta_rot, delta_rot_split, topple_label, meta_info = \\ self.get_seq(self.iter_inds[start_idx", "in the point cloud self.num_pts = self.data.point_cloud.shape[1] # load in", "np.radians(init_rot) R = transforms3d.euler.euler2mat(zrot, xrot, yrot, axes='szxy') # unity applies", "rot_out = np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat: delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out =", "self.iter_inds = range(0, self.data.size) # prepare to iterate through self.reset()", "self.num_steps, 4)) # change in rotation between steps in axis-angle", "find normalization info at ' + norm_info_file) return self.norm_info =", "y, z) self.delta_quat = np.zeros((self.size, self.num_steps, 4)) # change in", ": self.max_lin_vel, 'max_ang_vel' : self.max_ang_vel, 'max_pos' : self.max_pos, \\ 'max_rot'", "delta_rot_split_out = None if not self.use_topple_idx: topple_label_out = None if", "friction -> [0, 1] if norm_info.friction_offset is not None: data.body_friction", "align with first frame of sequence init_rot = self.data.rot_euler[idx][start_step] xrot,", "contiguous timesteps self.max_pos = None # max change in rotation", "1] for i, rot_steps in enumerate(data.total_rot): data.total_rot[i] = [(x /", "= np.zeros((self.size, self.num_steps, 3)) self.pos = np.zeros((self.size, self.num_steps, 3)) #", ": self.inertia_offset, 'inertia_max' : self.inertia_max, \\ 'friction_off' : self.friction_offset, 'friction_max'", "print(np.degrees(2*np.arccos(batch.delta_quat[0, :, 0]))) print('Total num batches: ' + str(count)) topple_data.reset()", "of data. ''' def __init__(self, size, seq_len, num_pts): self.size =", "= np.zeros((self.size, self.num_steps, 3)) self.ang_vel = np.zeros((self.size, self.num_steps, 3)) self.pos", "= None self.friction_max = None def print_out(self): print({'max_lin_vel' : self.max_lin_vel,", ": the number of points to use in the returned", "the number of points to use in the returned point", "/ norm_info.max_delta_rot) for x in delta_rot_steps] # make axes unit", "for i, lin_vel_steps in enumerate(data.lin_vel): data.lin_vel[i] = [(x / norm_info.max_lin_vel)", "for i, delta_rot_steps in enumerate(data.delta_rot): data.delta_rot[i] = [(x / norm_info.max_delta_rot)", "includes the part of the sequence where toppling occurs. '''", "3)) self.pos = np.zeros((self.size, self.num_steps, 3)) # cummulative euler angles", "unit and and normalize angle -> [-1, 1] if self.use_aa_split:", "normalization information for a dataset. ''' def __init__(self): # max", "to iterate through self.reset() def normalize_data(self, data, norm_info): ''' Normalizes", "number of points to use in the returned point cloud.", "# mass -> [0, 1] data.mass = (data.mass - norm_info.mass_offset)", "we're at the end of the data start_idx = self.batch_idx", "in data for root in roots: if not exists(root): print('Could", "settings self.batch_size = batch_size self.steps_per_seq = num_steps self.shuffle = shuffle", "'inertia_off' : self.inertia_offset, 'inertia_max' : self.inertia_max, \\ 'friction_off' : self.friction_offset,", "\\ 'friction_off' : self.friction_offset, 'friction_max' : self.friction_max }) def save(self,", "self.batch_size end_idx = min((self.batch_idx + 1) * self.batch_size, self.data.size) batch_size", "in rotation between steps in axis-angle rep (scaled 3 vec)", "True # normalize the data print('Normalizing data...') self.normalize_data(self.data, self.norm_info) print('Finished", "lin_vel_steps] for i, ang_vel_steps in enumerate(data.ang_vel): data.ang_vel[i] = [(x /", "and length num_steps. If num_steps > sim_length the final (sim_length-num_steps)", "batch = topple_data.next_batch() count += 1 print(batch.size) print('Total num batches:", "max_start_step = total_steps - num_steps start_step = 0 if max_start_step", "= batch.delta_rot[i] if self.use_aa_split: batch.delta_rot_split[batch_size + i] = batch.delta_rot_split[i] if", "batch.rot_euler[i] = meta_info[3] if self.use_body_friction: batch.body_friction[i] = meta_info[4] batch.mass[i] =", "self.shuffle: np.random.shuffle(self.iter_inds) # we consider an epoch as returning one", "the ToppleNormalizationInfo. ''' # point clouds -> [-1, 1] data.point_cloud", "in z, x, y ordering pc = np.dot(pc, R.T) toppled", "sys import math from topple_data_loader import ToppleData, ToppleDataLoader import transforms3d", "delta_quat_list = self.data.delta_quat[idx] delta_quat_out = np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len) euler_rot_list =", "(otherwise starts at 0). If focus_toppling=True, will make sure this", "[euler_rot_list[-1]]*pad_len) if self.use_aa: delta_rot_list = self.data.delta_rot[idx] delta_rot_out = np.array(delta_rot_list +", "-> [-1, 1] for i, rot_steps in enumerate(data.total_rot): data.total_rot[i] =", "x in delta_rot_steps] # make axes unit and and normalize", "window is guaranteed to see some part of toppling start_step", "<= start_step: topple_label_out[:] = 1 elif seq_topple_idx < end_step: topple_label_out[seq_topple_idx-start_step:]", "between positions in two contiguous timesteps self.max_pos = None #", "= self.batch_idx * self.batch_size end_idx = min((self.batch_idx + 1) *", "if len(self.data.delta_rot) > 0: self.use_aa = True if len(self.data.delta_rot_split) >", "the end of the data start_idx = self.batch_idx * self.batch_size", "If None no perturbation is performed. - ''' # settings", "None def print_out(self): print({'max_lin_vel' : self.max_lin_vel, 'max_ang_vel' : self.max_ang_vel, 'max_pos'", "in delta_rot_steps] # make axes unit and and normalize angle", "delta_rot_split_steps] def reset(self): ''' Prepares to iterate through dataset. '''", "body_fric, mass) if not self.use_aa: delta_rot_out = None if not", "open(pkl_file, 'wb') as f: pickle.dump(self, f) def load_from(self, pkl_file): '''", "def __init__(self, size, seq_len, num_pts): self.size = size self.num_steps =", "# print(batch.toppled[0]) # print(batch.delta_rot_split[0]) # print(batch.delta_rot[0]) # print(batch.topple_label[0]) # print(batch.pos)", "+ i] = batch.topple_label[i] if self.use_body_friction: batch.body_friction[batch_size + i] =", "enumerate(data.delta_rot): data.delta_rot[i] = [(x / norm_info.max_delta_rot) for x in delta_rot_steps]", "returning one sequence from every single simulation # ( though", "with the value at sim[sim_length]. ''' # get the normalized", "in rotation in quaternion rep (w, x, y, z) self.delta_quat", "- batch_size : number of sequences to return in each", "= batch.body_friction[i] self.batch_idx += 1 return batch def get_seq(self, idx,", "points to use in the returned point cloud. If None", "= num_steps self.shuffle = shuffle self.perturb_std = perturb_pts self.num_pts =", "force pos -> [-1, 1] data.force_pos /= norm_info.pc_max # force", "point cloud for this simulation pc = np.copy(self.data.point_cloud[self.data.shape_idx[idx]]) scale =", "None if not self.use_delta_quat: delta_quat_out = None return pc, lin_vel_out,", "[delta_quat_list[-1]]*pad_len) euler_rot_list = self.data.rot_euler[idx] euler_rot_out = np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len) if", "= True if len(self.data.topple_idx) > 0: self.use_topple_idx = True if", "print('Could not find normalization info at ' + norm_info_file) return", "= pickle.load(f) self.copy_from(norm_info) def copy_from(self, norm_info): ''' Takes values from", "if self.use_topple_idx: batch.topple_label[i] = topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i] = meta_info[2]", "index start_step = max_start_step else: # our window is guaranteed", "-1.0 if self.use_body_friction: body_fric = self.data.body_friction[idx] meta_info = (toppled, shape_name,", "data.delta_rot[i] = [(x / norm_info.max_delta_rot) for x in delta_rot_steps] #", "max_start_step else: # our window is guaranteed to see some", "if self.use_aa: delta_rot_list = self.data.delta_rot[idx] delta_rot_out = np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len)", "delta rot pass self.force_vec_max = norm_info.force_vec_max self.pc_max = norm_info.pc_max self.density_offset", "(start_step, end_step)) lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step]) ang_vel_out = np.array(self.data.ang_vel[idx][start_step:end_step]) pos_out =", "delta_quat_out = None return pc, lin_vel_out, ang_vel_out, pos_out, rot_out, delta_quat_out,", "norm_info.friction_offset is not None: data.body_friction = (data.body_friction - norm_info.friction_offset) /", "np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len) ang_vel_list = self.data.ang_vel[idx] ang_vel_out = np.array(ang_vel_list +", "(used for point cloud and force pos) self.pc_max = None", "for point cloud and force pos) self.pc_max = None #", "in two contiguous timesteps self.max_pos = None # max change", "= self.data.delta_rot[idx] delta_rot_out = np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len) if self.use_aa_split: delta_rot_split_list", "norm_info_file='./data/sim/normalization_info/cube_30k.pkl', \\ batch_size=5, num_steps=10, shuffle=True, num_pts=None, perturb_pts=0.01) count = 0", "for i, rot_steps in enumerate(data.total_rot): data.total_rot[i] = [(x / norm_info.max_rot)", "pos_out = np.array(self.data.pos[idx][start_step:end_step]) rot_out = np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat: delta_quat_out =", "else: start_step = 0 if random_window: if focus_toppling and self.data.toppled[idx]:", "body_fric = -1.0 if self.use_body_friction: body_fric = self.data.body_friction[idx] meta_info =", "length ) self.num_batches = (self.data.size + self.batch_size - 1) //", "= size self.num_steps = seq_len self.num_pts = num_pts self.point_cloud =", "pc += np.random.normal(0.0, self.perturb_std, pc.shape) # randomly draw a subset", "point cloud. If None uses all points in the data.", "= batch.rot_euler[i] batch.mass[batch_size + i] = batch.mass[i] if self.use_aa: batch.delta_rot[batch_size", "in delta_rot_split_steps] def reset(self): ''' Prepares to iterate through dataset.", "None # normalization values for shape-related stuff self.density_offset = None", "self.num_pts = num_pts self.point_cloud = np.zeros((self.size, self.num_pts, 3)) self.lin_vel =", "two steps for axis-angle representation self.max_delta_rot = None # max", "data. ''' def __init__(self, size, seq_len, num_pts): self.size = size", "None if not self.use_topple_idx: topple_label_out = None if not self.use_delta_quat:", "is either batch_size, or shorter if we're at the end", "choose window around the index where it topples topple_idx =", "data_loader = ToppleDataLoader() self.data = data_loader.load_data(roots) if num_pts is None:", "(for euler rot) self.max_rot = None # max angle of", "1] data.force_pos /= norm_info.pc_max # force vec -> [-1, 1]", "final (sim_length-num_steps) steps are padded with the value at sim[sim_length].", "topple_idx = self.data.topple_idx[idx] min_idx = max([topple_idx - num_steps + 1,", "np.array(rot_list + [rot_list[-1]]*pad_len) if self.use_delta_quat: delta_quat_list = self.data.delta_quat[idx] delta_quat_out =", "import pickle from os.path import exists, realpath import sys import", "self.use_body_friction = True if len(self.data.delta_quat) > 0: self.use_delta_quat = True", "in ang_vel_steps] # delta position -> [-1, 1] for i,", "save(self, pkl_file): ''' Saves normalization info object to a specified", "= pc batch.lin_vel[i] = lin_vel batch.ang_vel[i] = ang_vel batch.pos[i] =", "# print('Range: %d, %d' % (start_step, end_step)) lin_vel_out = np.array(self.data.lin_vel[idx][start_step:end_step])", ": number of timesteps to return in each sequence -", "batch.point_cloud[batch_size + i] = batch.point_cloud[i] batch.lin_vel[batch_size + i] = batch.lin_vel[i]", "quaternion rep (w, x, y, z) self.delta_quat = np.zeros((self.size, self.num_steps,", "len(self.data.delta_rot) > 0: self.use_aa = True if len(self.data.delta_rot_split) > 0:", "= pc[pc_inds, :] # randomly choose a size num_steps sequence", "point cloud self.num_pts = self.data.point_cloud.shape[1] # load in normalization info", "np.array(pos_list + [pos_list[-1]]*pad_len) rot_list = self.data.total_rot[idx] rot_out = np.array(rot_list +", "point cloud pc += np.random.normal(0.0, self.perturb_std, pc.shape) # randomly draw", "desired if self.num_pts < pc.shape[0]: pc_inds = np.random.choice(pc.shape[0], self.num_pts, replace=False)", "yrot, zrot = np.radians(init_rot) R = transforms3d.euler.euler2mat(zrot, xrot, yrot, axes='szxy')", "# load in data for root in roots: if not", "= batch.delta_quat[i] batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size + i] = batch.scale[i] batch.rot_euler[batch_size", "though if the sequence length is shorter than sim length", "batch.delta_quat[i] = delta_quat if self.use_aa: batch.delta_rot[i] = delta_rot if self.use_aa_split:", "we have axis-angle info (for backwards compat) self.use_aa = False", "through data when returning batches (in order by default) self.iter_inds", "model evaluation. ''' def __init__(self, roots, norm_info_file, batch_size=32, num_steps=15, shuffle=False,", "return in each batch - num_steps : number of timesteps", "np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat: delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out = np.array(self.data.rot_euler[idx][start_step:end_step]) if", "normalize the data print('Normalizing data...') self.normalize_data(self.data, self.norm_info) print('Finished normalizing!') #", "/ norm_info.inertia_max # friction -> [0, 1] if norm_info.friction_offset is", "num_steps self.shuffle = shuffle self.perturb_std = perturb_pts self.num_pts = num_pts", "1 else: start_step = 0 if random_window: if focus_toppling and", ": self.force_vec_max, 'pc_max' : self.pc_max, \\ 'density_off' : self.density_offset, 'density_max'", "random_window=True, focus_toppling=False): ''' Returns the next batch of data. if", "= shuffle self.perturb_std = perturb_pts self.num_pts = num_pts # load", "(toppled, shape_name, scale, euler_rot_out, body_fric, mass) if not self.use_aa: delta_rot_out", "'pc_max' : self.pc_max, \\ 'density_off' : self.density_offset, 'density_max' : self.density_max,", "topple_label_out[seq_topple_idx:] = 1 else: start_step = 0 if random_window: if", "print('Total num batches: ' + str(count)) topple_data.reset() count = 0", "self.num_steps, 3)) self.pos = np.zeros((self.size, self.num_steps, 3)) # cummulative euler", "total_steps = len(self.data.lin_vel[idx]) max_start_step = total_steps - num_steps start_step =", "topple_label, meta_info = \\ self.get_seq(self.iter_inds[start_idx + i], self.steps_per_seq, random_window, focus_toppling)", "normalization info!') # see if we have axis-angle info (for", "-> [-1, 1] for i, lin_vel_steps in enumerate(data.lin_vel): data.lin_vel[i] =", "class ToppleNormalizationInfo(): ''' Structure to hold all the normalization information", "self.use_delta_quat = True # normalize the data print('Normalizing data...') self.normalize_data(self.data,", "axis-angle -> [-1, 1] norm if self.use_aa: for i, delta_rot_steps", "delta_rot_split_steps in enumerate(data.delta_rot_split): data.delta_rot_split[i] = [np.append(x[:3] / np.linalg.norm(x[:3]), x[3] /", "clouds -> [-1, 1] data.point_cloud /= norm_info.pc_max # force pos", "= batch.ang_vel[i] batch.pos[batch_size + i] = batch.pos[i] batch.rot[batch_size + i]", "4)) # change in rotation between steps in axis-angle rep", "num_steps + 1, 0]) if min_idx >= max_start_step: # just", "if self.use_body_friction: batch.body_friction[i] = meta_info[4] batch.mass[i] = meta_info[5] if batch_size", "R.T) toppled = self.data.toppled[idx] shape_name = self.data.shape_name[idx] mass = self.data.mass[idx]", "self.max_pos = None # max change in rotation around any", "epoch as returning one sequence from every single simulation #", "''' # point clouds -> [-1, 1] data.point_cloud /= norm_info.pc_max", "batch.ang_vel[batch_size + i] = batch.ang_vel[i] batch.pos[batch_size + i] = batch.pos[i]", "if self.use_aa_split: batch.delta_rot_split[batch_size + i] = batch.delta_rot_split[i] if self.use_topple_idx: batch.topple_label[batch_size", "True if len(self.data.body_friction) > 0: self.use_body_friction = True if len(self.data.delta_quat)", "pc batch.lin_vel[i] = lin_vel batch.ang_vel[i] = ang_vel batch.pos[i] = pos", "= [(x / norm_info.max_ang_vel) for x in ang_vel_steps] # delta", "- norm_info.mass_offset) / norm_info.mass_max # inertia -> [0, 1] data.inertia", "= topple_data.next_batch() count += 1 print(batch.size) print('Total num batches: '", "return self.norm_info = ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded normalization info!') # see", "than an epoch length ) self.num_batches = (self.data.size + self.batch_size", "use all the points in the point cloud self.num_pts =", "value at sim[sim_length]. ''' # get the normalized canonical point", "return self.norm_info if __name__=='__main__': # norm_info = ToppleNormalizationInfo() # norm_info.load_from('../../data/sim/normalization_info/cube_train.pkl')", "meta_info[3] if self.use_body_friction: batch.body_friction[i] = meta_info[4] batch.mass[i] = meta_info[5] if", "timesteps self.max_pos = None # max change in rotation around", "dataset at ' + root) return data_loader = ToppleDataLoader() self.data", "# our window is guaranteed to see some part of", "= start_step + num_steps # print('Range: %d, %d' % (start_step,", "normalization information - batch_size : number of sequences to return", "place) the given ToppleData using the ToppleNormalizationInfo. ''' # point", "+ norm_info_file) return self.norm_info = ToppleNormalizationInfo() self.norm_info.load_from(norm_info_file) print('Loaded normalization info!')", "batch - num_steps : number of timesteps to return in", "default) self.iter_inds = range(0, self.data.size) # prepare to iterate through", "perturb_pts=0.01) count = 0 while topple_data.has_next_batch(): batch = topple_data.next_batch(random_window=True, focus_toppling=False)", "self.use_aa_split: batch.delta_rot_split[batch_size + i] = batch.delta_rot_split[i] if self.use_topple_idx: batch.topple_label[batch_size +", "# make axes unit and and normalize angle -> [-1,", "# delta rotation -> [-1, 1] for i, rot_steps in", "time sequence data # velocities -> [-1, 1] for i,", "into this object from a specified .pkl file. ''' with", "1 # rotate point cloud to align with first frame", "given normalization info object and copies them to this one", "self.use_delta_quat: batch.delta_quat[i] = delta_quat if self.use_aa: batch.delta_rot[i] = delta_rot if", "self.density_max, 'mass_off' : self.mass_offset, \\ 'mass_max' : self.mass_max, 'inertia_off' :", "self.use_topple_idx: batch.topple_label[i] = topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i] = meta_info[2] batch.rot_euler[i]", "= np.array(lin_vel_list + [lin_vel_list[-1]]*pad_len) ang_vel_list = self.data.ang_vel[idx] ang_vel_out = np.array(ang_vel_list", "sequence includes the part of the sequence where toppling occurs.", "topple_label_out = np.zeros((total_steps + pad_len), dtype=int) seq_topple_idx = self.data.topple_idx[idx] if", "batch.toppled.append(batch.toppled[i]) batch.shape_name.append(batch.shape_name[i]) batch.scale[batch_size + i] = batch.scale[i] batch.rot_euler[batch_size + i]", "np.random.shuffle(self.iter_inds) # we consider an epoch as returning one sequence", "batch_size self.steps_per_seq = num_steps self.shuffle = shuffle self.perturb_std = perturb_pts", "sequence where toppling occurs. ''' # size is either batch_size,", "= meta_info[2] batch.rot_euler[i] = meta_info[3] if self.use_body_friction: batch.body_friction[i] = meta_info[4]", "draw a subset of points if desired if self.num_pts <", "np.random.randint(0, max_start_step+1) end_step = start_step + num_steps # print('Range: %d,", "and self.data.toppled[idx]: # choose window around the index where it", "euler angles in z, x, y ordering pc = np.dot(pc,", "[-1, 1] data.point_cloud /= norm_info.pc_max # force pos -> [-1,", "* self.batch_size, self.data.size) batch_size = end_idx - start_idx # get", "a size num_steps sequence from the simulation to return time-series", "data.total_rot[i] = [(x / norm_info.max_rot) for x in rot_steps] #", "from the simulation to return time-series data total_steps = len(self.data.lin_vel[idx])", "self.batch_idx * self.batch_size end_idx = min((self.batch_idx + 1) * self.batch_size,", "+= 1 # print(batch.lin_vel[0]) # print(batch.toppled[0]) # print(batch.delta_rot_split[0]) # print(batch.delta_rot[0])", "self.num_steps, 3)) class ToppleDataset(object): ''' Loads toppling data and provides", "in normalization info if not exists(norm_info_file): print('Could not find normalization", "= np.array(self.data.rot_euler[idx][start_step:end_step]) if self.use_aa: delta_rot_out = np.array(self.data.delta_rot[idx][start_step:end_step]) if self.use_aa_split: delta_rot_split_out", "rotation in quaternion rep (w, x, y, z) self.delta_quat =", "i, delta_rot_steps in enumerate(data.delta_rot): data.delta_rot[i] = [(x / norm_info.max_delta_rot) for", "batch_size : number of sequences to return in each batch", "np.zeros((self.size, self.num_steps, 3)) self.ang_vel = np.zeros((self.size, self.num_steps, 3)) self.pos =", "consider an epoch as returning one sequence from every single", "randomly perturb point cloud pc += np.random.normal(0.0, self.perturb_std, pc.shape) #", "delta_rot_list = self.data.delta_rot[idx] delta_rot_out = np.array(delta_rot_list + [delta_rot_list[-1]]*pad_len) if self.use_aa_split:", "= None self.friction_offset = None self.friction_max = None def print_out(self):", "self.use_body_friction: batch.body_friction[i] = meta_info[4] batch.mass[i] = meta_info[5] if batch_size !=", "self.inertia_max = None self.friction_offset = None self.friction_max = None def", "with the current \"epoch\" (seen each sim once). ''' return", "delta_rot_split if self.use_topple_idx: batch.topple_label[i] = topple_label batch.toppled.append(meta_info[0]) batch.shape_name.append(meta_info[1]) batch.scale[i] =", "# inertia -> [0, 1] data.inertia = (data.inertia - norm_info.inertia_offset)", "shape_name = self.data.shape_name[idx] mass = self.data.mass[idx] body_fric = -1.0 if", "np.zeros((self.size, self.num_steps, 3)) class ToppleDataset(object): ''' Loads toppling data and", "not self.use_aa: delta_rot_out = None if not self.use_aa_split: delta_rot_split_out =", "None self.inertia_offset = None self.inertia_max = None self.friction_offset = None", "max_start_step+1) end_step = start_step + num_steps # print('Range: %d, %d'", "to a specified .pkl file. ''' with open(pkl_file, 'wb') as", "this pass class ToppleBatch(object): ''' Structure to hold a single", "for x in delta_rot_split_steps] def reset(self): ''' Prepares to iterate", "= 0 if max_start_step < 0: # simulation is shorter", "def __init__(self): # max element of any linear vel vector", "self.perturb_std = perturb_pts self.num_pts = num_pts # load in data", "Prepares to iterate through dataset. ''' if self.shuffle: np.random.shuffle(self.iter_inds) #", "this dataset - norm_info_file : .pkl file containing normalization information", "self.topple_label = np.zeros((self.size, self.num_steps), dtype=int) # other meta-data not directly", "= delta_rot if self.use_aa_split: batch.delta_rot_split[i] = delta_rot_split if self.use_topple_idx: batch.topple_label[i]", "'mass_off' : self.mass_offset, \\ 'mass_max' : self.mass_max, 'inertia_off' : self.inertia_offset,", "# 0 if before topple idx, 1 if after self.topple_label", "[-1, 1] norm if self.use_aa: for i, delta_rot_steps in enumerate(data.delta_rot):", "vector self.force_vec_max = None # max 2-norm of a point", "perturb point cloud pc += np.random.normal(0.0, self.perturb_std, pc.shape) # randomly", "+= 1 return batch def get_seq(self, idx, num_steps, random_window=True, focus_toppling=False):", ">= max_start_step: # just pick the max index start_step =", "*= np.reshape(scale, (1, -1)) # randomly perturb point cloud pc", "batches for training and model evaluation. ''' def __init__(self, roots,", "sequence from the simulation to return time-series data total_steps =", "def next_batch(self, random_window=True, focus_toppling=False): ''' Returns the next batch of", "/ norm_info.max_ang_vel) for x in ang_vel_steps] # delta position ->", "norm_info_file, batch_size=32, num_steps=15, shuffle=False, num_pts=None, perturb_pts=0.0): ''' - roots :", "if self.use_delta_quat: delta_quat_list = self.data.delta_quat[idx] delta_quat_out = np.array(delta_quat_list + [delta_quat_list[-1]]*pad_len)", "norm_info.force_vec_max self.pc_max = norm_info.pc_max self.density_offset = norm_info.density_offset self.density_max = norm_info.density_max", "order by default) self.iter_inds = range(0, self.data.size) # prepare to", "- batch_size): batch.point_cloud[batch_size + i] = batch.point_cloud[i] batch.lin_vel[batch_size + i]", "euler_rot_out = np.array(euler_rot_list + [euler_rot_list[-1]]*pad_len) if self.use_aa: delta_rot_list = self.data.delta_rot[idx]", "batch.ang_vel[i] batch.pos[batch_size + i] = batch.pos[i] batch.rot[batch_size + i] =", "in enumerate(data.ang_vel): data.ang_vel[i] = [(x / norm_info.max_ang_vel) for x in", "to randomly perturb point clouds with. If None no perturbation", "self.use_aa = False self.use_aa_split = False self.use_topple_idx = False self.use_delta_quat", "dtype=int) # other meta-data not directly used in network self.toppled", "in roots: if not exists(root): print('Could not find dataset at", "= batch.point_cloud[i] batch.lin_vel[batch_size + i] = batch.lin_vel[i] batch.ang_vel[batch_size + i]", "unique sequences contained # in the dataset will be much", "returned sequence ordering - num_pts : the number of points", "np.random.randint(min_idx, max_start_step+1) else: start_step = np.random.randint(0, max_start_step+1) end_step = start_step", "self.force_vec_max, 'pc_max' : self.pc_max, \\ 'density_off' : self.density_offset, 'density_max' :", "rotation around any axis between two contiguous timesteps (for euler", "None # max change in rotation around any axis between", "# point clouds -> [-1, 1] data.point_cloud /= norm_info.pc_max #", "self.inertia_offset = norm_info.inertia_offset self.inertia_max = norm_info.inertia_max try: self.friction_offset = norm_info.friction_offset", "= meta_info[4] batch.mass[i] = meta_info[5] if batch_size != self.batch_size: #", "is None: # use all the points in the point", "self.ang_vel = np.zeros((self.size, self.num_steps, 3)) self.pos = np.zeros((self.size, self.num_steps, 3))", "self.use_aa_split = True if len(self.data.topple_idx) > 0: self.use_topple_idx = True", "= None # max 2-norm of applied impulse vector self.force_vec_max", "/ norm_info.density_max # mass -> [0, 1] data.mass = (data.mass", "self.norm_info.load_from(norm_info_file) print('Loaded normalization info!') # see if we have axis-angle", "batch.delta_rot[i] if self.use_aa_split: batch.delta_rot_split[batch_size + i] = batch.delta_rot_split[i] if self.use_topple_idx:", "i] = batch.rot[i] if self.use_delta_quat: batch.delta_quat[batch_size + i] = batch.delta_quat[i]", "0: self.use_delta_quat = True # normalize the data print('Normalizing data...')", "meta_info = \\ self.get_seq(self.iter_inds[start_idx + i], self.steps_per_seq, random_window, focus_toppling) batch.point_cloud[i]", "for x in ang_vel_steps] # delta position -> [-1, 1]", "shorter if we're at the end of the data start_idx", "np.array(self.data.pos[idx][start_step:end_step]) rot_out = np.array(self.data.total_rot[idx][start_step:end_step]) if self.use_delta_quat: delta_quat_out = np.array(self.data.delta_quat[idx][start_step:end_step]) euler_rot_out", "1] data.mass = (data.mass - norm_info.mass_offset) / norm_info.mass_max # inertia", "def normalize_data(self, data, norm_info): ''' Normalizes (in place) the given", "def get_seq(self, idx, num_steps, random_window=True, focus_toppling=False): ''' Returns a random", "- roots : list of directories containing data to load", "axis-angle representation self.max_delta_rot = None # max 2-norm of applied", "random sequence of correct length (otherwise starts at 0). If", "containing normalization information - batch_size : number of sequences to", "velocities -> [-1, 1] for i, lin_vel_steps in enumerate(data.lin_vel): data.lin_vel[i]", "any axis between two contiguous timesteps (for euler rot) self.max_rot" ]
[ "def AA_andEachClassAccuracy(confusion_matrix): counter = confusion_matrix.shape[0] list_diag = np.diag(confusion_matrix) list_raw_sum =", "import numpy as np from operator import truediv def AA_andEachClassAccuracy(confusion_matrix):", "list_diag = np.diag(confusion_matrix) list_raw_sum = np.sum(confusion_matrix, axis=1) each_acc = np.nan_to_num(truediv(list_diag,", "operator import truediv def AA_andEachClassAccuracy(confusion_matrix): counter = confusion_matrix.shape[0] list_diag =", "from operator import truediv def AA_andEachClassAccuracy(confusion_matrix): counter = confusion_matrix.shape[0] list_diag", "confusion_matrix.shape[0] list_diag = np.diag(confusion_matrix) list_raw_sum = np.sum(confusion_matrix, axis=1) each_acc =", "np.sum(confusion_matrix, axis=1) each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum)) average_acc = np.mean(each_acc) return", "np from operator import truediv def AA_andEachClassAccuracy(confusion_matrix): counter = confusion_matrix.shape[0]", "list_raw_sum = np.sum(confusion_matrix, axis=1) each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum)) average_acc =", "numpy as np from operator import truediv def AA_andEachClassAccuracy(confusion_matrix): counter", "counter = confusion_matrix.shape[0] list_diag = np.diag(confusion_matrix) list_raw_sum = np.sum(confusion_matrix, axis=1)", "= np.sum(confusion_matrix, axis=1) each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum)) average_acc = np.mean(each_acc)", "import truediv def AA_andEachClassAccuracy(confusion_matrix): counter = confusion_matrix.shape[0] list_diag = np.diag(confusion_matrix)", "= np.diag(confusion_matrix) list_raw_sum = np.sum(confusion_matrix, axis=1) each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum))", "truediv def AA_andEachClassAccuracy(confusion_matrix): counter = confusion_matrix.shape[0] list_diag = np.diag(confusion_matrix) list_raw_sum", "= confusion_matrix.shape[0] list_diag = np.diag(confusion_matrix) list_raw_sum = np.sum(confusion_matrix, axis=1) each_acc", "AA_andEachClassAccuracy(confusion_matrix): counter = confusion_matrix.shape[0] list_diag = np.diag(confusion_matrix) list_raw_sum = np.sum(confusion_matrix,", "each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum)) average_acc = np.mean(each_acc) return each_acc, average_acc", "axis=1) each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum)) average_acc = np.mean(each_acc) return each_acc,", "as np from operator import truediv def AA_andEachClassAccuracy(confusion_matrix): counter =", "np.diag(confusion_matrix) list_raw_sum = np.sum(confusion_matrix, axis=1) each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum)) average_acc" ]
[ "# About the license: see the file LICENSE.TXT ######################################################################################### #", "verbose, 'warning') elif crop_reference == 1: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field, background=0).crop()", "dimensions of data sct.printv('\\nGet dimensions of data...', verbose) img_src =", "sct.init_sct() # # initialize parameters param = Param() # call", "not sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination data must be 3d') # N.B.", "in data_split_list: im.save() # apply transfo sct.printv('\\nApply transformation to each", "ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref", "== '': path_out = '' # output in user's current", "-ref '+warping_field+' -b 0') elif crop_reference == 2: ImageCropper(input_file=fname_out, output_file=fname_out,", "list, because sct_WarpImageMultiTransform concatenates in the reverse order fname_warp_list_invert.reverse() fname_warp_list_invert", "= self.remove_temp_files crop_reference = self.crop # if = 1, put", "nz, nt, px, py, pz, pt = img_src.dim # nx,", "if nt == 1: # Apply transformation sct.printv('\\nApply transformation...', verbose)", "'2']) return parser class Transform: def __init__(self, input_filename, warp, fname_dest,", "str(nz) + ' x ' + str(nt), verbose) # if", "= arguments[\"-w\"] transform = Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename) if \"-crop\" in", "'data_T' + str(it).zfill(4) + '.nii' file_data_split_reg = 'data_reg_T' + str(it).zfill(4)", "sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field+' -b 0') elif", "# im_list = [Image(file_name) for file_name in glob.glob('data_reg_T*.nii')] # concat_data", "input_filename if isinstance(warp, str): self.warp_input = list([warp]) else: self.warp_input =", "# Apply transformations. This function is a wrapper for sct_WarpImageMultiTransform", "image\", mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination image\", mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\",", "self.interp = interp self.crop = crop self.verbose = verbose self.remove_temp_files", "get_parser() arguments = parser.parse(args) input_filename = arguments[\"-i\"] fname_dest = arguments[\"-d\"]", "+ fname_warp_list_invert + [ '-r', fname_dest, ] + interp, verbose=verbose,", "1]: dim = '2' else: dim = '3' sct.run(['isct_antsApplyTransforms', '-d',", "T dimension else: path_tmp = sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) # convert to", "# nx, ny, nz, nt, px, py, pz, pt =", "'-i', fname_src, '-o', fname_out, '-t', ] + fname_warp_list_invert + [", "get_parser(): # parser initialisation parser = Parser(__file__) parser.usage.set_description('Apply transformations. This", "path_warp.endswith((\".nii\", \".nii.gz\")) \\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector': raise ValueError(\"Displacement field", "fields sct.printv('\\nParse list of warping fields...', verbose) use_inverse = []", "# Authors: <NAME>, <NAME> # Modified: 2014-07-20 # # About", "self.verbose remove_temp_files = self.remove_temp_files crop_reference = self.crop # if =", "must be 3d') # N.B. Here we take the inverse", "a 5D file with vector intent code\" \\ \" (see", "ext_src fname_out = os.path.join(path_out, file_out + ext_out) # Get dimensions", "'-o', fname_out, '-t', ] + fname_warp_list_invert + [ '-r', fname_dest,", "ext_warp) fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1] curdir = os.getcwd() os.chdir(path_tmp) # split", "crop the resulting image using dimensions from the warping field", "not args: args = sys.argv[1:] # Get parser info parser", "arguments[\"-o\"] if \"-x\" in arguments: transform.interp = arguments[\"-x\"] if \"-r\"", "the space of the concatenate warping field: if isLastAffine: sct.printv('WARNING:", "Here we take the inverse of the warp list, because", "affine transformation matrix (text file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop", "comma for idx_warp, path_warp in enumerate(fname_warp_list): # Check if inverse", "spinalcordtoolbox.image as msct_image from sct_crop_image import ImageCropper class Param: def", "0. 2 : use normal background\", mandatory=False, default_value='0', example=['0', '1',", "for file_name in glob.glob('data_reg_T*.nii')] # concat_data use to take a", "beginning of file name if path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp] = path_warp[1:]", "need to check if last warping field is an affine", "or an affine transformation matrix (text file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\",", "nx, ny, nz, nt, px, py, pz, pt = sct.get_dimension(fname_src)", "img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp, file_dest + ext_dest)) fname_warp_list_tmp = []", "for it in range(nt): file_data_split = 'data_T' + str(it).zfill(4) +", "file back...', verbose) import glob path_out, name_out, ext_out = sct.extract_fname(fname_out)", "0 everywhere around warping field, if = 2, real crop", "= fname_warp_list.split(\",\") # parse with comma for idx_warp, path_warp in", "ext_dest, ] + interp, verbose, is_sct_binary=True) # Merge files back", "path_src, file_src, ext_src = sct.extract_fname(fname_src) path_dest, file_dest, ext_dest = sct.extract_fname(fname_dest)", "PARSER # ========================================================================================== def get_parser(): # parser initialisation parser =", "remove spaces # fname_warp_list = fname_warp_list.split(\",\") # parse with comma", "to each 3D volume...', verbose) for it in range(nt): file_data_split", "im_out.save(name_out + ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out + ext_out), fname_out) #", "\\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector': raise ValueError(\"Displacement field in {}", "self.warp_input = warp self.fname_dest = fname_dest self.output_filename = output_filename self.interp", "] + fname_warp_list_invert_tmp + [ '-r', file_dest + ext_dest, ]", "wrapper for sct_WarpImageMultiTransform # # --------------------------------------------------------------------------------------- # Copyright (c) 2014", "'': path_out = '' # output in user's current directory", "as last transformation...', verbose, 'warning') elif crop_reference == 1: ImageCropper(input_file=fname_out,", "example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop Reference. 0 : no reference. 1", "fname_dest = arguments[\"-d\"] warp_filename = arguments[\"-w\"] transform = Transform(input_filename=input_filename, fname_dest=fname_dest,", "list of warping fields...', verbose) use_inverse = [] fname_warp_list_invert =", "description=\"destination image\", mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','], \"file\"], description=\"Transformation, which can", "specified if int(remove_temp_files): sct.printv('\\nRemove temporary files...', verbose) sct.rmtree(path_tmp, verbose=verbose) #", "self.input_filename # source image (moving) fname_warp_list = self.warp_input # list", "as msct_image from sct_crop_image import ImageCropper class Param: def __init__(self):", "else: dim = '3' sct.run(['isct_antsApplyTransforms', '-d', dim, '-i', fname_src, '-o',", "3D volume...', verbose) for it in range(nt): file_data_split = 'data_T'", "sct_convert import sct_image import spinalcordtoolbox.image as msct_image from sct_crop_image import", "Check if inverse matrix is specified with '-' at the", "ext_out) # Get dimensions of data sct.printv('\\nGet dimensions of data...',", "if not sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination data must be 3d') #", "if __name__ == \"__main__\": sct.init_sct() # # initialize parameters param", "os.chdir(path_tmp) # split along T dimension sct.printv('\\nSplit along T dimension...',", "fname_src = self.input_filename # source image (moving) fname_warp_list = self.warp_input", "of data...', verbose) img_src = msct_image.Image(fname_src) nx, ny, nz, nt,", "dim = '2' else: dim = '3' sct.run(['isct_antsApplyTransforms', '-d', dim,", "# ========================================================================================== def get_parser(): # parser initialisation parser = Parser(__file__)", "destination file is 3d if not sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination data", "in the reverse order fname_warp_list_invert.reverse() fname_warp_list_invert = functools.reduce(lambda x,y: x+y,", "is_sct_binary=True) # if 4d, loop across the T dimension else:", "parser.add_option(name=\"-i\", type_value=\"file\", description=\"input image\", mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination image\",", "file_src + '_reg' ext_out = ext_src fname_out = os.path.join(path_out, file_out", "glob.glob('data_reg_T*.nii')] # concat_data use to take a list of image", "= msct_image.Image('data.nii') im_header = im_dat.hdr data_split_list = sct_image.split_data(im_dat, 3) for", "into temp folder sct.printv('\\nCopying input data to tmp folder and", "have wrong apparent results. You should use an affine transformation", "========================================================================================== def get_parser(): # parser initialisation parser = Parser(__file__) parser.usage.set_description('Apply", "temporary files.\"\"\", mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False,", "to take a list of image in input, now takes", "'+fname_out+' -o '+fname_out+' -ref '+warping_field+' -b 0') elif crop_reference ==", "fname_warp_list[idx_warp]]] else: use_inverse.append('') fname_warp_list_invert += [[path_warp]] path_warp = fname_warp_list[idx_warp] if", "an affine transformation matrix (text file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\",", "warping fields fname_out = self.output_filename # output fname_dest = self.fname_dest", "nt == 1: # Apply transformation sct.printv('\\nApply transformation...', verbose) if", "the warp list, because sct_WarpImageMultiTransform concatenates in the reverse order", "type_value=\"multiple_choice\", description=\"Crop Reference. 0 : no reference. 1 : sets", "+ ' x ' + str(nt), verbose) # if 3d", "files...', verbose) sct.rmtree(path_tmp, verbose=verbose) # 2. crop the resulting image", "should use an affine transformation as last transformation...', verbose, 'warning')", "# split along T dimension sct.printv('\\nSplit along T dimension...', verbose)", "int(arguments[\"-r\"]) transform.verbose = int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True) # Update log level", "parser.parse(args) input_filename = arguments[\"-i\"] fname_dest = arguments[\"-d\"] warp_filename = arguments[\"-w\"]", "[] fname_warp_list_invert = [] # fname_warp_list = fname_warp_list.replace(' ', '')", "'1', '2']) parser.add_option(name=\"-c\", type_value=None, description=\"Crop Reference. 0 : no reference.", "<NAME>, <NAME> # Modified: 2014-07-20 # # About the license:", "else: self.warp_input = warp self.fname_dest = fname_dest self.output_filename = output_filename", "{} is invalid: should be encoded\" \\ \" in a", "######################################################################################### # # Apply transformations. This function is a wrapper", "file_fname, ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname in ['.txt', '.mat']: isLastAffine", "sct_image.split_data(im_dat, 3) for im in data_split_list: im.save() # apply transfo", "+ interp, verbose, is_sct_binary=True) # Merge files back sct.printv('\\nMerge file", "use to take a list of image in input, now", "transform.crop = arguments[\"-crop\"] if \"-o\" in arguments: transform.output_filename = arguments[\"-o\"]", "fname_warp in fname_warp_list: path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp,", "sct.printv('\\nParse list of warping fields...', verbose) use_inverse = [] fname_warp_list_invert", "level transform.apply() # START PROGRAM # ========================================================================================== if __name__ ==", "fname_warp_list_invert = functools.reduce(lambda x,y: x+y, fname_warp_list_invert) # Extract path, file", "transformations. This function is a wrapper for antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\",", "the file LICENSE.TXT ######################################################################################### # TODO: display message at the", "parser = Parser(__file__) parser.usage.set_description('Apply transformations. This function is a wrapper", "Parse list of warping fields sct.printv('\\nParse list of warping fields...',", "def __init__(self): self.verbose = '1' self.remove_temp_files = '1' # PARSER", "transformation to each 3D volume...', verbose) for it in range(nt):", "+ ext_dest, ] + interp, verbose, is_sct_binary=True) # Merge files", "+ '_reg' ext_out = ext_src fname_out = os.path.join(path_out, file_out +", "file_dest + ext_dest)) fname_warp_list_tmp = [] for fname_warp in fname_warp_list:", "image (fix) verbose = self.verbose remove_temp_files = self.remove_temp_files crop_reference =", "transform.apply() # START PROGRAM # ========================================================================================== if __name__ == \"__main__\":", "Get output folder and file name if fname_out == '':", "warp list, because sct_WarpImageMultiTransform concatenates in the reverse order fname_warp_list_invert.reverse()", "self.crop # if = 1, put 0 everywhere around warping", "use normal background\", mandatory=False, default_value='0', example=['0', '1', '2']) parser.add_option(name=\"-c\", type_value=None,", "START PROGRAM # ========================================================================================== if __name__ == \"__main__\": sct.init_sct() #", "(see issue #715) fname_list = glob.glob('data_reg_T*.nii') fname_list.sort() im_out = sct_image.concat_data(fname_list,", "= sct.get_dimension(fname_src) sct.printv(' ' + str(nx) + ' x '", "to 0. 2 : use normal background\", mandatory=False, default_value='0', example=['0',", "sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname in ['.txt', '.mat']: isLastAffine = True #", "im in data_split_list: im.save() # apply transfo sct.printv('\\nApply transformation to", "\"-r\" in arguments: transform.remove_temp_files = int(arguments[\"-r\"]) transform.verbose = int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose,", "transform.remove_temp_files = int(arguments[\"-r\"]) transform.verbose = int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True) # Update", "folder and convert to nii...', verbose) img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp,", "crop self.verbose = verbose self.remove_temp_files = remove_temp_files self.debug = debug", "1, put 0 everywhere around warping field, if = 2,", "# Parse list of warping fields sct.printv('\\nParse list of warping", "<www.neuro.polymtl.ca> # Authors: <NAME>, <NAME> # Modified: 2014-07-20 # #", "output_filename='', verbose=0, crop=0, interp='spline', remove_temp_files=1, debug=0): self.input_filename = input_filename if", "+ ' x ' + str(ny) + ' x '", "remove_temp_files=1, debug=0): self.input_filename = input_filename if isinstance(warp, str): self.warp_input =", "msct_image from sct_crop_image import ImageCropper class Param: def __init__(self): self.verbose", "to nii...', verbose) img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp, file_dest + ext_dest))", "os.path.join(path_tmp, file_dest + ext_dest)) fname_warp_list_tmp = [] for fname_warp in", "= warp self.fname_dest = fname_dest self.output_filename = output_filename self.interp =", "encoded\" \\ \" in a 5D file with vector intent", "+ str(it).zfill(4) + '.nii' file_data_split_reg = 'data_reg_T' + str(it).zfill(4) +", "example=['nn', 'linear', 'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove temporary files.\"\"\", mandatory=False, default_value='1',", "ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out + ext_out), fname_out) # Delete temporary", "crop_reference == 1: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field, background=0).crop() # sct.run('sct_crop_image -i", "debug def apply(self): # Initialization fname_src = self.input_filename # source", "\"__main__\": sct.init_sct() # # initialize parameters param = Param() #", "+ ext_warp) fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1] curdir = os.getcwd() os.chdir(path_tmp) #", "# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: <NAME>,", "\"-crop\" in arguments: transform.crop = arguments[\"-crop\"] if \"-o\" in arguments:", "str): self.warp_input = list([warp]) else: self.warp_input = warp self.fname_dest =", "interp self.crop = crop self.verbose = verbose self.remove_temp_files = remove_temp_files", "list of image in input, now takes a list of", "========================================================================================== def main(args=None): # check user arguments if not args:", "around warping field, if = 2, real crop interp =", "os.path.join(path_tmp, file_warp + ext_warp)) fname_warp_list_tmp.append(file_warp + ext_warp) fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1]", "= fname_dest self.output_filename = output_filename self.interp = interp self.crop =", "log level transform.apply() # START PROGRAM # ========================================================================================== if __name__", "the reverse order fname_warp_list_invert.reverse() fname_warp_list_invert = functools.reduce(lambda x,y: x+y, fname_warp_list_invert)", "0. 2 : use normal background\", mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\",", "path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp] = path_warp[1:] # remove '-' fname_warp_list_invert +=", "example=['0', '1', '2']) return parser class Transform: def __init__(self, input_filename,", "self.remove_temp_files = remove_temp_files self.debug = debug def apply(self): # Initialization", "= 2, real crop interp = sct.get_interpolation('isct_antsApplyTransforms', self.interp) # Parse", "in glob.glob('data_reg_T*.nii')] # concat_data use to take a list of", "# ========================================================================================== def main(args=None): # check user arguments if not", "fields fname_out = self.output_filename # output fname_dest = self.fname_dest #", "for im in data_split_list: im.save() # apply transfo sct.printv('\\nApply transformation", "'-r', fname_dest, ] + interp, verbose=verbose, is_sct_binary=True) # if 4d,", "code\" \\ \" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp)) # need to", "+ ext_warp)) fname_warp_list_tmp.append(file_warp + ext_warp) fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1] curdir =", "['.txt', '.mat']: isLastAffine = True # check if destination file", "== 1: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field, background=0).crop() # sct.run('sct_crop_image -i '+fname_out+'", "class Transform: def __init__(self, input_filename, warp, fname_dest, output_filename='', verbose=0, crop=0,", "range(nt): file_data_split = 'data_T' + str(it).zfill(4) + '.nii' file_data_split_reg =", "glob.glob('data_reg_T*.nii') fname_list.sort() im_out = sct_image.concat_data(fname_list, 3, im_header['pixdim']) im_out.save(name_out + ext_out)", "msct_image.Image('data.nii') im_header = im_dat.hdr data_split_list = sct_image.split_data(im_dat, 3) for im", "open the files one by one (see issue #715) fname_list", "__init__(self): self.verbose = '1' self.remove_temp_files = '1' # PARSER #", "inverse matrix is specified with '-' at the beginning of", "else: path_tmp = sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) # convert to nifti into", "isLastAffine: sct.printv('WARNING: the resulting image could have wrong apparent results.", "= interp self.crop = crop self.verbose = verbose self.remove_temp_files =", "sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination data must be 3d') # N.B. Here", "warping fields...', verbose) use_inverse = [] fname_warp_list_invert = [] #", "if = 2, real crop interp = sct.get_interpolation('isct_antsApplyTransforms', self.interp) #", "functools from msct_parser import Parser import sct_utils as sct import", "type_value=[[','], \"file\"], description=\"Transformation, which can be a warping field (nifti", "__future__ import division, absolute_import import sys, io, os, time, functools", "fname_dest, output_filename='', verbose=0, crop=0, interp='spline', remove_temp_files=1, debug=0): self.input_filename = input_filename", "if last warping field is an affine transfo isLastAffine =", "os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out + ext_out), fname_out) # Delete temporary folder", "3d if not sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination data must be 3d')", "license: see the file LICENSE.TXT ######################################################################################### # TODO: display message", "need to compute the space of the concatenate warping field:", "sys.argv[1:] # Get parser info parser = get_parser() arguments =", "debug=0): self.input_filename = input_filename if isinstance(warp, str): self.warp_input = list([warp])", "+ ext_out), fname_out) # Delete temporary folder if specified if", "verbose) im_dat = msct_image.Image('data.nii') im_header = im_dat.hdr data_split_list = sct_image.split_data(im_dat,", "description=\"Crop Reference. 0 : no reference. 1 : sets background", "update=True) # Update log level transform.apply() # START PROGRAM #", "type_value=\"file_output\", description=\"registered source.\", mandatory=False, default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation method\",", "issue #715) fname_list = glob.glob('data_reg_T*.nii') fname_list.sort() im_out = sct_image.concat_data(fname_list, 3,", "in enumerate(fname_warp_list): # Check if inverse matrix is specified with", "= path_warp[1:] # remove '-' fname_warp_list_invert += [[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else:", "data_split_list: im.save() # apply transfo sct.printv('\\nApply transformation to each 3D", "# # About the license: see the file LICENSE.TXT #########################################################################################", "parser.usage.set_description('Apply transformations. This function is a wrapper for antsApplyTransforms (ANTs).')", "type_value=\"multiple_choice\", description=\"interpolation method\", mandatory=False, default_value='spline', example=['nn', 'linear', 'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\",", "of the warp list, because sct_WarpImageMultiTransform concatenates in the reverse", "def get_parser(): # parser initialisation parser = Parser(__file__) parser.usage.set_description('Apply transformations.", "data must be 3d') # N.B. Here we take the", "volume...', verbose) for it in range(nt): file_data_split = 'data_T' +", "be encoded\" \\ \" in a 5D file with vector", "'2' else: dim = '3' sct.run(['isct_antsApplyTransforms', '-d', dim, '-i', fname_src,", "the inverse of the warp list, because sct_WarpImageMultiTransform concatenates in", "functools.reduce(lambda x,y: x+y, fname_warp_list_invert) # Extract path, file and extension", "import glob path_out, name_out, ext_out = sct.extract_fname(fname_out) # im_list =", "'-d', '3', '-i', file_data_split, '-o', file_data_split_reg, '-t', ] + fname_warp_list_invert_tmp", "ext_dest = sct.extract_fname(fname_dest) # Get output folder and file name", "the T dimension else: path_tmp = sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) # convert", "as sct import sct_convert import sct_image import spinalcordtoolbox.image as msct_image", "import sct_convert import sct_image import spinalcordtoolbox.image as msct_image from sct_crop_image", "warping field (nifti image) or an affine transformation matrix (text", "arguments: transform.crop = arguments[\"-crop\"] if \"-o\" in arguments: transform.output_filename =", "Update log level transform.apply() # START PROGRAM # ========================================================================================== if", "Initialization fname_src = self.input_filename # source image (moving) fname_warp_list =", "= crop self.verbose = verbose self.remove_temp_files = remove_temp_files self.debug =", "path_fname, file_fname, ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname in ['.txt', '.mat']:", "2 : use normal background\", mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered", "' + str(nt), verbose) # if 3d if nt ==", "take a list of image in input, now takes a", "sct_WarpImageMultiTransform # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal", "+ fname_warp_list_invert_tmp + [ '-r', file_dest + ext_dest, ] +", "example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation method\", mandatory=False, default_value='spline', example=['nn', 'linear', 'spline'])", "'.nii' status, output = sct.run(['isct_antsApplyTransforms', '-d', '3', '-i', file_data_split, '-o',", "Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: <NAME>, <NAME> # Modified: 2014-07-20", "ext_warp = sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp, file_warp + ext_warp)) fname_warp_list_tmp.append(file_warp +", "' x ' + str(nz) + ' x ' +", "fname_warp_list_invert[-1] # if last warping field is an affine transfo,", ": use normal background\", mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered source.\",", "path_out = '' # output in user's current directory file_out", "# Update log level transform.apply() # START PROGRAM # ==========================================================================================", "im_header['pixdim']) im_out.save(name_out + ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out + ext_out), fname_out)", "'2']) parser.add_option(name=\"-c\", type_value=None, description=\"Crop Reference. 0 : no reference. 1", "the warping field warping_field = fname_warp_list_invert[-1] # if last warping", "x ' + str(nt), verbose) # if 3d if nt", "5D file with vector intent code\" \\ \" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\"", "description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1', example=['0', '1', '2']) return parser class Transform:", "= 1, put 0 everywhere around warping field, if =", "parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination image\", mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','], \"file\"], description=\"Transformation,", "crop_reference = self.crop # if = 1, put 0 everywhere", "# TODO: interpolation methods from __future__ import division, absolute_import import", "a wrapper for antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\", type_value=\"file\", description=\"input image\", mandatory=True,", "output = sct.run(['isct_antsApplyTransforms', '-d', '3', '-i', file_data_split, '-o', file_data_split_reg, '-t',", "!= 'vector': raise ValueError(\"Displacement field in {} is invalid: should", "verbose) img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp, file_dest + ext_dest)) fname_warp_list_tmp =", "'1', '2']) return parser class Transform: def __init__(self, input_filename, warp,", "should be encoded\" \\ \" in a 5D file with", "data to tmp folder and convert to nii...', verbose) img_src.save(os.path.join(path_tmp,", "py, pz, pt = img_src.dim # nx, ny, nz, nt,", "\" in a 5D file with vector intent code\" \\", "main(args=None): # check user arguments if not args: args =", "mandatory=False, default_value='0', example=['0', '1', '2']) parser.add_option(name=\"-c\", type_value=None, description=\"Crop Reference. 0", "= os.path.join(path_out, file_out + ext_out) # Get dimensions of data", "isLastAffine = False path_fname, file_fname, ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname", "sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose) # MAIN # ========================================================================================== def main(args=None): #", "background to 0. 2 : use normal background\", mandatory=False, default_value='0',", "2 : use normal background\", mandatory=False, default_value='0', example=['0', '1', '2'])", "self.debug = debug def apply(self): # Initialization fname_src = self.input_filename", "initialize parameters param = Param() # call main function main()", "+= [[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else: use_inverse.append('') fname_warp_list_invert += [[path_warp]] path_warp =", "sct_utils as sct import sct_convert import sct_image import spinalcordtoolbox.image as", "ext_out), fname_out) # Delete temporary folder if specified if int(remove_temp_files):", "# output fname_dest = self.fname_dest # destination image (fix) verbose", "= debug def apply(self): # Initialization fname_src = self.input_filename #", "\".nii.gz\")) \\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector': raise ValueError(\"Displacement field in", "is invalid: should be encoded\" \\ \" in a 5D", "2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: <NAME>, <NAME> # Modified:", "of image in input, now takes a list of file", "Get parser info parser = get_parser() arguments = parser.parse(args) input_filename", "= 'data_T' + str(it).zfill(4) + '.nii' file_data_split_reg = 'data_reg_T' +", "compute the space of the concatenate warping field: if isLastAffine:", "This function is a wrapper for antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\", type_value=\"file\",", "+ ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out + ext_out), fname_out) # Delete", "ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field, background=0).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+'", "file_warp + ext_warp)) fname_warp_list_tmp.append(file_warp + ext_warp) fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1] curdir", "input_filename = arguments[\"-i\"] fname_dest = arguments[\"-d\"] warp_filename = arguments[\"-w\"] transform", "if \"-crop\" in arguments: transform.crop = arguments[\"-crop\"] if \"-o\" in", "nii...', verbose) img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp, file_dest + ext_dest)) fname_warp_list_tmp", "name if fname_out == '': path_out = '' # output", "= Parser(__file__) parser.usage.set_description('Apply transformations. This function is a wrapper for", "path_out, name_out, ext_out = sct.extract_fname(fname_out) # im_list = [Image(file_name) for", "= True # check if destination file is 3d if", "#715) fname_list = glob.glob('data_reg_T*.nii') fname_list.sort() im_out = sct_image.concat_data(fname_list, 3, im_header['pixdim'])", "user arguments if not args: args = sys.argv[1:] # Get", "field in {} is invalid: should be encoded\" \\ \"", "# PARSER # ========================================================================================== def get_parser(): # parser initialisation parser", "x ' + str(ny) + ' x ' + str(nz)", "= [] for fname_warp in fname_warp_list: path_warp, file_warp, ext_warp =", "it in range(nt): file_data_split = 'data_T' + str(it).zfill(4) + '.nii'", "the files one by one (see issue #715) fname_list =", "msct_parser import Parser import sct_utils as sct import sct_convert import", "ImageCropper class Param: def __init__(self): self.verbose = '1' self.remove_temp_files =", "-i '+fname_out+' -o '+fname_out+' -ref '+warping_field+' -b 0') elif crop_reference", "'linear', 'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove temporary files.\"\"\", mandatory=False, default_value='1', example=['0',", "temporary files...', verbose) sct.rmtree(path_tmp, verbose=verbose) # 2. crop the resulting", "# --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> #", "2014-07-20 # # About the license: see the file LICENSE.TXT", "use normal background\", mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered source.\", mandatory=False,", "parser.add_option(name=\"-w\", type_value=[[','], \"file\"], description=\"Transformation, which can be a warping field", "image) or an affine transformation matrix (text file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\")", "= sct_image.split_data(im_dat, 3) for im in data_split_list: im.save() # apply", "arguments = parser.parse(args) input_filename = arguments[\"-i\"] fname_dest = arguments[\"-d\"] warp_filename", "transformation...', verbose) if nz in [0, 1]: dim = '2'", "class Param: def __init__(self): self.verbose = '1' self.remove_temp_files = '1'", "= int(arguments[\"-r\"]) transform.verbose = int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True) # Update log", "if last warping field is an affine transfo, we need", "fname_dest self.output_filename = output_filename self.interp = interp self.crop = crop", "description=\"registered source.\", mandatory=False, default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation method\", mandatory=False,", "== 1: # Apply transformation sct.printv('\\nApply transformation...', verbose) if nz", "to nifti into temp folder sct.printv('\\nCopying input data to tmp", "3) for im in data_split_list: im.save() # apply transfo sct.printv('\\nApply", "int(remove_temp_files): sct.printv('\\nRemove temporary files...', verbose) sct.rmtree(path_tmp, verbose=verbose) # 2. crop", "absolute_import import sys, io, os, time, functools from msct_parser import", "arguments[\"-w\"] transform = Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename) if \"-crop\" in arguments:", "str(ny) + ' x ' + str(nz) + ' x", "LICENSE.TXT ######################################################################################### # TODO: display message at the end #", "concatenate warping field: if isLastAffine: sct.printv('WARNING: the resulting image could", "str(it).zfill(4) + '.nii' file_data_split_reg = 'data_reg_T' + str(it).zfill(4) + '.nii'", "= fname_warp_list.replace(' ', '') # remove spaces # fname_warp_list =", "# parse with comma for idx_warp, path_warp in enumerate(fname_warp_list): #", "# Check if inverse matrix is specified with '-' at", "is 3d if not sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination data must be", "<NAME> # Modified: 2014-07-20 # # About the license: see", "(text file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop Reference. 0 :", "fname_out = self.output_filename # output fname_dest = self.fname_dest # destination", "2. crop the resulting image using dimensions from the warping", "remove_temp_files = self.remove_temp_files crop_reference = self.crop # if = 1,", "output_file=fname_out, ref=warping_field, background=0).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref", "in {} is invalid: should be encoded\" \\ \" in", "= im_dat.hdr data_split_list = sct_image.split_data(im_dat, 3) for im in data_split_list:", "'.mat']: isLastAffine = True # check if destination file is", "] + interp, verbose, is_sct_binary=True) # Merge files back sct.printv('\\nMerge", "fields...', verbose) use_inverse = [] fname_warp_list_invert = [] # fname_warp_list", "names to open the files one by one (see issue", "[ '-r', fname_dest, ] + interp, verbose=verbose, is_sct_binary=True) # if", "list of warping fields sct.printv('\\nParse list of warping fields...', verbose)", "from __future__ import division, absolute_import import sys, io, os, time,", "'1' self.remove_temp_files = '1' # PARSER # ========================================================================================== def get_parser():", "self.output_filename # output fname_dest = self.fname_dest # destination image (fix)", "Merge files back sct.printv('\\nMerge file back...', verbose) import glob path_out,", "list of warping fields fname_out = self.output_filename # output fname_dest", "parser.add_option(name=\"-c\", type_value=None, description=\"Crop Reference. 0 : no reference. 1 :", "resulting image could have wrong apparent results. You should use", "========================================================================================== if __name__ == \"__main__\": sct.init_sct() # # initialize parameters", "__name__ == \"__main__\": sct.init_sct() # # initialize parameters param =", "= arguments[\"-x\"] if \"-r\" in arguments: transform.remove_temp_files = int(arguments[\"-r\"]) transform.verbose", "takes a list of file names to open the files", "= [] # fname_warp_list = fname_warp_list.replace(' ', '') # remove", "image in input, now takes a list of file names", "parse with comma for idx_warp, path_warp in enumerate(fname_warp_list): # Check", "method\", mandatory=False, default_value='spline', example=['nn', 'linear', 'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove temporary", "== 2: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop() # sct.run('sct_crop_image -i '+fname_out+' -o", "Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename) if \"-crop\" in arguments: transform.crop = arguments[\"-crop\"]", "along T dimension...', verbose) im_dat = msct_image.Image('data.nii') im_header = im_dat.hdr", "background\", mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered source.\", mandatory=False, default_value='', example=\"dest.nii.gz\")", "of the concatenate warping field: if isLastAffine: sct.printv('WARNING: the resulting", "self.input_filename = input_filename if isinstance(warp, str): self.warp_input = list([warp]) else:", "sct_crop_image import ImageCropper class Param: def __init__(self): self.verbose = '1'", "+ [ '-r', file_dest + ext_dest, ] + interp, verbose,", "nifti into temp folder sct.printv('\\nCopying input data to tmp folder", "= sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp, file_warp + ext_warp)) fname_warp_list_tmp.append(file_warp + ext_warp)", "'_reg' ext_out = ext_src fname_out = os.path.join(path_out, file_out + ext_out)", "# output in user's current directory file_out = file_src +", "using dimensions from the warping field warping_field = fname_warp_list_invert[-1] #", "args = sys.argv[1:] # Get parser info parser = get_parser()", "python ######################################################################################### # # Apply transformations. This function is a", "# if = 1, put 0 everywhere around warping field,", "= sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname in ['.txt', '.mat']: isLastAffine = True", "import sct_image import spinalcordtoolbox.image as msct_image from sct_crop_image import ImageCropper", "the license: see the file LICENSE.TXT ######################################################################################### # TODO: display", "= img_src.dim # nx, ny, nz, nt, px, py, pz,", "' x ' + str(nt), verbose) # if 3d if", "parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove temporary files.\"\"\", mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name=\"-v\",", "# sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field+' -b 0')", "in arguments: transform.output_filename = arguments[\"-o\"] if \"-x\" in arguments: transform.interp", "\"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp, file_dest + ext_dest)) fname_warp_list_tmp = [] for", "3d') # N.B. Here we take the inverse of the", "results. You should use an affine transformation as last transformation...',", "in arguments: transform.crop = arguments[\"-crop\"] if \"-o\" in arguments: transform.output_filename", "px, py, pz, pt = img_src.dim # nx, ny, nz,", "parser initialisation parser = Parser(__file__) parser.usage.set_description('Apply transformations. This function is", "from msct_parser import Parser import sct_utils as sct import sct_convert", "sct.printv('WARNING: the resulting image could have wrong apparent results. You", "= parser.parse(args) input_filename = arguments[\"-i\"] fname_dest = arguments[\"-d\"] warp_filename =", "warp=warp_filename) if \"-crop\" in arguments: transform.crop = arguments[\"-crop\"] if \"-o\"", "Parser(__file__) parser.usage.set_description('Apply transformations. This function is a wrapper for antsApplyTransforms", "of file name if path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp] = path_warp[1:] #", "1: # Apply transformation sct.printv('\\nApply transformation...', verbose) if nz in", "check user arguments if not args: args = sys.argv[1:] #", "'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove temporary files.\"\"\", mandatory=False, default_value='1', example=['0', '1'])", "ext_out = sct.extract_fname(fname_out) # im_list = [Image(file_name) for file_name in", "sct.extract_fname(fname_src) path_dest, file_dest, ext_dest = sct.extract_fname(fname_dest) # Get output folder", "ref=warping_field).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field) sct.display_viewer_syntax([fname_dest,", "could have wrong apparent results. You should use an affine", "path_warp[1:] # remove '-' fname_warp_list_invert += [[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else: use_inverse.append('')", "concatenates in the reverse order fname_warp_list_invert.reverse() fname_warp_list_invert = functools.reduce(lambda x,y:", "description=\"\"\"Remove temporary files.\"\"\", mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\",", "file_src, ext_src = sct.extract_fname(fname_src) path_dest, file_dest, ext_dest = sct.extract_fname(fname_dest) #", "# if 4d, loop across the T dimension else: path_tmp", "type_value=\"file\", description=\"destination image\", mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','], \"file\"], description=\"Transformation, which", "crop interp = sct.get_interpolation('isct_antsApplyTransforms', self.interp) # Parse list of warping", "ny, nz, nt, px, py, pz, pt = sct.get_dimension(fname_src) sct.printv('", "sct.printv('\\nRemove temporary files...', verbose) sct.rmtree(path_tmp, verbose=verbose) # 2. crop the", "# source image (moving) fname_warp_list = self.warp_input # list of", "spaces # fname_warp_list = fname_warp_list.split(\",\") # parse with comma for", "to tmp folder and convert to nii...', verbose) img_src.save(os.path.join(path_tmp, \"data.nii\"))", "file_data_split = 'data_T' + str(it).zfill(4) + '.nii' file_data_split_reg = 'data_reg_T'", "] + interp, verbose=verbose, is_sct_binary=True) # if 4d, loop across", "a wrapper for sct_WarpImageMultiTransform # # --------------------------------------------------------------------------------------- # Copyright (c)", "-i '+fname_out+' -o '+fname_out+' -ref '+warping_field) sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose) #", "to compute the space of the concatenate warping field: if", "if nz in [0, 1]: dim = '2' else: dim", "-ref '+warping_field) sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose) # MAIN # ========================================================================================== def", "False path_fname, file_fname, ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname in ['.txt',", "file name if fname_out == '': path_out = '' #", "order fname_warp_list_invert.reverse() fname_warp_list_invert = functools.reduce(lambda x,y: x+y, fname_warp_list_invert) # Extract", "loop across the T dimension else: path_tmp = sct.tmp_create(basename=\"apply_transfo\", verbose=verbose)", "which can be a warping field (nifti image) or an", "is a wrapper for sct_WarpImageMultiTransform # # --------------------------------------------------------------------------------------- # Copyright", "'') # remove spaces # fname_warp_list = fname_warp_list.split(\",\") # parse", "' + str(nz) + ' x ' + str(nt), verbose)", "elif crop_reference == 1: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field, background=0).crop() # sct.run('sct_crop_image", "if 3d if nt == 1: # Apply transformation sct.printv('\\nApply", "verbose) for it in range(nt): file_data_split = 'data_T' + str(it).zfill(4)", "transfo, we need to compute the space of the concatenate", "initialisation parser = Parser(__file__) parser.usage.set_description('Apply transformations. This function is a", "arguments: transform.interp = arguments[\"-x\"] if \"-r\" in arguments: transform.remove_temp_files =", "take the inverse of the warp list, because sct_WarpImageMultiTransform concatenates", "sct_image.concat_data(fname_list, 3, im_header['pixdim']) im_out.save(name_out + ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out +", "is a wrapper for antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\", type_value=\"file\", description=\"input image\",", "an affine transformation as last transformation...', verbose, 'warning') elif crop_reference", "verbose) sct.rmtree(path_tmp, verbose=verbose) # 2. crop the resulting image using", "input, now takes a list of file names to open", "= fname_warp_list_invert[-1] # if last warping field is an affine", "= sct.extract_fname(fname_dest) # Get output folder and file name if", "sct.run(['isct_antsApplyTransforms', '-d', '3', '-i', file_data_split, '-o', file_data_split_reg, '-t', ] +", "fname_warp_list_tmp = [] for fname_warp in fname_warp_list: path_warp, file_warp, ext_warp", "#!/usr/bin/env python ######################################################################################### # # Apply transformations. This function is", "transform.verbose = int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True) # Update log level transform.apply()", "source.\", mandatory=False, default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation method\", mandatory=False, default_value='spline',", "warping field, if = 2, real crop interp = sct.get_interpolation('isct_antsApplyTransforms',", "warping fields sct.printv('\\nParse list of warping fields...', verbose) use_inverse =", "= msct_image.Image(fname_src) nx, ny, nz, nt, px, py, pz, pt", "transformation sct.printv('\\nApply transformation...', verbose) if nz in [0, 1]: dim", "sct.run(['isct_antsApplyTransforms', '-d', dim, '-i', fname_src, '-o', fname_out, '-t', ] +", "nx, ny, nz, nt, px, py, pz, pt = img_src.dim", "data sct.printv('\\nGet dimensions of data...', verbose) img_src = msct_image.Image(fname_src) nx,", "= self.verbose remove_temp_files = self.remove_temp_files crop_reference = self.crop # if", "# fname_warp_list = fname_warp_list.replace(' ', '') # remove spaces #", "# # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>", "= list([warp]) else: self.warp_input = warp self.fname_dest = fname_dest self.output_filename", "'3' sct.run(['isct_antsApplyTransforms', '-d', dim, '-i', fname_src, '-o', fname_out, '-t', ]", "= 'data_reg_T' + str(it).zfill(4) + '.nii' status, output = sct.run(['isct_antsApplyTransforms',", "the resulting image using dimensions from the warping field warping_field", "'+fname_out+' -o '+fname_out+' -ref '+warping_field) sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose) # MAIN", "one by one (see issue #715) fname_list = glob.glob('data_reg_T*.nii') fname_list.sort()", "file_dest, ext_dest = sct.extract_fname(fname_dest) # Get output folder and file", "matrix is specified with '-' at the beginning of file", "apparent results. You should use an affine transformation as last", "# fname_warp_list = fname_warp_list.split(\",\") # parse with comma for idx_warp,", "interp, verbose=verbose, is_sct_binary=True) # if 4d, loop across the T", "# destination image (fix) verbose = self.verbose remove_temp_files = self.remove_temp_files", "'-t', ] + fname_warp_list_invert + [ '-r', fname_dest, ] +", "fname_warp_list_invert += [[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else: use_inverse.append('') fname_warp_list_invert += [[path_warp]] path_warp", "self.warp_input # list of warping fields fname_out = self.output_filename #", "a warping field (nifti image) or an affine transformation matrix", "intent code\" \\ \" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp)) # need", "if destination file is 3d if not sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination", "ext_src = sct.extract_fname(fname_src) path_dest, file_dest, ext_dest = sct.extract_fname(fname_dest) # Get", "2, real crop interp = sct.get_interpolation('isct_antsApplyTransforms', self.interp) # Parse list", "real crop interp = sct.get_interpolation('isct_antsApplyTransforms', self.interp) # Parse list of", "fname_out = os.path.join(path_out, file_out + ext_out) # Get dimensions of", "with comma for idx_warp, path_warp in enumerate(fname_warp_list): # Check if", "type_value=\"multiple_choice\", description=\"\"\"Remove temporary files.\"\"\", mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\",", "pt = sct.get_dimension(fname_src) sct.printv(' ' + str(nx) + ' x", "'-d', dim, '-i', fname_src, '-o', fname_out, '-t', ] + fname_warp_list_invert", "sct.copy(fname_dest, os.path.join(path_tmp, file_dest + ext_dest)) fname_warp_list_tmp = [] for fname_warp", "if \"-x\" in arguments: transform.interp = arguments[\"-x\"] if \"-r\" in", "= functools.reduce(lambda x,y: x+y, fname_warp_list_invert) # Extract path, file and", "if not args: args = sys.argv[1:] # Get parser info", "You should use an affine transformation as last transformation...', verbose,", "verbose) # if 3d if nt == 1: # Apply", "and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector': raise ValueError(\"Displacement field in {} is", "file_data_split, '-o', file_data_split_reg, '-t', ] + fname_warp_list_invert_tmp + [ '-r',", "# Apply transformation sct.printv('\\nApply transformation...', verbose) if nz in [0,", "fname_src, '-o', fname_out, '-t', ] + fname_warp_list_invert + [ '-r',", "fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1] curdir = os.getcwd() os.chdir(path_tmp) # split along", "input data to tmp folder and convert to nii...', verbose)", "one (see issue #715) fname_list = glob.glob('data_reg_T*.nii') fname_list.sort() im_out =", "else: use_inverse.append('') fname_warp_list_invert += [[path_warp]] path_warp = fname_warp_list[idx_warp] if path_warp.endswith((\".nii\",", "dimension sct.printv('\\nSplit along T dimension...', verbose) im_dat = msct_image.Image('data.nii') im_header", "use an affine transformation as last transformation...', verbose, 'warning') elif", "-o '+fname_out+' -ref '+warping_field+' -b 0') elif crop_reference == 2:", "path_dest, file_dest, ext_dest = sct.extract_fname(fname_dest) # Get output folder and", "and file name if fname_out == '': path_out = ''", "import sct_utils as sct import sct_convert import sct_image import spinalcordtoolbox.image", "-b 0') elif crop_reference == 2: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop() #", "function is a wrapper for sct_WarpImageMultiTransform # # --------------------------------------------------------------------------------------- #", "[[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else: use_inverse.append('') fname_warp_list_invert += [[path_warp]] path_warp = fname_warp_list[idx_warp]", "split along T dimension sct.printv('\\nSplit along T dimension...', verbose) im_dat", "the concatenate warping field: if isLastAffine: sct.printv('WARNING: the resulting image", "remove_temp_files self.debug = debug def apply(self): # Initialization fname_src =", "file LICENSE.TXT ######################################################################################### # TODO: display message at the end", "TODO: interpolation methods from __future__ import division, absolute_import import sys,", "put 0 everywhere around warping field, if = 2, real", "fname_warp_list_invert + [ '-r', fname_dest, ] + interp, verbose=verbose, is_sct_binary=True)", "the beginning of file name if path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp] =", "= sct.get_interpolation('isct_antsApplyTransforms', self.interp) # Parse list of warping fields sct.printv('\\nParse", "wrong apparent results. You should use an affine transformation as", "wrapper for antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\", type_value=\"file\", description=\"input image\", mandatory=True, example=\"t2.nii.gz\")", "warping field: if isLastAffine: sct.printv('WARNING: the resulting image could have", "affine transfo, we need to compute the space of the", "output_file=fname_out, ref=warping_field).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field)", "warp, fname_dest, output_filename='', verbose=0, crop=0, interp='spline', remove_temp_files=1, debug=0): self.input_filename =", "fname_warp_list_invert.reverse() fname_warp_list_invert = functools.reduce(lambda x,y: x+y, fname_warp_list_invert) # Extract path,", "im_dat = msct_image.Image('data.nii') im_header = im_dat.hdr data_split_list = sct_image.split_data(im_dat, 3)", "concat_data use to take a list of image in input,", "dimensions from the warping field warping_field = fname_warp_list_invert[-1] # if", "file_data_split_reg, '-t', ] + fname_warp_list_invert_tmp + [ '-r', file_dest +", "= '1' # PARSER # ========================================================================================== def get_parser(): # parser", "at the beginning of file name if path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp]", "verbose=0, crop=0, interp='spline', remove_temp_files=1, debug=0): self.input_filename = input_filename if isinstance(warp,", "background\", mandatory=False, default_value='0', example=['0', '1', '2']) parser.add_option(name=\"-c\", type_value=None, description=\"Crop Reference.", "we take the inverse of the warp list, because sct_WarpImageMultiTransform", "dimension...', verbose) im_dat = msct_image.Image('data.nii') im_header = im_dat.hdr data_split_list =", "file_name in glob.glob('data_reg_T*.nii')] # concat_data use to take a list", "of file names to open the files one by one", "'-t', ] + fname_warp_list_invert_tmp + [ '-r', file_dest + ext_dest,", "fname_warp_list = fname_warp_list.replace(' ', '') # remove spaces # fname_warp_list", "is specified with '-' at the beginning of file name", "verbose=verbose) # MAIN # ========================================================================================== def main(args=None): # check user", "the resulting image could have wrong apparent results. You should", "fname_list.sort() im_out = sct_image.concat_data(fname_list, 3, im_header['pixdim']) im_out.save(name_out + ext_out) os.chdir(curdir)", "(c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: <NAME>, <NAME> #", "display message at the end # TODO: interpolation methods from", "= self.fname_dest # destination image (fix) verbose = self.verbose remove_temp_files", "# remove '-' fname_warp_list_invert += [[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else: use_inverse.append('') fname_warp_list_invert", "in input, now takes a list of file names to", "= arguments[\"-d\"] warp_filename = arguments[\"-w\"] transform = Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename)", "img_src.dim # nx, ny, nz, nt, px, py, pz, pt", "raise ValueError(\"Displacement field in {} is invalid: should be encoded\"", "# 2. crop the resulting image using dimensions from the", ".format(path_warp)) # need to check if last warping field is", "Apply transformation sct.printv('\\nApply transformation...', verbose) if nz in [0, 1]:", "crop=0, interp='spline', remove_temp_files=1, debug=0): self.input_filename = input_filename if isinstance(warp, str):", "sct.printv('\\nApply transformation...', verbose) if nz in [0, 1]: dim =", "# apply transfo sct.printv('\\nApply transformation to each 3D volume...', verbose)", "Parser import sct_utils as sct import sct_convert import sct_image import", "ext_dest)) fname_warp_list_tmp = [] for fname_warp in fname_warp_list: path_warp, file_warp,", "isLastAffine = True # check if destination file is 3d", "== \"__main__\": sct.init_sct() # # initialize parameters param = Param()", "in range(nt): file_data_split = 'data_T' + str(it).zfill(4) + '.nii' file_data_split_reg", "Modified: 2014-07-20 # # About the license: see the file", "import division, absolute_import import sys, io, os, time, functools from", "fname_warp_list_invert) # Extract path, file and extension path_src, file_src, ext_src", "current directory file_out = file_src + '_reg' ext_out = ext_src", "fname_list = glob.glob('data_reg_T*.nii') fname_list.sort() im_out = sct_image.concat_data(fname_list, 3, im_header['pixdim']) im_out.save(name_out", "last transformation...', verbose, 'warning') elif crop_reference == 1: ImageCropper(input_file=fname_out, output_file=fname_out,", "'1' # PARSER # ========================================================================================== def get_parser(): # parser initialisation", "name if path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp] = path_warp[1:] # remove '-'", "verbose=verbose) # convert to nifti into temp folder sct.printv('\\nCopying input", "in fname_warp_list: path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp, file_warp", "dimensions of data...', verbose) img_src = msct_image.Image(fname_src) nx, ny, nz,", "use_inverse.append('') fname_warp_list_invert += [[path_warp]] path_warp = fname_warp_list[idx_warp] if path_warp.endswith((\".nii\", \".nii.gz\"))", "str(nx) + ' x ' + str(ny) + ' x", "file_warp, ext_warp = sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp, file_warp + ext_warp)) fname_warp_list_tmp.append(file_warp", "reverse order fname_warp_list_invert.reverse() fname_warp_list_invert = functools.reduce(lambda x,y: x+y, fname_warp_list_invert) #", "= '2' else: dim = '3' sct.run(['isct_antsApplyTransforms', '-d', dim, '-i',", "self.verbose = verbose self.remove_temp_files = remove_temp_files self.debug = debug def", "fname_out) # Delete temporary folder if specified if int(remove_temp_files): sct.printv('\\nRemove", "verbose) if nz in [0, 1]: dim = '2' else:", "1: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field, background=0).crop() # sct.run('sct_crop_image -i '+fname_out+' -o", "to 0. 2 : use normal background\", mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\",", "sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) # convert to nifti into temp folder sct.printv('\\nCopying", "= self.warp_input # list of warping fields fname_out = self.output_filename", "fname_warp_list_tmp.append(file_warp + ext_warp) fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1] curdir = os.getcwd() os.chdir(path_tmp)", "default_value='1', example=['0', '1', '2']) return parser class Transform: def __init__(self,", "path_warp in enumerate(fname_warp_list): # Check if inverse matrix is specified", "'1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1', example=['0', '1', '2']) return", "mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1', example=['0',", "= '' # output in user's current directory file_out =", "of data sct.printv('\\nGet dimensions of data...', verbose) img_src = msct_image.Image(fname_src)", "fname_warp_list[idx_warp] = path_warp[1:] # remove '-' fname_warp_list_invert += [[use_inverse[idx_warp], fname_warp_list[idx_warp]]]", "default_value='0', example=['0', '1', '2']) parser.add_option(name=\"-c\", type_value=None, description=\"Crop Reference. 0 :", "check if last warping field is an affine transfo isLastAffine", "'-' at the beginning of file name if path_warp.startswith(\"-\"): use_inverse.append('-i')", "default_value='spline', example=['nn', 'linear', 'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove temporary files.\"\"\", mandatory=False,", "if fname_out == '': path_out = '' # output in", "folder if specified if int(remove_temp_files): sct.printv('\\nRemove temporary files...', verbose) sct.rmtree(path_tmp,", "# initialize parameters param = Param() # call main function", "file_out = file_src + '_reg' ext_out = ext_src fname_out =", "isinstance(warp, str): self.warp_input = list([warp]) else: self.warp_input = warp self.fname_dest", "for fname_warp in fname_warp_list: path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp) sct.copy(fname_warp,", "'warning') elif crop_reference == 1: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field, background=0).crop() #", "= arguments[\"-o\"] if \"-x\" in arguments: transform.interp = arguments[\"-x\"] if", "= fname_warp_list_tmp[::-1] curdir = os.getcwd() os.chdir(path_tmp) # split along T", "fname_out, '-t', ] + fname_warp_list_invert + [ '-r', fname_dest, ]", "enumerate(fname_warp_list): # Check if inverse matrix is specified with '-'", "be a warping field (nifti image) or an affine transformation", "transformation matrix (text file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop Reference.", "warp self.fname_dest = fname_dest self.output_filename = output_filename self.interp = interp", "field, if = 2, real crop interp = sct.get_interpolation('isct_antsApplyTransforms', self.interp)", "sct.printv(' ' + str(nx) + ' x ' + str(ny)", "file and extension path_src, file_src, ext_src = sct.extract_fname(fname_src) path_dest, file_dest,", "+ [ '-r', fname_dest, ] + interp, verbose=verbose, is_sct_binary=True) #", "(nifti image) or an affine transformation matrix (text file).\", mandatory=True,", "im.save() # apply transfo sct.printv('\\nApply transformation to each 3D volume...',", "int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True) # Update log level transform.apply() # START", "[0, 1]: dim = '2' else: dim = '3' sct.run(['isct_antsApplyTransforms',", "for antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\", type_value=\"file\", description=\"input image\", mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\",", "arguments[\"-crop\"] if \"-o\" in arguments: transform.output_filename = arguments[\"-o\"] if \"-x\"", "https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp)) # need to check if last warping", "fname_warp_list_invert += [[path_warp]] path_warp = fname_warp_list[idx_warp] if path_warp.endswith((\".nii\", \".nii.gz\")) \\", "verbose) import glob path_out, name_out, ext_out = sct.extract_fname(fname_out) # im_list", "im_dat.hdr data_split_list = sct_image.split_data(im_dat, 3) for im in data_split_list: im.save()", "convert to nii...', verbose) img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp, file_dest +", "in user's current directory file_out = file_src + '_reg' ext_out", "= glob.glob('data_reg_T*.nii') fname_list.sort() im_out = sct_image.concat_data(fname_list, 3, im_header['pixdim']) im_out.save(name_out +", "warping field is an affine transfo, we need to compute", "'+fname_out+' -ref '+warping_field) sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose) # MAIN # ==========================================================================================", "transform = Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename) if \"-crop\" in arguments: transform.crop", "a list of file names to open the files one", "type_value=None, description=\"Crop Reference. 0 : no reference. 1 : sets", "everywhere around warping field, if = 2, real crop interp", "sct.printv('\\nGet dimensions of data...', verbose) img_src = msct_image.Image(fname_src) nx, ny,", "# parser initialisation parser = Parser(__file__) parser.usage.set_description('Apply transformations. This function", "PROGRAM # ========================================================================================== if __name__ == \"__main__\": sct.init_sct() # #", "fname_warp_list = fname_warp_list.split(\",\") # parse with comma for idx_warp, path_warp", "\"file\"], description=\"Transformation, which can be a warping field (nifti image)", "image (moving) fname_warp_list = self.warp_input # list of warping fields", "# MAIN # ========================================================================================== def main(args=None): # check user arguments", "# need to check if last warping field is an", "output folder and file name if fname_out == '': path_out", "img_src = msct_image.Image(fname_src) nx, ny, nz, nt, px, py, pz,", "no reference. 1 : sets background to 0. 2 :", "ny, nz, nt, px, py, pz, pt = img_src.dim #", "+ str(it).zfill(4) + '.nii' status, output = sct.run(['isct_antsApplyTransforms', '-d', '3',", "T dimension...', verbose) im_dat = msct_image.Image('data.nii') im_header = im_dat.hdr data_split_list", "+ str(ny) + ' x ' + str(nz) + '", "see the file LICENSE.TXT ######################################################################################### # TODO: display message at", "'+warping_field+' -b 0') elif crop_reference == 2: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop()", "background=0).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field+' -b", "now takes a list of file names to open the", "Montreal <www.neuro.polymtl.ca> # Authors: <NAME>, <NAME> # Modified: 2014-07-20 #", "image could have wrong apparent results. You should use an", "in a 5D file with vector intent code\" \\ \"", "idx_warp, path_warp in enumerate(fname_warp_list): # Check if inverse matrix is", "sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field) sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose)", "msct_image.Image(fname_src) nx, ny, nz, nt, px, py, pz, pt =", "im_header = im_dat.hdr data_split_list = sct_image.split_data(im_dat, 3) for im in", "# Merge files back sct.printv('\\nMerge file back...', verbose) import glob", "output in user's current directory file_out = file_src + '_reg'", "if \"-o\" in arguments: transform.output_filename = arguments[\"-o\"] if \"-x\" in", "sys, io, os, time, functools from msct_parser import Parser import", "space of the concatenate warping field: if isLastAffine: sct.printv('WARNING: the", "mandatory=False, default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation method\", mandatory=False, default_value='spline', example=['nn',", "= self.crop # if = 1, put 0 everywhere around", "[[path_warp]] path_warp = fname_warp_list[idx_warp] if path_warp.endswith((\".nii\", \".nii.gz\")) \\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0]", "file is 3d if not sct.check_if_3d(fname_dest): sct.printv('ERROR: Destination data must", "= sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) # convert to nifti into temp folder", "ref=warping_field, background=0).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field+'", "# concat_data use to take a list of image in", "TODO: display message at the end # TODO: interpolation methods", "field: if isLastAffine: sct.printv('WARNING: the resulting image could have wrong", "crop_reference == 2: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop() # sct.run('sct_crop_image -i '+fname_out+'", "sct.printv('ERROR: Destination data must be 3d') # N.B. Here we", "+= [[path_warp]] path_warp = fname_warp_list[idx_warp] if path_warp.endswith((\".nii\", \".nii.gz\")) \\ and", "nt, px, py, pz, pt = img_src.dim # nx, ny,", "Delete temporary folder if specified if int(remove_temp_files): sct.printv('\\nRemove temporary files...',", ": no reference. 1 : sets background to 0. 2", "name_out, ext_out = sct.extract_fname(fname_out) # im_list = [Image(file_name) for file_name", "[Image(file_name) for file_name in glob.glob('data_reg_T*.nii')] # concat_data use to take", "default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation method\", mandatory=False, default_value='spline', example=['nn', 'linear',", "0') elif crop_reference == 2: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop() # sct.run('sct_crop_image", "return parser class Transform: def __init__(self, input_filename, warp, fname_dest, output_filename='',", "ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname in ['.txt', '.mat']: isLastAffine =", "= arguments[\"-i\"] fname_dest = arguments[\"-d\"] warp_filename = arguments[\"-w\"] transform =", "in arguments: transform.remove_temp_files = int(arguments[\"-r\"]) transform.verbose = int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True)", "if specified if int(remove_temp_files): sct.printv('\\nRemove temporary files...', verbose) sct.rmtree(path_tmp, verbose=verbose)", "name_out + ext_out), fname_out) # Delete temporary folder if specified", "of warping fields...', verbose) use_inverse = [] fname_warp_list_invert = []", "' + str(ny) + ' x ' + str(nz) +", "parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop Reference. 0 : no reference. 1 :", "# check user arguments if not args: args = sys.argv[1:]", "tmp folder and convert to nii...', verbose) img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest,", "mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered source.\", mandatory=False, default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\",", "if isinstance(warp, str): self.warp_input = list([warp]) else: self.warp_input = warp", "fname_warp_list_invert = [] # fname_warp_list = fname_warp_list.replace(' ', '') #", "last warping field is an affine transfo isLastAffine = False", "sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp, file_warp + ext_warp)) fname_warp_list_tmp.append(file_warp + ext_warp) fname_warp_list_invert_tmp", "'-' fname_warp_list_invert += [[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else: use_inverse.append('') fname_warp_list_invert += [[path_warp]]", "sct.copy(fname_warp, os.path.join(path_tmp, file_warp + ext_warp)) fname_warp_list_tmp.append(file_warp + ext_warp) fname_warp_list_invert_tmp =", "'.nii' file_data_split_reg = 'data_reg_T' + str(it).zfill(4) + '.nii' status, output", "mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','], \"file\"], description=\"Transformation, which can be a", "an affine transfo isLastAffine = False path_fname, file_fname, ext_fname =", "is_sct_binary=True) # Merge files back sct.printv('\\nMerge file back...', verbose) import", "file_data_split_reg = 'data_reg_T' + str(it).zfill(4) + '.nii' status, output =", "if int(remove_temp_files): sct.printv('\\nRemove temporary files...', verbose) sct.rmtree(path_tmp, verbose=verbose) # 2.", "warping_field = fname_warp_list_invert[-1] # if last warping field is an", "verbose=verbose, is_sct_binary=True) # if 4d, loop across the T dimension", "type_value=\"file\", description=\"input image\", mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination image\", mandatory=True,", "Transform: def __init__(self, input_filename, warp, fname_dest, output_filename='', verbose=0, crop=0, interp='spline',", "fname_warp_list[idx_warp] if path_warp.endswith((\".nii\", \".nii.gz\")) \\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector': raise", "fname_warp_list_invert_tmp + [ '-r', file_dest + ext_dest, ] + interp,", "= '3' sct.run(['isct_antsApplyTransforms', '-d', dim, '-i', fname_src, '-o', fname_out, '-t',", "+ ' x ' + str(nz) + ' x '", "of warping fields fname_out = self.output_filename # output fname_dest =", "= '1' self.remove_temp_files = '1' # PARSER # ========================================================================================== def", "if = 1, put 0 everywhere around warping field, if", "'data_reg_T' + str(it).zfill(4) + '.nii' status, output = sct.run(['isct_antsApplyTransforms', '-d',", "sets background to 0. 2 : use normal background\", mandatory=False,", "field is an affine transfo, we need to compute the", "= input_filename if isinstance(warp, str): self.warp_input = list([warp]) else: self.warp_input", "remove '-' fname_warp_list_invert += [[use_inverse[idx_warp], fname_warp_list[idx_warp]]] else: use_inverse.append('') fname_warp_list_invert +=", "+ ext_out) # Get dimensions of data sct.printv('\\nGet dimensions of", "back sct.printv('\\nMerge file back...', verbose) import glob path_out, name_out, ext_out", "mandatory=False, default_value='spline', example=['nn', 'linear', 'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove temporary files.\"\"\",", "matrix (text file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop Reference. 0", "if path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp] = path_warp[1:] # remove '-' fname_warp_list_invert", "arguments if not args: args = sys.argv[1:] # Get parser", "apply(self): # Initialization fname_src = self.input_filename # source image (moving)", "if path_warp.endswith((\".nii\", \".nii.gz\")) \\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector': raise ValueError(\"Displacement", "field is an affine transfo isLastAffine = False path_fname, file_fname,", "mandatory=False, default_value='1', example=['0', '1', '2']) return parser class Transform: def", "path_warp = fname_warp_list[idx_warp] if path_warp.endswith((\".nii\", \".nii.gz\")) \\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] !=", "extension path_src, file_src, ext_src = sct.extract_fname(fname_src) path_dest, file_dest, ext_dest =", "# ========================================================================================== if __name__ == \"__main__\": sct.init_sct() # # initialize", "import sys, io, os, time, functools from msct_parser import Parser", "verbose) use_inverse = [] fname_warp_list_invert = [] # fname_warp_list =", "'3', '-i', file_data_split, '-o', file_data_split_reg, '-t', ] + fname_warp_list_invert_tmp +", "'+warping_field) sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose) # MAIN # ========================================================================================== def main(args=None):", "example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','], \"file\"], description=\"Transformation, which can be a warping", "(ANTs).') parser.add_option(name=\"-i\", type_value=\"file\", description=\"input image\", mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination", "sct_image import spinalcordtoolbox.image as msct_image from sct_crop_image import ImageCropper class", "# Extract path, file and extension path_src, file_src, ext_src =", "we need to compute the space of the concatenate warping", "if 4d, loop across the T dimension else: path_tmp =", "arguments[\"-x\"] if \"-r\" in arguments: transform.remove_temp_files = int(arguments[\"-r\"]) transform.verbose =", "# check if destination file is 3d if not sct.check_if_3d(fname_dest):", "# Initialization fname_src = self.input_filename # source image (moving) fname_warp_list", "transformations. This function is a wrapper for sct_WarpImageMultiTransform # #", "sct import sct_convert import sct_image import spinalcordtoolbox.image as msct_image from", "path_tmp = sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) # convert to nifti into temp", "Reference. 0 : no reference. 1 : sets background to", "because sct_WarpImageMultiTransform concatenates in the reverse order fname_warp_list_invert.reverse() fname_warp_list_invert =", "# N.B. Here we take the inverse of the warp", "# Get parser info parser = get_parser() arguments = parser.parse(args)", "convert to nifti into temp folder sct.printv('\\nCopying input data to", "N.B. Here we take the inverse of the warp list,", "os.path.join(path_out, file_out + ext_out) # Get dimensions of data sct.printv('\\nGet", "pz, pt = sct.get_dimension(fname_src) sct.printv(' ' + str(nx) + '", "Destination data must be 3d') # N.B. Here we take", "example=['0', '1', '2']) parser.add_option(name=\"-c\", type_value=None, description=\"Crop Reference. 0 : no", "def __init__(self, input_filename, warp, fname_dest, output_filename='', verbose=0, crop=0, interp='spline', remove_temp_files=1,", "parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered source.\", mandatory=False, default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation", "interp, verbose, is_sct_binary=True) # Merge files back sct.printv('\\nMerge file back...',", "mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop Reference. 0 : no reference.", "user's current directory file_out = file_src + '_reg' ext_out =", "# # Apply transformations. This function is a wrapper for", "--------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors:", "path, file and extension path_src, file_src, ext_src = sct.extract_fname(fname_src) path_dest,", "output fname_dest = self.fname_dest # destination image (fix) verbose =", "3, im_header['pixdim']) im_out.save(name_out + ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out + ext_out),", "x ' + str(nz) + ' x ' + str(nt),", "parser.add_option(name=\"-x\", type_value=\"multiple_choice\", description=\"interpolation method\", mandatory=False, default_value='spline', example=['nn', 'linear', 'spline']) parser.add_option(name=\"-r\",", "transform.output_filename = arguments[\"-o\"] if \"-x\" in arguments: transform.interp = arguments[\"-x\"]", "sct.init_sct(log_level=transform.verbose, update=True) # Update log level transform.apply() # START PROGRAM", "2: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop() # sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+'", "######################################################################################### # TODO: display message at the end # TODO:", "interpolation methods from __future__ import division, absolute_import import sys, io,", "list([warp]) else: self.warp_input = warp self.fname_dest = fname_dest self.output_filename =", "= fname_warp_list[idx_warp] if path_warp.endswith((\".nii\", \".nii.gz\")) \\ and msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector':", "fname_out], verbose=verbose) # MAIN # ========================================================================================== def main(args=None): # check", "default_value='1', example=['0', '1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1', example=['0', '1',", "description=\"interpolation method\", mandatory=False, default_value='spline', example=['nn', 'linear', 'spline']) parser.add_option(name=\"-r\", type_value=\"multiple_choice\", description=\"\"\"Remove", "# remove spaces # fname_warp_list = fname_warp_list.split(\",\") # parse with", "# convert to nifti into temp folder sct.printv('\\nCopying input data", "sct.printv('\\nCopying input data to tmp folder and convert to nii...',", "+ '.nii' status, output = sct.run(['isct_antsApplyTransforms', '-d', '3', '-i', file_data_split,", "'-i', file_data_split, '-o', file_data_split_reg, '-t', ] + fname_warp_list_invert_tmp + [", "source image (moving) fname_warp_list = self.warp_input # list of warping", "im_list = [Image(file_name) for file_name in glob.glob('data_reg_T*.nii')] # concat_data use", "can be a warping field (nifti image) or an affine", "description=\"input image\", mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination image\", mandatory=True, example=\"out.nii.gz\")", "files one by one (see issue #715) fname_list = glob.glob('data_reg_T*.nii')", "os, time, functools from msct_parser import Parser import sct_utils as", "arguments: transform.remove_temp_files = int(arguments[\"-r\"]) transform.verbose = int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True) #", "= self.input_filename # source image (moving) fname_warp_list = self.warp_input #", "if ext_fname in ['.txt', '.mat']: isLastAffine = True # check", "self.remove_temp_files crop_reference = self.crop # if = 1, put 0", "reference. 1 : sets background to 0. 2 : use", "x,y: x+y, fname_warp_list_invert) # Extract path, file and extension path_src,", "= sct.extract_fname(fname_src) path_dest, file_dest, ext_dest = sct.extract_fname(fname_dest) # Get output", "# sct.run('sct_crop_image -i '+fname_out+' -o '+fname_out+' -ref '+warping_field) sct.display_viewer_syntax([fname_dest, fname_out],", "self.warp_input = list([warp]) else: self.warp_input = warp self.fname_dest = fname_dest", "# TODO: display message at the end # TODO: interpolation", "self.remove_temp_files = '1' # PARSER # ========================================================================================== def get_parser(): #", "self.fname_dest # destination image (fix) verbose = self.verbose remove_temp_files =", "ValueError(\"Displacement field in {} is invalid: should be encoded\" \\", "T dimension sct.printv('\\nSplit along T dimension...', verbose) im_dat = msct_image.Image('data.nii')", "arguments: transform.output_filename = arguments[\"-o\"] if \"-x\" in arguments: transform.interp =", "fname_warp_list_tmp[::-1] curdir = os.getcwd() os.chdir(path_tmp) # split along T dimension", "sct.generate_output_file(os.path.join(path_tmp, name_out + ext_out), fname_out) # Delete temporary folder if", "methods from __future__ import division, absolute_import import sys, io, os,", "file name if path_warp.startswith(\"-\"): use_inverse.append('-i') fname_warp_list[idx_warp] = path_warp[1:] # remove", "each 3D volume...', verbose) for it in range(nt): file_data_split =", "= sct.extract_fname(fname_out) # im_list = [Image(file_name) for file_name in glob.glob('data_reg_T*.nii')]", "folder and file name if fname_out == '': path_out =", "last warping field is an affine transfo, we need to", "__init__(self, input_filename, warp, fname_dest, output_filename='', verbose=0, crop=0, interp='spline', remove_temp_files=1, debug=0):", "type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1', example=['0', '1', '2']) return parser class", "# Delete temporary folder if specified if int(remove_temp_files): sct.printv('\\nRemove temporary", "# list of warping fields fname_out = self.output_filename # output", "= ext_src fname_out = os.path.join(path_out, file_out + ext_out) # Get", "temp folder sct.printv('\\nCopying input data to tmp folder and convert", "files.\"\"\", mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1',", "and extension path_src, file_src, ext_src = sct.extract_fname(fname_src) path_dest, file_dest, ext_dest", "warp_filename = arguments[\"-w\"] transform = Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename) if \"-crop\"", "output_filename self.interp = interp self.crop = crop self.verbose = verbose", "file_dest + ext_dest, ] + interp, verbose, is_sct_binary=True) # Merge", "normal background\", mandatory=False, default_value='0', example=['0', '1', '2']) parser.add_option(name=\"-c\", type_value=None, description=\"Crop", "sct.rmtree(path_tmp, verbose=verbose) # 2. crop the resulting image using dimensions", "antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\", type_value=\"file\", description=\"input image\", mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\",", "file with vector intent code\" \\ \" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\", "interp='spline', remove_temp_files=1, debug=0): self.input_filename = input_filename if isinstance(warp, str): self.warp_input", "self.verbose = '1' self.remove_temp_files = '1' # PARSER # ==========================================================================================", "= arguments[\"-crop\"] if \"-o\" in arguments: transform.output_filename = arguments[\"-o\"] if", "list of file names to open the files one by", ": sets background to 0. 2 : use normal background\",", "'vector': raise ValueError(\"Displacement field in {} is invalid: should be", "normal background\", mandatory=False, deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered source.\", mandatory=False, default_value='',", "file_out + ext_out) # Get dimensions of data sct.printv('\\nGet dimensions", "+ str(nz) + ' x ' + str(nt), verbose) #", "function is a wrapper for antsApplyTransforms (ANTs).') parser.add_option(name=\"-i\", type_value=\"file\", description=\"input", "\\ .format(path_warp)) # need to check if last warping field", "at the end # TODO: interpolation methods from __future__ import", "field warping_field = fname_warp_list_invert[-1] # if last warping field is", "'-o', file_data_split_reg, '-t', ] + fname_warp_list_invert_tmp + [ '-r', file_dest", "affine transformation as last transformation...', verbose, 'warning') elif crop_reference ==", "message at the end # TODO: interpolation methods from __future__", "fname_dest = self.fname_dest # destination image (fix) verbose = self.verbose", "sct.printv('\\nSplit along T dimension...', verbose) im_dat = msct_image.Image('data.nii') im_header =", "verbose, is_sct_binary=True) # Merge files back sct.printv('\\nMerge file back...', verbose)", "directory file_out = file_src + '_reg' ext_out = ext_src fname_out", "self.crop = crop self.verbose = verbose self.remove_temp_files = remove_temp_files self.debug", "= output_filename self.interp = interp self.crop = crop self.verbose =", "= Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename) if \"-crop\" in arguments: transform.crop =", "' x ' + str(ny) + ' x ' +", "is an affine transfo, we need to compute the space", "msct_image.Image(fname_warp_list[idx_warp]).header.get_intent()[0] != 'vector': raise ValueError(\"Displacement field in {} is invalid:", "if inverse matrix is specified with '-' at the beginning", "files back sct.printv('\\nMerge file back...', verbose) import glob path_out, name_out,", "# # initialize parameters param = Param() # call main", "file).\", mandatory=True, example=\"warp1.nii.gz,warp2.nii.gz\") parser.add_option(name=\"-crop\", type_value=\"multiple_choice\", description=\"Crop Reference. 0 : no", "self.output_filename = output_filename self.interp = interp self.crop = crop self.verbose", "an affine transfo, we need to compute the space of", "parser = get_parser() arguments = parser.parse(args) input_filename = arguments[\"-i\"] fname_dest", "[] # fname_warp_list = fname_warp_list.replace(' ', '') # remove spaces", "image using dimensions from the warping field warping_field = fname_warp_list_invert[-1]", "mandatory=True, example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination image\", mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','],", "def apply(self): # Initialization fname_src = self.input_filename # source image", "= [Image(file_name) for file_name in glob.glob('data_reg_T*.nii')] # concat_data use to", "os.getcwd() os.chdir(path_tmp) # split along T dimension sct.printv('\\nSplit along T", "Authors: <NAME>, <NAME> # Modified: 2014-07-20 # # About the", "apply transfo sct.printv('\\nApply transformation to each 3D volume...', verbose) for", "across the T dimension else: path_tmp = sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) #", "\"-x\" in arguments: transform.interp = arguments[\"-x\"] if \"-r\" in arguments:", "import spinalcordtoolbox.image as msct_image from sct_crop_image import ImageCropper class Param:", "sct.extract_fname(fname_out) # im_list = [Image(file_name) for file_name in glob.glob('data_reg_T*.nii')] #", "sct.get_dimension(fname_src) sct.printv(' ' + str(nx) + ' x ' +", "arguments[\"-d\"] warp_filename = arguments[\"-w\"] transform = Transform(input_filename=input_filename, fname_dest=fname_dest, warp=warp_filename) if", "end # TODO: interpolation methods from __future__ import division, absolute_import", "affine transfo isLastAffine = False path_fname, file_fname, ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1])", "to open the files one by one (see issue #715)", "destination image (fix) verbose = self.verbose remove_temp_files = self.remove_temp_files crop_reference", "file names to open the files one by one (see", "arguments[\"-i\"] fname_dest = arguments[\"-d\"] warp_filename = arguments[\"-w\"] transform = Transform(input_filename=input_filename,", "1 : sets background to 0. 2 : use normal", "dim, '-i', fname_src, '-o', fname_out, '-t', ] + fname_warp_list_invert +", "= int(arguments.get('-v')) sct.init_sct(log_level=transform.verbose, update=True) # Update log level transform.apply() #", "along T dimension sct.printv('\\nSplit along T dimension...', verbose) im_dat =", "' + str(nx) + ' x ' + str(ny) +", "= False path_fname, file_fname, ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1]) if ext_fname in", "im_out = sct_image.concat_data(fname_list, 3, im_header['pixdim']) im_out.save(name_out + ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp,", "ext_fname in ['.txt', '.mat']: isLastAffine = True # check if", "# START PROGRAM # ========================================================================================== if __name__ == \"__main__\": sct.init_sct()", "invalid: should be encoded\" \\ \" in a 5D file", "time, functools from msct_parser import Parser import sct_utils as sct", "str(nt), verbose) # if 3d if nt == 1: #", "in ['.txt', '.mat']: isLastAffine = True # check if destination", "= sct.run(['isct_antsApplyTransforms', '-d', '3', '-i', file_data_split, '-o', file_data_split_reg, '-t', ]", "+ ext_dest)) fname_warp_list_tmp = [] for fname_warp in fname_warp_list: path_warp,", "= get_parser() arguments = parser.parse(args) input_filename = arguments[\"-i\"] fname_dest =", "py, pz, pt = sct.get_dimension(fname_src) sct.printv(' ' + str(nx) +", "description=\"Transformation, which can be a warping field (nifti image) or", "in arguments: transform.interp = arguments[\"-x\"] if \"-r\" in arguments: transform.remove_temp_files", "fname_warp_list.split(\",\") # parse with comma for idx_warp, path_warp in enumerate(fname_warp_list):", "str(it).zfill(4) + '.nii' status, output = sct.run(['isct_antsApplyTransforms', '-d', '3', '-i',", "transform.interp = arguments[\"-x\"] if \"-r\" in arguments: transform.remove_temp_files = int(arguments[\"-r\"])", "nt, px, py, pz, pt = sct.get_dimension(fname_src) sct.printv(' ' +", "use_inverse.append('-i') fname_warp_list[idx_warp] = path_warp[1:] # remove '-' fname_warp_list_invert += [[use_inverse[idx_warp],", "parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1', example=['0', '1', '2']) return parser", "warping field is an affine transfo isLastAffine = False path_fname,", "verbose=verbose) # 2. crop the resulting image using dimensions from", "= sys.argv[1:] # Get parser info parser = get_parser() arguments", "for sct_WarpImageMultiTransform # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique", "check if destination file is 3d if not sct.check_if_3d(fname_dest): sct.printv('ERROR:", "of warping fields sct.printv('\\nParse list of warping fields...', verbose) use_inverse", "(fix) verbose = self.verbose remove_temp_files = self.remove_temp_files crop_reference = self.crop", "\" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp)) # need to check if", "', '') # remove spaces # fname_warp_list = fname_warp_list.split(\",\") #", "warping field warping_field = fname_warp_list_invert[-1] # if last warping field", "vector intent code\" \\ \" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp)) #", "field (nifti image) or an affine transformation matrix (text file).\",", "fname_warp_list: path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp, file_warp +", "[ '-r', file_dest + ext_dest, ] + interp, verbose, is_sct_binary=True)", "+ str(nx) + ' x ' + str(ny) + '", "This function is a wrapper for sct_WarpImageMultiTransform # # ---------------------------------------------------------------------------------------", "import ImageCropper class Param: def __init__(self): self.verbose = '1' self.remove_temp_files", "glob path_out, name_out, ext_out = sct.extract_fname(fname_out) # im_list = [Image(file_name)", "the end # TODO: interpolation methods from __future__ import division,", "data...', verbose) img_src = msct_image.Image(fname_src) nx, ny, nz, nt, px,", "# if 3d if nt == 1: # Apply transformation", "\\ \" in a 5D file with vector intent code\"", ": use normal background\", mandatory=False, default_value='0', example=['0', '1', '2']) parser.add_option(name=\"-c\",", "MAIN # ========================================================================================== def main(args=None): # check user arguments if", "= os.getcwd() os.chdir(path_tmp) # split along T dimension sct.printv('\\nSplit along", "Extract path, file and extension path_src, file_src, ext_src = sct.extract_fname(fname_src)", "fname_out == '': path_out = '' # output in user's", "transfo sct.printv('\\nApply transformation to each 3D volume...', verbose) for it", "io, os, time, functools from msct_parser import Parser import sct_utils", "] + fname_warp_list_invert + [ '-r', fname_dest, ] + interp,", "dimension else: path_tmp = sct.tmp_create(basename=\"apply_transfo\", verbose=verbose) # convert to nifti", "if isLastAffine: sct.printv('WARNING: the resulting image could have wrong apparent", "px, py, pz, pt = sct.get_dimension(fname_src) sct.printv(' ' + str(nx)", "with vector intent code\" \\ \" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp))", "parser info parser = get_parser() arguments = parser.parse(args) input_filename =", "# Get output folder and file name if fname_out ==", "def main(args=None): # check user arguments if not args: args", "\"-o\" in arguments: transform.output_filename = arguments[\"-o\"] if \"-x\" in arguments:", "0 : no reference. 1 : sets background to 0.", "with '-' at the beginning of file name if path_warp.startswith(\"-\"):", "is an affine transfo isLastAffine = False path_fname, file_fname, ext_fname", "image\", mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','], \"file\"], description=\"Transformation, which can be", "Get dimensions of data sct.printv('\\nGet dimensions of data...', verbose) img_src", "sct.get_interpolation('isct_antsApplyTransforms', self.interp) # Parse list of warping fields sct.printv('\\nParse list", "data_split_list = sct_image.split_data(im_dat, 3) for im in data_split_list: im.save() #", "'-r', file_dest + ext_dest, ] + interp, verbose, is_sct_binary=True) #", "background to 0. 2 : use normal background\", mandatory=False, deprecated_by='-crop')", "inverse of the warp list, because sct_WarpImageMultiTransform concatenates in the", "and convert to nii...', verbose) img_src.save(os.path.join(path_tmp, \"data.nii\")) sct.copy(fname_dest, os.path.join(path_tmp, file_dest", "folder sct.printv('\\nCopying input data to tmp folder and convert to", "parser class Transform: def __init__(self, input_filename, warp, fname_dest, output_filename='', verbose=0,", "Param: def __init__(self): self.verbose = '1' self.remove_temp_files = '1' #", "# Get dimensions of data sct.printv('\\nGet dimensions of data...', verbose)", "verbose self.remove_temp_files = remove_temp_files self.debug = debug def apply(self): #", "in [0, 1]: dim = '2' else: dim = '3'", "4d, loop across the T dimension else: path_tmp = sct.tmp_create(basename=\"apply_transfo\",", "fname_warp_list = self.warp_input # list of warping fields fname_out =", "interp = sct.get_interpolation('isct_antsApplyTransforms', self.interp) # Parse list of warping fields", "from sct_crop_image import ImageCropper class Param: def __init__(self): self.verbose =", "be 3d') # N.B. Here we take the inverse of", "x+y, fname_warp_list_invert) # Extract path, file and extension path_src, file_src,", "by one (see issue #715) fname_list = glob.glob('data_reg_T*.nii') fname_list.sort() im_out", "# Modified: 2014-07-20 # # About the license: see the", "Apply transformations. This function is a wrapper for sct_WarpImageMultiTransform #", "= self.output_filename # output fname_dest = self.fname_dest # destination image", "elif crop_reference == 2: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field).crop() # sct.run('sct_crop_image -i", "fname_dest=fname_dest, warp=warp_filename) if \"-crop\" in arguments: transform.crop = arguments[\"-crop\"] if", "= sct_image.concat_data(fname_list, 3, im_header['pixdim']) im_out.save(name_out + ext_out) os.chdir(curdir) sct.generate_output_file(os.path.join(path_tmp, name_out", "transfo isLastAffine = False path_fname, file_fname, ext_fname = sct.extract_fname(fname_warp_list_invert[-1][-1]) if", "sct.printv('\\nMerge file back...', verbose) import glob path_out, name_out, ext_out =", "# if last warping field is an affine transfo, we", "temporary folder if specified if int(remove_temp_files): sct.printv('\\nRemove temporary files...', verbose)", "self.interp) # Parse list of warping fields sct.printv('\\nParse list of", "\\ \" (see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp)) # need to check", "'' # output in user's current directory file_out = file_src", "-o '+fname_out+' -ref '+warping_field) sct.display_viewer_syntax([fname_dest, fname_out], verbose=verbose) # MAIN #", "to check if last warping field is an affine transfo", "sct.printv('\\nApply transformation to each 3D volume...', verbose) for it in", "sct_WarpImageMultiTransform concatenates in the reverse order fname_warp_list_invert.reverse() fname_warp_list_invert = functools.reduce(lambda", "pt = img_src.dim # nx, ny, nz, nt, px, py,", "specified with '-' at the beginning of file name if", "example=\"t2.nii.gz\") parser.add_option(name=\"-d\", type_value=\"file\", description=\"destination image\", mandatory=True, example=\"out.nii.gz\") parser.add_option(name=\"-w\", type_value=[[','], \"file\"],", "resulting image using dimensions from the warping field warping_field =", "for idx_warp, path_warp in enumerate(fname_warp_list): # Check if inverse matrix", "= [] fname_warp_list_invert = [] # fname_warp_list = fname_warp_list.replace(' ',", "pz, pt = img_src.dim # nx, ny, nz, nt, px,", "True # check if destination file is 3d if not", "example=['0', '1']) parser.add_option(name=\"-v\", type_value=\"multiple_choice\", description=\"\"\"Verbose.\"\"\", mandatory=False, default_value='1', example=['0', '1', '2'])", "input_filename, warp, fname_dest, output_filename='', verbose=0, crop=0, interp='spline', remove_temp_files=1, debug=0): self.input_filename", "import Parser import sct_utils as sct import sct_convert import sct_image", "verbose = self.verbose remove_temp_files = self.remove_temp_files crop_reference = self.crop #", "if \"-r\" in arguments: transform.remove_temp_files = int(arguments[\"-r\"]) transform.verbose = int(arguments.get('-v'))", "+ interp, verbose=verbose, is_sct_binary=True) # if 4d, loop across the", "division, absolute_import import sys, io, os, time, functools from msct_parser", "transformation as last transformation...', verbose, 'warning') elif crop_reference == 1:", "deprecated_by='-crop') parser.add_option(name=\"-o\", type_value=\"file_output\", description=\"registered source.\", mandatory=False, default_value='', example=\"dest.nii.gz\") parser.add_option(name=\"-x\", type_value=\"multiple_choice\",", "nz in [0, 1]: dim = '2' else: dim =", "= verbose self.remove_temp_files = remove_temp_files self.debug = debug def apply(self):", "path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp) sct.copy(fname_warp, os.path.join(path_tmp, file_warp + ext_warp))", "args: args = sys.argv[1:] # Get parser info parser =", "ext_out = ext_src fname_out = os.path.join(path_out, file_out + ext_out) #", "transformation...', verbose, 'warning') elif crop_reference == 1: ImageCropper(input_file=fname_out, output_file=fname_out, ref=warping_field,", "fname_warp_list.replace(' ', '') # remove spaces # fname_warp_list = fname_warp_list.split(\",\")", "back...', verbose) import glob path_out, name_out, ext_out = sct.extract_fname(fname_out) #", "nz, nt, px, py, pz, pt = sct.get_dimension(fname_src) sct.printv(' '", "About the license: see the file LICENSE.TXT ######################################################################################### # TODO:", "a list of image in input, now takes a list", "(moving) fname_warp_list = self.warp_input # list of warping fields fname_out", "+ str(nt), verbose) # if 3d if nt == 1:", "= file_src + '_reg' ext_out = ext_src fname_out = os.path.join(path_out,", "= remove_temp_files self.debug = debug def apply(self): # Initialization fname_src", "use_inverse = [] fname_warp_list_invert = [] # fname_warp_list = fname_warp_list.replace('", "Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: <NAME>, <NAME>", "fname_dest, ] + interp, verbose=verbose, is_sct_binary=True) # if 4d, loop", "ext_warp)) fname_warp_list_tmp.append(file_warp + ext_warp) fname_warp_list_invert_tmp = fname_warp_list_tmp[::-1] curdir = os.getcwd()", "(see https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h\" \\ .format(path_warp)) # need to check if last", "+ '.nii' file_data_split_reg = 'data_reg_T' + str(it).zfill(4) + '.nii' status,", "'+fname_out+' -ref '+warping_field+' -b 0') elif crop_reference == 2: ImageCropper(input_file=fname_out,", "[] for fname_warp in fname_warp_list: path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp)", "status, output = sct.run(['isct_antsApplyTransforms', '-d', '3', '-i', file_data_split, '-o', file_data_split_reg,", "self.fname_dest = fname_dest self.output_filename = output_filename self.interp = interp self.crop", "verbose) img_src = msct_image.Image(fname_src) nx, ny, nz, nt, px, py,", "dim = '3' sct.run(['isct_antsApplyTransforms', '-d', dim, '-i', fname_src, '-o', fname_out,", "from the warping field warping_field = fname_warp_list_invert[-1] # if last", "3d if nt == 1: # Apply transformation sct.printv('\\nApply transformation...',", "sct.extract_fname(fname_dest) # Get output folder and file name if fname_out", "info parser = get_parser() arguments = parser.parse(args) input_filename = arguments[\"-i\"]", "curdir = os.getcwd() os.chdir(path_tmp) # split along T dimension sct.printv('\\nSplit" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True) def test_commit(self): \"\"\"Test commit. \"\"\" flag", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "import PluginBase from tests import unittest from tests.plugins.helpers import (BAD_PLUGIN_CONFIGS,", "class TestPluginBase(unittest.TestCase): \"\"\" Tests the utils \"\"\" def setUp(self): \"\"\"Initialize", "test_info(self): \"\"\"Test info. \"\"\" configs = self.namespace.plugins[0] for cfg in", "sys sys.path[0:0] = [\"\"] from mongo_connector.plugins.plugin_base import PluginBase from tests", "= copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for cfg in configs: obj = PluginBase(cfg)", "def _test_not_implemented_method_by_name(self, name): \"\"\"Test not implemented method by name. \"\"\"", "\"\"\" configs = copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for cfg in configs: obj", "# Bulk invoke is really implemented but it calls invoke", "not implemented exception. flag = self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True) def test_commit(self):", "def setUp(self): \"\"\"Initialize test instance. \"\"\" self.namespace = get_test_namespace() def", "distributed under the License is distributed on an \"AS IS\"", "flag = self._test_not_implemented_method_by_name('stop') self.assertEqual(flag, True) if __name__ == '__main__': unittest.main()", "by name. \"\"\" configs = copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for cfg in", "configs: obj = PluginBase(cfg) try: method = getattr(obj, name) if", "cfg in configs: obj = PluginBase(cfg) try: method = getattr(obj,", "the specific language governing permissions and # limitations under the", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name()) for cfg", "test instance. \"\"\" self.namespace = get_test_namespace() def test_name(self): \"\"\"Test name.", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "{}) def _test_not_implemented_method_by_name(self, name): \"\"\"Test not implemented method by name.", "invoke. \"\"\" flag = self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True) def test_bulk_invoke(self): \"\"\"Test", "except in compliance with the License. # You may obtain", "self.assertEqual(cfg['config'], obj.info()) for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.info(),", "Copyright 2013-2014 MongoDB, Inc. # # Licensed under the Apache", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "loop # which returns an not implemented exception. flag =", "implemented exception. flag = self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True) def test_commit(self): \"\"\"Test", "def test_commit(self): \"\"\"Test commit. \"\"\" flag = self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True)", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "from tests.plugins.helpers import (BAD_PLUGIN_CONFIGS, get_test_namespace) class TestPluginBase(unittest.TestCase): \"\"\" Tests the", "def test_stop(self): \"\"\"Test stop. \"\"\" flag = self._test_not_implemented_method_by_name('stop') self.assertEqual(flag, True)", "not use this file except in compliance with the License.", "for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.info(), {}) def", "= self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True) def test_bulk_invoke(self): \"\"\"Test bulk_invoke. \"\"\" #", "writing, software # distributed under the License is distributed on", "in plugin_base.py \"\"\" import copy import sys sys.path[0:0] = [\"\"]", "True) def test_bulk_invoke(self): \"\"\"Test bulk_invoke. \"\"\" # Bulk invoke is", "in writing, software # distributed under the License is distributed", "TestPluginBase(unittest.TestCase): \"\"\" Tests the utils \"\"\" def setUp(self): \"\"\"Initialize test", "you may not use this file except in compliance with", "\"\"\" Tests the utils \"\"\" def setUp(self): \"\"\"Initialize test instance.", "obj = PluginBase(cfg) self.assertEqual(obj.info(), {}) def _test_not_implemented_method_by_name(self, name): \"\"\"Test not", "not callable(method): raise KeyError method() except NotImplementedError as exc: pass", "KeyError method() except NotImplementedError as exc: pass return True def", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "\"\"\" flag = self._test_not_implemented_method_by_name('stop') self.assertEqual(flag, True) if __name__ == '__main__':", "\"\"\"Tests methods in plugin_base.py \"\"\" import copy import sys sys.path[0:0]", "name): \"\"\"Test not implemented method by name. \"\"\" configs =", "unittest from tests.plugins.helpers import (BAD_PLUGIN_CONFIGS, get_test_namespace) class TestPluginBase(unittest.TestCase): \"\"\" Tests", "self.assertEqual(cfg['pluginName'], obj.name()) for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.name().index('generated'),", "NotImplementedError as exc: pass return True def test_invoke(self): \"\"\"Test invoke.", "method() except NotImplementedError as exc: pass return True def test_invoke(self):", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "not method or not callable(method): raise KeyError method() except NotImplementedError", "except NotImplementedError as exc: pass return True def test_invoke(self): \"\"\"Test", "self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True) def test_commit(self): \"\"\"Test commit. \"\"\" flag =", "CONDITIONS OF ANY KIND, either express or implied. # See", "import unittest from tests.plugins.helpers import (BAD_PLUGIN_CONFIGS, get_test_namespace) class TestPluginBase(unittest.TestCase): \"\"\"", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "or not callable(method): raise KeyError method() except NotImplementedError as exc:", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "language governing permissions and # limitations under the License. \"\"\"Tests", "\"\"\" self.namespace = get_test_namespace() def test_name(self): \"\"\"Test name. \"\"\" configs", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "configs = self.namespace.plugins[0] for cfg in configs: obj = PluginBase(cfg)", "implemented method by name. \"\"\" configs = copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for", "exception. flag = self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True) def test_commit(self): \"\"\"Test commit.", "\"\"\"Test info. \"\"\" configs = self.namespace.plugins[0] for cfg in configs:", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "exc: pass return True def test_invoke(self): \"\"\"Test invoke. \"\"\" flag", "\"\"\" flag = self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True) def test_stop(self): \"\"\"Test stop.", "self.assertEqual(flag, True) def test_commit(self): \"\"\"Test commit. \"\"\" flag = self._test_not_implemented_method_by_name('commit')", "an not implemented exception. flag = self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True) def", "under the License is distributed on an \"AS IS\" BASIS,", "[\"\"] from mongo_connector.plugins.plugin_base import PluginBase from tests import unittest from", "governing permissions and # limitations under the License. \"\"\"Tests methods", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License. \"\"\"Tests methods in plugin_base.py \"\"\" import copy import sys", "\"\"\"Initialize test instance. \"\"\" self.namespace = get_test_namespace() def test_name(self): \"\"\"Test", "License for the specific language governing permissions and # limitations", "self.assertEqual(obj.name().index('generated'), 0) def test_info(self): \"\"\"Test info. \"\"\" configs = self.namespace.plugins[0]", "cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['config'], obj.info()) for cfg", "PluginBase(cfg) self.assertEqual(obj.info(), {}) def _test_not_implemented_method_by_name(self, name): \"\"\"Test not implemented method", "getattr(obj, name) if not method or not callable(method): raise KeyError", "get_test_namespace() def test_name(self): \"\"\"Test name. \"\"\" configs = self.namespace.plugins[0] for", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "name. \"\"\" configs = copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for cfg in configs:", "True def test_invoke(self): \"\"\"Test invoke. \"\"\" flag = self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag,", "def test_name(self): \"\"\"Test name. \"\"\" configs = self.namespace.plugins[0] for cfg", "mongo_connector.plugins.plugin_base import PluginBase from tests import unittest from tests.plugins.helpers import", "= get_test_namespace() def test_name(self): \"\"\"Test name. \"\"\" configs = self.namespace.plugins[0]", "configs = copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for cfg in configs: obj =", "copy import sys sys.path[0:0] = [\"\"] from mongo_connector.plugins.plugin_base import PluginBase", "tests import unittest from tests.plugins.helpers import (BAD_PLUGIN_CONFIGS, get_test_namespace) class TestPluginBase(unittest.TestCase):", "True) def test_commit(self): \"\"\"Test commit. \"\"\" flag = self._test_not_implemented_method_by_name('commit') self.assertEqual(flag,", "PluginBase from tests import unittest from tests.plugins.helpers import (BAD_PLUGIN_CONFIGS, get_test_namespace)", "# Copyright 2013-2014 MongoDB, Inc. # # Licensed under the", "True) def test_stop(self): \"\"\"Test stop. \"\"\" flag = self._test_not_implemented_method_by_name('stop') self.assertEqual(flag,", "flag = self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True) def test_commit(self): \"\"\"Test commit. \"\"\"", "= self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True) def test_stop(self): \"\"\"Test stop. \"\"\" flag", "it calls invoke in loop # which returns an not", "bulk_invoke. \"\"\" # Bulk invoke is really implemented but it", "the License for the specific language governing permissions and #", "\"\"\"Test name. \"\"\" configs = self.namespace.plugins[0] for cfg in configs:", "self.assertEqual(obj.info(), {}) def _test_not_implemented_method_by_name(self, name): \"\"\"Test not implemented method by", "2013-2014 MongoDB, Inc. # # Licensed under the Apache License,", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "is really implemented but it calls invoke in loop #", "# you may not use this file except in compliance", "configs: obj = PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name()) for cfg in BAD_PLUGIN_CONFIGS:", "either express or implied. # See the License for the", "def test_bulk_invoke(self): \"\"\"Test bulk_invoke. \"\"\" # Bulk invoke is really", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0) def test_info(self): \"\"\"Test info.", "# which returns an not implemented exception. flag = self._test_not_implemented_method_by_name('bulk_invoke')", "the License is distributed on an \"AS IS\" BASIS, #", "test_commit(self): \"\"\"Test commit. \"\"\" flag = self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True) def", "in compliance with the License. # You may obtain a", "PluginBase(cfg) self.assertEqual(cfg['config'], obj.info()) for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg)", "BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.info(), {}) def _test_not_implemented_method_by_name(self, name): \"\"\"Test", "software # distributed under the License is distributed on an", "PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0) def test_info(self): \"\"\"Test info. \"\"\" configs =", "test_stop(self): \"\"\"Test stop. \"\"\" flag = self._test_not_implemented_method_by_name('stop') self.assertEqual(flag, True) if", "name) if not method or not callable(method): raise KeyError method()", "callable(method): raise KeyError method() except NotImplementedError as exc: pass return", "= [\"\"] from mongo_connector.plugins.plugin_base import PluginBase from tests import unittest", "sys.path[0:0] = [\"\"] from mongo_connector.plugins.plugin_base import PluginBase from tests import", "_test_not_implemented_method_by_name(self, name): \"\"\"Test not implemented method by name. \"\"\" configs", "methods in plugin_base.py \"\"\" import copy import sys sys.path[0:0] =", "from mongo_connector.plugins.plugin_base import PluginBase from tests import unittest from tests.plugins.helpers", "\"\"\" # Bulk invoke is really implemented but it calls", "# # Unless required by applicable law or agreed to", "obj = PluginBase(cfg) self.assertEqual(cfg['config'], obj.info()) for cfg in BAD_PLUGIN_CONFIGS: obj", "not implemented method by name. \"\"\" configs = copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS)", "self.assertEqual(flag, True) def test_bulk_invoke(self): \"\"\"Test bulk_invoke. \"\"\" # Bulk invoke", "test_name(self): \"\"\"Test name. \"\"\" configs = self.namespace.plugins[0] for cfg in", "def test_info(self): \"\"\"Test info. \"\"\" configs = self.namespace.plugins[0] for cfg", "obj = PluginBase(cfg) try: method = getattr(obj, name) if not", "for cfg in configs: obj = PluginBase(cfg) try: method =", "cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0) def test_info(self):", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the License. \"\"\"Tests methods in plugin_base.py \"\"\" import copy import", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "\"\"\"Test invoke. \"\"\" flag = self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True) def test_bulk_invoke(self):", "method = getattr(obj, name) if not method or not callable(method):", "# limitations under the License. \"\"\"Tests methods in plugin_base.py \"\"\"", "= PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name()) for cfg in BAD_PLUGIN_CONFIGS: obj =", "0) def test_info(self): \"\"\"Test info. \"\"\" configs = self.namespace.plugins[0] for", "Version 2.0 (the \"License\"); # you may not use this", "and # limitations under the License. \"\"\"Tests methods in plugin_base.py", "(BAD_PLUGIN_CONFIGS, get_test_namespace) class TestPluginBase(unittest.TestCase): \"\"\" Tests the utils \"\"\" def", "obj.name()) for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0)", "for cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['config'], obj.info()) for", "test_invoke(self): \"\"\"Test invoke. \"\"\" flag = self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True) def", "flag = self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True) def test_bulk_invoke(self): \"\"\"Test bulk_invoke. \"\"\"", "raise KeyError method() except NotImplementedError as exc: pass return True", "obj = PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name()) for cfg in BAD_PLUGIN_CONFIGS: obj", "law or agreed to in writing, software # distributed under", "limitations under the License. \"\"\"Tests methods in plugin_base.py \"\"\" import", "permissions and # limitations under the License. \"\"\"Tests methods in", "method by name. \"\"\" configs = copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for cfg", "= PluginBase(cfg) self.assertEqual(obj.info(), {}) def _test_not_implemented_method_by_name(self, name): \"\"\"Test not implemented", "for cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name()) for", "name. \"\"\" configs = self.namespace.plugins[0] for cfg in configs: obj", "method or not callable(method): raise KeyError method() except NotImplementedError as", "\"\"\"Test not implemented method by name. \"\"\" configs = copy.deepcopy(self.namespace.plugins)", "= PluginBase(cfg) self.assertEqual(cfg['config'], obj.info()) for cfg in BAD_PLUGIN_CONFIGS: obj =", "calls invoke in loop # which returns an not implemented", "self.namespace.plugins[0] for cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name())", "= self.namespace.plugins[0] for cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['config'],", "Bulk invoke is really implemented but it calls invoke in", "flag = self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True) def test_stop(self): \"\"\"Test stop. \"\"\"", "invoke is really implemented but it calls invoke in loop", "import (BAD_PLUGIN_CONFIGS, get_test_namespace) class TestPluginBase(unittest.TestCase): \"\"\" Tests the utils \"\"\"", "implemented but it calls invoke in loop # which returns", "in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.info(), {}) def _test_not_implemented_method_by_name(self, name):", "\"\"\"Test bulk_invoke. \"\"\" # Bulk invoke is really implemented but", "implied. # See the License for the specific language governing", "try: method = getattr(obj, name) if not method or not", "import sys sys.path[0:0] = [\"\"] from mongo_connector.plugins.plugin_base import PluginBase from", "commit. \"\"\" flag = self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True) def test_stop(self): \"\"\"Test", "under the Apache License, Version 2.0 (the \"License\"); # you", "configs: obj = PluginBase(cfg) self.assertEqual(cfg['config'], obj.info()) for cfg in BAD_PLUGIN_CONFIGS:", "\"License\"); # you may not use this file except in", "in configs: obj = PluginBase(cfg) self.assertEqual(cfg['config'], obj.info()) for cfg in", "really implemented but it calls invoke in loop # which", "in loop # which returns an not implemented exception. flag", "tests.plugins.helpers import (BAD_PLUGIN_CONFIGS, get_test_namespace) class TestPluginBase(unittest.TestCase): \"\"\" Tests the utils", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "\"\"\" import copy import sys sys.path[0:0] = [\"\"] from mongo_connector.plugins.plugin_base", "from tests import unittest from tests.plugins.helpers import (BAD_PLUGIN_CONFIGS, get_test_namespace) class", "info. \"\"\" configs = self.namespace.plugins[0] for cfg in configs: obj", "which returns an not implemented exception. flag = self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag,", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "= getattr(obj, name) if not method or not callable(method): raise", "return True def test_invoke(self): \"\"\"Test invoke. \"\"\" flag = self._test_not_implemented_method_by_name('invoke')", "\"\"\" flag = self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True) def test_bulk_invoke(self): \"\"\"Test bulk_invoke.", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "the utils \"\"\" def setUp(self): \"\"\"Initialize test instance. \"\"\" self.namespace", "in configs: obj = PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name()) for cfg in", "for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0) def", "import copy import sys sys.path[0:0] = [\"\"] from mongo_connector.plugins.plugin_base import", "\"\"\" def setUp(self): \"\"\"Initialize test instance. \"\"\" self.namespace = get_test_namespace()", "setUp(self): \"\"\"Initialize test instance. \"\"\" self.namespace = get_test_namespace() def test_name(self):", "in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0) def test_info(self): \"\"\"Test", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "instance. \"\"\" self.namespace = get_test_namespace() def test_name(self): \"\"\"Test name. \"\"\"", "pass return True def test_invoke(self): \"\"\"Test invoke. \"\"\" flag =", "returns an not implemented exception. flag = self._test_not_implemented_method_by_name('bulk_invoke') self.assertEqual(flag, True)", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "test_bulk_invoke(self): \"\"\"Test bulk_invoke. \"\"\" # Bulk invoke is really implemented", "to in writing, software # distributed under the License is", "utils \"\"\" def setUp(self): \"\"\"Initialize test instance. \"\"\" self.namespace =", "copy.deepcopy(self.namespace.plugins) configs.extend(BAD_PLUGIN_CONFIGS) for cfg in configs: obj = PluginBase(cfg) try:", "def test_invoke(self): \"\"\"Test invoke. \"\"\" flag = self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True)", "= self.namespace.plugins[0] for cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['pluginName'],", "as exc: pass return True def test_invoke(self): \"\"\"Test invoke. \"\"\"", "Tests the utils \"\"\" def setUp(self): \"\"\"Initialize test instance. \"\"\"", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "# See the License for the specific language governing permissions", "if not method or not callable(method): raise KeyError method() except", "self.namespace = get_test_namespace() def test_name(self): \"\"\"Test name. \"\"\" configs =", "invoke in loop # which returns an not implemented exception.", "MongoDB, Inc. # # Licensed under the Apache License, Version", "You may obtain a copy of the License at #", "cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.info(), {}) def _test_not_implemented_method_by_name(self,", "\"\"\"Test commit. \"\"\" flag = self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True) def test_stop(self):", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "PluginBase(cfg) self.assertEqual(cfg['pluginName'], obj.name()) for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg)", "self.assertEqual(flag, True) def test_stop(self): \"\"\"Test stop. \"\"\" flag = self._test_not_implemented_method_by_name('stop')", "required by applicable law or agreed to in writing, software", "\"\"\" configs = self.namespace.plugins[0] for cfg in configs: obj =", "in configs: obj = PluginBase(cfg) try: method = getattr(obj, name)", "stop. \"\"\" flag = self._test_not_implemented_method_by_name('stop') self.assertEqual(flag, True) if __name__ ==", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "self.namespace.plugins[0] for cfg in configs: obj = PluginBase(cfg) self.assertEqual(cfg['config'], obj.info())", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "configs.extend(BAD_PLUGIN_CONFIGS) for cfg in configs: obj = PluginBase(cfg) try: method", "but it calls invoke in loop # which returns an", "PluginBase(cfg) try: method = getattr(obj, name) if not method or", "plugin_base.py \"\"\" import copy import sys sys.path[0:0] = [\"\"] from", "the Apache License, Version 2.0 (the \"License\"); # you may", "obj.info()) for cfg in BAD_PLUGIN_CONFIGS: obj = PluginBase(cfg) self.assertEqual(obj.info(), {})", "= PluginBase(cfg) try: method = getattr(obj, name) if not method", "self._test_not_implemented_method_by_name('invoke') self.assertEqual(flag, True) def test_bulk_invoke(self): \"\"\"Test bulk_invoke. \"\"\" # Bulk", "\"\"\"Test stop. \"\"\" flag = self._test_not_implemented_method_by_name('stop') self.assertEqual(flag, True) if __name__", "get_test_namespace) class TestPluginBase(unittest.TestCase): \"\"\" Tests the utils \"\"\" def setUp(self):", "obj = PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0) def test_info(self): \"\"\"Test info. \"\"\"", "= PluginBase(cfg) self.assertEqual(obj.name().index('generated'), 0) def test_info(self): \"\"\"Test info. \"\"\" configs", "self._test_not_implemented_method_by_name('commit') self.assertEqual(flag, True) def test_stop(self): \"\"\"Test stop. \"\"\" flag =", "under the License. \"\"\"Tests methods in plugin_base.py \"\"\" import copy" ]
[ "return obj # A dictionary of named address components. elif", "not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to save. address_obj.save()", "logger = logging.getLogger(__name__) if sys.version > '3': long = int", "verbose_name_plural = 'Localities' unique_together = ('name', 'postal_code', 'state') ordering =", "= Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length:", "address. ## def to_python(value): # Keep `None`s. if value is", "= self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name", "state = value.get('state', '') state_code = value.get('state_code', '') locality =", "formatted = value.get('formatted', '') latitude = value.get('latitude', None) longitude =", "with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not locality and sublocality: locality", "is no value (empty raw) then return None. if not", "an inconsistent set of value bail out now. if (country", "and sublocality: locality = sublocality # If we have an", "= None # Handle the address. try: if not (street_number", "This is mostly for # Django being a cunt. elif", "'') street_number = value.get('street_number', '') route = value.get('route', '') formatted", "return '%s' % (self.name or self.code) ## # A state.", "'Localities' unique_together = ('name', 'postal_code', 'state') ordering = ('state', 'name')", "'%s' % (self.name or self.code) ## # A state. Google", "models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True)", "= super(AddressField, self).deconstruct() # del kwargs['to'] # return name, path,", "ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor):", "we have an inconsistent set of value bail out now.", "(too long): %s' % country_code) country_code = '' country_obj =", "name = models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True) #", "# unique_together = ('locality', 'route', 'street_number') def __str__(self): if self.formatted", "= self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code", "cls, name, virtual_only=False): from address.compat import compat_contribute_to_class compat_contribute_to_class(self, cls, name,", "None # Handle the address. try: if not (street_number or", "ForeignObject from django.utils.encoding import python_2_unicode_compatible try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor", "# A country. ## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40,", "to construct it from other values. if not address_obj.formatted: address_obj.formatted", "a dictionary to an address. ## def to_python(value): # Keep", "= models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True)", "out now. if (country or state or locality) and not", "if self.street_number: txt = '%s' % self.street_number if self.route: if", "+= ', ' txt += locality else: txt = '%s'", "if self.state and self.state.country else '') if cntry: txt +=", "## # Convert a dictionary to an address. ## def", "value.get('country', '') country_code = value.get('country_code', '') state = value.get('state', '')", "locality_obj = Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj", "will store the raw address string in `raw`. ## @python_2_unicode_compatible", "= self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code", "logging import sys from django.core.exceptions import ValidationError from django.db import", "# del kwargs['to'] # return name, path, args, kwargs def", "and not (country and state and locality): raise InconsistentDictError #", "locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200)", "'') locality = value.get('locality', '') sublocality = value.get('sublocality', '') postal_code", "= models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states') class Meta: unique_together = ('name', 'country')", "def __str__(self): txt = '%s' % self.name state = self.state.to_str()", "and locality): raise InconsistentDictError # Handle the country. try: country_obj", "not (country and state and locality): raise InconsistentDictError # Handle", "ordering = ('locality', 'route', 'street_number') # unique_together = ('locality', 'route',", "country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states') class Meta: unique_together = ('name',", "If \"formatted\" is empty try to construct it from other", "on_delete=models.CASCADE, related_name='states') class Meta: unique_together = ('name', 'country') ordering =", "Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid country code (too", "string is considered a raw value. elif isinstance(value, basestring): obj", "class Meta: unique_together = ('name', 'country') ordering = ('country', 'name')", "ordering = ('country', 'name') def __str__(self): txt = self.to_str() country", "!= state: raise ValueError('Invalid state code (too long): %s' %", "If for any reason we are unable to find a", "country and txt: txt += ', ' txt += country", "unable to find a matching # decomposed address we will", "state_code != state: raise ValueError('Invalid state code (too long): %s'", "state: if len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise", "Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj", "= Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, )", "value.get('latitude', None) longitude = value.get('longitude', None) # If there is", "address components. elif isinstance(value, dict): # Attempt a conversion. try:", "txt += ' %s' % self.route locality = '%s' %", "null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude =", "('name', 'postal_code', 'state') ordering = ('state', 'name') def __str__(self): txt", "% self.route locality = '%s' % self.locality if txt and", "# Django being a cunt. elif isinstance(value, (int, long)): return", "str __all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception):", "= '%s' % self.street_number if self.route: if txt: txt +=", "(self.name or self.code) ## # A locality (suburb). ## @python_2_unicode_compatible", "elif isinstance(value, dict): # Attempt a conversion. try: return _to_python(value)", "string in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20,", "an integer, assume it is a model primary key. This", "'%s' % (self.name or self.code) ## # A locality (suburb).", "Is it already an address object? if isinstance(value, Address): return", "__set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## # A field", "path, args, kwargs def formfield(self, **kwargs): from .forms import AddressField", "else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist:", "A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165,", "self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state']", "raise InconsistentDictError # Handle the country. try: country_obj = Country.objects.get(name=country)", "from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor", "value. elif isinstance(value, basestring): obj = Address(raw=value) obj.save() return obj", "country. ## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True)", "ValidationError('Invalid address value.') ## # A country. ## @python_2_unicode_compatible class", "return txt def to_str(self): return '%s' % (self.name or self.code)", "models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted =", "code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states') class", "locality): address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route,", "txt += country return txt def to_str(self): return '%s' %", "'' if txt and state: txt += ', ' txt", "an address object? if isinstance(value, Address): return value # If", "address' def __init__(self, *args, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(*args,", "import python_2_unicode_compatible try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from", "import logging import sys from django.core.exceptions import ValidationError from django.db", "not raw: return None # Fix issue with NYC boroughs", "> '3': long = int basestring = (str, bytes) unicode", "= sublocality # If we have an inconsistent set of", "formatted=formatted, latitude=latitude, longitude=longitude, ) # If \"formatted\" is empty try", "sublocality: locality = sublocality # If we have an inconsistent", "# def deconstruct(self): # name, path, args, kwargs = super(AddressField,", ".forms import AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs) return", "else '' if txt and state: txt += ', '", "+= ', %s' % cntry return txt ## # An", "primary key. This is mostly for # Django being a", "considered a raw value. elif isinstance(value, basestring): obj = Address(raw=value)", "class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ##", "value # If we have an integer, assume it is", "self.country if country and txt: txt += ', ' txt", "'state') ordering = ('state', 'name') def __str__(self): txt = '%s'", "models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses' ordering = ('locality',", "values. if not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to", "value.get('postal_code', '') street_number = value.get('street_number', '') route = value.get('route', '')", "= '' if self.street_number: txt = '%s' % self.street_number if", "integer, assume it is a model primary key. This is", "super(AddressField, self).deconstruct() # del kwargs['to'] # return name, path, args,", "raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude", "'') route = value.get('route', '') formatted = value.get('formatted', '') latitude", "'': txt = '%s' % self.formatted elif self.locality: txt =", "txt and state: txt += ', ' txt += state", "ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] =", "else: country_obj = None # Handle the state. try: state_obj", "= value.get('formatted', '') latitude = value.get('latitude', None) longitude = value.get('longitude',", "if not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to save.", "formfield(self, **kwargs): from .forms import AddressField as AddressFormField defaults =", "return None # Is it already an address object? if", "self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class", "import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor logger = logging.getLogger(__name__) if sys.version >", "import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor", "if self.latitude else '', longitude=self.longitude if self.longitude else '', )", "', ' txt += country return txt def to_str(self): return", "txt = '%s' % self.raw return txt def clean(self): if", "Handle the address. try: if not (street_number or route or", "if state_code != state: raise ValueError('Invalid state code (too long):", "raise ValueError('Invalid state code (too long): %s' % state_code) state_code", "issue with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not locality and sublocality:", "# Not in any of the formats I recognise. raise", "locality = value.get('locality', '') sublocality = value.get('sublocality', '') postal_code =", "= self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value):", "__str__(self): txt = '%s' % self.name state = self.state.to_str() if", "A country. ## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True,", "self).deconstruct() # del kwargs['to'] # return name, path, args, kwargs", "('locality', 'route', 'street_number') def __str__(self): if self.formatted != '': txt", "Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) #", "postal_code = value.get('postal_code', '') street_number = value.get('street_number', '') route =", "class Meta: verbose_name_plural = 'Addresses' ordering = ('locality', 'route', 'street_number')", "txt += locality else: txt = '%s' % self.raw return", "of the formats I recognise. raise ValidationError('Invalid address value.') ##", "object? if isinstance(value, Address): return value # If we have", "any of the formats I recognise. raise ValidationError('Invalid address value.')", "Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality", "locality = sublocality # If we have an inconsistent set", "Meta: unique_together = ('name', 'country') ordering = ('country', 'name') def", "def deconstruct(self): # name, path, args, kwargs = super(AddressField, self).deconstruct()", "try to construct it from other values. if not address_obj.formatted:", "Done. return address_obj ## # Convert a dictionary to an", "value is None: return None # Is it already an", "raw address string in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number", "except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any of the", "super(AddressField, self).__init__(*args, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): from address.compat", "return address_obj ## # Convert a dictionary to an address.", "we are unable to find a matching # decomposed address", "AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs) return super(AddressField, self).formfield(**defaults)", "= int basestring = (str, bytes) unicode = str __all__", "if not (street_number or route or locality): address_obj = Address.objects.get(raw=raw)", "import ValidationError from django.db import models from django.db.models.fields.related import ForeignObject", "if isinstance(value, Address): return value # If we have an", "# super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def", "kwargs = super(AddressField, self).deconstruct() # del kwargs['to'] # return name,", "contribute_to_class(self, cls, name, virtual_only=False): from address.compat import compat_contribute_to_class compat_contribute_to_class(self, cls,", "unique_together = ('name', 'postal_code', 'state') ordering = ('state', 'name') def", "models. ## class AddressField(models.ForeignKey): description = 'An address' def __init__(self,", "= value.get('latitude', None) longitude = value.get('longitude', None) # If there", "a matching # decomposed address we will store the raw", "class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True)", "state code (too long): %s' % state_code) state_code = ''", "Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality,", "Need to save. address_obj.save() # Done. return address_obj ## #", "country return txt def to_str(self): return '%s' % (self.name or", "txt and locality: txt += ', ' txt += locality", "raw) then return None. if not raw: return None #", "self.state and self.state.country else '') if cntry: txt += ',", "# Keep `None`s. if value is None: return None #", "= ('name',) def __str__(self): return '%s' % (self.name or self.code)", "A dictionary of named address components. elif isinstance(value, dict): #", "% (self.state.country if self.state and self.state.country else '') if cntry:", "except Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code", "*args, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(*args, **kwargs) def contribute_to_class(self,", "txt += state if self.postal_code: txt += ' %s' %", "= value.get('route', '') formatted = value.get('formatted', '') latitude = value.get('latitude',", "django.core.exceptions import ValidationError from django.db import models from django.db.models.fields.related import", "elif isinstance(value, (int, long)): return value # A string is", "and state and locality): raise InconsistentDictError # Handle the country.", "import models from django.db.models.fields.related import ForeignObject from django.utils.encoding import python_2_unicode_compatible", "args, kwargs def formfield(self, **kwargs): from .forms import AddressField as", "raw value. elif isinstance(value, basestring): obj = Address(raw=value) obj.save() return", "= Country.objects.create(name=country, code=country_code) else: country_obj = None # Handle the", "Google refers to this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model):", "recognise. raise ValidationError('Invalid address value.') ## # A country. ##", "if self.formatted != '': txt = '%s' % self.formatted elif", "for any reason we are unable to find a matching", "# If \"formatted\" is empty try to construct it from", "models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities') class Meta: verbose_name_plural = 'Localities' unique_together =", "compat_contribute_to_class compat_contribute_to_class(self, cls, name, virtual_only) # super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)", "txt += ', %s' % cntry return txt ## #", "Address.objects.create(raw=value['raw']) # Not in any of the formats I recognise.", "None) # If there is no value (empty raw) then", "blank=True) code = models.CharField(max_length=2, blank=True) # not unique as there", "__str__(self): return '%s' % (self.name or self.code) ## # A", "Address): return value # If we have an integer, assume", "elif isinstance(value, basestring): obj = Address(raw=value) obj.save() return obj #", "## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code =", "models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, on_delete=models.CASCADE,", "'postal_code', 'state') ordering = ('state', 'name') def __str__(self): txt =", "= '%s' % self.locality if txt and locality: txt +=", "name, path, args, kwargs def formfield(self, **kwargs): from .forms import", "raw: return None # Fix issue with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635)", "Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except", "= ('country', 'name') def __str__(self): txt = self.to_str() country =", "' txt += locality else: txt = '%s' % self.raw", "class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2,", "then return None. if not raw: return None # Fix", "virtual_only) # super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) #", "locality_obj = None # Handle the address. try: if not", "self.code) ## # A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model):", "% (self.name or self.code) ## # A state. Google refers", "**kwargs): from .forms import AddressField as AddressFormField defaults = dict(form_class=AddressFormField)", "int basestring = (str, bytes) unicode = str __all__ =", "other values. if not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need", "any reason we are unable to find a matching #", "blank=True) route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses',", "models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude", "+= ' %s' % self.route locality = '%s' % self.locality", "we have an integer, assume it is a model primary", "# Attempt a conversion. try: return _to_python(value) except InconsistentDictError: return", "as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True)", "txt += ', ' txt += country return txt def", "formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude =", "it is a model primary key. This is mostly for", "@python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100,", "if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj =", "unique_together = ('locality', 'route', 'street_number') def __str__(self): if self.formatted !=", "'route', 'street_number') def __str__(self): if self.formatted != '': txt =", "the country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country:", "longitude=longitude, ) # If \"formatted\" is empty try to construct", "except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor logger =", "class InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw', '') country", "other models. ## class AddressField(models.ForeignKey): description = 'An address' def", "from address.compat import compat_contribute_to_class compat_contribute_to_class(self, cls, name, virtual_only) # super(ForeignObject,", "self.formatted != '': txt = '%s' % self.formatted elif self.locality:", "class Meta: verbose_name_plural = 'Localities' unique_together = ('name', 'postal_code', 'state')", "route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True,", "# Handle the locality. try: locality_obj = Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj)", "## class AddressField(models.ForeignKey): description = 'An address' def __init__(self, *args,", "null=True) class Meta: verbose_name_plural = 'Addresses' ordering = ('locality', 'route',", "address.compat import compat_contribute_to_class compat_contribute_to_class(self, cls, name, virtual_only) # super(ForeignObject, self).contribute_to_class(cls,", "isinstance(value, (int, long)): return value # A string is considered", "class State(models.Model): name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True)", "ordering = ('name',) def __str__(self): return '%s' % (self.name or", "= ('name', 'postal_code', 'state') ordering = ('state', 'name') def __str__(self):", "# A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name =", "if self.longitude else '', ) if self.locality: ad['locality'] = self.locality.name", "None. if not raw: return None # Fix issue with", "__init__(self, *args, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(*args, **kwargs) def", "except State.DoesNotExist: if state: if len(state_code) > State._meta.get_field('code').max_length: if state_code", "'%s' % self.street_number if self.route: if txt: txt += '", "ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst,", "# Is it already an address object? if isinstance(value, Address):", "'') state = value.get('state', '') state_code = value.get('state_code', '') locality", "self.code) ## # A state. Google refers to this as", "django.utils.encoding import python_2_unicode_compatible try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError:", "If we have an integer, assume it is a model", "', ' txt += locality else: txt = '%s' %", "not self.raw: raise ValidationError('Addresses may not have a blank `raw`", "blank=True, null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude", "('locality', 'route', 'street_number') # unique_together = ('locality', 'route', 'street_number') def", "txt: txt += ' %s' % self.route locality = '%s'", "self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code']", "and state: txt += ', ' txt += state if", "% self.postal_code cntry = '%s' % (self.state.country if self.state and", "**kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(*args, **kwargs) def contribute_to_class(self, cls,", "__str__(self): if self.formatted != '': txt = '%s' % self.formatted", "self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor,", "'name') def __str__(self): txt = self.to_str() country = '%s' %", "= self.state.to_str() if self.state else '' if txt and state:", "= self.to_str() country = '%s' % self.country if country and", "if self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state:", "import sys from django.core.exceptions import ValidationError from django.db import models", "If we have an inconsistent set of value bail out", "related_name='states') class Meta: unique_together = ('name', 'country') ordering = ('country',", "and txt: txt += ', ' txt += country return", "State(models.Model): name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country", "try: locality_obj = Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj) except Locality.DoesNotExist: if locality:", "Meta: verbose_name_plural = 'Localities' unique_together = ('name', 'postal_code', 'state') ordering", "sublocality = value.get('sublocality', '') postal_code = value.get('postal_code', '') street_number =", "self.locality: txt = '' if self.street_number: txt = '%s' %", "# decomposed address we will store the raw address string", "if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad", "street_number = value.get('street_number', '') route = value.get('route', '') formatted =", "route or locality): address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get(", "raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) # If \"formatted\" is", "## # A country. ## @python_2_unicode_compatible class Country(models.Model): name =", "txt def clean(self): if not self.raw: raise ValidationError('Addresses may not", "not have a blank `raw` field.') def as_dict(self): ad =", "locality. try: locality_obj = Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj) except Locality.DoesNotExist: if", "conversion. try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not", "models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True, null=True) raw", "path, args, kwargs = super(AddressField, self).deconstruct() # del kwargs['to'] #", "def to_python(value): # Keep `None`s. if value is None: return", "self.route locality = '%s' % self.locality if txt and locality:", "return value # A string is considered a raw value.", "value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## # A field for addresses", "dictionary of named address components. elif isinstance(value, dict): # Attempt", "= 'An address' def __init__(self, *args, **kwargs): kwargs['to'] = 'address.Address'", "related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True)", "= ('locality', 'route', 'street_number') # unique_together = ('locality', 'route', 'street_number')", "models from django.db.models.fields.related import ForeignObject from django.utils.encoding import python_2_unicode_compatible try:", "% cntry return txt ## # An address. If for", "self.name, AddressDescriptor(self)) # def deconstruct(self): # name, path, args, kwargs", "@python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code =", "= Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj =", "= models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities') class Meta: verbose_name_plural = 'Localities' unique_together", "__str__(self): txt = self.to_str() country = '%s' % self.country if", "% self.formatted elif self.locality: txt = '' if self.street_number: txt", "country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country: if", "I recognise. raise ValidationError('Invalid address value.') ## # A country.", "= value.get('street_number', '') route = value.get('route', '') formatted = value.get('formatted',", "formats I recognise. raise ValidationError('Invalid address value.') ## # A", "= models.CharField(max_length=2, blank=True) # not unique as there are duplicates", "cls, name, virtual_only) # super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name,", "else '') if cntry: txt += ', %s' % cntry", "as ForwardManyToOneDescriptor logger = logging.getLogger(__name__) if sys.version > '3': long", "if txt and state: txt += ', ' txt +=", "if len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid", "latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta:", "in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True)", "if not raw: return None # Fix issue with NYC", "value.get('longitude', None) # If there is no value (empty raw)", "value.get('formatted', '') latitude = value.get('latitude', None) longitude = value.get('longitude', None)", "else: state_obj = None # Handle the locality. try: locality_obj", "this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165,", "**kwargs) def contribute_to_class(self, cls, name, virtual_only=False): from address.compat import compat_contribute_to_class", "a blank `raw` field.') def as_dict(self): ad = dict( street_number=self.street_number,", "= 'Localities' unique_together = ('name', 'postal_code', 'state') ordering = ('state',", "= Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj )", "street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality =", "'Countries' ordering = ('name',) def __str__(self): return '%s' % (self.name", "(empty raw) then return None. if not raw: return None", "route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route,", "try: if not (street_number or route or locality): address_obj =", "def clean(self): if not self.raw: raise ValidationError('Addresses may not have", "name, path, args, kwargs = super(AddressField, self).deconstruct() # del kwargs['to']", "if country_code != country: raise ValueError('Invalid country code (too long):", "latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude else '',", "ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] =", "txt = '%s' % self.street_number if self.route: if txt: txt", "# Convert a dictionary to an address. ## def to_python(value):", "None # Is it already an address object? if isinstance(value,", "components. elif isinstance(value, dict): # Attempt a conversion. try: return", "address. try: if not (street_number or route or locality): address_obj", "(too long): %s' % state_code) state_code = '' state_obj =", "blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states') class Meta: unique_together =", "blank=True) # not unique as there are duplicates (IT) class", "(self.name or self.code) ## # A state. Google refers to", "bytes) unicode = str __all__ = ['Country', 'State', 'Locality', 'Address',", "boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not locality and sublocality: locality = sublocality", "txt: txt += ', ' txt += country return txt", "cntry return txt ## # An address. If for any", "(country or state or locality) and not (country and state", "on_delete=models.CASCADE, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200,", "# A field for addresses in other models. ## class", "in other models. ## class AddressField(models.ForeignKey): description = 'An address'", "= value.get('longitude', None) # If there is no value (empty", "ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor logger", "Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True)", "AddressDescriptor(self)) # def deconstruct(self): # name, path, args, kwargs =", "NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not locality and sublocality: locality =", "' txt += state if self.postal_code: txt += ' %s'", "## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code", "state = models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities') class Meta: verbose_name_plural = 'Localities'", "pass def _to_python(value): raw = value.get('raw', '') country = value.get('country',", "'' if self.street_number: txt = '%s' % self.street_number if self.route:", "'address.Address' super(AddressField, self).__init__(*args, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): from", "country_code != country: raise ValueError('Invalid country code (too long): %s'", "Not in any of the formats I recognise. raise ValidationError('Invalid", "# return name, path, args, kwargs def formfield(self, **kwargs): from", "street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj = Address( street_number=street_number,", "except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted,", "Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length: if", "if state: if len(state_code) > State._meta.get_field('code').max_length: if state_code != state:", "# A state. Google refers to this as `administration_level_1`. ##", "('state', 'name') def __str__(self): txt = '%s' % self.name state", "if self.postal_code: txt += ' %s' % self.postal_code cntry =", "def __str__(self): return '%s' % (self.name or self.code) ## #", "+= ', ' txt += state if self.postal_code: txt +=", "a conversion. try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) #", "return name, path, args, kwargs def formfield(self, **kwargs): from .forms", "_to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any of", "for addresses in other models. ## class AddressField(models.ForeignKey): description =", "None # Handle the locality. try: locality_obj = Locality.objects.get(name=locality, postal_code=postal_code,", "A state. Google refers to this as `administration_level_1`. ## @python_2_unicode_compatible", "self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): #", "%s' % state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code,", "self.locality if txt and locality: txt += ', ' txt", "or locality): address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number,", "have an inconsistent set of value bail out now. if", "long): %s' % country_code) country_code = '' country_obj = Country.objects.create(name=country,", "to_str(self): return '%s' % (self.name or self.code) ## # A", "route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) # If \"formatted\"", "else: locality_obj = None # Handle the address. try: if", "django.db.models.fields.related import ForeignObject from django.utils.encoding import python_2_unicode_compatible try: from django.db.models.fields.related_descriptors", "(https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not locality and sublocality: locality = sublocality #", "long)): return value # A string is considered a raw", "self.to_str() country = '%s' % self.country if country and txt:", "raise ValidationError('Addresses may not have a blank `raw` field.') def", "field for addresses in other models. ## class AddressField(models.ForeignKey): description", "sys.version > '3': long = int basestring = (str, bytes)", "InconsistentDictError # Handle the country. try: country_obj = Country.objects.get(name=country) except", "latitude=latitude, longitude=longitude, ) # If \"formatted\" is empty try to", "class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True)", "ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] =", "% self.country if country and txt: txt += ', '", "blank=True) postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities')", "## # A state. Google refers to this as `administration_level_1`.", "if not locality and sublocality: locality = sublocality # If", "blank=True) locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True, null=True) raw =", "= models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses' ordering =", "class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def __str__(self):", "empty try to construct it from other values. if not", "= '%s' % self.formatted elif self.locality: txt = '' if", "from django.db.models.fields.related import ForeignObject from django.utils.encoding import python_2_unicode_compatible try: from", "try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import", "= models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities') class Meta:", "= ('state', 'name') def __str__(self): txt = '%s' % self.name", "state or locality) and not (country and state and locality):", "%s' % self.postal_code cntry = '%s' % (self.state.country if self.state", "to find a matching # decomposed address we will store", "locality): raise InconsistentDictError # Handle the country. try: country_obj =", "## # A field for addresses in other models. ##", "now. if (country or state or locality) and not (country", "def __str__(self): txt = self.to_str() country = '%s' % self.country", "related_name='localities') class Meta: verbose_name_plural = 'Localities' unique_together = ('name', 'postal_code',", "%s' % country_code) country_code = '' country_obj = Country.objects.create(name=country, code=country_code)", "state=state_obj) else: locality_obj = None # Handle the address. try:", "txt = self.to_str() country = '%s' % self.country if country", "code=country_code) else: country_obj = None # Handle the state. try:", "if country and txt: txt += ', ' txt +=", "self.formatted elif self.locality: txt = '' if self.street_number: txt =", "self.longitude else '', ) if self.locality: ad['locality'] = self.locality.name ad['postal_code']", "is None: return None # Is it already an address", "and locality: txt += ', ' txt += locality else:", "field.') def as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted,", "A field for addresses in other models. ## class AddressField(models.ForeignKey):", "args, kwargs = super(AddressField, self).deconstruct() # del kwargs['to'] # return", "'3': long = int basestring = (str, bytes) unicode =", "'') latitude = value.get('latitude', None) longitude = value.get('longitude', None) #", "ValueError('Invalid state code (too long): %s' % state_code) state_code =", "Keep `None`s. if value is None: return None # Is", "= None # Handle the state. try: state_obj = State.objects.get(name=state,", "self.state.to_str() if self.state else '' if txt and state: txt", "and self.state.country else '') if cntry: txt += ', %s'", "return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any", "longitude = value.get('longitude', None) # If there is no value", "construct it from other values. if not address_obj.formatted: address_obj.formatted =", "bail out now. if (country or state or locality) and", "street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude", "the locality. try: locality_obj = Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj) except Locality.DoesNotExist:", "@python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3,", "None) longitude = value.get('longitude', None) # If there is no", "find a matching # decomposed address we will store the", "'') state_code = value.get('state_code', '') locality = value.get('locality', '') sublocality", "locality and sublocality: locality = sublocality # If we have", "obj = Address(raw=value) obj.save() return obj # A dictionary of", "## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route =", "InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw', '') country =", "country_code = '' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj =", "may not have a blank `raw` field.') def as_dict(self): ad", "country_obj = Country.objects.create(name=country, code=country_code) else: country_obj = None # Handle", "self.name state = self.state.to_str() if self.state else '' if txt", "obj.save() return obj # A dictionary of named address components.", "= value.get('locality', '') sublocality = value.get('sublocality', '') postal_code = value.get('postal_code',", "= models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted", "is a model primary key. This is mostly for #", "# Done. return address_obj ## # Convert a dictionary to", "return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst,", "## # A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name", "state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state:", "country = value.get('country', '') country_code = value.get('country_code', '') state =", "'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw", "return None. if not raw: return None # Fix issue", "is considered a raw value. elif isinstance(value, basestring): obj =", "# Need to save. address_obj.save() # Done. return address_obj ##", "state_code = value.get('state_code', '') locality = value.get('locality', '') sublocality =", "= Address(raw=value) obj.save() return obj # A dictionary of named", "models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True) # not unique", "address value.') ## # A country. ## @python_2_unicode_compatible class Country(models.Model):", "Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj = Address(", "__all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass", "self.street_number if self.route: if txt: txt += ' %s' %", "= '' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj = None", "deconstruct(self): # name, path, args, kwargs = super(AddressField, self).deconstruct() #", "# Fix issue with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not locality", "def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## # A", "locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None", "isinstance(value, Address): return value # If we have an integer,", "locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None #", "we will store the raw address string in `raw`. ##", "= '%s' % self.raw return txt def clean(self): if not", "the address. try: if not (street_number or route or locality):", "Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude,", "kwargs def formfield(self, **kwargs): from .forms import AddressField as AddressFormField", "= models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True,", "len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state", "!= country: raise ValueError('Invalid country code (too long): %s' %", "postal_code=postal_code, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code,", "Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None # Handle the", "state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj", "ValidationError from django.db import models from django.db.models.fields.related import ForeignObject from", "state = self.state.to_str() if self.state else '' if txt and", "from .forms import AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs)", "state if self.postal_code: txt += ' %s' % self.postal_code cntry", "matching # decomposed address we will store the raw address", "super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self):", "= dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else", "there are duplicates (IT) class Meta: verbose_name_plural = 'Countries' ordering", "address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude,", "address_obj.save() # Done. return address_obj ## # Convert a dictionary", "= str __all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField'] class", "unicode = str __all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField']", ") # If \"formatted\" is empty try to construct it", "= value.get('postal_code', '') street_number = value.get('street_number', '') route = value.get('route',", "= models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True) # not", "address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj", "description = 'An address' def __init__(self, *args, **kwargs): kwargs['to'] =", "% self.locality if txt and locality: txt += ', '", "have an integer, assume it is a model primary key.", "Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist:", "are duplicates (IT) class Meta: verbose_name_plural = 'Countries' ordering =", "'country') ordering = ('country', 'name') def __str__(self): txt = self.to_str()", "(suburb). ## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code", "AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## #", "= (str, bytes) unicode = str __all__ = ['Country', 'State',", "state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj = None #", "a cunt. elif isinstance(value, (int, long)): return value # A", "'name') def __str__(self): txt = '%s' % self.name state =", "import compat_contribute_to_class compat_contribute_to_class(self, cls, name, virtual_only) # super(ForeignObject, self).contribute_to_class(cls, name,", "from django.core.exceptions import ValidationError from django.db import models from django.db.models.fields.related", "code=state_code, country=country_obj) else: state_obj = None # Handle the locality.", "address we will store the raw address string in `raw`.", "are unable to find a matching # decomposed address we", "'An address' def __init__(self, *args, **kwargs): kwargs['to'] = 'address.Address' super(AddressField,", "Convert a dictionary to an address. ## def to_python(value): #", "'' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj = None", "= models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country,", "Handle the country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if", "blank=True) state = models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities') class Meta: verbose_name_plural =", "def __str__(self): if self.formatted != '': txt = '%s' %", "+= state if self.postal_code: txt += ' %s' % self.postal_code", "country_code = value.get('country_code', '') state = value.get('state', '') state_code =", "return None # Fix issue with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if", "State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state code (too", "country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code != country: raise", "\"formatted\" is empty try to construct it from other values.", "sublocality # If we have an inconsistent set of value", "`None`s. if value is None: return None # Is it", "the formats I recognise. raise ValidationError('Invalid address value.') ## #", "None # Fix issue with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not", "return '%s' % (self.name or self.code) ## # A locality", "# An address. If for any reason we are unable", "self.latitude else '', longitude=self.longitude if self.longitude else '', ) if", "def to_str(self): return '%s' % (self.name or self.code) ## #", "else: txt = '%s' % self.raw return txt def clean(self):", "'%s' % self.country if country and txt: txt += ',", "'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw',", "['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value):", "> Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid country code", "if sys.version > '3': long = int basestring = (str,", "State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj = None # Handle the", "is mostly for # Django being a cunt. elif isinstance(value,", "> State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state code", "'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw', '')", "it from other values. if not address_obj.formatted: address_obj.formatted = unicode(address_obj)", "= models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality,", "cunt. elif isinstance(value, (int, long)): return value # A string", "'street_number') def __str__(self): if self.formatted != '': txt = '%s'", "verbose_name_plural = 'Addresses' ordering = ('locality', 'route', 'street_number') # unique_together", "blank=True) code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states')", "(IT) class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def", "longitude=self.longitude if self.longitude else '', ) if self.locality: ad['locality'] =", "= value.get('state_code', '') locality = value.get('locality', '') sublocality = value.get('sublocality',", "value.get('sublocality', '') postal_code = value.get('postal_code', '') street_number = value.get('street_number', '')", "import ForeignObject from django.utils.encoding import python_2_unicode_compatible try: from django.db.models.fields.related_descriptors import", "django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as", "assume it is a model primary key. This is mostly", "the raw address string in `raw`. ## @python_2_unicode_compatible class Address(models.Model):", "of value bail out now. if (country or state or", "= unicode(address_obj) # Need to save. address_obj.save() # Done. return", "= ('locality', 'route', 'street_number') def __str__(self): if self.formatted != '':", "address_obj ## # Convert a dictionary to an address. ##", "= logging.getLogger(__name__) if sys.version > '3': long = int basestring", "= '%s' % (self.state.country if self.state and self.state.country else '')", "txt = '%s' % self.formatted elif self.locality: txt = ''", "dictionary to an address. ## def to_python(value): # Keep `None`s.", "value.get('country_code', '') state = value.get('state', '') state_code = value.get('state_code', '')", "= '%s' % self.country if country and txt: txt +=", "from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor logger = logging.getLogger(__name__) if", "% (self.name or self.code) ## # A locality (suburb). ##", "(int, long)): return value # A string is considered a", "+= locality else: txt = '%s' % self.raw return txt", "State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: if len(state_code) > State._meta.get_field('code').max_length:", "compat_contribute_to_class(self, cls, name, virtual_only) # super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls,", "models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states') class Meta: unique_together = ('name', 'country') ordering", "# name, path, args, kwargs = super(AddressField, self).deconstruct() # del", "isinstance(value, basestring): obj = Address(raw=value) obj.save() return obj # A", "return Address.objects.create(raw=value['raw']) # Not in any of the formats I", "', %s' % cntry return txt ## # An address.", "self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code']", "= 'address.Address' super(AddressField, self).__init__(*args, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False):", "cntry = '%s' % (self.state.country if self.state and self.state.country else", "## def to_python(value): # Keep `None`s. if value is None:", "virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): # name, path,", "txt def to_str(self): return '%s' % (self.name or self.code) ##", "basestring): obj = Address(raw=value) obj.save() return obj # A dictionary", "## # An address. If for any reason we are", "or self.code) ## # A state. Google refers to this", "ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] =", "self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country']", "ForwardManyToOneDescriptor logger = logging.getLogger(__name__) if sys.version > '3': long =", "mostly for # Django being a cunt. elif isinstance(value, (int,", "state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else:", "latitude = value.get('latitude', None) longitude = value.get('longitude', None) # If", "isinstance(value, dict): # Attempt a conversion. try: return _to_python(value) except", "+= ' %s' % self.postal_code cntry = '%s' % (self.state.country", "'') formatted = value.get('formatted', '') latitude = value.get('latitude', None) longitude", "state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: if len(state_code)", "= State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: if len(state_code) >", "if cntry: txt += ', %s' % cntry return txt", "formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude else", "= value.get('country_code', '') state = value.get('state', '') state_code = value.get('state_code',", "state. Google refers to this as `administration_level_1`. ## @python_2_unicode_compatible class", "('name', 'country') ordering = ('country', 'name') def __str__(self): txt =", "`administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True) code", "unique_together = ('name', 'country') ordering = ('country', 'name') def __str__(self):", "virtual_only=False): from address.compat import compat_contribute_to_class compat_contribute_to_class(self, cls, name, virtual_only) #", "models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities') class Meta: verbose_name_plural", "models.CharField(max_length=2, blank=True) # not unique as there are duplicates (IT)", "address object? if isinstance(value, Address): return value # If we", "return txt def clean(self): if not self.raw: raise ValidationError('Addresses may", "address string in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number =", "= value.get('country', '') country_code = value.get('country_code', '') state = value.get('state',", "'', longitude=self.longitude if self.longitude else '', ) if self.locality: ad['locality']", "to_python(value)) ## # A field for addresses in other models.", "value.get('raw', '') country = value.get('country', '') country_code = value.get('country_code', '')", "long = int basestring = (str, bytes) unicode = str", "if country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code != country:", "store the raw address string in `raw`. ## @python_2_unicode_compatible class", "'') country_code = value.get('country_code', '') state = value.get('state', '') state_code", "Attempt a conversion. try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw'])", "name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state =", "self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return", "Meta: verbose_name_plural = 'Addresses' ordering = ('locality', 'route', 'street_number') #", "locality = '%s' % self.locality if txt and locality: txt", "= Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None # Handle", "'route', 'street_number') # unique_together = ('locality', 'route', 'street_number') def __str__(self):", "from django.db import models from django.db.models.fields.related import ForeignObject from django.utils.encoding", "not (street_number or route or locality): address_obj = Address.objects.get(raw=raw) else:", "models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE,", "code (too long): %s' % state_code) state_code = '' state_obj", "= None # Handle the locality. try: locality_obj = Locality.objects.get(name=locality,", "logging.getLogger(__name__) if sys.version > '3': long = int basestring =", "dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '',", "or locality) and not (country and state and locality): raise", "no value (empty raw) then return None. if not raw:", "(country and state and locality): raise InconsistentDictError # Handle the", "= 'Countries' ordering = ('name',) def __str__(self): return '%s' %", "= '%s' % self.name state = self.state.to_str() if self.state else", "# If we have an inconsistent set of value bail", "an address. ## def to_python(value): # Keep `None`s. if value", "ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value))", "# If there is no value (empty raw) then return", "class AddressField(models.ForeignKey): description = 'An address' def __init__(self, *args, **kwargs):", "try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code)", "# Handle the address. try: if not (street_number or route", "value # A string is considered a raw value. elif", "name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country =", "' txt += country return txt def to_str(self): return '%s'", "raw = value.get('raw', '') country = value.get('country', '') country_code =", "% country_code) country_code = '' country_obj = Country.objects.create(name=country, code=country_code) else:", "country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code) >", "django.db import models from django.db.models.fields.related import ForeignObject from django.utils.encoding import", "Address(raw=value) obj.save() return obj # A dictionary of named address", "', ' txt += state if self.postal_code: txt += '", "self.postal_code: txt += ' %s' % self.postal_code cntry = '%s'", "'%s' % self.locality if txt and locality: txt += ',", "locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True)", "a raw value. elif isinstance(value, basestring): obj = Address(raw=value) obj.save()", "inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## # A field for", "def _to_python(value): raw = value.get('raw', '') country = value.get('country', '')", "= ('name', 'country') ordering = ('country', 'name') def __str__(self): txt", "already an address object? if isinstance(value, Address): return value #", "it already an address object? if isinstance(value, Address): return value", "'') if cntry: txt += ', %s' % cntry return", "txt += ', ' txt += locality else: txt =", "value.get('route', '') formatted = value.get('formatted', '') latitude = value.get('latitude', None)", "%s' % self.route locality = '%s' % self.locality if txt", "An address. If for any reason we are unable to", "duplicates (IT) class Meta: verbose_name_plural = 'Countries' ordering = ('name',)", "(str, bytes) unicode = str __all__ = ['Country', 'State', 'Locality',", "self.state else '' if txt and state: txt += ',", "% self.name state = self.state.to_str() if self.state else '' if", "txt ## # An address. If for any reason we", "('country', 'name') def __str__(self): txt = self.to_str() country = '%s'", "self.raw return txt def clean(self): if not self.raw: raise ValidationError('Addresses", "state: raise ValueError('Invalid state code (too long): %s' % state_code)", "address_obj.formatted = unicode(address_obj) # Need to save. address_obj.save() # Done.", "% self.raw return txt def clean(self): if not self.raw: raise", "blank `raw` field.') def as_dict(self): ad = dict( street_number=self.street_number, route=self.route,", "name, virtual_only) # super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self))", "# Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj) except", "# Handle the country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist:", "None # Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj)", "ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor logger = logging.getLogger(__name__) if sys.version > '3':", "value (empty raw) then return None. if not raw: return", "Country.objects.create(name=country, code=country_code) else: country_obj = None # Handle the state.", "= State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj = None # Handle", "refers to this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name", "model primary key. This is mostly for # Django being", "there is no value (empty raw) then return None. if", "= self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name", "'%s' % (self.state.country if self.state and self.state.country else '') if", "kwargs['to'] = 'address.Address' super(AddressField, self).__init__(*args, **kwargs) def contribute_to_class(self, cls, name,", "def __init__(self, *args, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(*args, **kwargs)", "except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else:", "= self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def", "models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural =", "(street_number or route or locality): address_obj = Address.objects.get(raw=raw) else: address_obj", "' %s' % self.postal_code cntry = '%s' % (self.state.country if", "if self.state else '' if txt and state: txt +=", "!= '': txt = '%s' % self.formatted elif self.locality: txt", "decomposed address we will store the raw address string in", "locality=locality_obj ) except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw,", "del kwargs['to'] # return name, path, args, kwargs def formfield(self,", "postal_code=postal_code, state=state_obj) else: locality_obj = None # Handle the address.", "postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities') class", "self.street_number: txt = '%s' % self.street_number if self.route: if txt:", "python_2_unicode_compatible try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related", "value.') ## # A country. ## @python_2_unicode_compatible class Country(models.Model): name", "or route or locality): address_obj = Address.objects.get(raw=raw) else: address_obj =", "elif self.locality: txt = '' if self.street_number: txt = '%s'", "value.get('locality', '') sublocality = value.get('sublocality', '') postal_code = value.get('postal_code', '')", "if (country or state or locality) and not (country and", "if self.route: if txt: txt += ' %s' % self.route", "value.get('state', '') state_code = value.get('state_code', '') locality = value.get('locality', '')", "self).__set__(inst, to_python(value)) ## # A field for addresses in other", "If there is no value (empty raw) then return None.", "long): %s' % state_code) state_code = '' state_obj = State.objects.create(name=state,", "set of value bail out now. if (country or state", "being a cunt. elif isinstance(value, (int, long)): return value #", "to an address. ## def to_python(value): # Keep `None`s. if", "self).__init__(*args, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): from address.compat import", "# not unique as there are duplicates (IT) class Meta:", "raise ValidationError('Invalid address value.') ## # A country. ## @python_2_unicode_compatible", "'street_number') # unique_together = ('locality', 'route', 'street_number') def __str__(self): if", "+= ', ' txt += country return txt def to_str(self):", "if txt and locality: txt += ', ' txt +=", "ValidationError('Addresses may not have a blank `raw` field.') def as_dict(self):", "if len(country_code) > Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid", "= models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True, null=True)", "len(country_code) > Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid country", "# If we have an integer, assume it is a", "self.postal_code cntry = '%s' % (self.state.country if self.state and self.state.country", "self.raw: raise ValidationError('Addresses may not have a blank `raw` field.')", "else '', ) if self.locality: ad['locality'] = self.locality.name ad['postal_code'] =", "country_code) country_code = '' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj", "or state or locality) and not (country and state and", "if value is None: return None # Is it already", "txt = '' if self.street_number: txt = '%s' % self.street_number", "django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor logger = logging.getLogger(__name__) if sys.version", "% state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj)", "Handle the locality. try: locality_obj = Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj) except", "'', ) if self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code", "route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if", "address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to save. address_obj.save() #", "state: txt += ', ' txt += state if self.postal_code:", "= models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State,", "setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): # name, path, args,", "def as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude", "country=country_obj) except State.DoesNotExist: if state: if len(state_code) > State._meta.get_field('code').max_length: if", "# A string is considered a raw value. elif isinstance(value,", "not locality and sublocality: locality = sublocality # If we", "addresses in other models. ## class AddressField(models.ForeignKey): description = 'An", "self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if", "value.get('street_number', '') route = value.get('route', '') formatted = value.get('formatted', '')", "country: raise ValueError('Invalid country code (too long): %s' % country_code)", "name, virtual_only=False): from address.compat import compat_contribute_to_class compat_contribute_to_class(self, cls, name, virtual_only)", "if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country:", "% self.street_number if self.route: if txt: txt += ' %s'", "if txt: txt += ' %s' % self.route locality =", "address. If for any reason we are unable to find", "' %s' % self.route locality = '%s' % self.locality if", "ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude", "blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class", "sys from django.core.exceptions import ValidationError from django.db import models from", "locality: txt += ', ' txt += locality else: txt", "locality) and not (country and state and locality): raise InconsistentDictError", "state=state_obj) except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj)", "try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in", "unique=True, blank=True) code = models.CharField(max_length=2, blank=True) # not unique as", "a model primary key. This is mostly for # Django", "name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): # name,", "def formfield(self, **kwargs): from .forms import AddressField as AddressFormField defaults", "key. This is mostly for # Django being a cunt.", "'' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj = None #", "txt += ', ' txt += state if self.postal_code: txt", "country_obj = None # Handle the state. try: state_obj =", "country=country_obj) else: state_obj = None # Handle the locality. try:", "save. address_obj.save() # Done. return address_obj ## # Convert a", "'Addresses' ordering = ('locality', 'route', 'street_number') # unique_together = ('locality',", "Meta: verbose_name_plural = 'Countries' ordering = ('name',) def __str__(self): return", "or self.code) ## # A locality (suburb). ## @python_2_unicode_compatible class", "value.get('state_code', '') locality = value.get('locality', '') sublocality = value.get('sublocality', '')", "ValueError('Invalid country code (too long): %s' % country_code) country_code =", "value bail out now. if (country or state or locality)", "self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self,", "'') sublocality = value.get('sublocality', '') postal_code = value.get('postal_code', '') street_number", "have a blank `raw` field.') def as_dict(self): ad = dict(", "InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any of the formats", "Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code !=", "route = value.get('route', '') formatted = value.get('formatted', '') latitude =", "in any of the formats I recognise. raise ValidationError('Invalid address", "named address components. elif isinstance(value, dict): # Attempt a conversion.", "= 'Addresses' ordering = ('locality', 'route', 'street_number') # unique_together =", "country = '%s' % self.country if country and txt: txt", "street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) # If", "Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state", "of named address components. elif isinstance(value, dict): # Attempt a", "def contribute_to_class(self, cls, name, virtual_only=False): from address.compat import compat_contribute_to_class compat_contribute_to_class(self,", "locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) # If \"formatted\" is empty", "from django.utils.encoding import python_2_unicode_compatible try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except", "as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if", "= value.get('raw', '') country = value.get('country', '') country_code = value.get('country_code',", "cntry: txt += ', %s' % cntry return txt ##", "for # Django being a cunt. elif isinstance(value, (int, long)):", "longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses' ordering", "basestring = (str, bytes) unicode = str __all__ = ['Country',", "A string is considered a raw value. elif isinstance(value, basestring):", "models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states') class Meta: unique_together", "raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True,", "= Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj =", "state and locality): raise InconsistentDictError # Handle the country. try:", "else '', longitude=self.longitude if self.longitude else '', ) if self.locality:", "'%s' % self.raw return txt def clean(self): if not self.raw:", "AddressField(models.ForeignKey): description = 'An address' def __init__(self, *args, **kwargs): kwargs['to']", "to this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name =", "return txt ## # An address. If for any reason", "the state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if", "reason we are unable to find a matching # decomposed", "models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, on_delete=models.CASCADE,", "country code (too long): %s' % country_code) country_code = ''", "import AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs) return super(AddressField,", "%s' % cntry return txt ## # An address. If", "= '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj =", "'%s' % self.formatted elif self.locality: txt = '' if self.street_number:", ") except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj,", "return value # If we have an integer, assume it", "as there are duplicates (IT) class Meta: verbose_name_plural = 'Countries'", "obj # A dictionary of named address components. elif isinstance(value,", "= value.get('sublocality', '') postal_code = value.get('postal_code', '') street_number = value.get('street_number',", "to_python(value): # Keep `None`s. if value is None: return None", "dict): # Attempt a conversion. try: return _to_python(value) except InconsistentDictError:", "(self.state.country if self.state and self.state.country else '') if cntry: txt", "clean(self): if not self.raw: raise ValidationError('Addresses may not have a", "super(AddressDescriptor, self).__set__(inst, to_python(value)) ## # A field for addresses in", "code = models.CharField(max_length=2, blank=True) # not unique as there are", "'') country = value.get('country', '') country_code = value.get('country_code', '') state", "state_obj = None # Handle the locality. try: locality_obj =", "`raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route", "self.route: if txt: txt += ' %s' % self.route locality", "Django being a cunt. elif isinstance(value, (int, long)): return value", "('name',) def __str__(self): return '%s' % (self.name or self.code) ##", "# A dictionary of named address components. elif isinstance(value, dict):", "txt = '%s' % self.name state = self.state.to_str() if self.state", "txt += ' %s' % self.postal_code cntry = '%s' %", "= models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural", "+= country return txt def to_str(self): return '%s' % (self.name", "from other values. if not address_obj.formatted: address_obj.formatted = unicode(address_obj) #", "ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor logger = logging.getLogger(__name__)", "self.state.country else '') if cntry: txt += ', %s' %", "if not self.raw: raise ValidationError('Addresses may not have a blank", "kwargs['to'] # return name, path, args, kwargs def formfield(self, **kwargs):", "address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj", "to save. address_obj.save() # Done. return address_obj ## # Convert", "'%s' % self.name state = self.state.to_str() if self.state else ''", "try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: if", "@python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10,", "Fix issue with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) if not locality and", "verbose_name_plural = 'Countries' ordering = ('name',) def __str__(self): return '%s'", "is empty try to construct it from other values. if", "'') postal_code = value.get('postal_code', '') street_number = value.get('street_number', '') route", "None: return None # Is it already an address object?", "= ['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def", "_to_python(value): raw = value.get('raw', '') country = value.get('country', '') country_code", "locality else: txt = '%s' % self.raw return txt def", "unicode(address_obj) # Need to save. address_obj.save() # Done. return address_obj", "unique as there are duplicates (IT) class Meta: verbose_name_plural =", ") if self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if", "State.DoesNotExist: if state: if len(state_code) > State._meta.get_field('code').max_length: if state_code !=", "`raw` field.') def as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw,", "code (too long): %s' % country_code) country_code = '' country_obj", "not unique as there are duplicates (IT) class Meta: verbose_name_plural", "'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw =", "## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True) code =", "= models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states') class Meta:", "ordering = ('state', 'name') def __str__(self): txt = '%s' %", "null=True) longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses'", "inconsistent set of value bail out now. if (country or", "on_delete=models.CASCADE, related_name='localities') class Meta: verbose_name_plural = 'Localities' unique_together = ('name',", "raise ValueError('Invalid country code (too long): %s' % country_code) country_code", "= value.get('state', '') state_code = value.get('state_code', '') locality = value.get('locality'," ]
[ "# -*- coding: utf-8 -*- \"\"\" Modules for exposing functions", "\"\"\" Modules for exposing functions that can be run as", "as tasks. \"\"\" from __future__ import (absolute_import, division, print_function, unicode_literals)", "<reponame>eavatar/ava # -*- coding: utf-8 -*- \"\"\" Modules for exposing", "that can be run as tasks. \"\"\" from __future__ import", "utf-8 -*- \"\"\" Modules for exposing functions that can be", "run as tasks. \"\"\" from __future__ import (absolute_import, division, print_function,", "for exposing functions that can be run as tasks. \"\"\"", "coding: utf-8 -*- \"\"\" Modules for exposing functions that can", "Modules for exposing functions that can be run as tasks.", "exposing functions that can be run as tasks. \"\"\" from", "-*- coding: utf-8 -*- \"\"\" Modules for exposing functions that", "-*- \"\"\" Modules for exposing functions that can be run", "functions that can be run as tasks. \"\"\" from __future__", "be run as tasks. \"\"\" from __future__ import (absolute_import, division,", "can be run as tasks. \"\"\" from __future__ import (absolute_import," ]
[ "= (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id,", "super(HrPayslip, self).action_payslip_done() for slip in self: line_ids = [] debit_sum", "HrPayslipRun(models.Model): _inherit = 'hr.payslip.run' journal_id = fields.Many2one('account.journal', 'Salary Journal', states={'draft':", "in self.env.context: vals['journal_id'] = self.env.context.get('journal_id') return super(HrPayslip, self).create(vals) @api.onchange('contract_id') def", "'general')], limit=1)) move_id = fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False) @api.model", "slip.date or slip.date_to currency = slip.company_id.currency_id or slip.journal_id.company_id.currency_id name =", "= fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True, default=lambda", "api, fields, models, _ from odoo.exceptions import UserError from odoo.tools", "create(self, vals): if 'journal_id' in self.env.context: vals['journal_id'] = self.env.context.get('journal_id') return", "< 0.0 and -amount or 0.0, 'credit': amount > 0.0", "amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, })", "% (slip.journal_id.name)) adjust_debit = (0, 0, { 'name': _('Adjustment Entry'),", "fields.Many2one('account.analytic.account', 'Analytic Account') journal_id = fields.Many2one('account.journal', 'Salary Journal') class HrPayslipRun(models.Model):", "line.total) if currency.is_zero(amount): continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id", "- debit_sum), 'credit': 0.0, }) line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids move", "configured the Debit Account!') % (slip.journal_id.name)) adjust_debit = (0, 0,", "= currency.round(slip.credit_note and -line.total or line.total) if currency.is_zero(amount): continue debit_account_id", "currency.round(debit_sum - credit_sum), }) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum) == -1:", "'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if", "- credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum) == -1: acc_id = slip.journal_id.default_credit_account_id.id", "account_credit = fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=', False)]) class HrContract(models.Model):", "Account!') % (slip.journal_id.name)) adjust_debit = (0, 0, { 'name': _('Adjustment", "= 'hr.payslip.line' def _get_partner_id(self, credit_account): \"\"\" Get partner_id of slip", "@api.multi def action_payslip_cancel(self): moves = self.mapped('move_id') moves.filtered(lambda x: x.state ==", "'journal_id': slip.journal_id.id, 'date': date, 'debit': amount > 0.0 and amount", "for slip in self: line_ids = [] debit_sum = 0.0", "debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line = (0, 0, {", "journal_id = fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True, states={'draft': [('readonly', False)]},", "'journal_id': slip.journal_id.id, 'date': date, 'debit': 0.0, 'credit': currency.round(debit_sum - credit_sum),", "HrPayslipLine(models.Model): _inherit = 'hr.payslip.line' def _get_partner_id(self, credit_account): \"\"\" Get partner_id", "= line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0, { 'name':", "'debit': amount < 0.0 and -amount or 0.0, 'credit': amount", "the Credit Account!') % (slip.journal_id.name)) adjust_credit = (0, 0, {", "self: line_ids = [] debit_sum = 0.0 credit_sum = 0.0", "('receivable', 'payable'): return partner_id else: if register_partner_id or self.salary_rule_id.account_debit.internal_type in", "or (not self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self): moves =", "'date': date, } for line in slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note", "slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit']", "-amount or 0.0, 'credit': amount > 0.0 and amount or", "Account', domain=[('deprecated', '=', False)]) class HrContract(models.Model): _inherit = 'hr.contract' _description", "date.\") journal_id = fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True, states={'draft': [('readonly',", "not properly configured the Debit Account!') % (slip.journal_id.name)) adjust_debit =", "'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum +=", "from odoo.exceptions import UserError from odoo.tools import float_compare, float_is_zero class", "% (slip.journal_id.name)) adjust_credit = (0, 0, { 'name': _('Adjustment Entry'),", "'credit': 0.0, }) line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids move = self.env['account.move'].create(move_dict)", "HrContract(models.Model): _inherit = 'hr.contract' _description = 'Employee Contract' analytic_account_id =", "'hr.contract' _description = 'Employee Contract' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account')", "-*- # Part of Odoo. See LICENSE file for full", "False class HrPayslip(models.Model): _inherit = 'hr.payslip' date = fields.Date('Date Account',", "self).create(vals) @api.onchange('contract_id') def onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id = self.contract_id.journal_id.id or", "False)]) account_credit = fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=', False)]) class", "= line_ids move = self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date': date}) move.post()", "and -amount or 0.0, 'credit': amount > 0.0 and amount", "use partner of salary rule or fallback on employee's address", "in ('receivable', 'payable'): return partner_id else: if register_partner_id or self.salary_rule_id.account_debit.internal_type", "domain=[('deprecated', '=', False)]) account_credit = fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=',", "odoo.exceptions import UserError from odoo.tools import float_compare, float_is_zero class HrPayslipLine(models.Model):", "res = super(HrPayslip, self).action_payslip_done() for slip in self: line_ids =", "}) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum) == -1: acc_id = slip.journal_id.default_debit_account_id.id", "= 'hr.payslip' date = fields.Date('Date Account', states={'draft': [('readonly', False)]}, readonly=True,", "action_payslip_done(self): res = super(HrPayslip, self).action_payslip_done() for slip in self: line_ids", "employee's address register_partner_id = self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id", "if register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return partner_id else:", "action_payslip_cancel(self): moves = self.mapped('move_id') moves.filtered(lambda x: x.state == 'posted').button_cancel() moves.unlink()", "date}) move.post() return res class HrSalaryRule(models.Model): _inherit = 'hr.salary.rule' analytic_account_id", "(slip.journal_id.name)) adjust_credit = (0, 0, { 'name': _('Adjustment Entry'), 'partner_id':", "acc_id: raise UserError(_('The Expense Journal \"%s\" has not properly configured", "super(HrPayslip, self).create(vals) @api.onchange('contract_id') def onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id = self.contract_id.journal_id.id", "= slip.company_id.currency_id or slip.journal_id.company_id.currency_id name = _('Payslip of %s') %", "> 0.0 and amount or 0.0, 'credit': amount < 0.0", "line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids move = self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date':", "'hr.payslip.run' journal_id = fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True,", "fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False) @api.model def create(self, vals): if", "0.0 and -amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id':", "slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note and -line.total or line.total) if currency.is_zero(amount):", "HrSalaryRule(models.Model): _inherit = 'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id", "False)]}, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1)) move_id = fields.Many2one('account.move',", "of salary rule or fallback on employee's address register_partner_id =", "analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id = fields.Many2one('account.tax', 'Tax') account_debit", "required=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1))", "self.journal_id = self.contract_id.journal_id.id or (not self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi def", "line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit']", "or line.total) if currency.is_zero(amount): continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id =", "credit_sum), }) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum) == -1: acc_id =", "register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return partner_id return False", "models, _ from odoo.exceptions import UserError from odoo.tools import float_compare,", "vals): if 'journal_id' in self.env.context: vals['journal_id'] = self.env.context.get('journal_id') return super(HrPayslip,", "= { 'narration': name, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'date': date,", "line to use in account_move_line \"\"\" # use partner of", "partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id if credit_account: if register_partner_id or", "< 0.0 and -amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id,", "line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount >", "or self.slip_id.employee_id.address_home_id.id if credit_account: if register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable',", "moves.filtered(lambda x: x.state == 'posted').button_cancel() moves.unlink() return super(HrPayslip, self).action_payslip_cancel() @api.multi", "amount or 0.0, 'credit': amount < 0.0 and -amount or", "full copyright and licensing details. from odoo import api, fields,", "slip.journal_id.default_credit_account_id.id if not acc_id: raise UserError(_('The Expense Journal \"%s\" has", "(0, 0, { 'name': _('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id,", "= slip.date or slip.date_to currency = slip.company_id.currency_id or slip.journal_id.company_id.currency_id name", "copy=False) @api.model def create(self, vals): if 'journal_id' in self.env.context: vals['journal_id']", "licensing details. from odoo import api, fields, models, _ from", "slip.write({'move_id': move.id, 'date': date}) move.post() return res class HrSalaryRule(models.Model): _inherit", "slip.journal_id.company_id.currency_id name = _('Payslip of %s') % (slip.employee_id.name) move_dict =", "x.state == 'posted').button_cancel() moves.unlink() return super(HrPayslip, self).action_payslip_cancel() @api.multi def action_payslip_done(self):", "'=', False)]) class HrContract(models.Model): _inherit = 'hr.contract' _description = 'Employee", "0.0, }) line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids move = self.env['account.move'].create(move_dict) slip.write({'move_id':", "or fallback on employee's address register_partner_id = self.salary_rule_id.register_id.partner_id partner_id =", "0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id,", "credit_line = (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id':", "credit_sum = 0.0 date = slip.date or slip.date_to currency =", "= register_partner_id.id or self.slip_id.employee_id.address_home_id.id if credit_account: if register_partner_id or self.salary_rule_id.account_credit.internal_type", "credit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount < 0.0 and", "Credit Account!') % (slip.journal_id.name)) adjust_credit = (0, 0, { 'name':", "rule or fallback on employee's address register_partner_id = self.salary_rule_id.register_id.partner_id partner_id", "@api.onchange('contract_id') def onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id = self.contract_id.journal_id.id or (not", "adjust_debit = (0, 0, { 'name': _('Adjustment Entry'), 'partner_id': False,", "line_ids = [] debit_sum = 0.0 credit_sum = 0.0 date", "continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line", "class HrPayslipLine(models.Model): _inherit = 'hr.payslip.line' def _get_partner_id(self, credit_account): \"\"\" Get", "not properly configured the Credit Account!') % (slip.journal_id.name)) adjust_credit =", "'Tax') account_debit = fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=', False)]) account_credit", "amount < 0.0 and -amount or 0.0, 'credit': amount >", "import UserError from odoo.tools import float_compare, float_is_zero class HrPayslipLine(models.Model): _inherit", "use in account_move_line \"\"\" # use partner of salary rule", "self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return partner_id else: if register_partner_id or", "move_dict['line_ids'] = line_ids move = self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date': date})", "'Analytic Account') journal_id = fields.Many2one('account.journal', 'Salary Journal') class HrPayslipRun(models.Model): _inherit", "return False class HrPayslip(models.Model): _inherit = 'hr.payslip' date = fields.Date('Date", "== -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise UserError(_('The", "credit_account): \"\"\" Get partner_id of slip line to use in", "'debit': amount > 0.0 and amount or 0.0, 'credit': amount", "float_compare, float_is_zero class HrPayslipLine(models.Model): _inherit = 'hr.payslip.line' def _get_partner_id(self, credit_account):", "= fields.Many2one('account.analytic.account', 'Analytic Account') journal_id = fields.Many2one('account.journal', 'Salary Journal') class", "'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': currency.round(credit_sum - debit_sum),", "[('readonly', False)]}, readonly=True, help=\"Keep empty to use the period of", "currency.round(credit_sum - debit_sum), 'credit': 0.0, }) line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids", "@api.model def create(self, vals): if 'journal_id' in self.env.context: vals['journal_id'] =", "= fields.Many2one('account.journal', 'Salary Journal') class HrPayslipRun(models.Model): _inherit = 'hr.payslip.run' journal_id", "Journal \"%s\" has not properly configured the Credit Account!') %", "line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum) ==", "-1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise UserError(_('The Expense", "Account', states={'draft': [('readonly', False)]}, readonly=True, help=\"Keep empty to use the", "moves = self.mapped('move_id') moves.filtered(lambda x: x.state == 'posted').button_cancel() moves.unlink() return", "self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date': date}) move.post() return res class HrSalaryRule(models.Model):", "debit_sum) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise", "and amount or 0.0, 'credit': amount < 0.0 and -amount", "line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit':", "date, } for line in slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note and", "'credit': amount > 0.0 and amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id", "self).action_payslip_cancel() @api.multi def action_payslip_done(self): res = super(HrPayslip, self).action_payslip_done() for slip", "= 'hr.contract' _description = 'Employee Contract' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic", "<reponame>jjiege/odoo<filename>addons/hr_payroll_account/models/hr_payroll_account.py #-*- coding:utf-8 -*- # Part of Odoo. See LICENSE", "partner_id return False class HrPayslip(models.Model): _inherit = 'hr.payslip' date =", "0.0, 'credit': currency.round(debit_sum - credit_sum), }) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum)", "Account!') % (slip.journal_id.name)) adjust_credit = (0, 0, { 'name': _('Adjustment", "or 0.0, 'credit': amount > 0.0 and amount or 0.0,", "date, 'debit': amount < 0.0 and -amount or 0.0, 'credit':", "'narration': name, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'date': date, } for", "= _('Payslip of %s') % (slip.employee_id.name) move_dict = { 'narration':", "amount > 0.0 and amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or", "False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': currency.round(credit_sum -", "file for full copyright and licensing details. from odoo import", "self).onchange_contract() self.journal_id = self.contract_id.journal_id.id or (not self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi", "if currency.is_zero(amount): continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if", "move = self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date': date}) move.post() return res", "self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return partner_id return False class HrPayslip(models.Model):", "self).action_payslip_done() for slip in self: line_ids = [] debit_sum =", "self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self): moves = self.mapped('move_id') moves.filtered(lambda", "slip.date_to currency = slip.company_id.currency_id or slip.journal_id.company_id.currency_id name = _('Payslip of", "of the validation(Payslip) date.\") journal_id = fields.Many2one('account.journal', 'Salary Journal', readonly=True,", "line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit':", "def action_payslip_cancel(self): moves = self.mapped('move_id') moves.filtered(lambda x: x.state == 'posted').button_cancel()", "\"%s\" has not properly configured the Credit Account!') % (slip.journal_id.name))", "return res class HrSalaryRule(models.Model): _inherit = 'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account',", "_inherit = 'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id =", "account_debit = fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=', False)]) account_credit =", "slip.journal_id.default_debit_account_id.id if not acc_id: raise UserError(_('The Expense Journal \"%s\" has", "= 0.0 credit_sum = 0.0 date = slip.date or slip.date_to", "readonly=True, help=\"Keep empty to use the period of the validation(Payslip)", "debit_account_id: debit_line = (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=False),", "line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0,", "(slip.employee_id.name) move_dict = { 'narration': name, 'ref': slip.number, 'journal_id': slip.journal_id.id,", "[] debit_sum = 0.0 credit_sum = 0.0 date = slip.date", "% (slip.employee_id.name) move_dict = { 'narration': name, 'ref': slip.number, 'journal_id':", "= (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id,", "fields.Many2one('account.tax', 'Tax') account_debit = fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=', False)])", "of Odoo. See LICENSE file for full copyright and licensing", "'Debit Account', domain=[('deprecated', '=', False)]) account_credit = fields.Many2one('account.account', 'Credit Account',", "limit=1)) move_id = fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False) @api.model def", "and -line.total or line.total) if currency.is_zero(amount): continue debit_account_id = line.salary_rule_id.account_debit.id", "0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id,", "date = fields.Date('Date Account', states={'draft': [('readonly', False)]}, readonly=True, help=\"Keep empty", "amount < 0.0 and -amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or", "details. from odoo import api, fields, models, _ from odoo.exceptions", "for full copyright and licensing details. from odoo import api,", "line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount <", "to use the period of the validation(Payslip) date.\") journal_id =", "= fields.Many2one('account.tax', 'Tax') account_debit = fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=',", "debit_sum), 'credit': 0.0, }) line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids move =", "'journal_id' in self.env.context: vals['journal_id'] = self.env.context.get('journal_id') return super(HrPayslip, self).create(vals) @api.onchange('contract_id')", "properly configured the Credit Account!') % (slip.journal_id.name)) adjust_credit = (0,", "raise UserError(_('The Expense Journal \"%s\" has not properly configured the", "fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id = fields.Many2one('account.tax', 'Tax') account_debit = fields.Many2one('account.account',", "_('Payslip of %s') % (slip.employee_id.name) move_dict = { 'narration': name,", "debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line = (0,", "= 'Employee Contract' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') journal_id =", "Account') account_tax_id = fields.Many2one('account.tax', 'Tax') account_debit = fields.Many2one('account.account', 'Debit Account',", "_inherit = 'hr.payslip.run' journal_id = fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly',", "credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum) == -1:", "'credit': amount < 0.0 and -amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id", "return super(HrPayslip, self).action_payslip_cancel() @api.multi def action_payslip_done(self): res = super(HrPayslip, self).action_payslip_done()", "account_move_line \"\"\" # use partner of salary rule or fallback", "UserError from odoo.tools import float_compare, float_is_zero class HrPayslipLine(models.Model): _inherit =", "move.post() return res class HrSalaryRule(models.Model): _inherit = 'hr.salary.rule' analytic_account_id =", "account_tax_id = fields.Many2one('account.tax', 'Tax') account_debit = fields.Many2one('account.account', 'Debit Account', domain=[('deprecated',", "debit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount > 0.0 and", "fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True, states={'draft': [('readonly', False)]}, default=lambda self:", "credit_line[2]['credit'] - credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum) == -1: acc_id =", "0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum", "odoo import api, fields, models, _ from odoo.exceptions import UserError", "the period of the validation(Payslip) date.\") journal_id = fields.Many2one('account.journal', 'Salary", "use the period of the validation(Payslip) date.\") journal_id = fields.Many2one('account.journal',", "validation(Payslip) date.\") journal_id = fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True, states={'draft':", "'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': currency.round(credit_sum", "- debit_line[2]['credit'] if credit_account_id: credit_line = (0, 0, { 'name':", "= self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id if credit_account: if", "debit_sum = 0.0 credit_sum = 0.0 date = slip.date or", "register_partner_id = self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id if credit_account:", "super(HrPayslip, self).action_payslip_cancel() @api.multi def action_payslip_done(self): res = super(HrPayslip, self).action_payslip_done() for", "\"%s\" has not properly configured the Debit Account!') % (slip.journal_id.name))", "_get_partner_id(self, credit_account): \"\"\" Get partner_id of slip line to use", "self.contract_id.journal_id.id or (not self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self): moves", "Part of Odoo. See LICENSE file for full copyright and", "states={'draft': [('readonly', False)]}, readonly=True, help=\"Keep empty to use the period", "slip.journal_id.id, 'date': date, } for line in slip.details_by_salary_rule_category: amount =", "fields, models, _ from odoo.exceptions import UserError from odoo.tools import", "credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0, {", "debit_line[2]['credit'] if credit_account_id: credit_line = (0, 0, { 'name': line.name,", "'journal_id': slip.journal_id.id, 'date': date, } for line in slip.details_by_salary_rule_category: amount", "\"\"\" Get partner_id of slip line to use in account_move_line", "or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] -", "= fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=', False)]) account_credit = fields.Many2one('account.account',", "float_is_zero class HrPayslipLine(models.Model): _inherit = 'hr.payslip.line' def _get_partner_id(self, credit_account): \"\"\"", "def _get_partner_id(self, credit_account): \"\"\" Get partner_id of slip line to", "import float_compare, float_is_zero class HrPayslipLine(models.Model): _inherit = 'hr.payslip.line' def _get_partner_id(self,", "states={'draft': [('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1)) move_id", "slip line to use in account_move_line \"\"\" # use partner", "acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': 0.0, 'credit': currency.round(debit_sum -", "_inherit = 'hr.payslip' date = fields.Date('Date Account', states={'draft': [('readonly', False)]},", "class HrContract(models.Model): _inherit = 'hr.contract' _description = 'Employee Contract' analytic_account_id", "= fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=', False)]) class HrContract(models.Model): _inherit", "acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise UserError(_('The Expense Journal", "line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id:", "self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self): moves = self.mapped('move_id') moves.filtered(lambda x: x.state", "or slip.journal_id.company_id.currency_id name = _('Payslip of %s') % (slip.employee_id.name) move_dict", "0.0 credit_sum = 0.0 date = slip.date or slip.date_to currency", "0.0 date = slip.date or slip.date_to currency = slip.company_id.currency_id or", "0.0 and amount or 0.0, 'credit': amount < 0.0 and", "self.env.context.get('journal_id') return super(HrPayslip, self).create(vals) @api.onchange('contract_id') def onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id", "if currency.compare_amounts(credit_sum, debit_sum) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not", "address register_partner_id = self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id if", "fields.Many2one('account.journal', 'Salary Journal') class HrPayslipRun(models.Model): _inherit = 'hr.payslip.run' journal_id =", "{ 'name': line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date':", "= fields.Date('Date Account', states={'draft': [('readonly', False)]}, readonly=True, help=\"Keep empty to", "if 'journal_id' in self.env.context: vals['journal_id'] = self.env.context.get('journal_id') return super(HrPayslip, self).create(vals)", "See LICENSE file for full copyright and licensing details. from", "from odoo import api, fields, models, _ from odoo.exceptions import", "or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line)", "x: x.state == 'posted').button_cancel() moves.unlink() return super(HrPayslip, self).action_payslip_cancel() @api.multi def", "@api.multi def action_payslip_done(self): res = super(HrPayslip, self).action_payslip_done() for slip in", "credit_account_id: credit_line = (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=True),", "self.env.context: vals['journal_id'] = self.env.context.get('journal_id') return super(HrPayslip, self).create(vals) @api.onchange('contract_id') def onchange_contract(self):", "0.0 and -amount or 0.0, 'credit': amount > 0.0 and", "= line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0,", "fields.Date('Date Account', states={'draft': [('readonly', False)]}, readonly=True, help=\"Keep empty to use", "} for line in slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note and -line.total", "return partner_id return False class HrPayslip(models.Model): _inherit = 'hr.payslip' date", "+= credit_line[2]['credit'] - credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum) == -1: acc_id", "Journal \"%s\" has not properly configured the Debit Account!') %", "partner of salary rule or fallback on employee's address register_partner_id", "'journal_id': slip.journal_id.id, 'date': date, 'debit': amount < 0.0 and -amount", "'Credit Account', domain=[('deprecated', '=', False)]) class HrContract(models.Model): _inherit = 'hr.contract'", "= fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False) @api.model def create(self, vals):", "'date': date, 'debit': amount < 0.0 and -amount or 0.0,", "amount = currency.round(slip.credit_note and -line.total or line.total) if currency.is_zero(amount): continue", "and -amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id,", "# Part of Odoo. See LICENSE file for full copyright", "self: self.env['account.journal'].search([('type', '=', 'general')], limit=1)) move_id = fields.Many2one('account.move', 'Accounting Entry',", "move_dict = { 'narration': name, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'date':", "{ 'name': _('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id,", "the validation(Payslip) date.\") journal_id = fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True,", "'posted').button_cancel() moves.unlink() return super(HrPayslip, self).action_payslip_cancel() @api.multi def action_payslip_done(self): res =", "'Salary Journal', readonly=True, required=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type',", "False)]) class HrContract(models.Model): _inherit = 'hr.contract' _description = 'Employee Contract'", "onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id = self.contract_id.journal_id.id or (not self.contract_id and", "# use partner of salary rule or fallback on employee's", "slip.number, 'journal_id': slip.journal_id.id, 'date': date, } for line in slip.details_by_salary_rule_category:", "_('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date,", "Odoo. See LICENSE file for full copyright and licensing details.", "slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit']", "-amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, })", "= 'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id = fields.Many2one('account.tax',", "'Salary Journal') class HrPayslipRun(models.Model): _inherit = 'hr.payslip.run' journal_id = fields.Many2one('account.journal',", "'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True, default=lambda self: self.env['account.journal'].search([('type',", "register_partner_id.id or self.slip_id.employee_id.address_home_id.id if credit_account: if register_partner_id or self.salary_rule_id.account_credit.internal_type in", "= self.env.context.get('journal_id') return super(HrPayslip, self).create(vals) @api.onchange('contract_id') def onchange_contract(self): super(HrPayslip, self).onchange_contract()", "0.0, 'credit': amount < 0.0 and -amount or 0.0, 'analytic_account_id':", "> 0.0 and amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id,", "res class HrSalaryRule(models.Model): _inherit = 'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic", "'Analytic Account') account_tax_id = fields.Many2one('account.tax', 'Tax') account_debit = fields.Many2one('account.account', 'Debit", "if debit_account_id: debit_line = (0, 0, { 'name': line.name, 'partner_id':", "else: if register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return partner_id", "odoo.tools import float_compare, float_is_zero class HrPayslipLine(models.Model): _inherit = 'hr.payslip.line' def", "moves.unlink() return super(HrPayslip, self).action_payslip_cancel() @api.multi def action_payslip_done(self): res = super(HrPayslip,", "= self.contract_id.journal_id.id or (not self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self):", "amount > 0.0 and amount or 0.0, 'credit': amount <", "if credit_account_id: credit_line = (0, 0, { 'name': line.name, 'partner_id':", "if credit_account: if register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return", "return super(HrPayslip, self).create(vals) @api.onchange('contract_id') def onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id =", "'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': 0.0, 'credit': currency.round(debit_sum", "fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=', False)]) class HrContract(models.Model): _inherit =", "LICENSE file for full copyright and licensing details. from odoo", "readonly=True, required=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')],", "currency.is_zero(amount): continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id:", "('receivable', 'payable'): return partner_id return False class HrPayslip(models.Model): _inherit =", "= super(HrPayslip, self).action_payslip_done() for slip in self: line_ids = []", "= [] debit_sum = 0.0 credit_sum = 0.0 date =", "_ from odoo.exceptions import UserError from odoo.tools import float_compare, float_is_zero", "of slip line to use in account_move_line \"\"\" # use", "and self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self): moves = self.mapped('move_id') moves.filtered(lambda x:", "= 0.0 date = slip.date or slip.date_to currency = slip.company_id.currency_id", "= self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date': date}) move.post() return res class", "if not acc_id: raise UserError(_('The Expense Journal \"%s\" has not", "analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') journal_id = fields.Many2one('account.journal', 'Salary Journal')", "period of the validation(Payslip) date.\") journal_id = fields.Many2one('account.journal', 'Salary Journal',", "'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': 0.0,", "\"\"\" # use partner of salary rule or fallback on", "name, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'date': date, } for line", "line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line =", "'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if", "_inherit = 'hr.contract' _description = 'Employee Contract' analytic_account_id = fields.Many2one('account.analytic.account',", "Contract' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') journal_id = fields.Many2one('account.journal', 'Salary", "= fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True, states={'draft': [('readonly', False)]}, default=lambda", "debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line =", "move_id = fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False) @api.model def create(self,", "False)]}, readonly=True, help=\"Keep empty to use the period of the", "to use in account_move_line \"\"\" # use partner of salary", "'Employee Contract' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') journal_id = fields.Many2one('account.journal',", "adjust_credit = (0, 0, { 'name': _('Adjustment Entry'), 'partner_id': False,", "'name': _('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date':", "_inherit = 'hr.payslip.line' def _get_partner_id(self, credit_account): \"\"\" Get partner_id of", "copyright and licensing details. from odoo import api, fields, models,", "#-*- coding:utf-8 -*- # Part of Odoo. See LICENSE file", "and amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id,", "partner_id else: if register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return", "-1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise UserError(_('The Expense", "slip.journal_id.id, 'date': date, 'debit': amount < 0.0 and -amount or", "%s') % (slip.employee_id.name) move_dict = { 'narration': name, 'ref': slip.number,", "slip.company_id.currency_id or slip.journal_id.company_id.currency_id name = _('Payslip of %s') % (slip.employee_id.name)", "}) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line", "help=\"Keep empty to use the period of the validation(Payslip) date.\")", "'debit': 0.0, 'credit': currency.round(debit_sum - credit_sum), }) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum,", "'Accounting Entry', readonly=True, copy=False) @api.model def create(self, vals): if 'journal_id'", "== -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise UserError(_('The", "Entry', readonly=True, copy=False) @api.model def create(self, vals): if 'journal_id' in", "or 0.0, 'credit': amount < 0.0 and -amount or 0.0,", "= 'hr.payslip.run' journal_id = fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]},", "Get partner_id of slip line to use in account_move_line \"\"\"", "states={'draft': [('readonly', False)]}, readonly=True, required=True, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')],", "register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return partner_id else: if", "and licensing details. from odoo import api, fields, models, _", "date = slip.date or slip.date_to currency = slip.company_id.currency_id or slip.journal_id.company_id.currency_id", "acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise UserError(_('The Expense Journal", "class HrPayslipRun(models.Model): _inherit = 'hr.payslip.run' journal_id = fields.Many2one('account.journal', 'Salary Journal',", "domain=[('deprecated', '=', False)]) class HrContract(models.Model): _inherit = 'hr.contract' _description =", "journal_id = fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True,", "= slip.journal_id.default_credit_account_id.id if not acc_id: raise UserError(_('The Expense Journal \"%s\"", "name = _('Payslip of %s') % (slip.employee_id.name) move_dict = {", "= (0, 0, { 'name': _('Adjustment Entry'), 'partner_id': False, 'account_id':", "0, { 'name': _('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id':", "Account') journal_id = fields.Many2one('account.journal', 'Salary Journal') class HrPayslipRun(models.Model): _inherit =", "'ref': slip.number, 'journal_id': slip.journal_id.id, 'date': date, } for line in", "line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if currency.compare_amounts(credit_sum,", "= slip.journal_id.default_debit_account_id.id if not acc_id: raise UserError(_('The Expense Journal \"%s\"", "in account_move_line \"\"\" # use partner of salary rule or", "default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1)) move_id = fields.Many2one('account.move', 'Accounting", "[('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1)) move_id =", "'date': date, 'debit': amount > 0.0 and amount or 0.0,", "Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True, default=lambda self: self.env['account.journal'].search([('type', '=',", "'payable'): return partner_id return False class HrPayslip(models.Model): _inherit = 'hr.payslip'", "def action_payslip_done(self): res = super(HrPayslip, self).action_payslip_done() for slip in self:", "'debit': currency.round(credit_sum - debit_sum), 'credit': 0.0, }) line_ids.append(adjust_debit) move_dict['line_ids'] =", "}) line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids move = self.env['account.move'].create(move_dict) slip.write({'move_id': move.id,", "import api, fields, models, _ from odoo.exceptions import UserError from", "'date': date, 'debit': currency.round(credit_sum - debit_sum), 'credit': 0.0, }) line_ids.append(adjust_debit)", "elif currency.compare_amounts(debit_sum, credit_sum) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not", "or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line)", "slip.journal_id.id, 'date': date, 'debit': 0.0, 'credit': currency.round(debit_sum - credit_sum), })", "date, 'debit': amount > 0.0 and amount or 0.0, 'credit':", "(0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id':", "self.env['account.journal'].search([('type', '=', 'general')], limit=1)) move_id = fields.Many2one('account.move', 'Accounting Entry', readonly=True,", "line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0, { 'name': line.name,", "class HrSalaryRule(models.Model): _inherit = 'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account')", "(slip.journal_id.name)) adjust_debit = (0, 0, { 'name': _('Adjustment Entry'), 'partner_id':", "journal_id = fields.Many2one('account.journal', 'Salary Journal') class HrPayslipRun(models.Model): _inherit = 'hr.payslip.run'", "line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum) == -1: acc_id = slip.journal_id.default_debit_account_id.id if", "currency.compare_amounts(debit_sum, credit_sum) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id:", "Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit':", "= fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id = fields.Many2one('account.tax', 'Tax') account_debit =", "-line.total or line.total) if currency.is_zero(amount): continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id", "currency = slip.company_id.currency_id or slip.journal_id.company_id.currency_id name = _('Payslip of %s')", "Journal', readonly=True, required=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type', '=',", "move.id, 'date': date}) move.post() return res class HrSalaryRule(models.Model): _inherit =", "currency.compare_amounts(credit_sum, debit_sum) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id:", "Account', domain=[('deprecated', '=', False)]) account_credit = fields.Many2one('account.account', 'Credit Account', domain=[('deprecated',", "fallback on employee's address register_partner_id = self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id", "the Debit Account!') % (slip.journal_id.name)) adjust_debit = (0, 0, {", "0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum", "empty to use the period of the validation(Payslip) date.\") journal_id", "class HrPayslip(models.Model): _inherit = 'hr.payslip' date = fields.Date('Date Account', states={'draft':", "[('readonly', False)]}, readonly=True, required=True, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1))", "or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return partner_id else: if register_partner_id", "'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum +=", "UserError(_('The Expense Journal \"%s\" has not properly configured the Credit", "'payable'): return partner_id else: if register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable',", "'name': line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date': date,", "def onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id = self.contract_id.journal_id.id or (not self.contract_id", "- credit_sum), }) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum) == -1: acc_id", "'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount > 0.0", "credit_sum) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise", "+= debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line = (0, 0,", "readonly=True, copy=False) @api.model def create(self, vals): if 'journal_id' in self.env.context:", "UserError(_('The Expense Journal \"%s\" has not properly configured the Debit", "0.0, 'credit': amount > 0.0 and amount or 0.0, 'analytic_account_id':", "Debit Account!') % (slip.journal_id.name)) adjust_debit = (0, 0, { 'name':", "or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return partner_id return False class", "self.mapped('move_id') moves.filtered(lambda x: x.state == 'posted').button_cancel() moves.unlink() return super(HrPayslip, self).action_payslip_cancel()", "salary rule or fallback on employee's address register_partner_id = self.salary_rule_id.register_id.partner_id", "def create(self, vals): if 'journal_id' in self.env.context: vals['journal_id'] = self.env.context.get('journal_id')", "return partner_id else: if register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'):", "partner_id of slip line to use in account_move_line \"\"\" #", "if register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return partner_id return", "Journal') class HrPayslipRun(models.Model): _inherit = 'hr.payslip.run' journal_id = fields.Many2one('account.journal', 'Salary", "= self.mapped('move_id') moves.filtered(lambda x: x.state == 'posted').button_cancel() moves.unlink() return super(HrPayslip,", "coding:utf-8 -*- # Part of Odoo. See LICENSE file for", "self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id if credit_account: if register_partner_id", "of %s') % (slip.employee_id.name) move_dict = { 'narration': name, 'ref':", "line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit']", "not acc_id: raise UserError(_('The Expense Journal \"%s\" has not properly", "date, 'debit': currency.round(credit_sum - debit_sum), 'credit': 0.0, }) line_ids.append(adjust_debit) move_dict['line_ids']", "acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': currency.round(credit_sum - debit_sum), 'credit':", "vals['journal_id'] = self.env.context.get('journal_id') return super(HrPayslip, self).create(vals) @api.onchange('contract_id') def onchange_contract(self): super(HrPayslip,", "line_ids move = self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date': date}) move.post() return", "slip.journal_id.id, 'date': date, 'debit': currency.round(credit_sum - debit_sum), 'credit': 0.0, })", "HrPayslip(models.Model): _inherit = 'hr.payslip' date = fields.Date('Date Account', states={'draft': [('readonly',", "slip in self: line_ids = [] debit_sum = 0.0 credit_sum", "Expense Journal \"%s\" has not properly configured the Credit Account!')", "False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': 0.0, 'credit':", "self.slip_id.employee_id.address_home_id.id if credit_account: if register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'):", "has not properly configured the Debit Account!') % (slip.journal_id.name)) adjust_debit", "super(HrPayslip, self).onchange_contract() self.journal_id = self.contract_id.journal_id.id or (not self.contract_id and self.default_get(['journal_id'])['journal_id'])", "debit_line = (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id':", "fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True, default=lambda self:", "from odoo.tools import float_compare, float_is_zero class HrPayslipLine(models.Model): _inherit = 'hr.payslip.line'", "'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount", "line in slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note and -line.total or line.total)", "_description = 'Employee Contract' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') journal_id", "'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount", "properly configured the Debit Account!') % (slip.journal_id.name)) adjust_debit = (0,", "has not properly configured the Credit Account!') % (slip.journal_id.name)) adjust_credit", "'journal_id': slip.journal_id.id, 'date': date, 'debit': currency.round(credit_sum - debit_sum), 'credit': 0.0,", "or slip.date_to currency = slip.company_id.currency_id or slip.journal_id.company_id.currency_id name = _('Payslip", "fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=', False)]) account_credit = fields.Many2one('account.account', 'Credit", "'credit': currency.round(debit_sum - credit_sum), }) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum) ==", "credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum) == -1: acc_id = slip.journal_id.default_credit_account_id.id if", "currency.round(slip.credit_note and -line.total or line.total) if currency.is_zero(amount): continue debit_account_id =", "'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount < 0.0", "'hr.payslip' date = fields.Date('Date Account', states={'draft': [('readonly', False)]}, readonly=True, help=\"Keep", "credit_account: if register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return partner_id", "0.0 and amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id, 'tax_line_id':", "'=', 'general')], limit=1)) move_id = fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False)", "}) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum)", "Expense Journal \"%s\" has not properly configured the Debit Account!')", "in slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note and -line.total or line.total) if", "== 'posted').button_cancel() moves.unlink() return super(HrPayslip, self).action_payslip_cancel() @api.multi def action_payslip_done(self): res", "{ 'narration': name, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'date': date, }", "in self: line_ids = [] debit_sum = 0.0 credit_sum =", "slip.journal_id.id, 'date': date, 'debit': amount > 0.0 and amount or", "{ 'name': line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date':", "(0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id':", "in ('receivable', 'payable'): return partner_id return False class HrPayslip(models.Model): _inherit", "(not self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self): moves = self.mapped('move_id')", "for line in slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note and -line.total or", "or slip.contract_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] -", "'date': date}) move.post() return res class HrSalaryRule(models.Model): _inherit = 'hr.salary.rule'", "configured the Credit Account!') % (slip.journal_id.name)) adjust_credit = (0, 0,", "'date': date, 'debit': 0.0, 'credit': currency.round(debit_sum - credit_sum), }) line_ids.append(adjust_credit)", "date, 'debit': 0.0, 'credit': currency.round(debit_sum - credit_sum), }) line_ids.append(adjust_credit) elif", "'=', False)]) account_credit = fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=', False)])", "'hr.payslip.line' def _get_partner_id(self, credit_account): \"\"\" Get partner_id of slip line", "'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id = fields.Many2one('account.tax', 'Tax')", "'name': line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date': date,", "on employee's address register_partner_id = self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id or" ]
[ "axis == \"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else: print(\"incorrect values for arg:", "+ list(np.where(y == list(labels.keys())[i])[0][: grid_x - 1]) label = labels[list(labels.keys())[i]]", "plt import matplotlib.gridspec as gridspec import sys import numpy as", "from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import BoundaryNorm def plot_images(", "\"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8, 8)) plt.scatter( x[:, 0], x[:, 1], s=18,", "= np.max(matrix) mat_min = -np.max([np.abs(mat_min), mat_max]) mat_max = np.max([np.abs(mat_min), mat_max])", "bounds = np.insert(bounds, idx, 0) norm = BoundaryNorm(bounds, cmap.N) plt.imshow(matrix,", "as np from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import BoundaryNorm", "sys.exit() plt.title(title) plt.show() def plot_dna(df, label): matrix = df.values col_names", "1 grid_y = len(labels) plt.figure(figsize=(grid_y, grid_x)) gs1 = gridspec.GridSpec(grid_y, grid_x)", "mat_min = -np.max([np.abs(mat_min), mat_max]) mat_max = np.max([np.abs(mat_min), mat_max]) matrix =", "j = 0 for i in range(grid_y): idxs = [0]", "plt.show() def plot_2D(x, y, title, axis=\"off\"): BLUE, ORANGE = \"#57B5E8\",", "label): matrix = df.values col_names = df.columns rows = np.arange(matrix.shape[0])", "0.1) idx = np.searchsorted(bounds, 0) bounds = np.insert(bounds, idx, 0)", "matrix = matrix[:, rows] col_names = col_names[cols[:100]] label = label[rows]", "import sys import numpy as np from matplotlib.colors import LinearSegmentedColormap", "\"bold\"} plt.suptitle(title) j = 0 for i in range(grid_y): idxs", "== \"off\": plt.axis(\"off\") elif axis == \"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else:", "which=u\"both\", labelsize=5, length=0.0) plt.tight_layout() fig = plt.gcf() # fig.set_size_inches((6, 12),", "0) norm = BoundaryNorm(bounds, cmap.N) plt.imshow(matrix, cmap=cmap, norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names)))", "= num_sample_perclass + 1 grid_y = len(labels) plt.figure(figsize=(grid_y, grid_x)) gs1", "# np.arange(mat_min + 6, mat_max - 6, 0.1) idx =", "BoundaryNorm(bounds, cmap.N) plt.imshow(matrix, cmap=cmap, norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax = plt.gca()", "def plot_images( num_sample_perclass=10, x=None, y=None, labels=None, title=None, cmap=None ): grid_x", "else: print(\"incorrect values for arg: axis (on or off only)\")", "= plt.gcf() # fig.set_size_inches((6, 12), forward=False) # fig.savefig(\"img/dna.png\", dpi=200) plt.show()", "\"darkred\", \"green\", \"lime\", \"lightgreen\"] cmap = LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list, len(cmap_list))", "mat_max = np.max([np.abs(mat_min), mat_max]) matrix = np.ma.masked_where(np.abs(matrix) <= 0.3, matrix)", "ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5, length=0.0) plt.tight_layout() fig = plt.gcf()", "np.ma.masked_where(np.abs(matrix) <= 0.3, matrix) plt.figure(figsize=(6, 12)) cmap_list = [\"red\", \"darkred\",", "title=None, cmap=None ): grid_x = num_sample_perclass + 1 grid_y =", "= np.searchsorted(bounds, 0) bounds = np.insert(bounds, idx, 0) norm =", "matplotlib.colors import BoundaryNorm def plot_images( num_sample_perclass=10, x=None, y=None, labels=None, title=None,", "np.arange(mat_min + 6, mat_max - 6, 0.1) idx = np.searchsorted(bounds,", "ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5, length=0.0) plt.tight_layout() fig = plt.gcf() # fig.set_size_inches((6,", "label, ha=\"right\", wrap=True, fontdict=font) else: ax1.imshow(x[idx, ...], cmap=cmap) plt.axis(\"off\") j", "np.searchsorted(bounds, 0) bounds = np.insert(bounds, idx, 0) norm = BoundaryNorm(bounds,", "(on or off only)\") sys.exit() plt.title(title) plt.show() def plot_dna(df, label):", "\"#E69E00\" plt.figure(figsize=(8, 8)) plt.scatter( x[:, 0], x[:, 1], s=18, facecolors=\"none\",", "as gridspec import sys import numpy as np from matplotlib.colors", "plt.tight_layout() fig = plt.gcf() # fig.set_size_inches((6, 12), forward=False) # fig.savefig(\"img/dna.png\",", "== \"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else: print(\"incorrect values for arg: axis", "= np.ma.masked_where(np.abs(matrix) <= 0.3, matrix) plt.figure(figsize=(6, 12)) cmap_list = [\"red\",", "grid_x = num_sample_perclass + 1 grid_y = len(labels) plt.figure(figsize=(grid_y, grid_x))", "labels[list(labels.keys())[i]] for k, idx in enumerate(idxs): ax1 = plt.subplot(gs1[j]) if", "= df.values col_names = df.columns rows = np.arange(matrix.shape[0]) cols =", "plt.ylabel(\"x_2\") else: print(\"incorrect values for arg: axis (on or off", "import LinearSegmentedColormap from matplotlib.colors import BoundaryNorm def plot_images( num_sample_perclass=10, x=None,", "= len(labels) plt.figure(figsize=(grid_y, grid_x)) gs1 = gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025, hspace=0.05)", "ORANGE])[y], ) if axis == \"off\": plt.axis(\"off\") elif axis ==", "= matrix[:, rows] col_names = col_names[cols[:100]] label = label[rows] mat_min", "np.insert(bounds, idx, 0) norm = BoundaryNorm(bounds, cmap.N) plt.imshow(matrix, cmap=cmap, norm=norm)", "col_names[cols[:100]] label = label[rows] mat_min = np.min(matrix) mat_max = np.max(matrix)", "np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols) matrix = matrix[:, cols[:100]].T matrix = matrix[:,", "matrix[:, rows] col_names = col_names[cols[:100]] label = label[rows] mat_min =", "col_names = df.columns rows = np.arange(matrix.shape[0]) cols = np.arange(matrix.shape[1]) np.random.seed(3)", "matrix) plt.figure(figsize=(6, 12)) cmap_list = [\"red\", \"darkred\", \"green\", \"lime\", \"lightgreen\"]", "matrix = matrix[:, cols[:100]].T matrix = matrix[:, rows] col_names =", "mat_min + 6, mat_max - 6, 5 ) # np.arange(mat_min", "= BoundaryNorm(bounds, cmap.N) plt.imshow(matrix, cmap=cmap, norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax =", "plt.figure(figsize=(6, 12)) cmap_list = [\"red\", \"darkred\", \"green\", \"lime\", \"lightgreen\"] cmap", "for k, idx in enumerate(idxs): ax1 = plt.subplot(gs1[j]) if k", "edgecolors=np.array([BLUE, ORANGE])[y], ) if axis == \"off\": plt.axis(\"off\") elif axis", "for arg: axis (on or off only)\") sys.exit() plt.title(title) plt.show()", "import matplotlib.gridspec as gridspec import sys import numpy as np", "i in range(grid_y): idxs = [0] + list(np.where(y == list(labels.keys())[i])[0][:", "- 1]) label = labels[list(labels.keys())[i]] for k, idx in enumerate(idxs):", "sys import numpy as np from matplotlib.colors import LinearSegmentedColormap from", "x[:, 1], s=18, facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y], ) if axis ==", "np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols) matrix = matrix[:, cols[:100]].T matrix =", "cmap = LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list, len(cmap_list)) cmap.set_bad(\"black\") bounds = np.linspace(", "\"weight\": \"bold\"} plt.suptitle(title) j = 0 for i in range(grid_y):", "= -np.max([np.abs(mat_min), mat_max]) mat_max = np.max([np.abs(mat_min), mat_max]) matrix = np.ma.masked_where(np.abs(matrix)", "+ 6, mat_max - 6, 0.1) idx = np.searchsorted(bounds, 0)", "facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y], ) if axis == \"off\": plt.axis(\"off\") elif", "\"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else: print(\"incorrect values for arg: axis (on", "12)) cmap_list = [\"red\", \"darkred\", \"green\", \"lime\", \"lightgreen\"] cmap =", "[0] + list(np.where(y == list(labels.keys())[i])[0][: grid_x - 1]) label =", "6, mat_max - 6, 5 ) # np.arange(mat_min + 6,", "idxs = [0] + list(np.where(y == list(labels.keys())[i])[0][: grid_x - 1])", "as plt import matplotlib.gridspec as gridspec import sys import numpy", "import BoundaryNorm def plot_images( num_sample_perclass=10, x=None, y=None, labels=None, title=None, cmap=None", "ax1.imshow(x[idx, ...], cmap=cmap) plt.axis(\"off\") j += 1 plt.show() def plot_2D(x,", "in enumerate(idxs): ax1 = plt.subplot(gs1[j]) if k == 0: ax1.text(0,", "= label[rows] mat_min = np.min(matrix) mat_max = np.max(matrix) mat_min =", "= plt.gca() ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5, length=0.0)", "label[rows] mat_min = np.min(matrix) mat_max = np.max(matrix) mat_min = -np.max([np.abs(mat_min),", "y=None, labels=None, title=None, cmap=None ): grid_x = num_sample_perclass + 1", "= gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025, hspace=0.05) font = {\"family\": \"serif\", \"weight\":", "ax1.text(0, 0.25, label, ha=\"right\", wrap=True, fontdict=font) else: ax1.imshow(x[idx, ...], cmap=cmap)", "\"green\", \"lime\", \"lightgreen\"] cmap = LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list, len(cmap_list)) cmap.set_bad(\"black\")", "k == 0: ax1.text(0, 0.25, label, ha=\"right\", wrap=True, fontdict=font) else:", "idx in enumerate(idxs): ax1 = plt.subplot(gs1[j]) if k == 0:", "mat_max - 6, 0.1) idx = np.searchsorted(bounds, 0) bounds =", "else: ax1.imshow(x[idx, ...], cmap=cmap) plt.axis(\"off\") j += 1 plt.show() def", "print(\"incorrect values for arg: axis (on or off only)\") sys.exit()", "+ 1 grid_y = len(labels) plt.figure(figsize=(grid_y, grid_x)) gs1 = gridspec.GridSpec(grid_y,", "plt.figure(figsize=(grid_y, grid_x)) gs1 = gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025, hspace=0.05) font =", "BLUE, ORANGE = \"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8, 8)) plt.scatter( x[:, 0],", "-np.max([np.abs(mat_min), mat_max]) mat_max = np.max([np.abs(mat_min), mat_max]) matrix = np.ma.masked_where(np.abs(matrix) <=", "= np.linspace( mat_min + 6, mat_max - 6, 5 )", "plt.gca() ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5, length=0.0) plt.tight_layout()", "5 ) # np.arange(mat_min + 6, mat_max - 6, 0.1)", "for i in range(grid_y): idxs = [0] + list(np.where(y ==", "s=18, facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y], ) if axis == \"off\": plt.axis(\"off\")", "mat_max - 6, 5 ) # np.arange(mat_min + 6, mat_max", "def plot_dna(df, label): matrix = df.values col_names = df.columns rows", "plt.yticks(np.arange(len(col_names))) ax = plt.gca() ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\",", "matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import sys import", "matrix[:, cols[:100]].T matrix = matrix[:, rows] col_names = col_names[cols[:100]] label", "list(np.where(y == list(labels.keys())[i])[0][: grid_x - 1]) label = labels[list(labels.keys())[i]] for", "plt.axis(\"off\") elif axis == \"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else: print(\"incorrect values", "= \"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8, 8)) plt.scatter( x[:, 0], x[:, 1],", "= col_names[cols[:100]] label = label[rows] mat_min = np.min(matrix) mat_max =", "grid_x)) gs1 = gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025, hspace=0.05) font = {\"family\":", "\"off\": plt.axis(\"off\") elif axis == \"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else: print(\"incorrect", "only)\") sys.exit() plt.title(title) plt.show() def plot_dna(df, label): matrix = df.values", "idx = np.searchsorted(bounds, 0) bounds = np.insert(bounds, idx, 0) norm", "axis=\"off\"): BLUE, ORANGE = \"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8, 8)) plt.scatter( x[:,", "): grid_x = num_sample_perclass + 1 grid_y = len(labels) plt.figure(figsize=(grid_y,", "import numpy as np from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors", "plot_dna(df, label): matrix = df.values col_names = df.columns rows =", "= LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list, len(cmap_list)) cmap.set_bad(\"black\") bounds = np.linspace( mat_min", "in range(grid_y): idxs = [0] + list(np.where(y == list(labels.keys())[i])[0][: grid_x", "list(labels.keys())[i])[0][: grid_x - 1]) label = labels[list(labels.keys())[i]] for k, idx", "plot_2D(x, y, title, axis=\"off\"): BLUE, ORANGE = \"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8,", "gs1.update(wspace=0.025, hspace=0.05) font = {\"family\": \"serif\", \"weight\": \"bold\"} plt.suptitle(title) j", "numpy as np from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import", "plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax = plt.gca() ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\",", "ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5, length=0.0) plt.tight_layout() fig", "= np.insert(bounds, idx, 0) norm = BoundaryNorm(bounds, cmap.N) plt.imshow(matrix, cmap=cmap,", "labels=None, title=None, cmap=None ): grid_x = num_sample_perclass + 1 grid_y", "matplotlib.gridspec as gridspec import sys import numpy as np from", "= 0 for i in range(grid_y): idxs = [0] +", "== 0: ax1.text(0, 0.25, label, ha=\"right\", wrap=True, fontdict=font) else: ax1.imshow(x[idx,", "...], cmap=cmap) plt.axis(\"off\") j += 1 plt.show() def plot_2D(x, y,", "elif axis == \"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else: print(\"incorrect values for", "cmap=None ): grid_x = num_sample_perclass + 1 grid_y = len(labels)", "= matrix[:, cols[:100]].T matrix = matrix[:, rows] col_names = col_names[cols[:100]]", "j += 1 plt.show() def plot_2D(x, y, title, axis=\"off\"): BLUE,", "plt.axis(\"off\") j += 1 plt.show() def plot_2D(x, y, title, axis=\"off\"):", "== list(labels.keys())[i])[0][: grid_x - 1]) label = labels[list(labels.keys())[i]] for k,", "rows = np.arange(matrix.shape[0]) cols = np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols) matrix", "plt.title(title) plt.show() def plot_dna(df, label): matrix = df.values col_names =", "cmap_list, len(cmap_list)) cmap.set_bad(\"black\") bounds = np.linspace( mat_min + 6, mat_max", "num_sample_perclass=10, x=None, y=None, labels=None, title=None, cmap=None ): grid_x = num_sample_perclass", "matrix = np.ma.masked_where(np.abs(matrix) <= 0.3, matrix) plt.figure(figsize=(6, 12)) cmap_list =", "+ 6, mat_max - 6, 5 ) # np.arange(mat_min +", ") if axis == \"off\": plt.axis(\"off\") elif axis == \"on\":", "norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax = plt.gca() ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right()", "bounds = np.linspace( mat_min + 6, mat_max - 6, 5", "BoundaryNorm def plot_images( num_sample_perclass=10, x=None, y=None, labels=None, title=None, cmap=None ):", "axis (on or off only)\") sys.exit() plt.title(title) plt.show() def plot_dna(df,", "= np.min(matrix) mat_max = np.max(matrix) mat_min = -np.max([np.abs(mat_min), mat_max]) mat_max", "6, 5 ) # np.arange(mat_min + 6, mat_max - 6,", "plt.imshow(matrix, cmap=cmap, norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax = plt.gca() ax.set_xticklabels(label, rotation=90)", "length=0.0) plt.tight_layout() fig = plt.gcf() # fig.set_size_inches((6, 12), forward=False) #", "mat_max = np.max(matrix) mat_min = -np.max([np.abs(mat_min), mat_max]) mat_max = np.max([np.abs(mat_min),", "= plt.subplot(gs1[j]) if k == 0: ax1.text(0, 0.25, label, ha=\"right\",", "cols = np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols) matrix = matrix[:, cols[:100]].T", "np.arange(matrix.shape[0]) cols = np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols) matrix = matrix[:,", "from matplotlib.colors import BoundaryNorm def plot_images( num_sample_perclass=10, x=None, y=None, labels=None,", "num_sample_perclass + 1 grid_y = len(labels) plt.figure(figsize=(grid_y, grid_x)) gs1 =", "values for arg: axis (on or off only)\") sys.exit() plt.title(title)", "plt.scatter( x[:, 0], x[:, 1], s=18, facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y], )", "rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5, length=0.0) plt.tight_layout() fig =", "= df.columns rows = np.arange(matrix.shape[0]) cols = np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows)", "fig = plt.gcf() # fig.set_size_inches((6, 12), forward=False) # fig.savefig(\"img/dna.png\", dpi=200)", "cmap_list = [\"red\", \"darkred\", \"green\", \"lime\", \"lightgreen\"] cmap = LinearSegmentedColormap.from_list(\"Custom", "ax = plt.gca() ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names) ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5,", "hspace=0.05) font = {\"family\": \"serif\", \"weight\": \"bold\"} plt.suptitle(title) j =", "grid_y = len(labels) plt.figure(figsize=(grid_y, grid_x)) gs1 = gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025,", "plt.subplot(gs1[j]) if k == 0: ax1.text(0, 0.25, label, ha=\"right\", wrap=True,", "mat_min = np.min(matrix) mat_max = np.max(matrix) mat_min = -np.max([np.abs(mat_min), mat_max])", "\"lightgreen\"] cmap = LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list, len(cmap_list)) cmap.set_bad(\"black\") bounds =", "6, 0.1) idx = np.searchsorted(bounds, 0) bounds = np.insert(bounds, idx,", "or off only)\") sys.exit() plt.title(title) plt.show() def plot_dna(df, label): matrix", "- 6, 0.1) idx = np.searchsorted(bounds, 0) bounds = np.insert(bounds,", "import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import sys", "x=None, y=None, labels=None, title=None, cmap=None ): grid_x = num_sample_perclass +", "mat_max]) matrix = np.ma.masked_where(np.abs(matrix) <= 0.3, matrix) plt.figure(figsize=(6, 12)) cmap_list", "plt.figure(figsize=(8, 8)) plt.scatter( x[:, 0], x[:, 1], s=18, facecolors=\"none\", edgecolors=np.array([BLUE,", "label = labels[list(labels.keys())[i]] for k, idx in enumerate(idxs): ax1 =", "matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import BoundaryNorm def plot_images( num_sample_perclass=10,", "grid_x) gs1.update(wspace=0.025, hspace=0.05) font = {\"family\": \"serif\", \"weight\": \"bold\"} plt.suptitle(title)", "= {\"family\": \"serif\", \"weight\": \"bold\"} plt.suptitle(title) j = 0 for", "ax1 = plt.subplot(gs1[j]) if k == 0: ax1.text(0, 0.25, label,", "mat_max]) mat_max = np.max([np.abs(mat_min), mat_max]) matrix = np.ma.masked_where(np.abs(matrix) <= 0.3,", ") # np.arange(mat_min + 6, mat_max - 6, 0.1) idx", "plt.xlabel(\"x_1\") plt.ylabel(\"x_2\") else: print(\"incorrect values for arg: axis (on or", "LinearSegmentedColormap from matplotlib.colors import BoundaryNorm def plot_images( num_sample_perclass=10, x=None, y=None,", "np.random.shuffle(cols) matrix = matrix[:, cols[:100]].T matrix = matrix[:, rows] col_names", "rows] col_names = col_names[cols[:100]] label = label[rows] mat_min = np.min(matrix)", "0], x[:, 1], s=18, facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y], ) if axis", "0.3, matrix) plt.figure(figsize=(6, 12)) cmap_list = [\"red\", \"darkred\", \"green\", \"lime\",", "= np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols) matrix = matrix[:, cols[:100]].T matrix", "0.25, label, ha=\"right\", wrap=True, fontdict=font) else: ax1.imshow(x[idx, ...], cmap=cmap) plt.axis(\"off\")", "np.linspace( mat_min + 6, mat_max - 6, 5 ) #", "0) bounds = np.insert(bounds, idx, 0) norm = BoundaryNorm(bounds, cmap.N)", "LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list, len(cmap_list)) cmap.set_bad(\"black\") bounds = np.linspace( mat_min +", "- 6, 5 ) # np.arange(mat_min + 6, mat_max -", "ha=\"right\", wrap=True, fontdict=font) else: ax1.imshow(x[idx, ...], cmap=cmap) plt.axis(\"off\") j +=", "font = {\"family\": \"serif\", \"weight\": \"bold\"} plt.suptitle(title) j = 0", "idx, 0) norm = BoundaryNorm(bounds, cmap.N) plt.imshow(matrix, cmap=cmap, norm=norm) plt.xticks(np.arange(len(label)))", "range(grid_y): idxs = [0] + list(np.where(y == list(labels.keys())[i])[0][: grid_x -", "wrap=True, fontdict=font) else: ax1.imshow(x[idx, ...], cmap=cmap) plt.axis(\"off\") j += 1", "np from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import BoundaryNorm def", "gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025, hspace=0.05) font = {\"family\": \"serif\", \"weight\": \"bold\"}", "plot_images( num_sample_perclass=10, x=None, y=None, labels=None, title=None, cmap=None ): grid_x =", "label = label[rows] mat_min = np.min(matrix) mat_max = np.max(matrix) mat_min", "len(cmap_list)) cmap.set_bad(\"black\") bounds = np.linspace( mat_min + 6, mat_max -", "\"lime\", \"lightgreen\"] cmap = LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list, len(cmap_list)) cmap.set_bad(\"black\") bounds", "6, mat_max - 6, 0.1) idx = np.searchsorted(bounds, 0) bounds", "labelsize=5, length=0.0) plt.tight_layout() fig = plt.gcf() # fig.set_size_inches((6, 12), forward=False)", "np.max([np.abs(mat_min), mat_max]) matrix = np.ma.masked_where(np.abs(matrix) <= 0.3, matrix) plt.figure(figsize=(6, 12))", "<= 0.3, matrix) plt.figure(figsize=(6, 12)) cmap_list = [\"red\", \"darkred\", \"green\",", "0: ax1.text(0, 0.25, label, ha=\"right\", wrap=True, fontdict=font) else: ax1.imshow(x[idx, ...],", "ax.yaxis.tick_right() ax.tick_params(axis=u\"both\", which=u\"both\", labelsize=5, length=0.0) plt.tight_layout() fig = plt.gcf() #", "\"serif\", \"weight\": \"bold\"} plt.suptitle(title) j = 0 for i in", "if axis == \"off\": plt.axis(\"off\") elif axis == \"on\": plt.xlabel(\"x_1\")", "df.columns rows = np.arange(matrix.shape[0]) cols = np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols)", "1]) label = labels[list(labels.keys())[i]] for k, idx in enumerate(idxs): ax1", "= np.max([np.abs(mat_min), mat_max]) matrix = np.ma.masked_where(np.abs(matrix) <= 0.3, matrix) plt.figure(figsize=(6,", "cmap.set_bad(\"black\") bounds = np.linspace( mat_min + 6, mat_max - 6,", "len(labels) plt.figure(figsize=(grid_y, grid_x)) gs1 = gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025, hspace=0.05) font", "y, title, axis=\"off\"): BLUE, ORANGE = \"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8, 8))", "= np.arange(matrix.shape[0]) cols = np.arange(matrix.shape[1]) np.random.seed(3) np.random.shuffle(rows) np.random.shuffle(cols) matrix =", "cmap=cmap) plt.axis(\"off\") j += 1 plt.show() def plot_2D(x, y, title,", "cmap\", cmap_list, len(cmap_list)) cmap.set_bad(\"black\") bounds = np.linspace( mat_min + 6,", "0 for i in range(grid_y): idxs = [0] + list(np.where(y", "title, axis=\"off\"): BLUE, ORANGE = \"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8, 8)) plt.scatter(", "[\"red\", \"darkred\", \"green\", \"lime\", \"lightgreen\"] cmap = LinearSegmentedColormap.from_list(\"Custom cmap\", cmap_list,", "gridspec import sys import numpy as np from matplotlib.colors import", "fontdict=font) else: ax1.imshow(x[idx, ...], cmap=cmap) plt.axis(\"off\") j += 1 plt.show()", "matrix = df.values col_names = df.columns rows = np.arange(matrix.shape[0]) cols", "cmap=cmap, norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax = plt.gca() ax.set_xticklabels(label, rotation=90) ax.set_yticklabels(col_names)", "{\"family\": \"serif\", \"weight\": \"bold\"} plt.suptitle(title) j = 0 for i", "arg: axis (on or off only)\") sys.exit() plt.title(title) plt.show() def", "cols[:100]].T matrix = matrix[:, rows] col_names = col_names[cols[:100]] label =", "np.max(matrix) mat_min = -np.max([np.abs(mat_min), mat_max]) mat_max = np.max([np.abs(mat_min), mat_max]) matrix", "= [\"red\", \"darkred\", \"green\", \"lime\", \"lightgreen\"] cmap = LinearSegmentedColormap.from_list(\"Custom cmap\",", "col_names = col_names[cols[:100]] label = label[rows] mat_min = np.min(matrix) mat_max", "axis == \"off\": plt.axis(\"off\") elif axis == \"on\": plt.xlabel(\"x_1\") plt.ylabel(\"x_2\")", "ORANGE = \"#57B5E8\", \"#E69E00\" plt.figure(figsize=(8, 8)) plt.scatter( x[:, 0], x[:,", "gs1 = gridspec.GridSpec(grid_y, grid_x) gs1.update(wspace=0.025, hspace=0.05) font = {\"family\": \"serif\",", "+= 1 plt.show() def plot_2D(x, y, title, axis=\"off\"): BLUE, ORANGE", "def plot_2D(x, y, title, axis=\"off\"): BLUE, ORANGE = \"#57B5E8\", \"#E69E00\"", "k, idx in enumerate(idxs): ax1 = plt.subplot(gs1[j]) if k ==", "if k == 0: ax1.text(0, 0.25, label, ha=\"right\", wrap=True, fontdict=font)", "x[:, 0], x[:, 1], s=18, facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y], ) if", "off only)\") sys.exit() plt.title(title) plt.show() def plot_dna(df, label): matrix =", "plt.show() def plot_dna(df, label): matrix = df.values col_names = df.columns", "8)) plt.scatter( x[:, 0], x[:, 1], s=18, facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y],", "np.min(matrix) mat_max = np.max(matrix) mat_min = -np.max([np.abs(mat_min), mat_max]) mat_max =", "= [0] + list(np.where(y == list(labels.keys())[i])[0][: grid_x - 1]) label", "np.random.shuffle(rows) np.random.shuffle(cols) matrix = matrix[:, cols[:100]].T matrix = matrix[:, rows]", "norm = BoundaryNorm(bounds, cmap.N) plt.imshow(matrix, cmap=cmap, norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax", "= labels[list(labels.keys())[i]] for k, idx in enumerate(idxs): ax1 = plt.subplot(gs1[j])", "1], s=18, facecolors=\"none\", edgecolors=np.array([BLUE, ORANGE])[y], ) if axis == \"off\":", "cmap.N) plt.imshow(matrix, cmap=cmap, norm=norm) plt.xticks(np.arange(len(label))) plt.yticks(np.arange(len(col_names))) ax = plt.gca() ax.set_xticklabels(label,", "enumerate(idxs): ax1 = plt.subplot(gs1[j]) if k == 0: ax1.text(0, 0.25,", "plt.suptitle(title) j = 0 for i in range(grid_y): idxs =", "1 plt.show() def plot_2D(x, y, title, axis=\"off\"): BLUE, ORANGE =", "grid_x - 1]) label = labels[list(labels.keys())[i]] for k, idx in", "df.values col_names = df.columns rows = np.arange(matrix.shape[0]) cols = np.arange(matrix.shape[1])" ]
[ "index.html {}'.format(http_response_code), extra=d) context.state = NormalState() class NormalState(State): def run(self,", "normal['sourceip'] = random.choice(SOURCEIP) if random.random() < 0.3: context.logger.info( 'Successful authorization", "['KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH', 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CLOCK_DAEMON',", "HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} while True: normal['sourceip']", "\\ 'message)s ' RESOURCES = ['index.html', 'document.xml', 'dashboard.html'] LOGS_PATH =", "d['severity'] = SEVERITY[5] for sourceip in SOURCEIP: d['sourceip'] = sourceip", "= logging.getLogger('simulator') if not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler = logging.FileHandler( os.path.join(LOGS_PATH,", "= 'logs' class State(ABC): @abstractmethod def run(self, context): return NotImplemented", "rand == 3: context.state = DatabaseError() context.state.run(context) class BruteForce(State): def", "'AUTH', 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV', 'FTP', 'NTP', 'LOGAUDIT',", "for i in range(30): if i > 5: attack['severity'] =", "class DoSAttack(State): def run(self, context): d = {'hostname': HOSTNAME[0], 'hostip':", "= {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[2], 'facility':", "= NormalState() class NormalState(State): def run(self, context): normal = {'hostname':", "['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32'] USERNAMES = ['user1', 'user2', 'user3',", "= randint(1, 3) if rand == 1: context.state = DoSAttack()", "'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger", "{'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} for i", "'document.xml', 'dashboard.html'] LOGS_PATH = 'logs' class State(ABC): @abstractmethod def run(self,", "sleep(0.5) context.logger.info('Failed authorization on username \"user1\"', extra=attack) sleep(0.5) context.state =", "os import random from abc import ABC, abstractmethod from random", "= ['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32'] USERNAMES = ['user1', 'user2',", "context.state = BruteForce() elif rand == 3: context.state = DatabaseError()", "'192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32'] USERNAMES = ['user1', 'user2', 'user3', 'user4',", "rand == 1: context.state = DoSAttack() elif rand == 2:", "['index.html', 'document.xml', 'dashboard.html'] LOGS_PATH = 'logs' class State(ABC): @abstractmethod def", "context.state = NormalState() class Context: def __init__(self): self.state = NormalState()", "= ['DEBUG', 'INFORMATIONAL', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'] FORMAT", "'172.16.58.3', '172.16.58.3', '172.16.17.32'] USERNAMES = ['user1', 'user2', 'user3', 'user4', 'user5']", "self.state = NormalState() formatter = logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\") logger =", "d = {'hostname': HOSTNAME[0], 'hostip': HOSTIP[0], 'severity': SEVERITY[1], 'facility': FACILITY[1]}", "for sourceip in SOURCEIP: d['sourceip'] = sourceip context.logger.info('Requested resource index.html", "{'hostname': HOSTNAME[2], 'hostip': HOSTIP[2], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[4], 'facility': FACILITY[3]}", "'severity': SEVERITY[2], 'facility': FACILITY[4]} normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1],", "SEVERITY[1], 'facility': FACILITY[1]} while True: normal['sourceip'] = random.choice(SOURCEIP) if random.random()", "'hostip': HOSTIP[2], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[4], 'facility': FACILITY[3]} context.logger.info('Database error',", "NormalState() class NormalState(State): def run(self, context): normal = {'hostname': HOSTNAME[1],", "http_response_code = '503' d['severity'] = SEVERITY[5] for sourceip in SOURCEIP:", "{}'.format(http_response_code), extra=d) context.state = NormalState() class NormalState(State): def run(self, context):", "from time import sleep, strftime HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru']", "'severity': SEVERITY[4], 'facility': FACILITY[3]} context.logger.info('Database error', extra=d) sleep(1) context.state =", "'LOGALERT', 'CRON', 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7']", "HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} while True: normal['sourceip'] = random.choice(SOURCEIP)", "resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(1) if random.random() < 0.1: rand", "200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5) context.logger.info('Failed authorization on username \"user1\"', extra=attack) sleep(0.5)", "Context: def __init__(self): self.state = NormalState() formatter = logging.Formatter(FORMAT, \"%Y-%m-%d", "\"%Y-%m-%d %H:%M:%S\") logger = logging.getLogger('simulator') if not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler", "SEVERITY[1], 'facility': FACILITY[1]} for i in range(30): if i >", "'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7'] SEVERITY =", "run(self, context): return NotImplemented class DoSAttack(State): def run(self, context): d", "\"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else: context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(1) if", "self.logger = logger def run(self): self.state.run(self) @property def state(self): return", "abc import ABC, abstractmethod from random import randint from time", "http_response_code = '200' for i in range(25): if i >=", "1: context.state = DoSAttack() elif rand == 2: context.state =", "class NormalState(State): def run(self, context): normal = {'hostname': HOSTNAME[1], 'hostip':", "'facility': FACILITY[3]} context.logger.info('Database error', extra=d) sleep(1) context.state = NormalState() class", "'defence-first.ru'] HOSTIP = ['172.16.17.32', '192.168.127.12', '172.16.58.3'] SOURCEIP = ['192.168.3.11', '192.168.127.12',", "def state(self, value): self._state = value if __name__ == '__main__':", "run(self): self.state.run(self) @property def state(self): return self._state @state.setter def state(self,", "'sourceip': SOURCEIP[0], 'severity': SEVERITY[4], 'facility': FACILITY[3]} context.logger.info('Database error', extra=d) sleep(1)", "if random.random() < 0.3: context.logger.info( 'Successful authorization on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]),", "'hostip': HOSTIP[0], 'severity': SEVERITY[1], 'facility': FACILITY[1]} http_response_code = '200' for", "class DatabaseError(State): def run(self, context): d = {'hostname': HOSTNAME[2], 'hostip':", "randint from time import sleep, strftime HOSTNAME = ['defence-first.rs', 'defence-first.de',", "if i > 5: attack['severity'] = SEVERITY[3] if random.random() <", "fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger =", "'severity': SEVERITY[1], 'facility': FACILITY[1]} http_response_code = '200' for i in", "'user4', 'user5'] FACILITY = ['KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH', 'SYSLOG',", "logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\") logger = logging.getLogger('simulator') if not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH)", "'%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %(' \\ 'message)s ' RESOURCES = ['index.html',", "%H:%M:%S\") logger = logging.getLogger('simulator') if not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler =", "= '503' d['severity'] = SEVERITY[5] for sourceip in SOURCEIP: d['sourceip']", "extra=d) sleep(1) context.state = NormalState() class Context: def __init__(self): self.state", "while True: normal['sourceip'] = random.choice(SOURCEIP) if random.random() < 0.3: context.logger.info(", "'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'] FORMAT = '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s", "'192.168.127.12', '172.16.58.3'] SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32'] USERNAMES", "def run(self, context): return NotImplemented class DoSAttack(State): def run(self, context):", "DatabaseError() context.state.run(context) class BruteForce(State): def run(self, context): attack = {'hostname':", "['172.16.17.32', '192.168.127.12', '172.16.58.3'] SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32']", "HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru'] HOSTIP = ['172.16.17.32', '192.168.127.12', '172.16.58.3']", "{} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(1) if random.random() < 0.1: rand =", "d['sourceip'] = sourceip context.logger.info('Requested resource index.html {}'.format(http_response_code), extra=d) context.state =", "= SEVERITY[3] if random.random() < 0.45: normal['sourceip'] = random.choice(SOURCEIP) context.logger.info('Requested", "return self._state @state.setter def state(self, value): self._state = value if", "DatabaseError(State): def run(self, context): d = {'hostname': HOSTNAME[2], 'hostip': HOSTIP[2],", "0.1: rand = randint(1, 3) if rand == 1: context.state", "sleep(0.5) context.state = NormalState() class DatabaseError(State): def run(self, context): d", "@state.setter def state(self, value): self._state = value if __name__ ==", "= logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler)", "context.state.run(context) class BruteForce(State): def run(self, context): attack = {'hostname': HOSTNAME[1],", "'CRON', 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7'] SEVERITY", "' RESOURCES = ['index.html', 'document.xml', 'dashboard.html'] LOGS_PATH = 'logs' class", "sleep(1) context.state = NormalState() class Context: def __init__(self): self.state =", "HOSTNAME[2], 'hostip': HOSTIP[2], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[4], 'facility': FACILITY[3]} context.logger.info('Database", "= ['user1', 'user2', 'user3', 'user4', 'user5'] FACILITY = ['KERN', 'USER',", "'dashboard.html'] LOGS_PATH = 'logs' class State(ABC): @abstractmethod def run(self, context):", "'172.16.58.3'] SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32'] USERNAMES =", "random.random() < 0.3: context.logger.info( 'Successful authorization on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal)", "sleep(1) if random.random() < 0.1: rand = randint(1, 3) if", "{} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5) context.logger.info('Failed authorization on username \"user1\"', extra=attack)", "['defence-first.rs', 'defence-first.de', 'defence-first.ru'] HOSTIP = ['172.16.17.32', '192.168.127.12', '172.16.58.3'] SOURCEIP =", "context.state = NormalState() class NormalState(State): def run(self, context): normal =", "'NEWS', 'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV', 'FTP', 'NTP', 'LOGAUDIT', 'LOGALERT', 'CRON', 'LOCAL0',", "'172.16.58.3', '172.16.17.32'] USERNAMES = ['user1', 'user2', 'user3', 'user4', 'user5'] FACILITY", ">= 20: http_response_code = '503' d['severity'] = SEVERITY[5] for sourceip", "FORMAT = '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %(' \\ 'message)s ' RESOURCES", "DoSAttack(State): def run(self, context): d = {'hostname': HOSTNAME[0], 'hostip': HOSTIP[0],", "HOSTIP = ['172.16.17.32', '192.168.127.12', '172.16.58.3'] SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16.58.3',", "rand = randint(1, 3) if rand == 1: context.state =", "LOGS_PATH = 'logs' class State(ABC): @abstractmethod def run(self, context): return", "'FTP', 'NTP', 'LOGAUDIT', 'LOGALERT', 'CRON', 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4',", "if not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler = logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter)", "context): d = {'hostname': HOSTNAME[0], 'hostip': HOSTIP[0], 'severity': SEVERITY[1], 'facility':", "if rand == 1: context.state = DoSAttack() elif rand ==", "self.state.run(self) @property def state(self): return self._state @state.setter def state(self, value):", "username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else: context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(1)", "context): normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility':", "def run(self, context): attack = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'sourceip':", "'user2', 'user3', 'user4', 'user5'] FACILITY = ['KERN', 'USER', 'MAIL', 'DAEMON',", "== 3: context.state = DatabaseError() context.state.run(context) class BruteForce(State): def run(self,", "'hostip': HOSTIP[1], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[2], 'facility': FACILITY[4]} normal =", "'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV', 'FTP', 'NTP', 'LOGAUDIT', 'LOGALERT', 'CRON', 'LOCAL0', 'LOCAL1',", "context.logger.info('Database error', extra=d) sleep(1) context.state = NormalState() class Context: def", "NormalState(State): def run(self, context): normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1],", "import os import random from abc import ABC, abstractmethod from", "< 0.45: normal['sourceip'] = random.choice(SOURCEIP) context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal)", "'user3', 'user4', 'user5'] FACILITY = ['KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH',", "self._state @state.setter def state(self, value): self._state = value if __name__", "from random import randint from time import sleep, strftime HOSTNAME", "context): d = {'hostname': HOSTNAME[2], 'hostip': HOSTIP[2], 'sourceip': SOURCEIP[0], 'severity':", "HOSTIP[1], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[2], 'facility': FACILITY[4]} normal = {'hostname':", "in range(30): if i > 5: attack['severity'] = SEVERITY[3] if", "random from abc import ABC, abstractmethod from random import randint", "SEVERITY[5] for sourceip in SOURCEIP: d['sourceip'] = sourceip context.logger.info('Requested resource", "= random.choice(SOURCEIP) context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5) context.logger.info('Failed authorization", "'USER', 'MAIL', 'DAEMON', 'AUTH', 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV',", "return NotImplemented class DoSAttack(State): def run(self, context): d = {'hostname':", "d = {'hostname': HOSTNAME[2], 'hostip': HOSTIP[2], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[4],", "= ['172.16.17.32', '192.168.127.12', '172.16.58.3'] SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3',", "'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7'] SEVERITY = ['DEBUG', 'INFORMATIONAL', 'NOTICE', 'WARNING',", "= random.choice(SOURCEIP) if random.random() < 0.3: context.logger.info( 'Successful authorization on", "BruteForce() elif rand == 3: context.state = DatabaseError() context.state.run(context) class", "import logging import os import random from abc import ABC,", "logging.getLogger('simulator') if not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler = logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d'))))", "authorization on username \"user1\"', extra=attack) sleep(0.5) context.state = NormalState() class", "os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler = logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler =", "3: context.state = DatabaseError() context.state.run(context) class BruteForce(State): def run(self, context):", "'logs' class State(ABC): @abstractmethod def run(self, context): return NotImplemented class", "FACILITY[3]} context.logger.info('Database error', extra=d) sleep(1) context.state = NormalState() class Context:", "'severity': SEVERITY[1], 'facility': FACILITY[1]} while True: normal['sourceip'] = random.choice(SOURCEIP) if", "= NormalState() formatter = logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\") logger = logging.getLogger('simulator')", "ABC, abstractmethod from random import randint from time import sleep,", "extra=d) context.state = NormalState() class NormalState(State): def run(self, context): normal", "'LPR', 'NEWS', 'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV', 'FTP', 'NTP', 'LOGAUDIT', 'LOGALERT', 'CRON',", "in SOURCEIP: d['sourceip'] = sourceip context.logger.info('Requested resource index.html {}'.format(http_response_code), extra=d)", "sourceip context.logger.info('Requested resource index.html {}'.format(http_response_code), extra=d) context.state = NormalState() class", "if i >= 20: http_response_code = '503' d['severity'] = SEVERITY[5]", "sleep, strftime HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru'] HOSTIP = ['172.16.17.32',", "SEVERITY[3] if random.random() < 0.45: normal['sourceip'] = random.choice(SOURCEIP) context.logger.info('Requested resource", "context.logger.info('Failed authorization on username \"user1\"', extra=attack) sleep(0.5) context.state = NormalState()", "context.logger.info('Requested resource index.html {}'.format(http_response_code), extra=d) context.state = NormalState() class NormalState(State):", "context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5) context.logger.info('Failed authorization on username", "logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger = logger def run(self): self.state.run(self) @property def", "normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]}", "['DEBUG', 'INFORMATIONAL', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'] FORMAT =", "USERNAMES = ['user1', 'user2', 'user3', 'user4', 'user5'] FACILITY = ['KERN',", "def state(self): return self._state @state.setter def state(self, value): self._state =", "'severity': SEVERITY[1], 'facility': FACILITY[1]} for i in range(30): if i", "NormalState() class Context: def __init__(self): self.state = NormalState() formatter =", "in range(25): if i >= 20: http_response_code = '503' d['severity']", "os.mkdir(LOGS_PATH) fileHandler = logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler()", "if random.random() < 0.1: rand = randint(1, 3) if rand", "'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} for i in range(30):", "resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5) context.logger.info('Failed authorization on username \"user1\"',", "normal['sourceip'] = random.choice(SOURCEIP) context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5) context.logger.info('Failed", "def run(self, context): d = {'hostname': HOSTNAME[2], 'hostip': HOSTIP[2], 'sourceip':", "consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger = logger def run(self): self.state.run(self)", "random import randint from time import sleep, strftime HOSTNAME =", "NotImplemented class DoSAttack(State): def run(self, context): d = {'hostname': HOSTNAME[0],", "extra=normal) else: context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(1) if random.random()", "if random.random() < 0.45: normal['sourceip'] = random.choice(SOURCEIP) context.logger.info('Requested resource {}", "= {'hostname': HOSTNAME[0], 'hostip': HOSTIP[0], 'severity': SEVERITY[1], 'facility': FACILITY[1]} http_response_code", "< 0.1: rand = randint(1, 3) if rand == 1:", "def __init__(self): self.state = NormalState() formatter = logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\")", "import random from abc import ABC, abstractmethod from random import", "context): return NotImplemented class DoSAttack(State): def run(self, context): d =", "class State(ABC): @abstractmethod def run(self, context): return NotImplemented class DoSAttack(State):", "'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV', 'FTP', 'NTP', 'LOGAUDIT', 'LOGALERT',", "'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'] FORMAT = '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s", "SOURCEIP: d['sourceip'] = sourceip context.logger.info('Requested resource index.html {}'.format(http_response_code), extra=d) context.state", "< 0.3: context.logger.info( 'Successful authorization on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else:", "logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger = logger def run(self): self.state.run(self) @property", "formatter = logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\") logger = logging.getLogger('simulator') if not", "= value if __name__ == '__main__': sm = Context() sm.run()", "@abstractmethod def run(self, context): return NotImplemented class DoSAttack(State): def run(self,", "context.logger.info( 'Successful authorization on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else: context.logger.info('Requested resource", "username \"user1\"', extra=attack) sleep(0.5) context.state = NormalState() class DatabaseError(State): def", "'sourceip': SOURCEIP[0], 'severity': SEVERITY[2], 'facility': FACILITY[4]} normal = {'hostname': HOSTNAME[1],", "= SEVERITY[5] for sourceip in SOURCEIP: d['sourceip'] = sourceip context.logger.info('Requested", "NormalState() formatter = logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\") logger = logging.getLogger('simulator') if", "strftime HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru'] HOSTIP = ['172.16.17.32', '192.168.127.12',", "context.state = DoSAttack() elif rand == 2: context.state = BruteForce()", "state(self): return self._state @state.setter def state(self, value): self._state = value", "HOSTIP[0], 'severity': SEVERITY[1], 'facility': FACILITY[1]} http_response_code = '200' for i", "logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler)", "logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger = logger def run(self):", "= ['KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH', 'SYSLOG', 'LPR', 'NEWS', 'UUCP',", "FACILITY[1]} for i in range(30): if i > 5: attack['severity']", "class BruteForce(State): def run(self, context): attack = {'hostname': HOSTNAME[1], 'hostip':", "def run(self, context): normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity':", "200'.format(random.choice(RESOURCES)), extra=normal) sleep(1) if random.random() < 0.1: rand = randint(1,", "= DatabaseError() context.state.run(context) class BruteForce(State): def run(self, context): attack =", "= NormalState() class DatabaseError(State): def run(self, context): d = {'hostname':", "error', extra=d) sleep(1) context.state = NormalState() class Context: def __init__(self):", "os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO)", "else: context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(1) if random.random() <", "abstractmethod from random import randint from time import sleep, strftime", "{'hostname': HOSTNAME[0], 'hostip': HOSTIP[0], 'severity': SEVERITY[1], 'facility': FACILITY[1]} http_response_code =", "'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} while True: normal['sourceip'] =", "5: attack['severity'] = SEVERITY[3] if random.random() < 0.45: normal['sourceip'] =", "['user1', 'user2', 'user3', 'user4', 'user5'] FACILITY = ['KERN', 'USER', 'MAIL',", "FACILITY[1]} while True: normal['sourceip'] = random.choice(SOURCEIP) if random.random() < 0.3:", "i > 5: attack['severity'] = SEVERITY[3] if random.random() < 0.45:", "= {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} for", "random.random() < 0.1: rand = randint(1, 3) if rand ==", "FACILITY = ['KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH', 'SYSLOG', 'LPR', 'NEWS',", "context.state = NormalState() class DatabaseError(State): def run(self, context): d =", "logging import os import random from abc import ABC, abstractmethod", "'Successful authorization on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else: context.logger.info('Requested resource {}", "i >= 20: http_response_code = '503' d['severity'] = SEVERITY[5] for", "'facility': FACILITY[1]} http_response_code = '200' for i in range(25): if", "sourceip in SOURCEIP: d['sourceip'] = sourceip context.logger.info('Requested resource index.html {}'.format(http_response_code),", "'INFORMATIONAL', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'] FORMAT = '%(asctime)s", "True: normal['sourceip'] = random.choice(SOURCEIP) if random.random() < 0.3: context.logger.info( 'Successful", "= {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} while", "NormalState() class DatabaseError(State): def run(self, context): d = {'hostname': HOSTNAME[2],", "= '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %(' \\ 'message)s ' RESOURCES =", "{'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[2], 'facility': FACILITY[4]}", "'CRITICAL', 'ALERT', 'EMERGENCY'] FORMAT = '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %(' \\", "'LOCAL5', 'LOCAL6', 'LOCAL7'] SEVERITY = ['DEBUG', 'INFORMATIONAL', 'NOTICE', 'WARNING', 'ERROR',", "= ['index.html', 'document.xml', 'dashboard.html'] LOGS_PATH = 'logs' class State(ABC): @abstractmethod", "State(ABC): @abstractmethod def run(self, context): return NotImplemented class DoSAttack(State): def", "'503' d['severity'] = SEVERITY[5] for sourceip in SOURCEIP: d['sourceip'] =", "i in range(30): if i > 5: attack['severity'] = SEVERITY[3]", "'CLOCK_DAEMON', 'AUTHPRIV', 'FTP', 'NTP', 'LOGAUDIT', 'LOGALERT', 'CRON', 'LOCAL0', 'LOCAL1', 'LOCAL2',", "%(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %(' \\ 'message)s ' RESOURCES = ['index.html', 'document.xml',", "%(' \\ 'message)s ' RESOURCES = ['index.html', 'document.xml', 'dashboard.html'] LOGS_PATH", "'user5'] FACILITY = ['KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH', 'SYSLOG', 'LPR',", "elif rand == 2: context.state = BruteForce() elif rand ==", "= {'hostname': HOSTNAME[2], 'hostip': HOSTIP[2], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[4], 'facility':", "random.choice(SOURCEIP) if random.random() < 0.3: context.logger.info( 'Successful authorization on username", "== 2: context.state = BruteForce() elif rand == 3: context.state", "randint(1, 3) if rand == 1: context.state = DoSAttack() elif", "run(self, context): d = {'hostname': HOSTNAME[2], 'hostip': HOSTIP[2], 'sourceip': SOURCEIP[0],", "logger def run(self): self.state.run(self) @property def state(self): return self._state @state.setter", "logger = logging.getLogger('simulator') if not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler = logging.FileHandler(", "for i in range(25): if i >= 20: http_response_code =", "'EMERGENCY'] FORMAT = '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %(' \\ 'message)s '", "on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else: context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal)", "context): attack = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'sourceip': SOURCEIP[0], 'severity':", "context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(1) if random.random() < 0.1:", "= sourceip context.logger.info('Requested resource index.html {}'.format(http_response_code), extra=d) context.state = NormalState()", "state(self, value): self._state = value if __name__ == '__main__': sm", "2: context.state = BruteForce() elif rand == 3: context.state =", "not os.path.exists(LOGS_PATH): os.mkdir(LOGS_PATH) fileHandler = logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler", "> 5: attack['severity'] = SEVERITY[3] if random.random() < 0.45: normal['sourceip']", "'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7'] SEVERITY = ['DEBUG', 'INFORMATIONAL', 'NOTICE',", "RESOURCES = ['index.html', 'document.xml', 'dashboard.html'] LOGS_PATH = 'logs' class State(ABC):", "range(30): if i > 5: attack['severity'] = SEVERITY[3] if random.random()", "attack = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[2],", "'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7'] SEVERITY = ['DEBUG',", "context.state = DatabaseError() context.state.run(context) class BruteForce(State): def run(self, context): attack", "'DAEMON', 'AUTH', 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV', 'FTP', 'NTP',", "from abc import ABC, abstractmethod from random import randint from", "HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} for i in range(30): if", "%(severity)s-%(facility)s %(' \\ 'message)s ' RESOURCES = ['index.html', 'document.xml', 'dashboard.html']", "{'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} while True:", "FACILITY[1]} http_response_code = '200' for i in range(25): if i", "SEVERITY[1], 'facility': FACILITY[1]} http_response_code = '200' for i in range(25):", "class Context: def __init__(self): self.state = NormalState() formatter = logging.Formatter(FORMAT,", "extra=attack) sleep(0.5) context.state = NormalState() class DatabaseError(State): def run(self, context):", "'LOCAL6', 'LOCAL7'] SEVERITY = ['DEBUG', 'INFORMATIONAL', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL',", "value): self._state = value if __name__ == '__main__': sm =", "random.choice(SOURCEIP) context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5) context.logger.info('Failed authorization on", "= logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger = logger def", "import randint from time import sleep, strftime HOSTNAME = ['defence-first.rs',", "'facility': FACILITY[1]} while True: normal['sourceip'] = random.choice(SOURCEIP) if random.random() <", "SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32'] USERNAMES = ['user1',", "range(25): if i >= 20: http_response_code = '503' d['severity'] =", "'facility': FACILITY[1]} for i in range(30): if i > 5:", "elif rand == 3: context.state = DatabaseError() context.state.run(context) class BruteForce(State):", "BruteForce(State): def run(self, context): attack = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1],", "SEVERITY[4], 'facility': FACILITY[3]} context.logger.info('Database error', extra=d) sleep(1) context.state = NormalState()", "attack['severity'] = SEVERITY[3] if random.random() < 0.45: normal['sourceip'] = random.choice(SOURCEIP)", "import sleep, strftime HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru'] HOSTIP =", "'facility': FACILITY[4]} normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1],", "'message)s ' RESOURCES = ['index.html', 'document.xml', 'dashboard.html'] LOGS_PATH = 'logs'", "HOSTIP[2], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[4], 'facility': FACILITY[3]} context.logger.info('Database error', extra=d)", "HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility': FACILITY[1]} for i in", "__init__(self): self.state = NormalState() formatter = logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\") logger", "= BruteForce() elif rand == 3: context.state = DatabaseError() context.state.run(context)", "= NormalState() class Context: def __init__(self): self.state = NormalState() formatter", "DoSAttack() elif rand == 2: context.state = BruteForce() elif rand", "FACILITY[4]} normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1], 'facility':", "'defence-first.de', 'defence-first.ru'] HOSTIP = ['172.16.17.32', '192.168.127.12', '172.16.58.3'] SOURCEIP = ['192.168.3.11',", "'ALERT', 'EMERGENCY'] FORMAT = '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %(' \\ 'message)s", "'NTP', 'LOGAUDIT', 'LOGALERT', 'CRON', 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5',", "@property def state(self): return self._state @state.setter def state(self, value): self._state", "def run(self, context): d = {'hostname': HOSTNAME[0], 'hostip': HOSTIP[0], 'severity':", "time import sleep, strftime HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru'] HOSTIP", "== 1: context.state = DoSAttack() elif rand == 2: context.state", "extra=normal) sleep(1) if random.random() < 0.1: rand = randint(1, 3)", "import ABC, abstractmethod from random import randint from time import", "3) if rand == 1: context.state = DoSAttack() elif rand", "'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7'] SEVERITY = ['DEBUG', 'INFORMATIONAL',", "'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'] FORMAT = '%(asctime)s %(hostname)s-Application-%(hostip)s-%(sourceip)s %(severity)s-%(facility)s %('", "'MAIL', 'DAEMON', 'AUTH', 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CLOCK_DAEMON', 'AUTHPRIV', 'FTP',", "on username \"user1\"', extra=attack) sleep(0.5) context.state = NormalState() class DatabaseError(State):", "run(self, context): d = {'hostname': HOSTNAME[0], 'hostip': HOSTIP[0], 'severity': SEVERITY[1],", "consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.setLevel(logging.INFO) self.logger = logger", "def run(self): self.state.run(self) @property def state(self): return self._state @state.setter def", "HOSTNAME[0], 'hostip': HOSTIP[0], 'severity': SEVERITY[1], 'facility': FACILITY[1]} http_response_code = '200'", "rand == 2: context.state = BruteForce() elif rand == 3:", "0.45: normal['sourceip'] = random.choice(SOURCEIP) context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)), extra=normal) sleep(0.5)", "= logging.Formatter(FORMAT, \"%Y-%m-%d %H:%M:%S\") logger = logging.getLogger('simulator') if not os.path.exists(LOGS_PATH):", "'LOCAL7'] SEVERITY = ['DEBUG', 'INFORMATIONAL', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT',", "resource index.html {}'.format(http_response_code), extra=d) context.state = NormalState() class NormalState(State): def", "\"user1\"', extra=attack) sleep(0.5) context.state = NormalState() class DatabaseError(State): def run(self,", "'172.16.17.32'] USERNAMES = ['user1', 'user2', 'user3', 'user4', 'user5'] FACILITY =", "SOURCEIP[0], 'severity': SEVERITY[4], 'facility': FACILITY[3]} context.logger.info('Database error', extra=d) sleep(1) context.state", "= DoSAttack() elif rand == 2: context.state = BruteForce() elif", "SEVERITY[2], 'facility': FACILITY[4]} normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity':", "fileHandler = logging.FileHandler( os.path.join(LOGS_PATH, 'application_log-{}.log'.format(strftime('%Y-%m-%d')))) fileHandler.setFormatter(formatter) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter)", "'200' for i in range(25): if i >= 20: http_response_code", "random.random() < 0.45: normal['sourceip'] = random.choice(SOURCEIP) context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)),", "authorization on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else: context.logger.info('Requested resource {} 200'.format(random.choice(RESOURCES)),", "extra=normal) sleep(0.5) context.logger.info('Failed authorization on username \"user1\"', extra=attack) sleep(0.5) context.state", "'LOGAUDIT', 'LOGALERT', 'CRON', 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6',", "'AUTHPRIV', 'FTP', 'NTP', 'LOGAUDIT', 'LOGALERT', 'CRON', 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3',", "= ['defence-first.rs', 'defence-first.de', 'defence-first.ru'] HOSTIP = ['172.16.17.32', '192.168.127.12', '172.16.58.3'] SOURCEIP", "run(self, context): attack = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'sourceip': SOURCEIP[0],", "SEVERITY = ['DEBUG', 'INFORMATIONAL', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY']", "0.3: context.logger.info( 'Successful authorization on username \"{}\"'.format(USERNAMES[SOURCEIP.index(normal['sourceip'])]), extra=normal) else: context.logger.info('Requested", "= '200' for i in range(25): if i >= 20:", "self._state = value if __name__ == '__main__': sm = Context()", "HOSTNAME[1], 'hostip': HOSTIP[1], 'sourceip': SOURCEIP[0], 'severity': SEVERITY[2], 'facility': FACILITY[4]} normal", "i in range(25): if i >= 20: http_response_code = '503'", "SOURCEIP[0], 'severity': SEVERITY[2], 'facility': FACILITY[4]} normal = {'hostname': HOSTNAME[1], 'hostip':", "= logger def run(self): self.state.run(self) @property def state(self): return self._state", "20: http_response_code = '503' d['severity'] = SEVERITY[5] for sourceip in", "run(self, context): normal = {'hostname': HOSTNAME[1], 'hostip': HOSTIP[1], 'severity': SEVERITY[1],", "logger.setLevel(logging.INFO) self.logger = logger def run(self): self.state.run(self) @property def state(self):" ]
[]
[ "typing import Optional import numpy as np from . import", "return error assert lhs.shape[-1] == self._state_vec.perturb_dim jacs = dict() if", "\"\"\"Error evaluator for a measured vector space state variable\"\"\" def", "self._state_vec: VectorSpaceStateVar = state_vec def is_active(self): return not self._state_vec.locked def", "jacs = dict() if not self._state_vec.locked: jacs = {self._state_vec.key: -lhs}", "def is_active(self): return not self._state_vec.locked def evaluate(self, lhs: Optional[np.ndarray] =", "np.ndarray = meas self._state_vec: VectorSpaceStateVar = state_vec def is_active(self): return", "self._state_vec.perturb_dim jacs = dict() if not self._state_vec.locked: jacs = {self._state_vec.key:", "VectorSpaceStateVar = state_vec def is_active(self): return not self._state_vec.locked def evaluate(self,", "import VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator for a measured vector", "np.ndarray, state_vec: VectorSpaceStateVar) -> None: super().__init__() self._meas: np.ndarray = meas", "self._meas - self._state_vec.value if lhs is None: return error assert", "vector space state variable\"\"\" def __init__(self, meas: np.ndarray, state_vec: VectorSpaceStateVar)", "- self._state_vec.value if lhs is None: return error assert lhs.shape[-1]", "dict() if not self._state_vec.locked: jacs = {self._state_vec.key: -lhs} return error,", "if not self._state_vec.locked: jacs = {self._state_vec.key: -lhs} return error, jacs", "if lhs is None: return error assert lhs.shape[-1] == self._state_vec.perturb_dim", "numpy as np from . import Evaluator from ..state import", "= self._meas - self._state_vec.value if lhs is None: return error", "__init__(self, meas: np.ndarray, state_vec: VectorSpaceStateVar) -> None: super().__init__() self._meas: np.ndarray", "variable\"\"\" def __init__(self, meas: np.ndarray, state_vec: VectorSpaceStateVar) -> None: super().__init__()", "import numpy as np from . import Evaluator from ..state", "class VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator for a measured vector space state", "= meas self._state_vec: VectorSpaceStateVar = state_vec def is_active(self): return not", "error = self._meas - self._state_vec.value if lhs is None: return", "VectorSpaceStateVar) -> None: super().__init__() self._meas: np.ndarray = meas self._state_vec: VectorSpaceStateVar", "state_vec def is_active(self): return not self._state_vec.locked def evaluate(self, lhs: Optional[np.ndarray]", "self._state_vec.locked def evaluate(self, lhs: Optional[np.ndarray] = None): error = self._meas", "def evaluate(self, lhs: Optional[np.ndarray] = None): error = self._meas -", "from ..state import VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator for a", "None: return error assert lhs.shape[-1] == self._state_vec.perturb_dim jacs = dict()", "state_vec: VectorSpaceStateVar) -> None: super().__init__() self._meas: np.ndarray = meas self._state_vec:", "<reponame>utiasASRL/pysteam from typing import Optional import numpy as np from", "assert lhs.shape[-1] == self._state_vec.perturb_dim jacs = dict() if not self._state_vec.locked:", "not self._state_vec.locked def evaluate(self, lhs: Optional[np.ndarray] = None): error =", "evaluator for a measured vector space state variable\"\"\" def __init__(self,", "measured vector space state variable\"\"\" def __init__(self, meas: np.ndarray, state_vec:", "Optional import numpy as np from . import Evaluator from", "lhs is None: return error assert lhs.shape[-1] == self._state_vec.perturb_dim jacs", "import Evaluator from ..state import VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator", "None: super().__init__() self._meas: np.ndarray = meas self._state_vec: VectorSpaceStateVar = state_vec", "a measured vector space state variable\"\"\" def __init__(self, meas: np.ndarray,", "from typing import Optional import numpy as np from .", "self._meas: np.ndarray = meas self._state_vec: VectorSpaceStateVar = state_vec def is_active(self):", "return not self._state_vec.locked def evaluate(self, lhs: Optional[np.ndarray] = None): error", "= None): error = self._meas - self._state_vec.value if lhs is", "is_active(self): return not self._state_vec.locked def evaluate(self, lhs: Optional[np.ndarray] = None):", "None): error = self._meas - self._state_vec.value if lhs is None:", ". import Evaluator from ..state import VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator): \"\"\"Error", "meas: np.ndarray, state_vec: VectorSpaceStateVar) -> None: super().__init__() self._meas: np.ndarray =", "meas self._state_vec: VectorSpaceStateVar = state_vec def is_active(self): return not self._state_vec.locked", "Evaluator from ..state import VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator for", "VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator for a measured vector space state variable\"\"\"", "import Optional import numpy as np from . import Evaluator", "Optional[np.ndarray] = None): error = self._meas - self._state_vec.value if lhs", "self._state_vec.value if lhs is None: return error assert lhs.shape[-1] ==", "for a measured vector space state variable\"\"\" def __init__(self, meas:", "error assert lhs.shape[-1] == self._state_vec.perturb_dim jacs = dict() if not", "-> None: super().__init__() self._meas: np.ndarray = meas self._state_vec: VectorSpaceStateVar =", "from . import Evaluator from ..state import VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator):", "= state_vec def is_active(self): return not self._state_vec.locked def evaluate(self, lhs:", "state variable\"\"\" def __init__(self, meas: np.ndarray, state_vec: VectorSpaceStateVar) -> None:", "VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator for a measured vector space", "space state variable\"\"\" def __init__(self, meas: np.ndarray, state_vec: VectorSpaceStateVar) ->", "is None: return error assert lhs.shape[-1] == self._state_vec.perturb_dim jacs =", "np from . import Evaluator from ..state import VectorSpaceStateVar class", "lhs.shape[-1] == self._state_vec.perturb_dim jacs = dict() if not self._state_vec.locked: jacs", "super().__init__() self._meas: np.ndarray = meas self._state_vec: VectorSpaceStateVar = state_vec def", "== self._state_vec.perturb_dim jacs = dict() if not self._state_vec.locked: jacs =", "= dict() if not self._state_vec.locked: jacs = {self._state_vec.key: -lhs} return", "def __init__(self, meas: np.ndarray, state_vec: VectorSpaceStateVar) -> None: super().__init__() self._meas:", "evaluate(self, lhs: Optional[np.ndarray] = None): error = self._meas - self._state_vec.value", "..state import VectorSpaceStateVar class VectorSpaceErrorEval(Evaluator): \"\"\"Error evaluator for a measured", "lhs: Optional[np.ndarray] = None): error = self._meas - self._state_vec.value if", "as np from . import Evaluator from ..state import VectorSpaceStateVar" ]
[ "<reponame>mwussow/pytorch_geometric from .knn_interpolate import knn_interpolate __all__ = [ 'knn_interpolate', ]" ]
[ "def dummy_address(dummy_identifier) -> PyAddress: assert len(dummy_identifier) == 20 return PyAddress.from_param('dummy',", "assert len(dummy_identifier) == 20 return PyAddress.from_param('dummy', 0, dummy_identifier) __all__ =", "PyAddress.from_param('dummy', 0, dummy_identifier) __all__ = [ \"is_address\", \"get_address\", \"convert_address\", \"dummy_address\",", "key\"\"\" identifier = hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp, ver, identifier) def", "def convert_address(ck: PyAddress, hrp, ver) -> PyAddress: \"\"\"convert address's version\"\"\"", "PyAddress.from_param(hrp, ver, ck.identifier()) def dummy_address(dummy_identifier) -> PyAddress: assert len(dummy_identifier) ==", "0, dummy_identifier) __all__ = [ \"is_address\", \"get_address\", \"convert_address\", \"dummy_address\", ]", "20 return PyAddress.from_param('dummy', 0, dummy_identifier) __all__ = [ \"is_address\", \"get_address\",", "version\"\"\" return PyAddress.from_param(hrp, ver, ck.identifier()) def dummy_address(dummy_identifier) -> PyAddress: assert", "dummy_address(dummy_identifier) -> PyAddress: assert len(dummy_identifier) == 20 return PyAddress.from_param('dummy', 0,", "hrp, ver): \"\"\"check bech32 format and version\"\"\" try: if ck.hrp", "except ValueError: return False return True def get_address(pk, hrp, ver)", "!= hrp: return False if ck.version != ver: return False", "-> PyAddress: \"\"\"convert address's version\"\"\" return PyAddress.from_param(hrp, ver, ck.identifier()) def", "len(dummy_identifier) == 20 return PyAddress.from_param('dummy', 0, dummy_identifier) __all__ = [", "from public key\"\"\" identifier = hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp, ver,", "def is_address(ck: PyAddress, hrp, ver): \"\"\"check bech32 format and version\"\"\"", "PyAddress: \"\"\"convert address's version\"\"\" return PyAddress.from_param(hrp, ver, ck.identifier()) def dummy_address(dummy_identifier)", "identifier) def convert_address(ck: PyAddress, hrp, ver) -> PyAddress: \"\"\"convert address's", "ver, identifier) def convert_address(ck: PyAddress, hrp, ver) -> PyAddress: \"\"\"convert", "hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp, ver, identifier) def convert_address(ck: PyAddress, hrp,", "== 20 return PyAddress.from_param('dummy', 0, dummy_identifier) __all__ = [ \"is_address\",", "ver, ck.identifier()) def dummy_address(dummy_identifier) -> PyAddress: assert len(dummy_identifier) == 20", "hrp: return False if ck.version != ver: return False except", "return False if ck.version != ver: return False except ValueError:", "get_address(pk, hrp, ver) -> PyAddress: \"\"\"get address from public key\"\"\"", "try: if ck.hrp != hrp: return False if ck.version !=", "PyAddress import hashlib def is_address(ck: PyAddress, hrp, ver): \"\"\"check bech32", "False return True def get_address(pk, hrp, ver) -> PyAddress: \"\"\"get", "return True def get_address(pk, hrp, ver) -> PyAddress: \"\"\"get address", "PyAddress.from_param(hrp, ver, identifier) def convert_address(ck: PyAddress, hrp, ver) -> PyAddress:", "= hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp, ver, identifier) def convert_address(ck: PyAddress,", "is_address(ck: PyAddress, hrp, ver): \"\"\"check bech32 format and version\"\"\" try:", "-> PyAddress: assert len(dummy_identifier) == 20 return PyAddress.from_param('dummy', 0, dummy_identifier)", "PyAddress, hrp, ver) -> PyAddress: \"\"\"convert address's version\"\"\" return PyAddress.from_param(hrp,", "address's version\"\"\" return PyAddress.from_param(hrp, ver, ck.identifier()) def dummy_address(dummy_identifier) -> PyAddress:", "identifier = hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp, ver, identifier) def convert_address(ck:", "return False except ValueError: return False return True def get_address(pk,", "!= ver: return False except ValueError: return False return True", "False except ValueError: return False return True def get_address(pk, hrp,", "return PyAddress.from_param(hrp, ver, ck.identifier()) def dummy_address(dummy_identifier) -> PyAddress: assert len(dummy_identifier)", "ck.version != ver: return False except ValueError: return False return", "if ck.hrp != hrp: return False if ck.version != ver:", "from bc4py_extension import PyAddress import hashlib def is_address(ck: PyAddress, hrp,", "hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp, ver, identifier) def convert_address(ck: PyAddress, hrp, ver)", "bc4py_extension import PyAddress import hashlib def is_address(ck: PyAddress, hrp, ver):", "PyAddress, hrp, ver): \"\"\"check bech32 format and version\"\"\" try: if", "bech32 format and version\"\"\" try: if ck.hrp != hrp: return", "ver) -> PyAddress: \"\"\"get address from public key\"\"\" identifier =", "\"\"\"check bech32 format and version\"\"\" try: if ck.hrp != hrp:", "\"\"\"convert address's version\"\"\" return PyAddress.from_param(hrp, ver, ck.identifier()) def dummy_address(dummy_identifier) ->", "ck.identifier()) def dummy_address(dummy_identifier) -> PyAddress: assert len(dummy_identifier) == 20 return", "def get_address(pk, hrp, ver) -> PyAddress: \"\"\"get address from public", "True def get_address(pk, hrp, ver) -> PyAddress: \"\"\"get address from", "ver) -> PyAddress: \"\"\"convert address's version\"\"\" return PyAddress.from_param(hrp, ver, ck.identifier())", "-> PyAddress: \"\"\"get address from public key\"\"\" identifier = hashlib.new('ripemd160',", "ValueError: return False return True def get_address(pk, hrp, ver) ->", "and version\"\"\" try: if ck.hrp != hrp: return False if", "ver: return False except ValueError: return False return True def", "version\"\"\" try: if ck.hrp != hrp: return False if ck.version", "address from public key\"\"\" identifier = hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp,", "False if ck.version != ver: return False except ValueError: return", "public key\"\"\" identifier = hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return PyAddress.from_param(hrp, ver, identifier)", "return PyAddress.from_param(hrp, ver, identifier) def convert_address(ck: PyAddress, hrp, ver) ->", "hrp, ver) -> PyAddress: \"\"\"convert address's version\"\"\" return PyAddress.from_param(hrp, ver,", "return False return True def get_address(pk, hrp, ver) -> PyAddress:", "convert_address(ck: PyAddress, hrp, ver) -> PyAddress: \"\"\"convert address's version\"\"\" return", "\"\"\"get address from public key\"\"\" identifier = hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() return", "hashlib def is_address(ck: PyAddress, hrp, ver): \"\"\"check bech32 format and", "import PyAddress import hashlib def is_address(ck: PyAddress, hrp, ver): \"\"\"check", "format and version\"\"\" try: if ck.hrp != hrp: return False", "ck.hrp != hrp: return False if ck.version != ver: return", "import hashlib def is_address(ck: PyAddress, hrp, ver): \"\"\"check bech32 format", "ver): \"\"\"check bech32 format and version\"\"\" try: if ck.hrp !=", "hrp, ver) -> PyAddress: \"\"\"get address from public key\"\"\" identifier", "PyAddress: \"\"\"get address from public key\"\"\" identifier = hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest()", "PyAddress: assert len(dummy_identifier) == 20 return PyAddress.from_param('dummy', 0, dummy_identifier) __all__", "if ck.version != ver: return False except ValueError: return False", "return PyAddress.from_param('dummy', 0, dummy_identifier) __all__ = [ \"is_address\", \"get_address\", \"convert_address\"," ]
[ "import logger from toposort import toposort from . import common", "{name for name in common.DEPENDENCIES if (path / name).exists()} steps:", "in jids] cmd = [\"sbatch\"] if dep_jids: cmd += [\"--dependency\",", "jid = stdout.split()[-1] logger.info(\" => JID: %s\", jid) jids[step] =", "``cubi-tk snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\", \"-n\",", "args.dry_run: jid = \"<%s>\" % step else: stdout_raw = subprocess.check_output(cmd,", "parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\", \"-n\", default=False, action=\"store_true\", help=\"Perform", "typing from logzero import logger from toposort import toposort from", "os import subprocess import typing from logzero import logger from", "\"-n\", default=False, action=\"store_true\", help=\"Perform dry-run, do not do anything.\", )", "logzero import logger from toposort import toposort from . import", "= [jids[dep] for dep in common.DEPENDENCIES[step] if dep in jids]", "jid return None def setup_argparse(parser: argparse.ArgumentParser) -> None: \"\"\"Setup argument", "step else: stdout_raw = subprocess.check_output(cmd, cwd=str(path / step), timeout=args.timeout) stdout", "if (path / name).exists()} steps: typing.List[str] = [] for names", "-> typing.Optional[int]: logger.info(\"Try to find SNAPPY pipeline directory...\") try: path", "if name in step_set] logger.info(\"Will run the steps: %s\", \",", "which is a limitation... logger.info(\"Looking for pipeline directories (assuming standard", "do anything.\", ) parser.add_argument( \"--timeout\", default=10, type=int, help=\"Number of seconds", "logger from toposort import toposort from . import common from", "\"<%s>\" % step else: stdout_raw = subprocess.check_output(cmd, cwd=str(path / step),", ") parser.add_argument( \"path\", nargs=\"?\", help=\"Path into SNAPPY directory (below a", "cwd=str(path / step), timeout=args.timeout) stdout = stdout_raw.decode(\"utf-8\") if not stdout.startswith(\"Submitted", "set(v) for k, v in common.DEPENDENCIES.items()}): steps += [name for", "logger.info(\"Will run the steps: %s\", \", \".join(steps)) logger.info(\"Submitting with sbatch...\")", "kickoff``: kickoff SNAPPY pipeline.\"\"\" import argparse import os import subprocess", "standard naming which is a limitation... logger.info(\"Looking for pipeline directories", "= jid return None def setup_argparse(parser: argparse.ArgumentParser) -> None: \"\"\"Setup", "subprocess import typing from logzero import logger from toposort import", "wait for commands.\" ) parser.add_argument( \"path\", nargs=\"?\", help=\"Path into SNAPPY", "jids: typing.Dict[str, str] = {} for step in steps: dep_jids", "argparse import os import subprocess import typing from logzero import", "argparse.ArgumentParser, _subparser: argparse.ArgumentParser ) -> typing.Optional[int]: logger.info(\"Try to find SNAPPY", "common.DEPENDENCIES if (path / name).exists()} steps: typing.List[str] = [] for", "\".join(cmd)) if args.dry_run: jid = \"<%s>\" % step else: stdout_raw", "of seconds to wait for commands.\" ) parser.add_argument( \"path\", nargs=\"?\",", "toposort from . import common from cubi_tk.exceptions import ParseOutputException def", "standard naming)...\") logger.debug(\"Looking in %s\", path) step_set = {name for", "for k, v in common.DEPENDENCIES.items()}): steps += [name for name", "for name in common.DEPENDENCIES if (path / name).exists()} steps: typing.List[str]", "from cubi_tk.exceptions import ParseOutputException def run( args, _parser: argparse.ArgumentParser, _subparser:", "dep_jids = [jids[dep] for dep in common.DEPENDENCIES[step] if dep in", "from logzero import logger from toposort import toposort from .", "%s\", step, \" \".join(cmd)) if args.dry_run: jid = \"<%s>\" %", "[name for name in names if name in step_set] logger.info(\"Will", "_subparser: argparse.ArgumentParser ) -> typing.Optional[int]: logger.info(\"Try to find SNAPPY pipeline", "[] for names in toposort({k: set(v) for k, v in", "args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser ) -> typing.Optional[int]: logger.info(\"Try to", "dep in common.DEPENDENCIES[step] if dep in jids] cmd = [\"sbatch\"]", "seconds to wait for commands.\" ) parser.add_argument( \"path\", nargs=\"?\", help=\"Path", "help=\"Path into SNAPPY directory (below a directory containing .snappy_pipeline).\", )", "cmd += [\"pipeline_job.sh\"] logger.info(\"Submitting step %s: %s\", step, \" \".join(cmd))", "SNAPPY pipeline directory...\") try: path = common.find_snappy_root_dir(args.path or os.getcwd(), common.DEPENDENCIES.keys())", "/ name).exists()} steps: typing.List[str] = [] for names in toposort({k:", "k, v in common.DEPENDENCIES.items()}): steps += [name for name in", "naming)...\") logger.debug(\"Looking in %s\", path) step_set = {name for name", "in common.DEPENDENCIES.items()}): steps += [name for name in names if", "os.getcwd(), common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot: return 1 # TODO: this assumes", "with sbatch...\") jids: typing.Dict[str, str] = {} for step in", "in toposort({k: set(v) for k, v in common.DEPENDENCIES.items()}): steps +=", "jids] cmd = [\"sbatch\"] if dep_jids: cmd += [\"--dependency\", \"afterok:%s\"", "dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\", \"-n\", default=False, action=\"store_true\", help=\"Perform dry-run,", "TODO: this assumes standard naming which is a limitation... logger.info(\"Looking", "not do anything.\", ) parser.add_argument( \"--timeout\", default=10, type=int, help=\"Number of", "to wait for commands.\" ) parser.add_argument( \"path\", nargs=\"?\", help=\"Path into", "if args.dry_run: jid = \"<%s>\" % step else: stdout_raw =", "if dep_jids: cmd += [\"--dependency\", \"afterok:%s\" % \":\".join(map(str, dep_jids))] cmd", "limitation... logger.info(\"Looking for pipeline directories (assuming standard naming)...\") logger.debug(\"Looking in", "dep_jids: cmd += [\"--dependency\", \"afterok:%s\" % \":\".join(map(str, dep_jids))] cmd +=", "help=\"Perform dry-run, do not do anything.\", ) parser.add_argument( \"--timeout\", default=10,", "parser.add_argument( \"--timeout\", default=10, type=int, help=\"Number of seconds to wait for", "typing.Optional[int]: logger.info(\"Try to find SNAPPY pipeline directory...\") try: path =", "or os.getcwd(), common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot: return 1 # TODO: this", "step in steps: dep_jids = [jids[dep] for dep in common.DEPENDENCIES[step]", "for dep in common.DEPENDENCIES[step] if dep in jids] cmd =", "# TODO: this assumes standard naming which is a limitation...", "from toposort import toposort from . import common from cubi_tk.exceptions", ") -> typing.Optional[int]: logger.info(\"Try to find SNAPPY pipeline directory...\") try:", "= {} for step in steps: dep_jids = [jids[dep] for", "None def setup_argparse(parser: argparse.ArgumentParser) -> None: \"\"\"Setup argument parser for", "snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\", \"-n\", default=False,", "[\"--dependency\", \"afterok:%s\" % \":\".join(map(str, dep_jids))] cmd += [\"pipeline_job.sh\"] logger.info(\"Submitting step", "logger.info(\"Submitting step %s: %s\", step, \" \".join(cmd)) if args.dry_run: jid", "name in common.DEPENDENCIES if (path / name).exists()} steps: typing.List[str] =", "is a limitation... logger.info(\"Looking for pipeline directories (assuming standard naming)...\")", "%s\", \", \".join(steps)) logger.info(\"Submitting with sbatch...\") jids: typing.Dict[str, str] =", "default=False, action=\"store_true\", help=\"Perform dry-run, do not do anything.\", ) parser.add_argument(", "steps: dep_jids = [jids[dep] for dep in common.DEPENDENCIES[step] if dep", "common.DEPENDENCIES.items()}): steps += [name for name in names if name", "import ParseOutputException def run( args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser )", "name in step_set] logger.info(\"Will run the steps: %s\", \", \".join(steps))", "run the steps: %s\", \", \".join(steps)) logger.info(\"Submitting with sbatch...\") jids:", "else: stdout_raw = subprocess.check_output(cmd, cwd=str(path / step), timeout=args.timeout) stdout =", "\"\"\"Setup argument parser for ``cubi-tk snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run,", "= stdout_raw.decode(\"utf-8\") if not stdout.startswith(\"Submitted batch job \"): raise ParseOutputException(\"Did", "= {name for name in common.DEPENDENCIES if (path / name).exists()}", "common.DEPENDENCIES[step] if dep in jids] cmd = [\"sbatch\"] if dep_jids:", "[\"sbatch\"] if dep_jids: cmd += [\"--dependency\", \"afterok:%s\" % \":\".join(map(str, dep_jids))]", "default=10, type=int, help=\"Number of seconds to wait for commands.\" )", "[jids[dep] for dep in common.DEPENDENCIES[step] if dep in jids] cmd", "name in names if name in step_set] logger.info(\"Will run the", "stdout = stdout_raw.decode(\"utf-8\") if not stdout.startswith(\"Submitted batch job \"): raise", "toposort import toposort from . import common from cubi_tk.exceptions import", "1 # TODO: this assumes standard naming which is a", "import typing from logzero import logger from toposort import toposort", "kickoff SNAPPY pipeline.\"\"\" import argparse import os import subprocess import", "[\"pipeline_job.sh\"] logger.info(\"Submitting step %s: %s\", step, \" \".join(cmd)) if args.dry_run:", "subprocess.check_output(cmd, cwd=str(path / step), timeout=args.timeout) stdout = stdout_raw.decode(\"utf-8\") if not", "import common from cubi_tk.exceptions import ParseOutputException def run( args, _parser:", "dry-run, do not do anything.\", ) parser.add_argument( \"--timeout\", default=10, type=int,", "find SNAPPY pipeline directory...\") try: path = common.find_snappy_root_dir(args.path or os.getcwd(),", "pipeline.\"\"\" import argparse import os import subprocess import typing from", "stdout.split()[-1] logger.info(\" => JID: %s\", jid) jids[step] = jid return", "snappy kickoff``: kickoff SNAPPY pipeline.\"\"\" import argparse import os import", "directory...\") try: path = common.find_snappy_root_dir(args.path or os.getcwd(), common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot:", "{} for step in steps: dep_jids = [jids[dep] for dep", "sbatch output: %s\" % stdout) jid = stdout.split()[-1] logger.info(\" =>", "str] = {} for step in steps: dep_jids = [jids[dep]", "logger.info(\" => JID: %s\", jid) jids[step] = jid return None", "argument parser for ``cubi-tk snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS)", "+= [name for name in names if name in step_set]", "stdout.startswith(\"Submitted batch job \"): raise ParseOutputException(\"Did not understand sbatch output:", ") parser.add_argument( \"--timeout\", default=10, type=int, help=\"Number of seconds to wait", "typing.List[str] = [] for names in toposort({k: set(v) for k,", "a limitation... logger.info(\"Looking for pipeline directories (assuming standard naming)...\") logger.debug(\"Looking", "= subprocess.check_output(cmd, cwd=str(path / step), timeout=args.timeout) stdout = stdout_raw.decode(\"utf-8\") if", "def setup_argparse(parser: argparse.ArgumentParser) -> None: \"\"\"Setup argument parser for ``cubi-tk", "import subprocess import typing from logzero import logger from toposort", "return 1 # TODO: this assumes standard naming which is", "%s: %s\", step, \" \".join(cmd)) if args.dry_run: jid = \"<%s>\"", "SNAPPY pipeline.\"\"\" import argparse import os import subprocess import typing", "= [\"sbatch\"] if dep_jids: cmd += [\"--dependency\", \"afterok:%s\" % \":\".join(map(str,", "the steps: %s\", \", \".join(steps)) logger.info(\"Submitting with sbatch...\") jids: typing.Dict[str,", "jid) jids[step] = jid return None def setup_argparse(parser: argparse.ArgumentParser) ->", "+= [\"pipeline_job.sh\"] logger.info(\"Submitting step %s: %s\", step, \" \".join(cmd)) if", "not stdout.startswith(\"Submitted batch job \"): raise ParseOutputException(\"Did not understand sbatch", "default=run, help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\", \"-n\", default=False, action=\"store_true\", help=\"Perform dry-run, do", "anything.\", ) parser.add_argument( \"--timeout\", default=10, type=int, help=\"Number of seconds to", "dep in jids] cmd = [\"sbatch\"] if dep_jids: cmd +=", "\"): raise ParseOutputException(\"Did not understand sbatch output: %s\" % stdout)", "step_set] logger.info(\"Will run the steps: %s\", \", \".join(steps)) logger.info(\"Submitting with", "\", \".join(steps)) logger.info(\"Submitting with sbatch...\") jids: typing.Dict[str, str] = {}", "assumes standard naming which is a limitation... logger.info(\"Looking for pipeline", "logger.info(\"Try to find SNAPPY pipeline directory...\") try: path = common.find_snappy_root_dir(args.path", "% \":\".join(map(str, dep_jids))] cmd += [\"pipeline_job.sh\"] logger.info(\"Submitting step %s: %s\",", "logger.info(\"Looking for pipeline directories (assuming standard naming)...\") logger.debug(\"Looking in %s\",", "batch job \"): raise ParseOutputException(\"Did not understand sbatch output: %s\"", "raise ParseOutputException(\"Did not understand sbatch output: %s\" % stdout) jid", "None: \"\"\"Setup argument parser for ``cubi-tk snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\",", "\"afterok:%s\" % \":\".join(map(str, dep_jids))] cmd += [\"pipeline_job.sh\"] logger.info(\"Submitting step %s:", "parser for ``cubi-tk snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS) parser.add_argument(", "common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot: return 1 # TODO: this assumes standard", "in common.DEPENDENCIES[step] if dep in jids] cmd = [\"sbatch\"] if", "\"\"\"``cubi-tk snappy kickoff``: kickoff SNAPPY pipeline.\"\"\" import argparse import os", "in names if name in step_set] logger.info(\"Will run the steps:", "steps: %s\", \", \".join(steps)) logger.info(\"Submitting with sbatch...\") jids: typing.Dict[str, str]", "for name in names if name in step_set] logger.info(\"Will run", "logger.info(\"Submitting with sbatch...\") jids: typing.Dict[str, str] = {} for step", "% step else: stdout_raw = subprocess.check_output(cmd, cwd=str(path / step), timeout=args.timeout)", "stdout_raw.decode(\"utf-8\") if not stdout.startswith(\"Submitted batch job \"): raise ParseOutputException(\"Did not", "path = common.find_snappy_root_dir(args.path or os.getcwd(), common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot: return 1", "_parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser ) -> typing.Optional[int]: logger.info(\"Try to find", "steps += [name for name in names if name in", "dep_jids))] cmd += [\"pipeline_job.sh\"] logger.info(\"Submitting step %s: %s\", step, \"", "common from cubi_tk.exceptions import ParseOutputException def run( args, _parser: argparse.ArgumentParser,", "job \"): raise ParseOutputException(\"Did not understand sbatch output: %s\" %", "not understand sbatch output: %s\" % stdout) jid = stdout.split()[-1]", "= stdout.split()[-1] logger.info(\" => JID: %s\", jid) jids[step] = jid", "JID: %s\", jid) jids[step] = jid return None def setup_argparse(parser:", "parser.add_argument( \"path\", nargs=\"?\", help=\"Path into SNAPPY directory (below a directory", "stdout) jid = stdout.split()[-1] logger.info(\" => JID: %s\", jid) jids[step]", "(assuming standard naming)...\") logger.debug(\"Looking in %s\", path) step_set = {name", "argparse.ArgumentParser ) -> typing.Optional[int]: logger.info(\"Try to find SNAPPY pipeline directory...\")", "for names in toposort({k: set(v) for k, v in common.DEPENDENCIES.items()}):", "%s\", jid) jids[step] = jid return None def setup_argparse(parser: argparse.ArgumentParser)", "import toposort from . import common from cubi_tk.exceptions import ParseOutputException", "in common.DEPENDENCIES if (path / name).exists()} steps: typing.List[str] = []", "help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\", \"-n\", default=False, action=\"store_true\", help=\"Perform dry-run, do not", "in steps: dep_jids = [jids[dep] for dep in common.DEPENDENCIES[step] if", "/ step), timeout=args.timeout) stdout = stdout_raw.decode(\"utf-8\") if not stdout.startswith(\"Submitted batch", "-> None: \"\"\"Setup argument parser for ``cubi-tk snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\",", ". import common from cubi_tk.exceptions import ParseOutputException def run( args,", "% stdout) jid = stdout.split()[-1] logger.info(\" => JID: %s\", jid)", "setup_argparse(parser: argparse.ArgumentParser) -> None: \"\"\"Setup argument parser for ``cubi-tk snappy", "for ``cubi-tk snappy pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\",", "jid = \"<%s>\" % step else: stdout_raw = subprocess.check_output(cmd, cwd=str(path", "for step in steps: dep_jids = [jids[dep] for dep in", "v in common.DEPENDENCIES.items()}): steps += [name for name in names", "= [] for names in toposort({k: set(v) for k, v", "logger.debug(\"Looking in %s\", path) step_set = {name for name in", "stdout_raw = subprocess.check_output(cmd, cwd=str(path / step), timeout=args.timeout) stdout = stdout_raw.decode(\"utf-8\")", "output: %s\" % stdout) jid = stdout.split()[-1] logger.info(\" => JID:", "import argparse import os import subprocess import typing from logzero", "step), timeout=args.timeout) stdout = stdout_raw.decode(\"utf-8\") if not stdout.startswith(\"Submitted batch job", "type=int, help=\"Number of seconds to wait for commands.\" ) parser.add_argument(", "nargs=\"?\", help=\"Path into SNAPPY directory (below a directory containing .snappy_pipeline).\",", "sbatch...\") jids: typing.Dict[str, str] = {} for step in steps:", "common.CouldNotFindPipelineRoot: return 1 # TODO: this assumes standard naming which", "in step_set] logger.info(\"Will run the steps: %s\", \", \".join(steps)) logger.info(\"Submitting", "common.find_snappy_root_dir(args.path or os.getcwd(), common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot: return 1 # TODO:", "=> JID: %s\", jid) jids[step] = jid return None def", "in %s\", path) step_set = {name for name in common.DEPENDENCIES", "return None def setup_argparse(parser: argparse.ArgumentParser) -> None: \"\"\"Setup argument parser", "action=\"store_true\", help=\"Perform dry-run, do not do anything.\", ) parser.add_argument( \"--timeout\",", "= \"<%s>\" % step else: stdout_raw = subprocess.check_output(cmd, cwd=str(path /", "steps: typing.List[str] = [] for names in toposort({k: set(v) for", "+= [\"--dependency\", \"afterok:%s\" % \":\".join(map(str, dep_jids))] cmd += [\"pipeline_job.sh\"] logger.info(\"Submitting", "step_set = {name for name in common.DEPENDENCIES if (path /", "(path / name).exists()} steps: typing.List[str] = [] for names in", "run( args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser ) -> typing.Optional[int]: logger.info(\"Try", "\"--dry-run\", \"-n\", default=False, action=\"store_true\", help=\"Perform dry-run, do not do anything.\",", "from . import common from cubi_tk.exceptions import ParseOutputException def run(", "\"--timeout\", default=10, type=int, help=\"Number of seconds to wait for commands.\"", "step %s: %s\", step, \" \".join(cmd)) if args.dry_run: jid =", "names in toposort({k: set(v) for k, v in common.DEPENDENCIES.items()}): steps", "jids[step] = jid return None def setup_argparse(parser: argparse.ArgumentParser) -> None:", "step, \" \".join(cmd)) if args.dry_run: jid = \"<%s>\" % step", "<reponame>LaborBerlin/cubi-tk<filename>cubi_tk/snappy/kickoff.py \"\"\"``cubi-tk snappy kickoff``: kickoff SNAPPY pipeline.\"\"\" import argparse import", "\" \".join(cmd)) if args.dry_run: jid = \"<%s>\" % step else:", "pipeline directories (assuming standard naming)...\") logger.debug(\"Looking in %s\", path) step_set", "to find SNAPPY pipeline directory...\") try: path = common.find_snappy_root_dir(args.path or", "%s\", path) step_set = {name for name in common.DEPENDENCIES if", "if dep in jids] cmd = [\"sbatch\"] if dep_jids: cmd", "do not do anything.\", ) parser.add_argument( \"--timeout\", default=10, type=int, help=\"Number", "directories (assuming standard naming)...\") logger.debug(\"Looking in %s\", path) step_set =", "ParseOutputException(\"Did not understand sbatch output: %s\" % stdout) jid =", "= common.find_snappy_root_dir(args.path or os.getcwd(), common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot: return 1 #", "for pipeline directories (assuming standard naming)...\") logger.debug(\"Looking in %s\", path)", "argparse.ArgumentParser) -> None: \"\"\"Setup argument parser for ``cubi-tk snappy pull-sheet``.\"\"\"", "help=\"Number of seconds to wait for commands.\" ) parser.add_argument( \"path\",", "cubi_tk.exceptions import ParseOutputException def run( args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser", "for commands.\" ) parser.add_argument( \"path\", nargs=\"?\", help=\"Path into SNAPPY directory", "parser.add_argument( \"--dry-run\", \"-n\", default=False, action=\"store_true\", help=\"Perform dry-run, do not do", "path) step_set = {name for name in common.DEPENDENCIES if (path", "timeout=args.timeout) stdout = stdout_raw.decode(\"utf-8\") if not stdout.startswith(\"Submitted batch job \"):", "toposort({k: set(v) for k, v in common.DEPENDENCIES.items()}): steps += [name", "name).exists()} steps: typing.List[str] = [] for names in toposort({k: set(v)", "commands.\" ) parser.add_argument( \"path\", nargs=\"?\", help=\"Path into SNAPPY directory (below", "this assumes standard naming which is a limitation... logger.info(\"Looking for", "%s\" % stdout) jid = stdout.split()[-1] logger.info(\" => JID: %s\",", "typing.Dict[str, str] = {} for step in steps: dep_jids =", "cmd = [\"sbatch\"] if dep_jids: cmd += [\"--dependency\", \"afterok:%s\" %", "ParseOutputException def run( args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser ) ->", "except common.CouldNotFindPipelineRoot: return 1 # TODO: this assumes standard naming", "understand sbatch output: %s\" % stdout) jid = stdout.split()[-1] logger.info(\"", "def run( args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser ) -> typing.Optional[int]:", "import os import subprocess import typing from logzero import logger", "\".join(steps)) logger.info(\"Submitting with sbatch...\") jids: typing.Dict[str, str] = {} for", "if not stdout.startswith(\"Submitted batch job \"): raise ParseOutputException(\"Did not understand", "pull-sheet``.\"\"\" parser.add_argument(\"--hidden-cmd\", dest=\"snappy_cmd\", default=run, help=argparse.SUPPRESS) parser.add_argument( \"--dry-run\", \"-n\", default=False, action=\"store_true\",", "cmd += [\"--dependency\", \"afterok:%s\" % \":\".join(map(str, dep_jids))] cmd += [\"pipeline_job.sh\"]", "naming which is a limitation... logger.info(\"Looking for pipeline directories (assuming", "\"path\", nargs=\"?\", help=\"Path into SNAPPY directory (below a directory containing", "pipeline directory...\") try: path = common.find_snappy_root_dir(args.path or os.getcwd(), common.DEPENDENCIES.keys()) except", "names if name in step_set] logger.info(\"Will run the steps: %s\",", "try: path = common.find_snappy_root_dir(args.path or os.getcwd(), common.DEPENDENCIES.keys()) except common.CouldNotFindPipelineRoot: return", "\":\".join(map(str, dep_jids))] cmd += [\"pipeline_job.sh\"] logger.info(\"Submitting step %s: %s\", step," ]
[ "in i] assert len(out) == 4 assert all('in 1 timesteps'", "dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, autotune=True) out = [i for", "True})) op(infield=infield, outfield=outfield, autotune=True) out = [i for i in", "i] assert len(out) == 4 assert all('in 1 timesteps' in", "a given block shape) takes ``autotuning.core.options['at_squeezer']`` timesteps, for an operator", "{'blockalways': True})) op(infield=infield, outfield=outfield, autotune=True) out = [i for i", "running when switched on, in both 2D and 3D operators.", "in buffer.getvalue().split('\\n') if 'took' in i] assert len(out) == 4", "= logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape = (30, 30, 30) grid =", "options['at_squeezer'] in i for i in out) buffer.truncate(0) logger.removeHandler(temporary_handler) temporary_handler.flush()", "the time order # shouldn't affect how many iterations the", "aggressive autotuning, which tries 9 more cases configuration['autotuning'] = 'aggressive'", "Function, TimeFunction, Eq, Operator, configuration, silencio from devito.logger import logger,", "op = Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, t=2, autotune=True)", "30), 21) ]) def test_at_is_actually_working(shape, expected): \"\"\" Check that autotuning", "StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape = (30, 30, 30)", "increasing the time order # shouldn't affect how many iterations", "time_order=to) infield.data[:] = np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape) outfield = TimeFunction(name='outfield', grid=grid,", "import reduce from operator import mul try: from StringIO import", "\"\"\" Check that autotuning is actually running when switched on,", "@skipif_yask @pytest.mark.parametrize(\"shape,expected\", [ ((30, 30), 17), ((30, 30, 30), 21)", "x, y, z = grid.dimensions t = grid.stepping_dim # Function", "autotune=True) out = [i for i in buffer.getvalue().split('\\n') if 'took'", "+ infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockinner': True, 'blockalways': True}))", "logger, logging @silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\", [ ((30, 30), 17), ((30,", "test_at_is_actually_working(shape, expected): \"\"\" Check that autotuning is actually running when", "from io import StringIO import pytest from conftest import skipif_yask", "Grid(shape=shape) buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield =", "expected configuration['autotuning'] = configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close() @silencio(log_level='DEBUG')", "'took' in i] assert len(out) == expected configuration['autotuning'] = configuration._defaults['autotuning']", "f(a[t, ...], ...)``. \"\"\" from devito.core.autotuning import options buffer =", "= [i for i in buffer.getvalue().split('\\n') if 'took' in i]", "buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape = (30,", "out) buffer.truncate(0) # TimeFunction with increasing time order; increasing the", "run for to in [1, 2, 4]: infield = TimeFunction(name='infield',", "21) ]) def test_at_is_actually_working(shape, expected): \"\"\" Check that autotuning is", "op(infield=infield, outfield=outfield, t=2, autotune=True) out = [i for i in", "logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield = Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul, shape),", "= Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, t=2, autotune=True) out", "len(out) == expected configuration['autotuning'] = configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush()", "buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield = Function(name='infield',", "from devito import Grid, Function, TimeFunction, Eq, Operator, configuration, silencio", "assert all('in 1 timesteps' in i for i in out)", "StringIO import StringIO except ImportError: # Python3 compatibility from io", "infield = Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape) outfield", "grid=grid) infield.data[:] = np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape) outfield = Function(name='outfield', grid=grid)", "import options buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape", "# TimeFunction with increasing time order; increasing the time order", "infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, autotune=True)", "how many iterations the autotuner is gonna run for to", "import numpy as np from devito import Grid, Function, TimeFunction,", "= StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape = (30, 30,", "temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close() @silencio(log_level='DEBUG') @skipif_yask def test_timesteps_per_at_run(): \"\"\" Check", "silencio from devito.logger import logger, logging @silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\", [", "when switched on, in both 2D and 3D operators. \"\"\"", "for the given shape op(infield=infield, outfield=outfield, autotune=True) out = [i", "= Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways':", "for i in out) buffer.truncate(0) # TimeFunction with increasing time", "Eq(outfield.indexed[t + to, x, y, z], outfield.indexify() + infield.indexify()*3.0) op", "# Expected 3 AT attempts for the given shape op(infield=infield,", "numpy as np from devito import Grid, Function, TimeFunction, Eq,", "shape) takes ``autotuning.core.options['at_squeezer']`` timesteps, for an operator performing the increment", "Grid, Function, TimeFunction, Eq, Operator, configuration, silencio from devito.logger import", "logger.addHandler(temporary_handler) infield = Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape)", "conftest import skipif_yask import numpy as np from devito import", "stencil = Eq(outfield.indexed[t + to, x, y, z], outfield.indexify() +", "[1, 2, 4]: infield = TimeFunction(name='infield', grid=grid, time_order=to) infield.data[:] =", "buffer.getvalue().split('\\n') if 'took' in i] assert len(out) == 4 #", "import StringIO import pytest from conftest import skipif_yask import numpy", "compatibility from io import StringIO import pytest from conftest import", "tries 9 more cases configuration['autotuning'] = 'aggressive' op(infield=infield, outfield=outfield, autotune=True)", "# Now try the same with aggressive autotuning, which tries", "StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield = Function(name='infield', grid=grid) infield.data[:]", "logger.addHandler(temporary_handler) shape = (30, 30, 30) grid = Grid(shape=shape) x,", "shouldn't affect how many iterations the autotuner is gonna run", "assert len(out) == 4 assert all('in %d timesteps' % options['at_squeezer']", "TimeFunction, Eq, Operator, configuration, silencio from devito.logger import logger, logging", "skipif_yask import numpy as np from devito import Grid, Function,", "= configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close() @silencio(log_level='DEBUG') @skipif_yask def", "on, in both 2D and 3D operators. \"\"\" grid =", "= Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockinner':", "Operator(stencil, dle=('blocking', {'blockinner': True, 'blockalways': True})) # Expected 3 AT", "in i] assert len(out) == expected configuration['autotuning'] = configuration._defaults['autotuning'] logger.removeHandler(temporary_handler)", "= grid.dimensions t = grid.stepping_dim # Function infield = Function(name='infield',", "reduce from operator import mul try: from StringIO import StringIO", "which tries 9 more cases configuration['autotuning'] = 'aggressive' op(infield=infield, outfield=outfield,", "# Function infield = Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul, shape),", "]) def test_at_is_actually_working(shape, expected): \"\"\" Check that autotuning is actually", "with a given block shape) takes ``autotuning.core.options['at_squeezer']`` timesteps, for an", "in i for i in out) buffer.truncate(0) # TimeFunction with", "= Function(name='outfield', grid=grid) stencil = Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op", "i for i in out) buffer.truncate(0) logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush()", "operator import mul try: from StringIO import StringIO except ImportError:", "in out) buffer.truncate(0) # TimeFunction with increasing time order; increasing", "from devito.logger import logger, logging @silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\", [ ((30,", "= StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield = Function(name='infield', grid=grid)", "op(infield=infield, outfield=outfield, autotune=True) out = [i for i in buffer.getvalue().split('\\n')", "2D and 3D operators. \"\"\" grid = Grid(shape=shape) buffer =", "import skipif_yask import numpy as np from devito import Grid,", "in both 2D and 3D operators. \"\"\" grid = Grid(shape=shape)", "from StringIO import StringIO except ImportError: # Python3 compatibility from", "configuration['autotuning'] = configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close() @silencio(log_level='DEBUG') @skipif_yask", "options buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape =", "from operator import mul try: from StringIO import StringIO except", "in [1, 2, 4]: infield = TimeFunction(name='infield', grid=grid, time_order=to) infield.data[:]", "z = grid.dimensions t = grid.stepping_dim # Function infield =", "4 assert all('in %d timesteps' % options['at_squeezer'] in i for", "TimeFunction(name='infield', grid=grid, time_order=to) infield.data[:] = np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape) outfield =", "try the same with aggressive autotuning, which tries 9 more", "<filename>tests/test_autotuner.py from __future__ import absolute_import from functools import reduce from", "# Python3 compatibility from io import StringIO import pytest from", "= np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape) outfield = TimeFunction(name='outfield', grid=grid, time_order=to) stencil", "= grid.stepping_dim # Function infield = Function(name='infield', grid=grid) infield.data[:] =", "grid = Grid(shape=shape) buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler)", "and 3D operators. \"\"\" grid = Grid(shape=shape) buffer = StringIO()", "30, 30) grid = Grid(shape=shape) x, y, z = grid.dimensions", "dtype=np.int32).reshape(infield.shape) outfield = TimeFunction(name='outfield', grid=grid, time_order=to) stencil = Eq(outfield.indexed[t +", "i in out) buffer.truncate(0) # TimeFunction with increasing time order;", "def test_at_is_actually_working(shape, expected): \"\"\" Check that autotuning is actually running", "Check that each autotuning run (ie with a given block", "9 more cases configuration['autotuning'] = 'aggressive' op(infield=infield, outfield=outfield, autotune=True) out", "operators. \"\"\" grid = Grid(shape=shape) buffer = StringIO() temporary_handler =", "temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield = Function(name='infield', grid=grid) infield.data[:] =", "__future__ import absolute_import from functools import reduce from operator import", "i] assert len(out) == 4 # Now try the same", "except ImportError: # Python3 compatibility from io import StringIO import", "def test_timesteps_per_at_run(): \"\"\" Check that each autotuning run (ie with", "grid = Grid(shape=shape) x, y, z = grid.dimensions t =", "functools import reduce from operator import mul try: from StringIO", "shape = (30, 30, 30) grid = Grid(shape=shape) x, y,", "devito.core.autotuning import options buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler)", "== 4 assert all('in 1 timesteps' in i for i", "logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape = (30, 30, 30) grid = Grid(shape=shape)", "if 'took' in i] assert len(out) == expected configuration['autotuning'] =", "increment ``a[t + timeorder, ...] = f(a[t, ...], ...)``. \"\"\"", "4 assert all('in 1 timesteps' in i for i in", "len(out) == 4 assert all('in %d timesteps' % options['at_squeezer'] in", "assert len(out) == expected configuration['autotuning'] = configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close()", "%d timesteps' % options['at_squeezer'] in i for i in out)", "autotuning run (ie with a given block shape) takes ``autotuning.core.options['at_squeezer']``", "import logger, logging @silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\", [ ((30, 30), 17),", "devito.logger import logger, logging @silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\", [ ((30, 30),", "outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockinner': True, 'blockalways':", "io import StringIO import pytest from conftest import skipif_yask import", "outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield,", "is actually running when switched on, in both 2D and", "in i] assert len(out) == 4 # Now try the", "StringIO except ImportError: # Python3 compatibility from io import StringIO", "infield = TimeFunction(name='infield', grid=grid, time_order=to) infield.data[:] = np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape)", "with increasing time order; increasing the time order # shouldn't", "= Eq(outfield.indexed[t + to, x, y, z], outfield.indexify() + infield.indexify()*3.0)", "op = Operator(stencil, dle=('blocking', {'blockinner': True, 'blockalways': True})) # Expected", "buffer.close() @silencio(log_level='DEBUG') @skipif_yask def test_timesteps_per_at_run(): \"\"\" Check that each autotuning", "actually running when switched on, in both 2D and 3D", "in buffer.getvalue().split('\\n') if 'took' in i] assert len(out) == expected", "an operator performing the increment ``a[t + timeorder, ...] =", "outfield = TimeFunction(name='outfield', grid=grid, time_order=to) stencil = Eq(outfield.indexed[t + to,", "for an operator performing the increment ``a[t + timeorder, ...]", "from devito.core.autotuning import options buffer = StringIO() temporary_handler = logging.StreamHandler(buffer)", "order # shouldn't affect how many iterations the autotuner is", "assert len(out) == 4 # Now try the same with", "4]: infield = TimeFunction(name='infield', grid=grid, time_order=to) infield.data[:] = np.arange(reduce(mul, infield.shape),", "'took' in i] assert len(out) == 4 assert all('in 1", "assert len(out) == 4 assert all('in 1 timesteps' in i", "block shape) takes ``autotuning.core.options['at_squeezer']`` timesteps, for an operator performing the", "timesteps' in i for i in out) buffer.truncate(0) # TimeFunction", "True})) # Expected 3 AT attempts for the given shape", "30, 30), 21) ]) def test_at_is_actually_working(shape, expected): \"\"\" Check that", "for to in [1, 2, 4]: infield = TimeFunction(name='infield', grid=grid,", "operator performing the increment ``a[t + timeorder, ...] = f(a[t,", "StringIO import pytest from conftest import skipif_yask import numpy as", "import Grid, Function, TimeFunction, Eq, Operator, configuration, silencio from devito.logger", "dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, t=2, autotune=True) out = [i", "the given shape op(infield=infield, outfield=outfield, autotune=True) out = [i for", "((30, 30), 17), ((30, 30, 30), 21) ]) def test_at_is_actually_working(shape,", "to, x, y, z], outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil,", "Operator, configuration, silencio from devito.logger import logger, logging @silencio(log_level='DEBUG') @skipif_yask", "logging @silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\", [ ((30, 30), 17), ((30, 30,", "TimeFunction(name='outfield', grid=grid, time_order=to) stencil = Eq(outfield.indexed[t + to, x, y,", "Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape) outfield = Function(name='outfield',", "+ timeorder, ...] = f(a[t, ...], ...)``. \"\"\" from devito.core.autotuning", "'took' in i] assert len(out) == 4 # Now try", "infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockinner': True, 'blockalways': True})) #", "Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways': True}))", "to in [1, 2, 4]: infield = TimeFunction(name='infield', grid=grid, time_order=to)", "= TimeFunction(name='outfield', grid=grid, time_order=to) stencil = Eq(outfield.indexed[t + to, x,", "Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockinner': True,", "timesteps, for an operator performing the increment ``a[t + timeorder,", "@skipif_yask def test_timesteps_per_at_run(): \"\"\" Check that each autotuning run (ie", "4 # Now try the same with aggressive autotuning, which", "if 'took' in i] assert len(out) == 4 assert all('in", "== 4 assert all('in %d timesteps' % options['at_squeezer'] in i", "(30, 30, 30) grid = Grid(shape=shape) x, y, z =", "more cases configuration['autotuning'] = 'aggressive' op(infield=infield, outfield=outfield, autotune=True) out =", "= TimeFunction(name='infield', grid=grid, time_order=to) infield.data[:] = np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape) outfield", "@silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\", [ ((30, 30), 17), ((30, 30, 30),", "i in buffer.getvalue().split('\\n') if 'took' in i] assert len(out) ==", "Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, t=2, autotune=True) out =", "{'blockalways': True})) op(infield=infield, outfield=outfield, t=2, autotune=True) out = [i for", "+ to, x, y, z], outfield.indexify() + infield.indexify()*3.0) op =", "in i] assert len(out) == 4 assert all('in %d timesteps'", "= Grid(shape=shape) x, y, z = grid.dimensions t = grid.stepping_dim", "{'blockinner': True, 'blockalways': True})) # Expected 3 AT attempts for", "y, z], outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways':", "buffer.getvalue().split('\\n') if 'took' in i] assert len(out) == 4 assert", "time order; increasing the time order # shouldn't affect how", "order; increasing the time order # shouldn't affect how many", "Grid(shape=shape) x, y, z = grid.dimensions t = grid.stepping_dim #", "i for i in out) buffer.truncate(0) # TimeFunction with increasing", "shape), dtype=np.int32).reshape(shape) outfield = Function(name='outfield', grid=grid) stencil = Eq(outfield.indexify(), outfield.indexify()", "[ ((30, 30), 17), ((30, 30, 30), 21) ]) def", "takes ``autotuning.core.options['at_squeezer']`` timesteps, for an operator performing the increment ``a[t", "...)``. \"\"\" from devito.core.autotuning import options buffer = StringIO() temporary_handler", "each autotuning run (ie with a given block shape) takes", "i] assert len(out) == 4 assert all('in %d timesteps' %", "Check that autotuning is actually running when switched on, in", "infield.data[:] = np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape) outfield = Function(name='outfield', grid=grid) stencil", "((30, 30, 30), 21) ]) def test_at_is_actually_working(shape, expected): \"\"\" Check", "Now try the same with aggressive autotuning, which tries 9", "import StringIO except ImportError: # Python3 compatibility from io import", "AT attempts for the given shape op(infield=infield, outfield=outfield, autotune=True) out", "cases configuration['autotuning'] = 'aggressive' op(infield=infield, outfield=outfield, autotune=True) out = [i", "dtype=np.int32).reshape(shape) outfield = Function(name='outfield', grid=grid) stencil = Eq(outfield.indexify(), outfield.indexify() +", "i] assert len(out) == expected configuration['autotuning'] = configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush()", "configuration, silencio from devito.logger import logger, logging @silencio(log_level='DEBUG') @skipif_yask @pytest.mark.parametrize(\"shape,expected\",", "the autotuner is gonna run for to in [1, 2,", "the increment ``a[t + timeorder, ...] = f(a[t, ...], ...)``.", "stencil = Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking',", "for i in out) buffer.truncate(0) logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close()", "= f(a[t, ...], ...)``. \"\"\" from devito.core.autotuning import options buffer", "if 'took' in i] assert len(out) == 4 # Now", "mul try: from StringIO import StringIO except ImportError: # Python3", "the same with aggressive autotuning, which tries 9 more cases", "as np from devito import Grid, Function, TimeFunction, Eq, Operator,", "time order # shouldn't affect how many iterations the autotuner", "% options['at_squeezer'] in i for i in out) buffer.truncate(0) logger.removeHandler(temporary_handler)", "assert all('in %d timesteps' % options['at_squeezer'] in i for i", "both 2D and 3D operators. \"\"\" grid = Grid(shape=shape) buffer", "@silencio(log_level='DEBUG') @skipif_yask def test_timesteps_per_at_run(): \"\"\" Check that each autotuning run", "# shouldn't affect how many iterations the autotuner is gonna", "many iterations the autotuner is gonna run for to in", "outfield=outfield, t=2, autotune=True) out = [i for i in buffer.getvalue().split('\\n')", "logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close() @silencio(log_level='DEBUG') @skipif_yask def test_timesteps_per_at_run(): \"\"\"", "...], ...)``. \"\"\" from devito.core.autotuning import options buffer = StringIO()", "\"\"\" grid = Grid(shape=shape) buffer = StringIO() temporary_handler = logging.StreamHandler(buffer)", "grid=grid) stencil = Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil,", "Python3 compatibility from io import StringIO import pytest from conftest", "attempts for the given shape op(infield=infield, outfield=outfield, autotune=True) out =", "t=2, autotune=True) out = [i for i in buffer.getvalue().split('\\n') if", "= Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape) outfield =", "autotuning, which tries 9 more cases configuration['autotuning'] = 'aggressive' op(infield=infield,", "@pytest.mark.parametrize(\"shape,expected\", [ ((30, 30), 17), ((30, 30, 30), 21) ])", "op = Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, autotune=True) out", "buffer.getvalue().split('\\n') if 'took' in i] assert len(out) == expected configuration['autotuning']", "30), 17), ((30, 30, 30), 21) ]) def test_at_is_actually_working(shape, expected):", "\"\"\" Check that each autotuning run (ie with a given", "autotuner is gonna run for to in [1, 2, 4]:", "infield.data[:] = np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape) outfield = TimeFunction(name='outfield', grid=grid, time_order=to)", "in i for i in out) buffer.truncate(0) logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close()", "17), ((30, 30, 30), 21) ]) def test_at_is_actually_working(shape, expected): \"\"\"", "Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, autotune=True) out = [i", "= logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield = Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul,", "time_order=to) stencil = Eq(outfield.indexed[t + to, x, y, z], outfield.indexify()", "x, y, z], outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking',", "is gonna run for to in [1, 2, 4]: infield", "(ie with a given block shape) takes ``autotuning.core.options['at_squeezer']`` timesteps, for", "timesteps' % options['at_squeezer'] in i for i in out) buffer.truncate(0)", "from __future__ import absolute_import from functools import reduce from operator", "that autotuning is actually running when switched on, in both", "expected): \"\"\" Check that autotuning is actually running when switched", "TimeFunction with increasing time order; increasing the time order #", "ImportError: # Python3 compatibility from io import StringIO import pytest", "infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, t=2,", "3 AT attempts for the given shape op(infield=infield, outfield=outfield, autotune=True)", "len(out) == 4 # Now try the same with aggressive", "for i in buffer.getvalue().split('\\n') if 'took' in i] assert len(out)", "1 timesteps' in i for i in out) buffer.truncate(0) #", "performing the increment ``a[t + timeorder, ...] = f(a[t, ...],", "configuration['autotuning'] = 'aggressive' op(infield=infield, outfield=outfield, autotune=True) out = [i for", "Function(name='outfield', grid=grid) stencil = Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0) op =", "np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape) outfield = TimeFunction(name='outfield', grid=grid, time_order=to) stencil =", "given shape op(infield=infield, outfield=outfield, autotune=True) out = [i for i", "autotuning is actually running when switched on, in both 2D", "np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape) outfield = Function(name='outfield', grid=grid) stencil = Eq(outfield.indexify(),", "grid.stepping_dim # Function infield = Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul,", "Expected 3 AT attempts for the given shape op(infield=infield, outfield=outfield,", "devito import Grid, Function, TimeFunction, Eq, Operator, configuration, silencio from", "Eq, Operator, configuration, silencio from devito.logger import logger, logging @silencio(log_level='DEBUG')", "= Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield, autotune=True) out =", "[i for i in buffer.getvalue().split('\\n') if 'took' in i] assert", "temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) shape = (30, 30, 30) grid", "grid=grid, time_order=to) infield.data[:] = np.arange(reduce(mul, infield.shape), dtype=np.int32).reshape(infield.shape) outfield = TimeFunction(name='outfield',", "True})) op(infield=infield, outfield=outfield, t=2, autotune=True) out = [i for i", "absolute_import from functools import reduce from operator import mul try:", "== 4 # Now try the same with aggressive autotuning,", "+ infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways': True})) op(infield=infield, outfield=outfield,", "timeorder, ...] = f(a[t, ...], ...)``. \"\"\" from devito.core.autotuning import", "buffer.flush() buffer.close() @silencio(log_level='DEBUG') @skipif_yask def test_timesteps_per_at_run(): \"\"\" Check that each", "outfield = Function(name='outfield', grid=grid) stencil = Eq(outfield.indexify(), outfield.indexify() + infield.indexify()*3.0)", "from functools import reduce from operator import mul try: from", "temporary_handler.close() buffer.flush() buffer.close() @silencio(log_level='DEBUG') @skipif_yask def test_timesteps_per_at_run(): \"\"\" Check that", "'took' in i] assert len(out) == 4 assert all('in %d", "import absolute_import from functools import reduce from operator import mul", "'aggressive' op(infield=infield, outfield=outfield, autotune=True) out = [i for i in", "z], outfield.indexify() + infield.indexify()*3.0) op = Operator(stencil, dle=('blocking', {'blockalways': True}))", "from conftest import skipif_yask import numpy as np from devito", "that each autotuning run (ie with a given block shape)", "grid=grid, time_order=to) stencil = Eq(outfield.indexed[t + to, x, y, z],", "dle=('blocking', {'blockinner': True, 'blockalways': True})) # Expected 3 AT attempts", "run (ie with a given block shape) takes ``autotuning.core.options['at_squeezer']`` timesteps,", "True, 'blockalways': True})) # Expected 3 AT attempts for the", "= np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape) outfield = Function(name='outfield', grid=grid) stencil =", "= Operator(stencil, dle=('blocking', {'blockinner': True, 'blockalways': True})) # Expected 3", "Function infield = Function(name='infield', grid=grid) infield.data[:] = np.arange(reduce(mul, shape), dtype=np.int32).reshape(shape)", "30) grid = Grid(shape=shape) x, y, z = grid.dimensions t", "infield.shape), dtype=np.int32).reshape(infield.shape) outfield = TimeFunction(name='outfield', grid=grid, time_order=to) stencil = Eq(outfield.indexed[t", "gonna run for to in [1, 2, 4]: infield =", "configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close() @silencio(log_level='DEBUG') @skipif_yask def test_timesteps_per_at_run():", "import mul try: from StringIO import StringIO except ImportError: #", "import pytest from conftest import skipif_yask import numpy as np", "t = grid.stepping_dim # Function infield = Function(name='infield', grid=grid) infield.data[:]", "``a[t + timeorder, ...] = f(a[t, ...], ...)``. \"\"\" from", "3D operators. \"\"\" grid = Grid(shape=shape) buffer = StringIO() temporary_handler", "2, 4]: infield = TimeFunction(name='infield', grid=grid, time_order=to) infield.data[:] = np.arange(reduce(mul,", "np from devito import Grid, Function, TimeFunction, Eq, Operator, configuration,", "``autotuning.core.options['at_squeezer']`` timesteps, for an operator performing the increment ``a[t +", "pytest from conftest import skipif_yask import numpy as np from", "affect how many iterations the autotuner is gonna run for", "y, z = grid.dimensions t = grid.stepping_dim # Function infield", "with aggressive autotuning, which tries 9 more cases configuration['autotuning'] =", "= (30, 30, 30) grid = Grid(shape=shape) x, y, z", "test_timesteps_per_at_run(): \"\"\" Check that each autotuning run (ie with a", "'blockalways': True})) # Expected 3 AT attempts for the given", "given block shape) takes ``autotuning.core.options['at_squeezer']`` timesteps, for an operator performing", "outfield=outfield, autotune=True) out = [i for i in buffer.getvalue().split('\\n') if", "switched on, in both 2D and 3D operators. \"\"\" grid", "grid.dimensions t = grid.stepping_dim # Function infield = Function(name='infield', grid=grid)", "= Grid(shape=shape) buffer = StringIO() temporary_handler = logging.StreamHandler(buffer) logger.addHandler(temporary_handler) infield", "== expected configuration['autotuning'] = configuration._defaults['autotuning'] logger.removeHandler(temporary_handler) temporary_handler.flush() temporary_handler.close() buffer.flush() buffer.close()", "all('in %d timesteps' % options['at_squeezer'] in i for i in", "increasing time order; increasing the time order # shouldn't affect", "= 'aggressive' op(infield=infield, outfield=outfield, autotune=True) out = [i for i", "\"\"\" from devito.core.autotuning import options buffer = StringIO() temporary_handler =", "...] = f(a[t, ...], ...)``. \"\"\" from devito.core.autotuning import options", "shape op(infield=infield, outfield=outfield, autotune=True) out = [i for i in", "iterations the autotuner is gonna run for to in [1,", "out = [i for i in buffer.getvalue().split('\\n') if 'took' in", "same with aggressive autotuning, which tries 9 more cases configuration['autotuning']", "buffer.truncate(0) # TimeFunction with increasing time order; increasing the time", "try: from StringIO import StringIO except ImportError: # Python3 compatibility", "len(out) == 4 assert all('in 1 timesteps' in i for", "all('in 1 timesteps' in i for i in out) buffer.truncate(0)" ]
[ "as f: json.dump(coco_json, f) if __name__ == '__main__': parser =", "key }) with open(id_list) as fp: ids = fp.readlines() for", "as fp: ids = fp.readlines() for idx, file_id in enumerate(ids):", "f) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--img_dir', type=str)", "gt = BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')), str(image_dir / file_id))[ 0] for", "as np def convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir, out_name): coco_json =", "'height': height, 'width': width }) try: gt = BizcardDataParser.parse_data(str((json_dir /", "width }) try: gt = BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')), str(image_dir /", "file_id)).shape[:2] images.append({ 'file_name': str(file_id), 'id': idx, 'height': height, 'width': width", "with open(Path(out_dir, out_name), 'w') as f: json.dump(coco_json, f) if __name__", "argparse from pathlib import Path import os import json import", "if not Path(args.out_dir).exists(): Path(args.out_dir).mkdir() convert_bizcard_to_coco_format( Path(args.img_dir), Path(args.gt_dir), args.data_list, args.out_dir, args.out_name)", "= file_id.with_suffix('.jpeg') else: file_id = file_id.with_suffix('.jpg') height, width = cv2.imread(str(image_dir", "'w') as f: json.dump(coco_json, f) if __name__ == '__main__': parser", "import os import json import cv2 import numpy as np", "= [] categories = [] for _, key in enumerate(BIZCARD_LABEL_MAP.keys()):", "categories = [] for _, key in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id':", "np def convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir, out_name): coco_json = {}", "BIZCARD_LABEL_MAP, BizcardDataParser import argparse from pathlib import Path import os", "try: gt = BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')), str(image_dir / file_id))[ 0]", "f: json.dump(coco_json, f) if __name__ == '__main__': parser = argparse.ArgumentParser()", "/ file_id)) coco_json['images'] = images coco_json['annotations'] = annotations coco_json['categories'] =", "(image_dir / file_id).with_suffix('.jpg').exists(): file_id = file_id.with_suffix('.jpeg') else: file_id = file_id.with_suffix('.jpg')", "}) try: gt = BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')), str(image_dir / file_id))[", "if not (image_dir / file_id).with_suffix('.jpg').exists(): file_id = file_id.with_suffix('.jpeg') else: file_id", "'name': key }) with open(id_list) as fp: ids = fp.readlines()", "file_id).with_suffix('.json')), str(image_dir / file_id))[ 0] for word in gt.words: anno", "type=str) parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name', type=str) args", "file_id.with_suffix('.jpg') height, width = cv2.imread(str(image_dir / file_id)).shape[:2] images.append({ 'file_name': str(file_id),", "for idx, file_id in enumerate(ids): file_id = Path(file_id.strip()) print(idx, file_id)", "cv2 import numpy as np def convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir,", "'id': idx, 'height': height, 'width': width }) try: gt =", "word.bbox.min_y, (word.bbox.max_x - word.bbox.min_x), (word.bbox.max_y - word.bbox.min_y)], 'segmentation': [word.bbox.val], 'category_id':", "len(annotations), 'image_id': idx, 'bbox': [word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x - word.bbox.min_x), (word.bbox.max_y", "except Exception as e: print(e) print(str(image_dir / file_id)) coco_json['images'] =", "categories with open(Path(out_dir, out_name), 'w') as f: json.dump(coco_json, f) if", "open(Path(out_dir, out_name), 'w') as f: json.dump(coco_json, f) if __name__ ==", "file_id in enumerate(ids): file_id = Path(file_id.strip()) print(idx, file_id) if not", "not (image_dir / file_id).with_suffix('.jpg').exists(): file_id = file_id.with_suffix('.jpeg') else: file_id =", "e: print(e) print(str(image_dir / file_id)) coco_json['images'] = images coco_json['annotations'] =", "in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id': BIZCARD_LABEL_MAP[key], 'name': key }) with open(id_list)", "print(idx, file_id) if not (image_dir / file_id).with_suffix('.jpg').exists(): file_id = file_id.with_suffix('.jpeg')", "= Path(file_id.strip()) print(idx, file_id) if not (image_dir / file_id).with_suffix('.jpg').exists(): file_id", "= cv2.imread(str(image_dir / file_id)).shape[:2] images.append({ 'file_name': str(file_id), 'id': idx, 'height':", "json import cv2 import numpy as np def convert_bizcard_to_coco_format(image_dir, json_dir,", "'id': len(annotations), 'image_id': idx, 'bbox': [word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x - word.bbox.min_x),", "import BIZCARD_LABEL_MAP, BizcardDataParser import argparse from pathlib import Path import", "BizcardDataParser import argparse from pathlib import Path import os import", "idx, 'bbox': [word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x - word.bbox.min_x), (word.bbox.max_y - word.bbox.min_y)],", "print(str(image_dir / file_id)) coco_json['images'] = images coco_json['annotations'] = annotations coco_json['categories']", "parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name', type=str) args = parser.parse_args() if", "= {} images = [] annotations = [] categories =", "} annotations.append(anno) except Exception as e: print(e) print(str(image_dir / file_id))", "from data.data_reader import BIZCARD_LABEL_MAP, BizcardDataParser import argparse from pathlib import", "BIZCARD_LABEL_MAP[key], 'name': key }) with open(id_list) as fp: ids =", "(word.bbox.max_x - word.bbox.min_x), (word.bbox.max_y - word.bbox.min_y)], 'segmentation': [word.bbox.val], 'category_id': word.label,", "as e: print(e) print(str(image_dir / file_id)) coco_json['images'] = images coco_json['annotations']", "import Path import os import json import cv2 import numpy", "if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir',", "type=str) parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name', type=str) args = parser.parse_args() if not", "type=str) parser.add_argument('--out_name', type=str) args = parser.parse_args() if not Path(args.out_dir).exists(): Path(args.out_dir).mkdir()", "= file_id.with_suffix('.jpg') height, width = cv2.imread(str(image_dir / file_id)).shape[:2] images.append({ 'file_name':", "= parser.parse_args() if not Path(args.out_dir).exists(): Path(args.out_dir).mkdir() convert_bizcard_to_coco_format( Path(args.img_dir), Path(args.gt_dir), args.data_list,", "annotations.append(anno) except Exception as e: print(e) print(str(image_dir / file_id)) coco_json['images']", "args = parser.parse_args() if not Path(args.out_dir).exists(): Path(args.out_dir).mkdir() convert_bizcard_to_coco_format( Path(args.img_dir), Path(args.gt_dir),", "Path import os import json import cv2 import numpy as", "parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name', type=str)", "height, 'width': width }) try: gt = BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')),", "pathlib import Path import os import json import cv2 import", "_, key in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id': BIZCARD_LABEL_MAP[key], 'name': key })", "file_id))[ 0] for word in gt.words: anno = { 'id':", "'bbox': [word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x - word.bbox.min_x), (word.bbox.max_y - word.bbox.min_y)], 'segmentation':", "'area': cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32)) } annotations.append(anno) except Exception as e:", "== '__main__': parser = argparse.ArgumentParser() parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list',", "out_name): coco_json = {} images = [] annotations = []", "file_id.with_suffix('.jpeg') else: file_id = file_id.with_suffix('.jpg') height, width = cv2.imread(str(image_dir /", "- word.bbox.min_x), (word.bbox.max_y - word.bbox.min_y)], 'segmentation': [word.bbox.val], 'category_id': word.label, 'iscrowd':", "width = cv2.imread(str(image_dir / file_id)).shape[:2] images.append({ 'file_name': str(file_id), 'id': idx,", "import json import cv2 import numpy as np def convert_bizcard_to_coco_format(image_dir,", "parser.parse_args() if not Path(args.out_dir).exists(): Path(args.out_dir).mkdir() convert_bizcard_to_coco_format( Path(args.img_dir), Path(args.gt_dir), args.data_list, args.out_dir,", "cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32)) } annotations.append(anno) except Exception as e: print(e)", "in enumerate(ids): file_id = Path(file_id.strip()) print(idx, file_id) if not (image_dir", "str(image_dir / file_id))[ 0] for word in gt.words: anno =", "idx, 'height': height, 'width': width }) try: gt = BizcardDataParser.parse_data(str((json_dir", "'segmentation': [word.bbox.val], 'category_id': word.label, 'iscrowd': 0, 'area': cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32))", "= annotations coco_json['categories'] = categories with open(Path(out_dir, out_name), 'w') as", "argparse.ArgumentParser() parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name',", "parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name', type=str) args = parser.parse_args() if not Path(args.out_dir).exists():", "str(file_id), 'id': idx, 'height': height, 'width': width }) try: gt", "= fp.readlines() for idx, file_id in enumerate(ids): file_id = Path(file_id.strip())", "'file_name': str(file_id), 'id': idx, 'height': height, 'width': width }) try:", "file_id) if not (image_dir / file_id).with_suffix('.jpg').exists(): file_id = file_id.with_suffix('.jpeg') else:", "id_list, out_dir, out_name): coco_json = {} images = [] annotations", "/ file_id)).shape[:2] images.append({ 'file_name': str(file_id), 'id': idx, 'height': height, 'width':", "/ file_id))[ 0] for word in gt.words: anno = {", "[] annotations = [] categories = [] for _, key", "coco_json = {} images = [] annotations = [] categories", "}) with open(id_list) as fp: ids = fp.readlines() for idx,", "type=str) parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name', type=str) args = parser.parse_args()", "out_name), 'w') as f: json.dump(coco_json, f) if __name__ == '__main__':", "'width': width }) try: gt = BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')), str(image_dir", "file_id).with_suffix('.jpg').exists(): file_id = file_id.with_suffix('.jpeg') else: file_id = file_id.with_suffix('.jpg') height, width", "enumerate(ids): file_id = Path(file_id.strip()) print(idx, file_id) if not (image_dir /", "[word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x - word.bbox.min_x), (word.bbox.max_y - word.bbox.min_y)], 'segmentation': [word.bbox.val],", "height, width = cv2.imread(str(image_dir / file_id)).shape[:2] images.append({ 'file_name': str(file_id), 'id':", "import argparse from pathlib import Path import os import json", "key in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id': BIZCARD_LABEL_MAP[key], 'name': key }) with", "for _, key in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id': BIZCARD_LABEL_MAP[key], 'name': key", "word.label, 'iscrowd': 0, 'area': cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32)) } annotations.append(anno) except", "parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir', type=str) parser.add_argument('--out_name', type=str) args =", "fp.readlines() for idx, file_id in enumerate(ids): file_id = Path(file_id.strip()) print(idx,", "Path(file_id.strip()) print(idx, file_id) if not (image_dir / file_id).with_suffix('.jpg').exists(): file_id =", "'iscrowd': 0, 'area': cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32)) } annotations.append(anno) except Exception", "cv2.imread(str(image_dir / file_id)).shape[:2] images.append({ 'file_name': str(file_id), 'id': idx, 'height': height,", "idx, file_id in enumerate(ids): file_id = Path(file_id.strip()) print(idx, file_id) if", "[] categories = [] for _, key in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({", "'image_id': idx, 'bbox': [word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x - word.bbox.min_x), (word.bbox.max_y -", "= { 'id': len(annotations), 'image_id': idx, 'bbox': [word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x", "2]).astype(np.float32)) } annotations.append(anno) except Exception as e: print(e) print(str(image_dir /", "images coco_json['annotations'] = annotations coco_json['categories'] = categories with open(Path(out_dir, out_name),", "annotations = [] categories = [] for _, key in", "images = [] annotations = [] categories = [] for", "[word.bbox.val], 'category_id': word.label, 'iscrowd': 0, 'area': cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32)) }", "= [] annotations = [] categories = [] for _,", "images.append({ 'file_name': str(file_id), 'id': idx, 'height': height, 'width': width })", "parser = argparse.ArgumentParser() parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir',", "enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id': BIZCARD_LABEL_MAP[key], 'name': key }) with open(id_list) as", "else: file_id = file_id.with_suffix('.jpg') height, width = cv2.imread(str(image_dir / file_id)).shape[:2]", "json.dump(coco_json, f) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--img_dir',", "Exception as e: print(e) print(str(image_dir / file_id)) coco_json['images'] = images", "__name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir', type=str)", "= argparse.ArgumentParser() parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list', type=str) parser.add_argument('--out_dir', type=str)", "for word in gt.words: anno = { 'id': len(annotations), 'image_id':", "numpy as np def convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir, out_name): coco_json", "print(e) print(str(image_dir / file_id)) coco_json['images'] = images coco_json['annotations'] = annotations", "'category_id': word.label, 'iscrowd': 0, 'area': cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32)) } annotations.append(anno)", "(word.bbox.max_y - word.bbox.min_y)], 'segmentation': [word.bbox.val], 'category_id': word.label, 'iscrowd': 0, 'area':", "out_dir, out_name): coco_json = {} images = [] annotations =", "[] for _, key in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id': BIZCARD_LABEL_MAP[key], 'name':", "0] for word in gt.words: anno = { 'id': len(annotations),", "0, 'area': cv2.contourArea(np.reshape(word.bbox.val, [-1, 2]).astype(np.float32)) } annotations.append(anno) except Exception as", "= images coco_json['annotations'] = annotations coco_json['categories'] = categories with open(Path(out_dir,", "{} images = [] annotations = [] categories = []", "word.bbox.min_y)], 'segmentation': [word.bbox.val], 'category_id': word.label, 'iscrowd': 0, 'area': cv2.contourArea(np.reshape(word.bbox.val, [-1,", "gt.words: anno = { 'id': len(annotations), 'image_id': idx, 'bbox': [word.bbox.min_x,", "/ file_id).with_suffix('.jpg').exists(): file_id = file_id.with_suffix('.jpeg') else: file_id = file_id.with_suffix('.jpg') height,", "from pathlib import Path import os import json import cv2", "word in gt.words: anno = { 'id': len(annotations), 'image_id': idx,", "def convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir, out_name): coco_json = {} images", "/ file_id).with_suffix('.json')), str(image_dir / file_id))[ 0] for word in gt.words:", "parser.add_argument('--out_name', type=str) args = parser.parse_args() if not Path(args.out_dir).exists(): Path(args.out_dir).mkdir() convert_bizcard_to_coco_format(", "file_id = file_id.with_suffix('.jpg') height, width = cv2.imread(str(image_dir / file_id)).shape[:2] images.append({", "os import json import cv2 import numpy as np def", "fp: ids = fp.readlines() for idx, file_id in enumerate(ids): file_id", "word.bbox.min_x), (word.bbox.max_y - word.bbox.min_y)], 'segmentation': [word.bbox.val], 'category_id': word.label, 'iscrowd': 0,", "BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')), str(image_dir / file_id))[ 0] for word in", "coco_json['annotations'] = annotations coco_json['categories'] = categories with open(Path(out_dir, out_name), 'w')", "file_id = Path(file_id.strip()) print(idx, file_id) if not (image_dir / file_id).with_suffix('.jpg').exists():", "file_id)) coco_json['images'] = images coco_json['annotations'] = annotations coco_json['categories'] = categories", "with open(id_list) as fp: ids = fp.readlines() for idx, file_id", "categories.append({ 'id': BIZCARD_LABEL_MAP[key], 'name': key }) with open(id_list) as fp:", "- word.bbox.min_y)], 'segmentation': [word.bbox.val], 'category_id': word.label, 'iscrowd': 0, 'area': cv2.contourArea(np.reshape(word.bbox.val,", "'id': BIZCARD_LABEL_MAP[key], 'name': key }) with open(id_list) as fp: ids", "convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir, out_name): coco_json = {} images =", "import numpy as np def convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir, out_name):", "file_id = file_id.with_suffix('.jpeg') else: file_id = file_id.with_suffix('.jpg') height, width =", "in gt.words: anno = { 'id': len(annotations), 'image_id': idx, 'bbox':", "ids = fp.readlines() for idx, file_id in enumerate(ids): file_id =", "open(id_list) as fp: ids = fp.readlines() for idx, file_id in", "'__main__': parser = argparse.ArgumentParser() parser.add_argument('--img_dir', type=str) parser.add_argument('--gt_dir', type=str) parser.add_argument('--data_list', type=str)", "annotations coco_json['categories'] = categories with open(Path(out_dir, out_name), 'w') as f:", "data.data_reader import BIZCARD_LABEL_MAP, BizcardDataParser import argparse from pathlib import Path", "coco_json['images'] = images coco_json['annotations'] = annotations coco_json['categories'] = categories with", "coco_json['categories'] = categories with open(Path(out_dir, out_name), 'w') as f: json.dump(coco_json,", "= categories with open(Path(out_dir, out_name), 'w') as f: json.dump(coco_json, f)", "= BizcardDataParser.parse_data(str((json_dir / file_id).with_suffix('.json')), str(image_dir / file_id))[ 0] for word", "anno = { 'id': len(annotations), 'image_id': idx, 'bbox': [word.bbox.min_x, word.bbox.min_y,", "import cv2 import numpy as np def convert_bizcard_to_coco_format(image_dir, json_dir, id_list,", "[-1, 2]).astype(np.float32)) } annotations.append(anno) except Exception as e: print(e) print(str(image_dir", "json_dir, id_list, out_dir, out_name): coco_json = {} images = []", "= [] for _, key in enumerate(BIZCARD_LABEL_MAP.keys()): categories.append({ 'id': BIZCARD_LABEL_MAP[key],", "{ 'id': len(annotations), 'image_id': idx, 'bbox': [word.bbox.min_x, word.bbox.min_y, (word.bbox.max_x -", "type=str) args = parser.parse_args() if not Path(args.out_dir).exists(): Path(args.out_dir).mkdir() convert_bizcard_to_coco_format( Path(args.img_dir)," ]
[ "True, presentation: bool = True, print: bool = True, deck_path:", "True, print: bool = True, deck_path: Path = Path(\".\"), )", "targets.\"\"\" paths = Paths.from_defaults(deck_path) running_run( paths=paths, build_handout=handout, build_presentation=presentation, build_print=print, target_whitelist=targets,", "= True, presentation: bool = True, print: bool = True,", "None: \"\"\"Compile main targets.\"\"\" paths = Paths.from_defaults(deck_path) running_run( paths=paths, build_handout=handout,", "import run as running_run @app.command() def run( targets: Optional[List[str]] =", "run as running_run @app.command() def run( targets: Optional[List[str]] = Argument(None),", "pathlib import Path from typing import List, Optional from typer", "Path from typing import List, Optional from typer import Argument", "from deckz.paths import Paths from deckz.running import run as running_run", "from pathlib import Path from typing import List, Optional from", "def run( targets: Optional[List[str]] = Argument(None), handout: bool = True,", "typing import List, Optional from typer import Argument from deckz.cli", "from typer import Argument from deckz.cli import app from deckz.paths", "from typing import List, Optional from typer import Argument from", "List, Optional from typer import Argument from deckz.cli import app", "<reponame>m09/deckz from pathlib import Path from typing import List, Optional", "bool = True, deck_path: Path = Path(\".\"), ) -> None:", ") -> None: \"\"\"Compile main targets.\"\"\" paths = Paths.from_defaults(deck_path) running_run(", "handout: bool = True, presentation: bool = True, print: bool", "import Argument from deckz.cli import app from deckz.paths import Paths", "Argument from deckz.cli import app from deckz.paths import Paths from", "\"\"\"Compile main targets.\"\"\" paths = Paths.from_defaults(deck_path) running_run( paths=paths, build_handout=handout, build_presentation=presentation,", "deckz.paths import Paths from deckz.running import run as running_run @app.command()", "@app.command() def run( targets: Optional[List[str]] = Argument(None), handout: bool =", "= True, deck_path: Path = Path(\".\"), ) -> None: \"\"\"Compile", "deckz.cli import app from deckz.paths import Paths from deckz.running import", "True, deck_path: Path = Path(\".\"), ) -> None: \"\"\"Compile main", "Path = Path(\".\"), ) -> None: \"\"\"Compile main targets.\"\"\" paths", "paths = Paths.from_defaults(deck_path) running_run( paths=paths, build_handout=handout, build_presentation=presentation, build_print=print, target_whitelist=targets, )", "from deckz.running import run as running_run @app.command() def run( targets:", "Path(\".\"), ) -> None: \"\"\"Compile main targets.\"\"\" paths = Paths.from_defaults(deck_path)", "typer import Argument from deckz.cli import app from deckz.paths import", "-> None: \"\"\"Compile main targets.\"\"\" paths = Paths.from_defaults(deck_path) running_run( paths=paths,", "run( targets: Optional[List[str]] = Argument(None), handout: bool = True, presentation:", "import List, Optional from typer import Argument from deckz.cli import", "Optional from typer import Argument from deckz.cli import app from", "= Argument(None), handout: bool = True, presentation: bool = True,", "bool = True, presentation: bool = True, print: bool =", "bool = True, print: bool = True, deck_path: Path =", "import Paths from deckz.running import run as running_run @app.command() def", "= Path(\".\"), ) -> None: \"\"\"Compile main targets.\"\"\" paths =", "import app from deckz.paths import Paths from deckz.running import run", "as running_run @app.command() def run( targets: Optional[List[str]] = Argument(None), handout:", "targets: Optional[List[str]] = Argument(None), handout: bool = True, presentation: bool", "main targets.\"\"\" paths = Paths.from_defaults(deck_path) running_run( paths=paths, build_handout=handout, build_presentation=presentation, build_print=print,", "presentation: bool = True, print: bool = True, deck_path: Path", "app from deckz.paths import Paths from deckz.running import run as", "= True, print: bool = True, deck_path: Path = Path(\".\"),", "running_run @app.command() def run( targets: Optional[List[str]] = Argument(None), handout: bool", "Optional[List[str]] = Argument(None), handout: bool = True, presentation: bool =", "Paths from deckz.running import run as running_run @app.command() def run(", "Argument(None), handout: bool = True, presentation: bool = True, print:", "from deckz.cli import app from deckz.paths import Paths from deckz.running", "import Path from typing import List, Optional from typer import", "deckz.running import run as running_run @app.command() def run( targets: Optional[List[str]]", "deck_path: Path = Path(\".\"), ) -> None: \"\"\"Compile main targets.\"\"\"", "print: bool = True, deck_path: Path = Path(\".\"), ) ->" ]
[ "register = template.Library() @register.filter(name='isboolean') def isboolean(value): return isinstance(value, bool) @register.filter(name='vartypename')", "@register.filter(name='isboolean') def isboolean(value): return isinstance(value, bool) @register.filter(name='vartypename') def vartypename(value): return", "import template register = template.Library() @register.filter(name='isboolean') def isboolean(value): return isinstance(value,", "def isboolean(value): return isinstance(value, bool) @register.filter(name='vartypename') def vartypename(value): return type(value).__name__", "django import template register = template.Library() @register.filter(name='isboolean') def isboolean(value): return", "template register = template.Library() @register.filter(name='isboolean') def isboolean(value): return isinstance(value, bool)", "<gh_stars>0 from django import template register = template.Library() @register.filter(name='isboolean') def", "template.Library() @register.filter(name='isboolean') def isboolean(value): return isinstance(value, bool) @register.filter(name='vartypename') def vartypename(value):", "from django import template register = template.Library() @register.filter(name='isboolean') def isboolean(value):", "= template.Library() @register.filter(name='isboolean') def isboolean(value): return isinstance(value, bool) @register.filter(name='vartypename') def" ]
[ "import uvloop from aioredis import Redis from fastapi import FastAPI", "rprint(\"Starting app\") rprint(dir(app)) rprint(app.url_path_for('websocket_endpoint')) uvicorn.run('chat:app', host=HOST, port=PORT, log_level='info', reload=True)#, uds='uvicorn.sock')", "else: rprint(\"ERROR: cvar_redis.get() devuelve NONE\") if __name__ == \"__main__\": import", "cvar_redis.set(pool) rprint(\"Connected to Redis on \", REDIS_HOST, REDIS_PORT) except ConnectionRefusedError", "import BaseHTTPMiddleware from starlette.staticfiles import StaticFiles from RLog import rprint", "import Redis from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware", "import rprint from routers import apirest, websockets REDIS_HOST = 'redis'", "top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"),", "-> None: rprint(\"startup\") try: pool = await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8',", "is built on top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app =", "REDIS_HOST, REDIS_PORT) return @app.on_event(\"shutdown\") async def handle_shutdown() -> None: if", "dispatch(self, request, call_next): response = await call_next(request) response.headers['Custom'] = self.header_value", "== \"__main__\": import uvicorn rprint(\"Starting app\") rprint(dir(app)) rprint(app.url_path_for('websocket_endpoint')) uvicorn.run('chat:app', host=HOST,", "http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router)", "uvloop is written in Cython and is built on top", "RLog import rprint from routers import apirest, websockets REDIS_HOST =", "= FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\") async", "is not None: redis: Redis = cvar_redis.get() redis.close() await redis.wait_closed()", "NONE\") if __name__ == \"__main__\": import uvicorn rprint(\"Starting app\") rprint(dir(app))", "= contextvars.ContextVar('redis', default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self, app, header_value='Example'): rprint('__init__')", "StaticFiles from RLog import rprint from routers import apirest, websockets", "written in Cython and is built on top of libuv", "async def handle_shutdown() -> None: if cvar_redis.get() is not None:", "aioredis import Redis from fastapi import FastAPI from starlette.middleware.base import", "from starlette.staticfiles import StaticFiles from RLog import rprint from routers", "= \"0.0.0.0\" cvar_redis = contextvars.ContextVar('redis', default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self,", "Redis from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from", "starlette.staticfiles import StaticFiles from RLog import rprint from routers import", "= cvar_redis.get() redis.close() await redis.wait_closed() rprint(\"closed connection Redis on \",", "from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.staticfiles", "BaseHTTPMiddleware from starlette.staticfiles import StaticFiles from RLog import rprint from", "= await call_next(request) response.headers['Custom'] = self.header_value return response # uvloop", "REDIS_PORT) except ConnectionRefusedError as e: rprint('cannot connect to redis on:',", "def __init__(self, app, header_value='Example'): rprint('__init__') super().__init__(app) self.header_value = header_value async", "pool = await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8', maxsize=20) cvar_redis.set(pool) rprint(\"Connected to", "ConnectionRefusedError as e: rprint('cannot connect to redis on:', REDIS_HOST, REDIS_PORT)", "CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self, app, header_value='Example'): rprint('__init__') super().__init__(app) self.header_value = header_value", "to Redis on \", REDIS_HOST, REDIS_PORT) except ConnectionRefusedError as e:", "if __name__ == \"__main__\": import uvicorn rprint(\"Starting app\") rprint(dir(app)) rprint(app.url_path_for('websocket_endpoint'))", "rprint(\"startup\") try: pool = await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8', maxsize=20) cvar_redis.set(pool)", "redis: Redis = cvar_redis.get() redis.close() await redis.wait_closed() rprint(\"closed connection Redis", "@app.on_event(\"shutdown\") async def handle_shutdown() -> None: if cvar_redis.get() is not", "PORT = 9080 HOST = \"0.0.0.0\" cvar_redis = contextvars.ContextVar('redis', default=None)", "= self.header_value return response # uvloop is written in Cython", "encoding='utf-8', maxsize=20) cvar_redis.set(pool) rprint(\"Connected to Redis on \", REDIS_HOST, REDIS_PORT)", "uvicorn rprint(\"Starting app\") rprint(dir(app)) rprint(app.url_path_for('websocket_endpoint')) uvicorn.run('chat:app', host=HOST, port=PORT, log_level='info', reload=True)#,", "handle_shutdown() -> None: if cvar_redis.get() is not None: redis: Redis", "on \", REDIS_HOST, REDIS_PORT) else: rprint(\"ERROR: cvar_redis.get() devuelve NONE\") if", "header_value async def dispatch(self, request, call_next): response = await call_next(request)", "super().__init__(app) self.header_value = header_value async def dispatch(self, request, call_next): response", "response.headers['Custom'] = self.header_value return response # uvloop is written in", "async def dispatch(self, request, call_next): response = await call_next(request) response.headers['Custom']", "REDIS_PORT = 6379 PORT = 9080 HOST = \"0.0.0.0\" cvar_redis", "response # uvloop is written in Cython and is built", "to redis on:', REDIS_HOST, REDIS_PORT) return @app.on_event(\"shutdown\") async def handle_shutdown()", "REDIS_PORT) else: rprint(\"ERROR: cvar_redis.get() devuelve NONE\") if __name__ == \"__main__\":", "Redis = cvar_redis.get() redis.close() await redis.wait_closed() rprint(\"closed connection Redis on", "except ConnectionRefusedError as e: rprint('cannot connect to redis on:', REDIS_HOST,", "handle_startup() -> None: rprint(\"startup\") try: pool = await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT),", "app = FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\")", "import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.staticfiles import StaticFiles", "\", REDIS_HOST, REDIS_PORT) else: rprint(\"ERROR: cvar_redis.get() devuelve NONE\") if __name__", "from routers import apirest, websockets REDIS_HOST = 'redis' REDIS_PORT =", "rprint(\"closed connection Redis on \", REDIS_HOST, REDIS_PORT) else: rprint(\"ERROR: cvar_redis.get()", "header_value='Example'): rprint('__init__') super().__init__(app) self.header_value = header_value async def dispatch(self, request,", "response = await call_next(request) response.headers['Custom'] = self.header_value return response #", "contextvars import aioredis import uvloop from aioredis import Redis from", "asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router)", "rprint('__init__') super().__init__(app) self.header_value = header_value async def dispatch(self, request, call_next):", "routers import apirest, websockets REDIS_HOST = 'redis' REDIS_PORT = 6379", "cvar_redis.get() is not None: redis: Redis = cvar_redis.get() redis.close() await", "aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8', maxsize=20) cvar_redis.set(pool) rprint(\"Connected to Redis on \",", "= 'redis' REDIS_PORT = 6379 PORT = 9080 HOST =", "9080 HOST = \"0.0.0.0\" cvar_redis = contextvars.ContextVar('redis', default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware):", "import asyncio import contextvars import aioredis import uvloop from aioredis", "import apirest, websockets REDIS_HOST = 'redis' REDIS_PORT = 6379 PORT", "import uvicorn rprint(\"Starting app\") rprint(dir(app)) rprint(app.url_path_for('websocket_endpoint')) uvicorn.run('chat:app', host=HOST, port=PORT, log_level='info',", "rprint from routers import apirest, websockets REDIS_HOST = 'redis' REDIS_PORT", "app.include_router(websockets.router) @app.on_event(\"startup\") async def handle_startup() -> None: rprint(\"startup\") try: pool", "REDIS_HOST = 'redis' REDIS_PORT = 6379 PORT = 9080 HOST", "cvar_redis = contextvars.ContextVar('redis', default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self, app, header_value='Example'):", "of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")", "\", REDIS_HOST, REDIS_PORT) except ConnectionRefusedError as e: rprint('cannot connect to", "call_next(request) response.headers['Custom'] = self.header_value return response # uvloop is written", "asyncio import contextvars import aioredis import uvloop from aioredis import", "def dispatch(self, request, call_next): response = await call_next(request) response.headers['Custom'] =", "Redis on \", REDIS_HOST, REDIS_PORT) except ConnectionRefusedError as e: rprint('cannot", "async def handle_startup() -> None: rprint(\"startup\") try: pool = await", "connect to redis on:', REDIS_HOST, REDIS_PORT) return @app.on_event(\"shutdown\") async def", "REDIS_HOST, REDIS_PORT) else: rprint(\"ERROR: cvar_redis.get() devuelve NONE\") if __name__ ==", "is written in Cython and is built on top of", "StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\") async def handle_startup() ->", "Redis on \", REDIS_HOST, REDIS_PORT) else: rprint(\"ERROR: cvar_redis.get() devuelve NONE\")", "6379 PORT = 9080 HOST = \"0.0.0.0\" cvar_redis = contextvars.ContextVar('redis',", "@app.on_event(\"startup\") async def handle_startup() -> None: rprint(\"startup\") try: pool =", "and is built on top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app", "app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\") async def handle_startup() -> None: rprint(\"startup\")", "return response # uvloop is written in Cython and is", "HOST = \"0.0.0.0\" cvar_redis = contextvars.ContextVar('redis', default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware): def", "contextvars.ContextVar('redis', default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self, app, header_value='Example'): rprint('__init__') super().__init__(app)", "devuelve NONE\") if __name__ == \"__main__\": import uvicorn rprint(\"Starting app\")", "REDIS_PORT), encoding='utf-8', maxsize=20) cvar_redis.set(pool) rprint(\"Connected to Redis on \", REDIS_HOST,", "__name__ == \"__main__\": import uvicorn rprint(\"Starting app\") rprint(dir(app)) rprint(app.url_path_for('websocket_endpoint')) uvicorn.run('chat:app',", "from RLog import rprint from routers import apirest, websockets REDIS_HOST", "try: pool = await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8', maxsize=20) cvar_redis.set(pool) rprint(\"Connected", "not None: redis: Redis = cvar_redis.get() redis.close() await redis.wait_closed() rprint(\"closed", "websockets REDIS_HOST = 'redis' REDIS_PORT = 6379 PORT = 9080", "# uvloop is written in Cython and is built on", "apirest, websockets REDIS_HOST = 'redis' REDIS_PORT = 6379 PORT =", "on top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = FastAPI() app.mount(\"/static\",", "FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.staticfiles import StaticFiles from", "from starlette.middleware.base import BaseHTTPMiddleware from starlette.staticfiles import StaticFiles from RLog", "connection Redis on \", REDIS_HOST, REDIS_PORT) else: rprint(\"ERROR: cvar_redis.get() devuelve", "if cvar_redis.get() is not None: redis: Redis = cvar_redis.get() redis.close()", "fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.staticfiles import", "e: rprint('cannot connect to redis on:', REDIS_HOST, REDIS_PORT) return @app.on_event(\"shutdown\")", "uvloop from aioredis import Redis from fastapi import FastAPI from", "rprint(\"Connected to Redis on \", REDIS_HOST, REDIS_PORT) except ConnectionRefusedError as", "REDIS_HOST, REDIS_PORT) except ConnectionRefusedError as e: rprint('cannot connect to redis", "self.header_value return response # uvloop is written in Cython and", "rprint(\"ERROR: cvar_redis.get() devuelve NONE\") if __name__ == \"__main__\": import uvicorn", "libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware)", "as e: rprint('cannot connect to redis on:', REDIS_HOST, REDIS_PORT) return", "return @app.on_event(\"shutdown\") async def handle_shutdown() -> None: if cvar_redis.get() is", "await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8', maxsize=20) cvar_redis.set(pool) rprint(\"Connected to Redis on", "None: redis: Redis = cvar_redis.get() redis.close() await redis.wait_closed() rprint(\"closed connection", "default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self, app, header_value='Example'): rprint('__init__') super().__init__(app) self.header_value", "= await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8', maxsize=20) cvar_redis.set(pool) rprint(\"Connected to Redis", "\"__main__\": import uvicorn rprint(\"Starting app\") rprint(dir(app)) rprint(app.url_path_for('websocket_endpoint')) uvicorn.run('chat:app', host=HOST, port=PORT,", "class CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self, app, header_value='Example'): rprint('__init__') super().__init__(app) self.header_value =", "call_next): response = await call_next(request) response.headers['Custom'] = self.header_value return response", "app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\") async def handle_startup() -> None: rprint(\"startup\") try:", "__init__(self, app, header_value='Example'): rprint('__init__') super().__init__(app) self.header_value = header_value async def", "import contextvars import aioredis import uvloop from aioredis import Redis", "def handle_startup() -> None: rprint(\"startup\") try: pool = await aioredis.create_redis_pool((REDIS_HOST,", "self.header_value = header_value async def dispatch(self, request, call_next): response =", "aioredis import uvloop from aioredis import Redis from fastapi import", "redis on:', REDIS_HOST, REDIS_PORT) return @app.on_event(\"shutdown\") async def handle_shutdown() ->", "REDIS_PORT) return @app.on_event(\"shutdown\") async def handle_shutdown() -> None: if cvar_redis.get()", "rprint('cannot connect to redis on:', REDIS_HOST, REDIS_PORT) return @app.on_event(\"shutdown\") async", "from aioredis import Redis from fastapi import FastAPI from starlette.middleware.base", "None: if cvar_redis.get() is not None: redis: Redis = cvar_redis.get()", "app, header_value='Example'): rprint('__init__') super().__init__(app) self.header_value = header_value async def dispatch(self,", "= 9080 HOST = \"0.0.0.0\" cvar_redis = contextvars.ContextVar('redis', default=None) class", "import aioredis import uvloop from aioredis import Redis from fastapi", "FastAPI() app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\") async def", "request, call_next): response = await call_next(request) response.headers['Custom'] = self.header_value return", "import StaticFiles from RLog import rprint from routers import apirest,", "'redis' REDIS_PORT = 6379 PORT = 9080 HOST = \"0.0.0.0\"", "built on top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = FastAPI()", "-> None: if cvar_redis.get() is not None: redis: Redis =", "None: rprint(\"startup\") try: pool = await aioredis.create_redis_pool((REDIS_HOST, REDIS_PORT), encoding='utf-8', maxsize=20)", "cvar_redis.get() devuelve NONE\") if __name__ == \"__main__\": import uvicorn rprint(\"Starting", "\"0.0.0.0\" cvar_redis = contextvars.ContextVar('redis', default=None) class CustomHeaderMiddleware(BaseHTTPMiddleware): def __init__(self, app,", "maxsize=20) cvar_redis.set(pool) rprint(\"Connected to Redis on \", REDIS_HOST, REDIS_PORT) except", "on:', REDIS_HOST, REDIS_PORT) return @app.on_event(\"shutdown\") async def handle_shutdown() -> None:", "def handle_shutdown() -> None: if cvar_redis.get() is not None: redis:", "starlette.middleware.base import BaseHTTPMiddleware from starlette.staticfiles import StaticFiles from RLog import", "await redis.wait_closed() rprint(\"closed connection Redis on \", REDIS_HOST, REDIS_PORT) else:", "= 6379 PORT = 9080 HOST = \"0.0.0.0\" cvar_redis =", "on \", REDIS_HOST, REDIS_PORT) except ConnectionRefusedError as e: rprint('cannot connect", "cvar_redis.get() redis.close() await redis.wait_closed() rprint(\"closed connection Redis on \", REDIS_HOST,", "= header_value async def dispatch(self, request, call_next): response = await", "name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\") async def handle_startup() -> None:", "Cython and is built on top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())", "redis.wait_closed() rprint(\"closed connection Redis on \", REDIS_HOST, REDIS_PORT) else: rprint(\"ERROR:", "redis.close() await redis.wait_closed() rprint(\"closed connection Redis on \", REDIS_HOST, REDIS_PORT)", "app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\") app.add_middleware(CustomHeaderMiddleware) app.include_router(apirest.router) app.include_router(websockets.router) @app.on_event(\"startup\") async def handle_startup()", "await call_next(request) response.headers['Custom'] = self.header_value return response # uvloop is", "in Cython and is built on top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/" ]
[ "dest='output', help='Output image file name', required=True) opts = parser.parse_args() if", "image file name', required=True) opts = parser.parse_args() if opts.action ==", "help='File with exchanged data', required=True) parser = argparse.ArgumentParser() subparsers =", "autoencoder def addTrainablesArg(parser): parser.add_argument('--model', dest='model', help='Trained model', default='model.pt') def addExchangeArg(parser):", "exchanged data', required=True) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest=\"action\") encode_parser", "dest='model', help='Trained model', default='model.pt') def addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange', help='File with", "help='Output image file name', required=True) opts = parser.parse_args() if opts.action", "parser.parse_args() if opts.action == 'encode': autoencoder.encode(opts.model, opts.input, opts.exchange) elif opts.action", "addExchangeArg(encode_parser) decode_parser = subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output', help='Output image", "parser.add_argument('--exchange', dest='exchange', help='File with exchanged data', required=True) parser = argparse.ArgumentParser()", "encode_parser = subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input', help='Input image file name',", "parser.add_argument('--model', dest='model', help='Trained model', default='model.pt') def addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange', help='File", "subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input', help='Input image file name', required=True) addExchangeArg(encode_parser)", "with exchanged data', required=True) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest=\"action\")", "addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange', help='File with exchanged data', required=True) parser =", "subparsers = parser.add_subparsers(dest=\"action\") encode_parser = subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input', help='Input", "if opts.action == 'encode': autoencoder.encode(opts.model, opts.input, opts.exchange) elif opts.action ==", "parser.add_subparsers(dest=\"action\") encode_parser = subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input', help='Input image file", "image file name', required=True) addExchangeArg(encode_parser) decode_parser = subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser)", "autoencoder.encode(opts.model, opts.input, opts.exchange) elif opts.action == 'decode': autoencoder.decode(opts.model, opts.exchange, opts.output)", "addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input', help='Input image file name', required=True) addExchangeArg(encode_parser) decode_parser", "opts = parser.parse_args() if opts.action == 'encode': autoencoder.encode(opts.model, opts.input, opts.exchange)", "file name', required=True) addExchangeArg(encode_parser) decode_parser = subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output',", "= subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input', help='Input image file name', required=True)", "addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output', help='Output image file name', required=True) opts =", "file name', required=True) opts = parser.parse_args() if opts.action == 'encode':", "def addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange', help='File with exchanged data', required=True) parser", "dest='exchange', help='File with exchanged data', required=True) parser = argparse.ArgumentParser() subparsers", "def addTrainablesArg(parser): parser.add_argument('--model', dest='model', help='Trained model', default='model.pt') def addExchangeArg(parser): parser.add_argument('--exchange',", "'encode': autoencoder.encode(opts.model, opts.input, opts.exchange) elif opts.action == 'decode': autoencoder.decode(opts.model, opts.exchange,", "= argparse.ArgumentParser() subparsers = parser.add_subparsers(dest=\"action\") encode_parser = subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input',", "== 'encode': autoencoder.encode(opts.model, opts.input, opts.exchange) elif opts.action == 'decode': autoencoder.decode(opts.model,", "addTrainablesArg(parser): parser.add_argument('--model', dest='model', help='Trained model', default='model.pt') def addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange',", "= parser.add_subparsers(dest=\"action\") encode_parser = subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input', help='Input image", "= parser.parse_args() if opts.action == 'encode': autoencoder.encode(opts.model, opts.input, opts.exchange) elif", "help='Trained model', default='model.pt') def addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange', help='File with exchanged", "<reponame>abel-bernabeu/facecompressor<gh_stars>1-10 import argparse import autoencoder def addTrainablesArg(parser): parser.add_argument('--model', dest='model', help='Trained", "encode_parser.add_argument('--input', dest='input', help='Input image file name', required=True) addExchangeArg(encode_parser) decode_parser =", "= subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output', help='Output image file name',", "model', default='model.pt') def addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange', help='File with exchanged data',", "decode_parser = subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output', help='Output image file", "subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output', help='Output image file name', required=True)", "data', required=True) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest=\"action\") encode_parser =", "required=True) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest=\"action\") encode_parser = subparsers.add_parser('encode')", "name', required=True) opts = parser.parse_args() if opts.action == 'encode': autoencoder.encode(opts.model,", "parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest=\"action\") encode_parser = subparsers.add_parser('encode') addTrainablesArg(encode_parser)", "help='Input image file name', required=True) addExchangeArg(encode_parser) decode_parser = subparsers.add_parser('decode') addTrainablesArg(decode_parser)", "import argparse import autoencoder def addTrainablesArg(parser): parser.add_argument('--model', dest='model', help='Trained model',", "name', required=True) addExchangeArg(encode_parser) decode_parser = subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output',", "opts.action == 'encode': autoencoder.encode(opts.model, opts.input, opts.exchange) elif opts.action == 'decode':", "default='model.pt') def addExchangeArg(parser): parser.add_argument('--exchange', dest='exchange', help='File with exchanged data', required=True)", "required=True) opts = parser.parse_args() if opts.action == 'encode': autoencoder.encode(opts.model, opts.input,", "addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output', help='Output image file name', required=True) opts", "import autoencoder def addTrainablesArg(parser): parser.add_argument('--model', dest='model', help='Trained model', default='model.pt') def", "required=True) addExchangeArg(encode_parser) decode_parser = subparsers.add_parser('decode') addTrainablesArg(decode_parser) addExchangeArg(decode_parser) decode_parser.add_argument('--output', dest='output', help='Output", "dest='input', help='Input image file name', required=True) addExchangeArg(encode_parser) decode_parser = subparsers.add_parser('decode')", "argparse.ArgumentParser() subparsers = parser.add_subparsers(dest=\"action\") encode_parser = subparsers.add_parser('encode') addTrainablesArg(encode_parser) encode_parser.add_argument('--input', dest='input',", "decode_parser.add_argument('--output', dest='output', help='Output image file name', required=True) opts = parser.parse_args()", "argparse import autoencoder def addTrainablesArg(parser): parser.add_argument('--model', dest='model', help='Trained model', default='model.pt')" ]
[ "the email distributor. .. \"\"\" from __future__ import print_function from", "\"\"\"Figure out which :class:`Bridges.BridgeFilter`s to apply, or offer help. ..", "was received through the email distributor. .. \"\"\" from __future__", "__future__ import print_function from __future__ import unicode_literals import logging import", "the email line contains the ``'transport'`` command. :param str line:", "email distributor. bridgedb.email.request ====================== Classes for parsing and storing information", "the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest, self).__init__() self._isValid = False self._wantsKey =", "type of Pluggable Transport. \"\"\" unblocked = None logging.debug(\"Parsing 'unblocked'", "bridgerequest from bridgedb.Dist import EmailRequestedHelp from bridgedb.Dist import EmailRequestedKey #:", "requested bridges not blocked in: %r\" % unblocked) def withPluggableTransportType(self,", "EmailRequestedKey #: A regular expression for matching the Pluggable Transport", "<filename>lib/bridgedb/email/request.py # -*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ #", "of validity for this request. :param bool valid: If given,", "called with the **wantsKey** parameter set), it will set the", "the client requested some type of Pluggable Transport. \"\"\" transport", "in line: request.wantsKey(True) raise EmailRequestedKey(\"Email requested a copy of our", "is not None: self._wantsKey = bool(wantsKey) return self._wantsKey def withoutBlockInCountry(self,", "of Pluggable Transport. \"\"\" unblocked = None logging.debug(\"Parsing 'unblocked' line:", "False self._wantsKey = False def isValid(self, valid=None): \"\"\"Get or set", "line: if not line: skippedHeaders = True if not skippedHeaders:", "re.compile(TRANSPORT_REGEXP) #: A regular expression that matches country codes in", "requested a copy of our GnuPG key.\") if \"ipv6\" in", "request.isValid(True) logging.debug(\"Email request was valid.\") if \"key\" in line: request.wantsKey(True)", "the current state, otherwise (if called with the **valid** parameter),", "line: %r\" % line) try: unblocked = UNBLOCKED_PATTERN.match(line).group(1) except (TypeError,", "found in the **line** to the list of ``transports``. Currently,", "self._wantsKey = False def isValid(self, valid=None): \"\"\"Get or set the", "<NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME> <<EMAIL>> # please also see", "current state for whether or not this request wanted our", "\"transport\" in line: request.withPluggableTransportType(line) if \"unblocked\" in line: request.withoutBlockInCountry(line) logging.debug(\"Generating", "current state, otherwise (if called with the **wantsKey** parameter set),", "country: The line from the email wherein the client requested", "distributor. .. \"\"\" from __future__ import print_function from __future__ import", "Transport. \"\"\" transport = None logging.debug(\"Parsing 'transport' line: %r\" %", "line = line.strip().lower() # Ignore all lines before the first", "valid.\") if \"key\" in line: request.wantsKey(True) raise EmailRequestedKey(\"Email requested a", "try: unblocked = UNBLOCKED_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if unblocked:", "contains the ``'unblocked'`` command. :param str country: The line from", "requested help.\") if \"get\" in line: request.isValid(True) logging.debug(\"Email request was", "__future__ import unicode_literals import logging import re from bridgedb import", "set. The returned ``BridgeRequest`` will have already had its filters", "logging.info(\"Email requested bridges not blocked in: %r\" % unblocked) def", "for whether or not this request wanted our key. :param", "file is part of BridgeDB, a Tor bridge distribution system.", "the first empty line: if not line: skippedHeaders = True", "%r\" % line) try: unblocked = UNBLOCKED_PATTERN.match(line).group(1) except (TypeError, AttributeError):", "the **wantsKey** parameter set), it will set the current state", "not line: skippedHeaders = True if not skippedHeaders: continue if", "state. \"\"\" if valid is not None: self._isValid = bool(valid)", "the email distributor. bridgedb.email.request ====================== Classes for parsing and storing", "line): \"\"\"This request was for bridges not blocked in **country**.", "bridges not blocked in **country**. Add any country code found", "state of this request. Otherwise, get the current state. \"\"\"", "= TRANSPORT_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if transport: self.transports.append(transport) logging.info(\"Email", "expression that matches country codes in requests for unblocked #:", "state for whether or not this request wanted our key.", "import EmailRequestedHelp from bridgedb.Dist import EmailRequestedKey #: A regular expression", "any Pluggable Transport method TYPE found in the **line** to", "except (TypeError, AttributeError): pass if transport: self.transports.append(transport) logging.info(\"Email requested transport", "self.notBlockedIn.append(unblocked) logging.info(\"Email requested bridges not blocked in: %r\" % unblocked)", "request for bridges which was received through the email distributor.", "the current state of validity for this request. :param bool", "valid: If given, set the validity state of this request.", "if unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email requested bridges not blocked in: %r\"", ":returns: A :class:`~bridgerequst.BridgeRequest` with all of the requested parameters set.", "parameter set), it will set the current state for whether", "bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # # This file is part of", "utf-8; test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # # This file is", "via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request = EmailBridgeRequest() skippedHeaders = False for", "(TypeError, AttributeError): pass if transport: self.transports.append(transport) logging.info(\"Email requested transport type:", "(c) 2013-2015, Isis Lovecruft # :license: see LICENSE for licensing", "wantsKey: If given, set the validity state of this request.", "UNBLOCKED_REGEXP = \".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines): \"\"\"Figure", "TRANSPORT_REGEXP = \".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP) #: A regular", "note:: If any ``'transport TYPE'`` was requested, or bridges not", "\"\"\" unblocked = None logging.debug(\"Parsing 'unblocked' line: %r\" % line)", "is not None: self._isValid = bool(valid) return self._isValid def wantsKey(self,", "before the first empty line: if not line: skippedHeaders =", "skippedHeaders = False for line in lines: line = line.strip().lower()", "line: The line from the email wherein the client requested", "state. \"\"\" if wantsKey is not None: self._wantsKey = bool(wantsKey)", "email distributor. :: bridgedb.email.request | |_ determineBridgeRequestOptions - Figure out", "through the email distributor. .. \"\"\" from __future__ import print_function", "distributor.\"\"\" def __init__(self): \"\"\"Process a new bridge request received through", "self).__init__() self._isValid = False self._wantsKey = False def isValid(self, valid=None):", "already had its filters generated via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request =", "self._isValid = bool(valid) return self._isValid def wantsKey(self, wantsKey=None): \"\"\"Get or", "print_function from __future__ import unicode_literals import logging import re from", "str country: The line from the email wherein the client", "raise EmailRequestedHelp(\"Client requested help.\") if \"get\" in line: request.isValid(True) logging.debug(\"Email", "wantsKey is not None: self._wantsKey = bool(wantsKey) return self._wantsKey def", "([a-z]{2,4})\" UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines): \"\"\"Figure out which :class:`Bridges.BridgeFilter`s", "also see AUTHORS file # :copyright: (c) 2007-2015, The Tor", "state, otherwise (if called with the **wantsKey** parameter set), it", "\"unblocked\" in line: request.withoutBlockInCountry(line) logging.debug(\"Generating hashring filters for request.\") request.generateFilters()", "import unicode_literals import logging import re from bridgedb import bridgerequest", "in line) or (\"halp\" in line): raise EmailRequestedHelp(\"Client requested help.\")", "raise EmailRequestedKey(\"Email requested a copy of our GnuPG key.\") if", "if \"unblocked\" in line: request.withoutBlockInCountry(line) logging.debug(\"Generating hashring filters for request.\")", "#: emailed requests for Pluggable Transports. TRANSPORT_REGEXP = \".*transport ([a-z][_a-z0-9]*)\"", "if wantsKey is not None: self._wantsKey = bool(wantsKey) return self._wantsKey", "parameters set. The returned ``BridgeRequest`` will have already had its", "client requested help. :raises EmailRequestedKey: if the client requested our", "request received through the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest, self).__init__() self._isValid =", "**line** to the list of ``notBlockedIn``. Currently, a request for", "**line** to the list of ``transports``. Currently, a request for", "%r\" % line) try: transport = TRANSPORT_PATTERN.match(line).group(1) except (TypeError, AttributeError):", "with all of the requested parameters set. The returned ``BridgeRequest``", "\"\"\" if valid is not None: self._isValid = bool(valid) return", "requested some type of Pluggable Transport. \"\"\" unblocked = None", "self._isValid = False self._wantsKey = False def isValid(self, valid=None): \"\"\"Get", "re from bridgedb import bridgerequest from bridgedb.Dist import EmailRequestedHelp from", "\"\"\" request = EmailBridgeRequest() skippedHeaders = False for line in", "the current state, otherwise (if called with the **wantsKey** parameter", "if the email line contains the ``'unblocked'`` command. :param str", "The line from the email wherein the client requested some", "= \".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines): \"\"\"Figure out", "wanted our GnuPG key. If called without parameters, this method", "TYPE in #: emailed requests for Pluggable Transports. TRANSPORT_REGEXP =", "bridgedb.Dist import EmailRequestedKey #: A regular expression for matching the", "2007-2015, The Tor Project, Inc. # (c) 2013-2015, Isis Lovecruft", "in #: emailed requests for Pluggable Transports. TRANSPORT_REGEXP = \".*transport", "help. |_ EmailBridgeRequest - A request for bridges which was", "= re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines): \"\"\"Figure out which :class:`Bridges.BridgeFilter`s to apply,", "and/or ``CC`` will *always* be stored as a *lowercase* string.", "if the client requested our GnuPG key. :rtype: :class:`EmailBridgeRequest` :returns:", "the email line contains the ``'unblocked'`` command. :param str country:", "UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines): \"\"\"Figure out which :class:`Bridges.BridgeFilter`s to", "``transports``. Currently, a request for a transport is recognized if", "wantsKey(self, wantsKey=None): \"\"\"Get or set whether this bridge request wanted", "in **country**. Add any country code found in the **line**", "Pluggable Transport method TYPE in #: emailed requests for Pluggable", "self._wantsKey = bool(wantsKey) return self._wantsKey def withoutBlockInCountry(self, line): \"\"\"This request", "bridges which are sent to the email distributor. bridgedb.email.request ======================", "offer help. |_ EmailBridgeRequest - A request for bridges which", "lines before the first empty line: if not line: skippedHeaders", "UNBLOCKED_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email requested", "if the client requested help. :raises EmailRequestedKey: if the client", "\"\"\" super(EmailBridgeRequest, self).__init__() self._isValid = False self._wantsKey = False def", "AUTHORS file # :copyright: (c) 2007-2015, The Tor Project, Inc.", "in line: request.withoutBlockInCountry(line) logging.debug(\"Generating hashring filters for request.\") request.generateFilters() return", "matching the Pluggable Transport method TYPE in #: emailed requests", "None logging.debug(\"Parsing 'transport' line: %r\" % line) try: transport =", "regular expression that matches country codes in requests for unblocked", "the ``TYPE`` and/or ``CC`` will *always* be stored as a", "see LICENSE for licensing information #_____________________________________________________________________________ \"\"\" .. py:module:: bridgedb.email.request", "requests for Pluggable Transports. TRANSPORT_REGEXP = \".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN =", "# :license: see LICENSE for licensing information #_____________________________________________________________________________ \"\"\" ..", "sent to the email distributor. :: bridgedb.email.request | |_ determineBridgeRequestOptions", "unicode_literals import logging import re from bridgedb import bridgerequest from", "apply, or | offer help. |_ EmailBridgeRequest - A request", "Pluggable Transport method TYPE found in the **line** to the", "- Figure out which filters to apply, or | offer", "have already had its filters generated via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request", "request.\") request.generateFilters() return request class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received a request", "to the list of ``notBlockedIn``. Currently, a request for a", ":: bridgedb.email.request | |_ determineBridgeRequestOptions - Figure out which filters", "a request for bridges through the email distributor.\"\"\" def __init__(self):", "code found in the **line** to the list of ``notBlockedIn``.", "recognized if the email line contains the ``'transport'`` command. :param", "line: request.isValid(True) logging.debug(\"Email request was valid.\") if \"key\" in line:", "Tor Project, Inc. # (c) 2013-2015, Isis Lovecruft # :license:", "#_____________________________________________________________________________ # # This file is part of BridgeDB, a", "'transport' line: %r\" % line) try: transport = TRANSPORT_PATTERN.match(line).group(1) except", "#_____________________________________________________________________________ \"\"\" .. py:module:: bridgedb.email.request :synopsis: Classes for parsing and", "parsing and storing information about requests for bridges which are", "bridges which are sent to the email distributor. :: bridgedb.email.request", "not blocked in a specific CC (``'unblocked CC'``), then the", "from an email, including the headers. :raises EmailRequestedHelp: if the", "in line: request.isValid(True) logging.debug(\"Email request was valid.\") if \"key\" in", "blocked in: %r\" % unblocked) def withPluggableTransportType(self, line): \"\"\"This request", "country code found in the **line** to the list of", "return the current state, otherwise (if called with the **wantsKey**", "bridgedb.email.request :synopsis: Classes for parsing and storing information about requests", "EmailBridgeRequest - A request for bridges which was received through", "\"\"\" from __future__ import print_function from __future__ import unicode_literals import", "TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP) #: A regular expression that matches country", "(``'unblocked CC'``), then the ``TYPE`` and/or ``CC`` will *always* be", "line: request.wantsKey(True) raise EmailRequestedKey(\"Email requested a copy of our GnuPG", "determineBridgeRequestOptions - Figure out which filters to apply, or |", "= False self._wantsKey = False def isValid(self, valid=None): \"\"\"Get or", "some type of Pluggable Transport. \"\"\" unblocked = None logging.debug(\"Parsing", "line) try: unblocked = UNBLOCKED_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if", "If called without parameters, this method will return the current", "in the **line** to the list of ``notBlockedIn``. Currently, a", "any country code found in the **line** to the list", "which filters to apply, or | offer help. |_ EmailBridgeRequest", "def isValid(self, valid=None): \"\"\"Get or set the validity of this", "if not line: skippedHeaders = True if not skippedHeaders: continue", "email distributor.\"\"\" def __init__(self): \"\"\"Process a new bridge request received", "Inc. # (c) 2013-2015, Isis Lovecruft # :license: see LICENSE", "<NAME> <<EMAIL>> # please also see AUTHORS file # :copyright:", "it will set the current state of validity for this", "False for line in lines: line = line.strip().lower() # Ignore", "of BridgeDB, a Tor bridge distribution system. # # :authors:", "matches country codes in requests for unblocked #: bridges. UNBLOCKED_REGEXP", "this request. Otherwise, get the current state. \"\"\" if wantsKey", "requested some type of Pluggable Transport. \"\"\" transport = None", "|_ EmailBridgeRequest - A request for bridges which was received", "Project, Inc. # (c) 2013-2015, Isis Lovecruft # :license: see", "EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received a request for bridges through the email", "is part of BridgeDB, a Tor bridge distribution system. #", "import EmailRequestedKey #: A regular expression for matching the Pluggable", "#: bridges. UNBLOCKED_REGEXP = \".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP) def", "headers. :raises EmailRequestedHelp: if the client requested help. :raises EmailRequestedKey:", "the client requested help. :raises EmailRequestedKey: if the client requested", "our GnuPG key.\") if \"ipv6\" in line: request.withIPv6() if \"transport\"", "this method will return the current state, otherwise (if called", "the email wherein the client requested some type of Pluggable", "request wanted our GnuPG key. If called without parameters, this", "line): raise EmailRequestedHelp(\"Client requested help.\") if \"get\" in line: request.isValid(True)", "through the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest, self).__init__() self._isValid = False self._wantsKey", ":synopsis: Classes for parsing and storing information about requests for", "line): \"\"\"This request included a specific Pluggable Transport identifier. Add", "request.generateFilters() return request class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received a request for", "(\"help\" in line) or (\"halp\" in line): raise EmailRequestedHelp(\"Client requested", "# please also see AUTHORS file # :copyright: (c) 2007-2015,", "If any ``'transport TYPE'`` was requested, or bridges not blocked", "# :authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME>", "current state. \"\"\" if wantsKey is not None: self._wantsKey =", "requested, or bridges not blocked in a specific CC (``'unblocked", "state of validity for this request. :param bool valid: If", "request included a specific Pluggable Transport identifier. Add any Pluggable", "this bridge request. If called without parameters, this method will", "def wantsKey(self, wantsKey=None): \"\"\"Get or set whether this bridge request", "client requested some type of Pluggable Transport. \"\"\" unblocked =", "identifier. Add any Pluggable Transport method TYPE found in the", "or (\"halp\" in line): raise EmailRequestedHelp(\"Client requested help.\") if \"get\"", "country codes in requests for unblocked #: bridges. UNBLOCKED_REGEXP =", "the current state for whether or not this request wanted", "for licensing information #_____________________________________________________________________________ \"\"\" .. py:module:: bridgedb.email.request :synopsis: Classes", "logging.debug(\"Email request was valid.\") if \"key\" in line: request.wantsKey(True) raise", "blocked in a specific CC (``'unblocked CC'``), then the ``TYPE``", "\".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP) #: A regular expression that", "<<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME> <<EMAIL>> # please also see AUTHORS", "= True if not skippedHeaders: continue if (\"help\" in line)", "# Ignore all lines before the first empty line: if", "if \"ipv6\" in line: request.withIPv6() if \"transport\" in line: request.withPluggableTransportType(line)", "or offer help. .. note:: If any ``'transport TYPE'`` was", ":class:`Bridges.BridgeFilter`s to apply, or offer help. .. note:: If any", "continue if (\"help\" in line) or (\"halp\" in line): raise", "of this bridge request. If called without parameters, this method", "the client requested some type of Pluggable Transport. \"\"\" unblocked", "(\"halp\" in line): raise EmailRequestedHelp(\"Client requested help.\") if \"get\" in", "except (TypeError, AttributeError): pass if unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email requested bridges", "in a specific CC (``'unblocked CC'``), then the ``TYPE`` and/or", "request. If called without parameters, this method will return the", "a transport is recognized if the email line contains the", "lines: line = line.strip().lower() # Ignore all lines before the", ":param list lines: A list of lines from an email,", "= None logging.debug(\"Parsing 'unblocked' line: %r\" % line) try: unblocked", ":raises EmailRequestedHelp: if the client requested help. :raises EmailRequestedKey: if", "import logging import re from bridgedb import bridgerequest from bridgedb.Dist", "logging.debug(\"Generating hashring filters for request.\") request.generateFilters() return request class EmailBridgeRequest(bridgerequest.BridgeRequestBase):", "unblocked = UNBLOCKED_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if unblocked: self.notBlockedIn.append(unblocked)", "= UNBLOCKED_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email", "all of the requested parameters set. The returned ``BridgeRequest`` will", ":rtype: :class:`EmailBridgeRequest` :returns: A :class:`~bridgerequst.BridgeRequest` with all of the requested", "request wanted our key. :param bool wantsKey: If given, set", "super(EmailBridgeRequest, self).__init__() self._isValid = False self._wantsKey = False def isValid(self,", "__init__(self): \"\"\"Process a new bridge request received through the :class:`~bridgedb.Dist.EmailBasedDistributor`.", "file # :copyright: (c) 2007-2015, The Tor Project, Inc. #", "from __future__ import print_function from __future__ import unicode_literals import logging", "generated via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request = EmailBridgeRequest() skippedHeaders = False", "bridges which was received through the email distributor. .. \"\"\"", "an email, including the headers. :raises EmailRequestedHelp: if the client", "``'transport'`` command. :param str line: The line from the email", "for bridges which are sent to the email distributor. ::", "offer help. .. note:: If any ``'transport TYPE'`` was requested,", "if (\"help\" in line) or (\"halp\" in line): raise EmailRequestedHelp(\"Client", "A regular expression for matching the Pluggable Transport method TYPE", "the ``'unblocked'`` command. :param str country: The line from the", "**wantsKey** parameter set), it will set the current state for", "line: request.withIPv6() if \"transport\" in line: request.withPluggableTransportType(line) if \"unblocked\" in", "line in lines: line = line.strip().lower() # Ignore all lines", "copy of our GnuPG key.\") if \"ipv6\" in line: request.withIPv6()", "was requested, or bridges not blocked in a specific CC", "import re from bridgedb import bridgerequest from bridgedb.Dist import EmailRequestedHelp", "our GnuPG key. :rtype: :class:`EmailBridgeRequest` :returns: A :class:`~bridgerequst.BridgeRequest` with all", "A list of lines from an email, including the headers.", "for a transport is recognized if the email line contains", "EmailRequestedHelp(\"Client requested help.\") if \"get\" in line: request.isValid(True) logging.debug(\"Email request", "distributor. bridgedb.email.request ====================== Classes for parsing and storing information about", "get the current state. \"\"\" if wantsKey is not None:", "= bool(wantsKey) return self._wantsKey def withoutBlockInCountry(self, line): \"\"\"This request was", "method will return the current state, otherwise (if called with", "to apply, or | offer help. |_ EmailBridgeRequest - A", "request. Otherwise, get the current state. \"\"\" if valid is", "bridges not blocked in a specific CC (``'unblocked CC'``), then", "str line: The line from the email wherein the client", "py:module:: bridgedb.email.request :synopsis: Classes for parsing and storing information about", "2013-2015, Isis Lovecruft # :license: see LICENSE for licensing information", "Transport method TYPE found in the **line** to the list", "line) try: transport = TRANSPORT_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if", "Pluggable Transport identifier. Add any Pluggable Transport method TYPE found", "all lines before the first empty line: if not line:", "the current state. \"\"\" if valid is not None: self._isValid", "the validity of this bridge request. If called without parameters,", "None: self._isValid = bool(valid) return self._isValid def wantsKey(self, wantsKey=None): \"\"\"Get", "email wherein the client requested some type of Pluggable Transport.", "will return the current state, otherwise (if called with the", "= line.strip().lower() # Ignore all lines before the first empty", "EmailRequestedHelp: if the client requested help. :raises EmailRequestedKey: if the", "the list of ``transports``. Currently, a request for a transport", "see AUTHORS file # :copyright: (c) 2007-2015, The Tor Project,", "key. If called without parameters, this method will return the", "will set the current state of validity for this request.", "AttributeError): pass if transport: self.transports.append(transport) logging.info(\"Email requested transport type: %r\"", "GnuPG key. :rtype: :class:`EmailBridgeRequest` :returns: A :class:`~bridgerequst.BridgeRequest` with all of", "will *always* be stored as a *lowercase* string. :param list", "(c) 2007-2015, The Tor Project, Inc. # (c) 2013-2015, Isis", "# (c) 2013-2015, Isis Lovecruft # :license: see LICENSE for", "some type of Pluggable Transport. \"\"\" transport = None logging.debug(\"Parsing", "determineBridgeRequestOptions(lines): \"\"\"Figure out which :class:`Bridges.BridgeFilter`s to apply, or offer help.", "# This file is part of BridgeDB, a Tor bridge", "lines from an email, including the headers. :raises EmailRequestedHelp: if", "are sent to the email distributor. :: bridgedb.email.request | |_", "hashring filters for request.\") request.generateFilters() return request class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We", "the **line** to the list of ``notBlockedIn``. Currently, a request", "stored as a *lowercase* string. :param list lines: A list", "expression for matching the Pluggable Transport method TYPE in #:", "from the email wherein the client requested some type of", "\"\"\" if wantsKey is not None: self._wantsKey = bool(wantsKey) return", "the ``'transport'`` command. :param str line: The line from the", "the client requested our GnuPG key. :rtype: :class:`EmailBridgeRequest` :returns: A", "class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received a request for bridges through the", "transport is recognized if the email line contains the ``'transport'``", "#: A regular expression that matches country codes in requests", "TRANSPORT_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if transport: self.transports.append(transport) logging.info(\"Email requested", "from bridgedb.Dist import EmailRequestedKey #: A regular expression for matching", "Pluggable Transport. \"\"\" unblocked = None logging.debug(\"Parsing 'unblocked' line: %r\"", "be stored as a *lowercase* string. :param list lines: A", "will set the current state for whether or not this", "None: self._wantsKey = bool(wantsKey) return self._wantsKey def withoutBlockInCountry(self, line): \"\"\"This", "self._isValid def wantsKey(self, wantsKey=None): \"\"\"Get or set whether this bridge", "if the email line contains the ``'transport'`` command. :param str", "``'unblocked'`` command. :param str country: The line from the email", ":param bool valid: If given, set the validity state of", "set the validity of this bridge request. If called without", "\".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines): \"\"\"Figure out which", "state, otherwise (if called with the **valid** parameter), it will", "are sent to the email distributor. bridgedb.email.request ====================== Classes for", ".. note:: If any ``'transport TYPE'`` was requested, or bridges", ":raises EmailRequestedKey: if the client requested our GnuPG key. :rtype:", "for bridges which are sent to the email distributor. bridgedb.email.request", "a Tor bridge distribution system. # # :authors: <NAME> <<EMAIL>>", "If given, set the validity state of this request. Otherwise,", "#: A regular expression for matching the Pluggable Transport method", "Transports. TRANSPORT_REGEXP = \".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP) #: A", "\"\"\" .. py:module:: bridgedb.email.request :synopsis: Classes for parsing and storing", "= bool(valid) return self._isValid def wantsKey(self, wantsKey=None): \"\"\"Get or set", "Lovecruft # :license: see LICENSE for licensing information #_____________________________________________________________________________ \"\"\"", "% line) try: unblocked = UNBLOCKED_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass", "bridge request received through the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest, self).__init__() self._isValid", "received through the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest, self).__init__() self._isValid = False", "please also see AUTHORS file # :copyright: (c) 2007-2015, The", "in: %r\" % unblocked) def withPluggableTransportType(self, line): \"\"\"This request included", "including the headers. :raises EmailRequestedHelp: if the client requested help.", "current state of validity for this request. :param bool valid:", "requested help. :raises EmailRequestedKey: if the client requested our GnuPG", "return the current state, otherwise (if called with the **valid**", "the email distributor. :: bridgedb.email.request | |_ determineBridgeRequestOptions - Figure", "filters generated via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request = EmailBridgeRequest() skippedHeaders =", "list lines: A list of lines from an email, including", "in line: request.withIPv6() if \"transport\" in line: request.withPluggableTransportType(line) if \"unblocked\"", ":authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME> <<EMAIL>>", "if \"transport\" in line: request.withPluggableTransportType(line) if \"unblocked\" in line: request.withoutBlockInCountry(line)", "is recognized if the email line contains the ``'transport'`` command.", "skippedHeaders: continue if (\"help\" in line) or (\"halp\" in line):", "bool valid: If given, set the validity state of this", "email line contains the ``'unblocked'`` command. :param str country: The", "requested our GnuPG key. :rtype: :class:`EmailBridgeRequest` :returns: A :class:`~bridgerequst.BridgeRequest` with", "coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # # This file", ".. \"\"\" from __future__ import print_function from __future__ import unicode_literals", "help. :raises EmailRequestedKey: if the client requested our GnuPG key.", "A :class:`~bridgerequst.BridgeRequest` with all of the requested parameters set. The", "for line in lines: line = line.strip().lower() # Ignore all", "contains the ``'transport'`` command. :param str line: The line from", ".. py:module:: bridgedb.email.request :synopsis: Classes for parsing and storing information", "A regular expression that matches country codes in requests for", "**country**. Add any country code found in the **line** to", "bridge request. If called without parameters, this method will return", "*lowercase* string. :param list lines: A list of lines from", "list of ``transports``. Currently, a request for a transport is", "with the **wantsKey** parameter set), it will set the current", "requests for unblocked #: bridges. UNBLOCKED_REGEXP = \".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN", "unblocked #: bridges. UNBLOCKED_REGEXP = \".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP)", "called with the **valid** parameter), it will set the current", "storing information about requests for bridges which are sent to", "bridge request wanted our GnuPG key. If called without parameters,", "def __init__(self): \"\"\"Process a new bridge request received through the", "not skippedHeaders: continue if (\"help\" in line) or (\"halp\" in", "AttributeError): pass if unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email requested bridges not blocked", "included a specific Pluggable Transport identifier. Add any Pluggable Transport", "\"ipv6\" in line: request.withIPv6() if \"transport\" in line: request.withPluggableTransportType(line) if", "request for bridges through the email distributor.\"\"\" def __init__(self): \"\"\"Process", "or set the validity of this bridge request. If called", "logging.debug(\"Parsing 'transport' line: %r\" % line) try: transport = TRANSPORT_PATTERN.match(line).group(1)", "or not this request wanted our key. :param bool wantsKey:", "A request for bridges which was received through the email", "'unblocked' line: %r\" % line) try: unblocked = UNBLOCKED_PATTERN.match(line).group(1) except", "request. :param bool valid: If given, set the validity state", ":param bool wantsKey: If given, set the validity state of", "blocked in **country**. Add any country code found in the", "# <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME> <<EMAIL>> # please also", "logging import re from bridgedb import bridgerequest from bridgedb.Dist import", "(if called with the **wantsKey** parameter set), it will set", "of this request. Otherwise, get the current state. \"\"\" if", "system. # # :authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35", "returned ``BridgeRequest`` will have already had its filters generated via", "test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # # This file is part", "out which filters to apply, or | offer help. |_", "-*- #_____________________________________________________________________________ # # This file is part of BridgeDB,", "def determineBridgeRequestOptions(lines): \"\"\"Figure out which :class:`Bridges.BridgeFilter`s to apply, or offer", "None logging.debug(\"Parsing 'unblocked' line: %r\" % line) try: unblocked =", "received through the email distributor. .. \"\"\" from __future__ import", "a specific CC (``'unblocked CC'``), then the ``TYPE`` and/or ``CC``", "\"\"\"This request was for bridges not blocked in **country**. Add", "validity for this request. :param bool valid: If given, set", "EmailRequestedHelp from bridgedb.Dist import EmailRequestedKey #: A regular expression for", "it will set the current state for whether or not", "or set whether this bridge request wanted our GnuPG key.", "line: request.withPluggableTransportType(line) if \"unblocked\" in line: request.withoutBlockInCountry(line) logging.debug(\"Generating hashring filters", "received a request for bridges through the email distributor.\"\"\" def", "about requests for bridges which are sent to the email", "request for a transport is recognized if the email line", "for Pluggable Transports. TRANSPORT_REGEXP = \".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP)", "parameter), it will set the current state of validity for", "command. :param str line: The line from the email wherein", "The returned ``BridgeRequest`` will have already had its filters generated", "in line: request.withPluggableTransportType(line) if \"unblocked\" in line: request.withoutBlockInCountry(line) logging.debug(\"Generating hashring", "current state, otherwise (if called with the **valid** parameter), it", ":class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest, self).__init__() self._isValid = False self._wantsKey = False", "part of BridgeDB, a Tor bridge distribution system. # #", "Transport method TYPE in #: emailed requests for Pluggable Transports.", "request = EmailBridgeRequest() skippedHeaders = False for line in lines:", "line: %r\" % line) try: transport = TRANSPORT_PATTERN.match(line).group(1) except (TypeError,", "for this request. :param bool valid: If given, set the", "# -*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # #", "line) or (\"halp\" in line): raise EmailRequestedHelp(\"Client requested help.\") if", "Currently, a request for a transport is recognized if the", "type of Pluggable Transport. \"\"\" transport = None logging.debug(\"Parsing 'transport'", "return self._isValid def wantsKey(self, wantsKey=None): \"\"\"Get or set whether this", "= re.compile(TRANSPORT_REGEXP) #: A regular expression that matches country codes", "was for bridges not blocked in **country**. Add any country", "bridgedb import bridgerequest from bridgedb.Dist import EmailRequestedHelp from bridgedb.Dist import", "False def isValid(self, valid=None): \"\"\"Get or set the validity of", "GnuPG key. If called without parameters, this method will return", "not blocked in: %r\" % unblocked) def withPluggableTransportType(self, line): \"\"\"This", "help.\") if \"get\" in line: request.isValid(True) logging.debug(\"Email request was valid.\")", "otherwise (if called with the **valid** parameter), it will set", "specific CC (``'unblocked CC'``), then the ``TYPE`` and/or ``CC`` will", "-*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # # This", "of lines from an email, including the headers. :raises EmailRequestedHelp:", "\"\"\"Get or set the validity of this bridge request. If", "EmailBridgeRequest() skippedHeaders = False for line in lines: line =", "unblocked = None logging.debug(\"Parsing 'unblocked' line: %r\" % line) try:", "from __future__ import unicode_literals import logging import re from bridgedb", "in the **line** to the list of ``transports``. Currently, a", "*always* be stored as a *lowercase* string. :param list lines:", "codes in requests for unblocked #: bridges. UNBLOCKED_REGEXP = \".*unblocked", "if not skippedHeaders: continue if (\"help\" in line) or (\"halp\"", "GnuPG key.\") if \"ipv6\" in line: request.withIPv6() if \"transport\" in", ":copyright: (c) 2007-2015, The Tor Project, Inc. # (c) 2013-2015,", "current state. \"\"\" if valid is not None: self._isValid =", "the **line** to the list of ``transports``. Currently, a request", "help. .. note:: If any ``'transport TYPE'`` was requested, or", "transport = None logging.debug(\"Parsing 'transport' line: %r\" % line) try:", "in line): raise EmailRequestedHelp(\"Client requested help.\") if \"get\" in line:", "the list of ``notBlockedIn``. Currently, a request for a transport", "specific Pluggable Transport identifier. Add any Pluggable Transport method TYPE", "out which :class:`Bridges.BridgeFilter`s to apply, or offer help. .. note::", "this request. Otherwise, get the current state. \"\"\" if valid", "logging.debug(\"Parsing 'unblocked' line: %r\" % line) try: unblocked = UNBLOCKED_PATTERN.match(line).group(1)", "email distributor. .. \"\"\" from __future__ import print_function from __future__", "as a *lowercase* string. :param list lines: A list of", "empty line: if not line: skippedHeaders = True if not", "emailed requests for Pluggable Transports. TRANSPORT_REGEXP = \".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN", "line from the email wherein the client requested some type", "string. :param list lines: A list of lines from an", "parameters, this method will return the current state, otherwise (if", "if valid is not None: self._isValid = bool(valid) return self._isValid", "this bridge request wanted our GnuPG key. If called without", "of Pluggable Transport. \"\"\" transport = None logging.debug(\"Parsing 'transport' line:", "withPluggableTransportType(self, line): \"\"\"This request included a specific Pluggable Transport identifier.", "\"\"\"Process a new bridge request received through the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\"", "EmailRequestedKey: if the client requested our GnuPG key. :rtype: :class:`EmailBridgeRequest`", "= None logging.debug(\"Parsing 'transport' line: %r\" % line) try: transport", "to the email distributor. bridgedb.email.request ====================== Classes for parsing and", "self._wantsKey def withoutBlockInCountry(self, line): \"\"\"This request was for bridges not", "unblocked) def withPluggableTransportType(self, line): \"\"\"This request included a specific Pluggable", "new bridge request received through the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest, self).__init__()", "information #_____________________________________________________________________________ \"\"\" .. py:module:: bridgedb.email.request :synopsis: Classes for parsing", "sent to the email distributor. bridgedb.email.request ====================== Classes for parsing", "import print_function from __future__ import unicode_literals import logging import re", "\"get\" in line: request.isValid(True) logging.debug(\"Email request was valid.\") if \"key\"", "through the email distributor.\"\"\" def __init__(self): \"\"\"Process a new bridge", "Otherwise, get the current state. \"\"\" if valid is not", "% line) try: transport = TRANSPORT_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass", "with the **valid** parameter), it will set the current state", "Ignore all lines before the first empty line: if not", "Add any country code found in the **line** to the", "list of ``notBlockedIn``. Currently, a request for a transport is", "our GnuPG key. If called without parameters, this method will", "if \"key\" in line: request.wantsKey(True) raise EmailRequestedKey(\"Email requested a copy", "import bridgerequest from bridgedb.Dist import EmailRequestedHelp from bridgedb.Dist import EmailRequestedKey", "lines: A list of lines from an email, including the", "key. :param bool wantsKey: If given, set the validity state", "for bridges not blocked in **country**. Add any country code", "of ``notBlockedIn``. Currently, a request for a transport is recognized", "isValid(self, valid=None): \"\"\"Get or set the validity of this bridge", "for bridges which was received through the email distributor. ..", "set the validity state of this request. Otherwise, get the", "wantsKey=None): \"\"\"Get or set whether this bridge request wanted our", "line contains the ``'transport'`` command. :param str line: The line", "information about requests for bridges which are sent to the", "of the requested parameters set. The returned ``BridgeRequest`` will have", "then the ``TYPE`` and/or ``CC`` will *always* be stored as", "not None: self._isValid = bool(valid) return self._isValid def wantsKey(self, wantsKey=None):", "this request. :param bool valid: If given, set the validity", "bridgedb.email.request | |_ determineBridgeRequestOptions - Figure out which filters to", "distribution system. # # :authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>>", "if \"get\" in line: request.isValid(True) logging.debug(\"Email request was valid.\") if", "whether or not this request wanted our key. :param bool", "that matches country codes in requests for unblocked #: bridges.", "CC (``'unblocked CC'``), then the ``TYPE`` and/or ``CC`` will *always*", "its filters generated via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request = EmailBridgeRequest() skippedHeaders", "of our GnuPG key.\") if \"ipv6\" in line: request.withIPv6() if", "\"\"\"Get or set whether this bridge request wanted our GnuPG", "====================== Classes for parsing and storing information about requests for", "request.withPluggableTransportType(line) if \"unblocked\" in line: request.withoutBlockInCountry(line) logging.debug(\"Generating hashring filters for", "called without parameters, this method will return the current state,", "the validity state of this request. Otherwise, get the current", "not None: self._wantsKey = bool(wantsKey) return self._wantsKey def withoutBlockInCountry(self, line):", "bool(wantsKey) return self._wantsKey def withoutBlockInCountry(self, line): \"\"\"This request was for", "\"\"\"We received a request for bridges through the email distributor.\"\"\"", "request was valid.\") if \"key\" in line: request.wantsKey(True) raise EmailRequestedKey(\"Email", "bridge distribution system. # # :authors: <NAME> <<EMAIL>> # <NAME>", "Transport identifier. Add any Pluggable Transport method TYPE found in", "<NAME> <<EMAIL>> # <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME> <<EMAIL>> #", "return request class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received a request for bridges", "set), it will set the current state for whether or", "- A request for bridges which was received through the", "if transport: self.transports.append(transport) logging.info(\"Email requested transport type: %r\" % transport)", "``'transport TYPE'`` was requested, or bridges not blocked in a", "email line contains the ``'transport'`` command. :param str line: The", "request class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received a request for bridges through", "this request wanted our key. :param bool wantsKey: If given,", "re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines): \"\"\"Figure out which :class:`Bridges.BridgeFilter`s to apply, or", ":class:`EmailBridgeRequest` :returns: A :class:`~bridgerequst.BridgeRequest` with all of the requested parameters", "a request for a transport is recognized if the email", "had its filters generated via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request = EmailBridgeRequest()", "a *lowercase* string. :param list lines: A list of lines", ":meth:`~EmailBridgeRequest.generateFilters`. \"\"\" request = EmailBridgeRequest() skippedHeaders = False for line", "Transport. \"\"\" unblocked = None logging.debug(\"Parsing 'unblocked' line: %r\" %", "bridgedb.email.request ====================== Classes for parsing and storing information about requests", "bridges through the email distributor.\"\"\" def __init__(self): \"\"\"Process a new", "for unblocked #: bridges. UNBLOCKED_REGEXP = \".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN =", "CC'``), then the ``TYPE`` and/or ``CC`` will *always* be stored", "given, set the validity state of this request. Otherwise, get", "skippedHeaders = True if not skippedHeaders: continue if (\"help\" in", "line.strip().lower() # Ignore all lines before the first empty line:", "in requests for unblocked #: bridges. UNBLOCKED_REGEXP = \".*unblocked ([a-z]{2,4})\"", "The Tor Project, Inc. # (c) 2013-2015, Isis Lovecruft #", "set whether this bridge request wanted our GnuPG key. If", "\"key\" in line: request.wantsKey(True) raise EmailRequestedKey(\"Email requested a copy of", "licensing information #_____________________________________________________________________________ \"\"\" .. py:module:: bridgedb.email.request :synopsis: Classes for", "Add any Pluggable Transport method TYPE found in the **line**", "pass if transport: self.transports.append(transport) logging.info(\"Email requested transport type: %r\" %", "which was received through the email distributor. .. \"\"\" from", "return self._wantsKey def withoutBlockInCountry(self, line): \"\"\"This request was for bridges", "(if called with the **valid** parameter), it will set the", "filters for request.\") request.generateFilters() return request class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received", "Pluggable Transports. TRANSPORT_REGEXP = \".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP) #:", "% unblocked) def withPluggableTransportType(self, line): \"\"\"This request included a specific", "bool wantsKey: If given, set the validity state of this", "Classes for parsing and storing information about requests for bridges", "TYPE'`` was requested, or bridges not blocked in a specific", "transport is recognized if the email line contains the ``'unblocked'``", "the headers. :raises EmailRequestedHelp: if the client requested help. :raises", "|_ determineBridgeRequestOptions - Figure out which filters to apply, or", "regular expression for matching the Pluggable Transport method TYPE in", "method TYPE in #: emailed requests for Pluggable Transports. TRANSPORT_REGEXP", "valid is not None: self._isValid = bool(valid) return self._isValid def", "set the current state of validity for this request. :param", "the **valid** parameter), it will set the current state of", "withoutBlockInCountry(self, line): \"\"\"This request was for bridges not blocked in", "not blocked in **country**. Add any country code found in", "which are sent to the email distributor. bridgedb.email.request ====================== Classes", "TYPE found in the **line** to the list of ``transports``.", "the email distributor.\"\"\" def __init__(self): \"\"\"Process a new bridge request", "([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP) #: A regular expression that matches", "for request.\") request.generateFilters() return request class EmailBridgeRequest(bridgerequest.BridgeRequestBase): \"\"\"We received a", "a specific Pluggable Transport identifier. Add any Pluggable Transport method", "client requested our GnuPG key. :rtype: :class:`EmailBridgeRequest` :returns: A :class:`~bridgerequst.BridgeRequest`", "whether this bridge request wanted our GnuPG key. If called", "<<EMAIL>> # please also see AUTHORS file # :copyright: (c)", "transport = TRANSPORT_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if transport: self.transports.append(transport)", "a new bridge request received through the :class:`~bridgedb.Dist.EmailBasedDistributor`. \"\"\" super(EmailBridgeRequest,", "# # This file is part of BridgeDB, a Tor", "a copy of our GnuPG key.\") if \"ipv6\" in line:", "| offer help. |_ EmailBridgeRequest - A request for bridges", "validity state of this request. Otherwise, get the current state.", "``CC`` will *always* be stored as a *lowercase* string. :param", "validity of this bridge request. If called without parameters, this", "from bridgedb import bridgerequest from bridgedb.Dist import EmailRequestedHelp from bridgedb.Dist", "Otherwise, get the current state. \"\"\" if wantsKey is not", "pass if unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email requested bridges not blocked in:", "which :class:`Bridges.BridgeFilter`s to apply, or offer help. .. note:: If", "bool(valid) return self._isValid def wantsKey(self, wantsKey=None): \"\"\"Get or set whether", "Pluggable Transport. \"\"\" transport = None logging.debug(\"Parsing 'transport' line: %r\"", "Figure out which filters to apply, or | offer help.", "line: skippedHeaders = True if not skippedHeaders: continue if (\"help\"", "= False def isValid(self, valid=None): \"\"\"Get or set the validity", "<<EMAIL>> # <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME> <<EMAIL>> # please", "\"\"\" transport = None logging.debug(\"Parsing 'transport' line: %r\" % line)", "# <NAME> <<EMAIL>> # please also see AUTHORS file #", "from bridgedb.Dist import EmailRequestedHelp from bridgedb.Dist import EmailRequestedKey #: A", "filters to apply, or | offer help. |_ EmailBridgeRequest -", "unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email requested bridges not blocked in: %r\" %", "# :copyright: (c) 2007-2015, The Tor Project, Inc. # (c)", "BridgeDB, a Tor bridge distribution system. # # :authors: <NAME>", "# # :authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 #", "for matching the Pluggable Transport method TYPE in #: emailed", "\"\"\"This request included a specific Pluggable Transport identifier. Add any", "without parameters, this method will return the current state, otherwise", "This file is part of BridgeDB, a Tor bridge distribution", "= False for line in lines: line = line.strip().lower() #", "EmailRequestedKey(\"Email requested a copy of our GnuPG key.\") if \"ipv6\"", "0xA3ADB67A2CDB8B35 # <NAME> <<EMAIL>> # please also see AUTHORS file", "otherwise (if called with the **wantsKey** parameter set), it will", "or bridges not blocked in a specific CC (``'unblocked CC'``),", "= EmailBridgeRequest() skippedHeaders = False for line in lines: line", "= \".*transport ([a-z][_a-z0-9]*)\" TRANSPORT_PATTERN = re.compile(TRANSPORT_REGEXP) #: A regular expression", "request.withoutBlockInCountry(line) logging.debug(\"Generating hashring filters for request.\") request.generateFilters() return request class", "email, including the headers. :raises EmailRequestedHelp: if the client requested", "to the list of ``transports``. Currently, a request for a", "our key. :param bool wantsKey: If given, set the validity", "wanted our key. :param bool wantsKey: If given, set the", "the current state. \"\"\" if wantsKey is not None: self._wantsKey", "requests for bridges which are sent to the email distributor.", "LICENSE for licensing information #_____________________________________________________________________________ \"\"\" .. py:module:: bridgedb.email.request :synopsis:", "line contains the ``'unblocked'`` command. :param str country: The line", "key.\") if \"ipv6\" in line: request.withIPv6() if \"transport\" in line:", "def withoutBlockInCountry(self, line): \"\"\"This request was for bridges not blocked", "apply, or offer help. .. note:: If any ``'transport TYPE'``", ":class:`~bridgerequst.BridgeRequest` with all of the requested parameters set. The returned", "Tor bridge distribution system. # # :authors: <NAME> <<EMAIL>> #", "try: transport = TRANSPORT_PATTERN.match(line).group(1) except (TypeError, AttributeError): pass if transport:", "**valid** parameter), it will set the current state of validity", "bridges not blocked in: %r\" % unblocked) def withPluggableTransportType(self, line):", "line: request.withoutBlockInCountry(line) logging.debug(\"Generating hashring filters for request.\") request.generateFilters() return request", "request. Otherwise, get the current state. \"\"\" if wantsKey is", "get the current state. \"\"\" if valid is not None:", "will have already had its filters generated via :meth:`~EmailBridgeRequest.generateFilters`. \"\"\"", "in lines: line = line.strip().lower() # Ignore all lines before", "True if not skippedHeaders: continue if (\"help\" in line) or", "client requested some type of Pluggable Transport. \"\"\" transport =", "``BridgeRequest`` will have already had its filters generated via :meth:`~EmailBridgeRequest.generateFilters`.", "bridges. UNBLOCKED_REGEXP = \".*unblocked ([a-z]{2,4})\" UNBLOCKED_PATTERN = re.compile(UNBLOCKED_REGEXP) def determineBridgeRequestOptions(lines):", ":license: see LICENSE for licensing information #_____________________________________________________________________________ \"\"\" .. py:module::", "valid=None): \"\"\"Get or set the validity of this bridge request.", "set the current state for whether or not this request", "Isis Lovecruft # :license: see LICENSE for licensing information #_____________________________________________________________________________", "``notBlockedIn``. Currently, a request for a transport is recognized if", ":param str line: The line from the email wherein the", "request.wantsKey(True) raise EmailRequestedKey(\"Email requested a copy of our GnuPG key.\")", "to the email distributor. :: bridgedb.email.request | |_ determineBridgeRequestOptions -", "for parsing and storing information about requests for bridges which", "to apply, or offer help. .. note:: If any ``'transport", "command. :param str country: The line from the email wherein", "request.withIPv6() if \"transport\" in line: request.withPluggableTransportType(line) if \"unblocked\" in line:", "key. :rtype: :class:`EmailBridgeRequest` :returns: A :class:`~bridgerequst.BridgeRequest` with all of the", "or | offer help. |_ EmailBridgeRequest - A request for", "bridgedb.Dist import EmailRequestedHelp from bridgedb.Dist import EmailRequestedKey #: A regular", "recognized if the email line contains the ``'unblocked'`` command. :param", "and storing information about requests for bridges which are sent", "``TYPE`` and/or ``CC`` will *always* be stored as a *lowercase*", "wherein the client requested some type of Pluggable Transport. \"\"\"", ":param str country: The line from the email wherein the", "not this request wanted our key. :param bool wantsKey: If", "(TypeError, AttributeError): pass if unblocked: self.notBlockedIn.append(unblocked) logging.info(\"Email requested bridges not", "the Pluggable Transport method TYPE in #: emailed requests for", "request was for bridges not blocked in **country**. Add any", "found in the **line** to the list of ``notBlockedIn``. Currently,", "requested parameters set. The returned ``BridgeRequest`` will have already had", "of ``transports``. Currently, a request for a transport is recognized", "def withPluggableTransportType(self, line): \"\"\"This request included a specific Pluggable Transport", "was valid.\") if \"key\" in line: request.wantsKey(True) raise EmailRequestedKey(\"Email requested", "method TYPE found in the **line** to the list of", "list of lines from an email, including the headers. :raises", "distributor. :: bridgedb.email.request | |_ determineBridgeRequestOptions - Figure out which", "which are sent to the email distributor. :: bridgedb.email.request |", "is recognized if the email line contains the ``'unblocked'`` command.", "first empty line: if not line: skippedHeaders = True if", "| |_ determineBridgeRequestOptions - Figure out which filters to apply,", "the requested parameters set. The returned ``BridgeRequest`` will have already", "for bridges through the email distributor.\"\"\" def __init__(self): \"\"\"Process a", "any ``'transport TYPE'`` was requested, or bridges not blocked in", "%r\" % unblocked) def withPluggableTransportType(self, line): \"\"\"This request included a" ]
[ "Module docstring \"\"\" def _impl(_ctx): \"\"\" Function docstring \"\"\" pass", "<gh_stars>1000+ \"\"\" Module docstring \"\"\" def _impl(_ctx): \"\"\" Function docstring", "= { \"attr1\": attr.int( default = 2, mandatory = False,", "mandatory = False, ), \"attr2\": 5, }, implementation = _impl,", "attrs = { \"attr1\": attr.int( default = 2, mandatory =", "docstring \"\"\" def _impl(_ctx): \"\"\" Function docstring \"\"\" pass some_rule", "attr.int( default = 2, mandatory = False, ), \"attr2\": 5,", "= 2, mandatory = False, ), \"attr2\": 5, }, implementation", "def _impl(_ctx): \"\"\" Function docstring \"\"\" pass some_rule = rule(", "\"\"\" Function docstring \"\"\" pass some_rule = rule( attrs =", "{ \"attr1\": attr.int( default = 2, mandatory = False, ),", "_impl(_ctx): \"\"\" Function docstring \"\"\" pass some_rule = rule( attrs", "docstring \"\"\" pass some_rule = rule( attrs = { \"attr1\":", "= rule( attrs = { \"attr1\": attr.int( default = 2,", "2, mandatory = False, ), \"attr2\": 5, }, implementation =", "pass some_rule = rule( attrs = { \"attr1\": attr.int( default", "Function docstring \"\"\" pass some_rule = rule( attrs = {", "\"\"\" Module docstring \"\"\" def _impl(_ctx): \"\"\" Function docstring \"\"\"", "default = 2, mandatory = False, ), \"attr2\": 5, },", "\"\"\" def _impl(_ctx): \"\"\" Function docstring \"\"\" pass some_rule =", "some_rule = rule( attrs = { \"attr1\": attr.int( default =", "\"attr1\": attr.int( default = 2, mandatory = False, ), \"attr2\":", "\"\"\" pass some_rule = rule( attrs = { \"attr1\": attr.int(", "= False, ), \"attr2\": 5, }, implementation = _impl, )", "rule( attrs = { \"attr1\": attr.int( default = 2, mandatory" ]
[ ": result['mobile'], \"depName\" : result['depName'], \"IFSC\" : result['IFSC'], \"ACNo\" :", "\"SELECT e.*, b.*, d.`depName` \" sql += \"FROM `employees` e,", "result['pin'], \"state\" : result['state'], \"adharID\" : result['adharID'], \"panID\" : result['panID'],", "+=\"WHERE e.`empID` = b.`empdb_empID` \" sql +=\"AND e.`depDB_depID` = d.`depID`", ") # self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName']) # self.entry_text(self.entry_personalno,", "`employees` e, `baccounts` b, `departments` d \" sql +=\"WHERE e.`empID`", "static_file.write(content) webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName'] ) # self.entry_text(self.entry_EmpID, result['empID'])", "} content = template.render(template_vars) with open('print.html', 'w') as static_file: static_file.write(content)", "import print_function from connection import * from jinja2 import Environment,", "result['email'], \"mobile\" : result['mobile'], \"depName\" : result['depName'], \"IFSC\" : result['IFSC'],", "result = result[0] print(result) template_vars = {\"empID\" : result['empID'], \"firstName\"", "e.`empID` = '\"+ id +\"'\" # print(sql) cursor.execute(sql) result =", "# self.entry_text(self.entry_personalno, result['empID']) # self.entry_text(self.entry_address,result['address'] ) # self.entry_text(self.entry_pin, result['pin']) #", "\"+result['lastName'] ) # self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName']) #", "\"FROM `employees` e, `baccounts` b, `departments` d \" sql +=\"WHERE", "result['mobile']) # self.entry_text(self.entry_department, result['depName']) # self.entry_text(self.entry_ifsc, result['IFSC']) # self.entry_text(self.enrtry_acno, result['ACNo'])", "self.entry_text(self.entry_mobile, result['mobile']) # self.entry_text(self.entry_department, result['depName']) # self.entry_text(self.entry_ifsc, result['IFSC']) # self.entry_text(self.enrtry_acno,", "open('print.html', 'w') as static_file: static_file.write(content) webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName']", "d.`depName` \" sql += \"FROM `employees` e, `baccounts` b, `departments`", "b, `departments` d \" sql +=\"WHERE e.`empID` = b.`empdb_empID` \"", "# self.entry_text(self.entry_pin, result['pin']) # self.entry_text(self.entry_state, result['state']) # self.entry_text(self.entry_adhar, result['adharID']) #", "result['state'], \"adharID\" : result['adharID'], \"panID\" : result['panID'], \"designation\" : result['designation'],", "result['email']) # self.entry_text(self.entry_mobile, result['mobile']) # self.entry_text(self.entry_department, result['depName']) # self.entry_text(self.entry_ifsc, result['IFSC'])", "'\"+ id +\"'\" # print(sql) cursor.execute(sql) result = cursor.fetchall() #", "template.render(template_vars) with open('print.html', 'w') as static_file: static_file.write(content) webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name,", "# self.entry_text(self.entry_state, result['state']) # self.entry_text(self.entry_adhar, result['adharID']) # self.entry_text(self.entry_pan, result['panID']) #", "env.get_template(\"src/template.html\") cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = \"SELECT e.*, b.*, d.`depName`", "\"depName\" : result['depName'], \"IFSC\" : result['IFSC'], \"ACNo\" : result['ACNo'], \"BranchAdd\"", "import * from jinja2 import Environment, FileSystemLoader import webbrowser def", "self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName']) # self.entry_text(self.entry_personalno, result['empID']) #", "{\"empID\" : result['empID'], \"firstName\" : result['firstName'], \"lastName\" : result['lastName'], \"address\"", "* from jinja2 import Environment, FileSystemLoader import webbrowser def print_report(id):", "+= \"FROM `employees` e, `baccounts` b, `departments` d \" sql", "\"unit\" : result['unit'], \"email\" : result['email'], \"mobile\" : result['mobile'], \"depName\"", "id +\"'\" # print(sql) cursor.execute(sql) result = cursor.fetchall() # print(result[0])", "jinja2 import Environment, FileSystemLoader import webbrowser def print_report(id): env =", "result['BranchAdd'] } content = template.render(template_vars) with open('print.html', 'w') as static_file:", "= '\"+ id +\"'\" # print(sql) cursor.execute(sql) result = cursor.fetchall()", "= {\"empID\" : result['empID'], \"firstName\" : result['firstName'], \"lastName\" : result['lastName'],", "# self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName']) # self.entry_text(self.entry_personalno, result['empID'])", "d \" sql +=\"WHERE e.`empID` = b.`empdb_empID` \" sql +=\"AND", "# self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName'] ) # self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName,", "print(result[0]) result = result[0] print(result) template_vars = {\"empID\" : result['empID'],", "\"lastName\" : result['lastName'], \"address\" : result['address'], \"pin\" : result['pin'], \"state\"", "'w') as static_file: static_file.write(content) webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName'] )", "result['panID']) # self.entry_text(self.entry_designation, result['designation']) # self.entry_text(self.entry_unit, result['unit']) # self.entry_text(self.entry_emailid, result['email'])", "result['empID']) # self.entry_text(self.entry_address,result['address'] ) # self.entry_text(self.entry_pin, result['pin']) # self.entry_text(self.entry_state, result['state'])", "result['adharID']) # self.entry_text(self.entry_pan, result['panID']) # self.entry_text(self.entry_designation, result['designation']) # self.entry_text(self.entry_unit, result['unit'])", "+=\"AND e.`empID` = '\"+ id +\"'\" # print(sql) cursor.execute(sql) result", "\" sql +=\"AND e.`empID` = '\"+ id +\"'\" # print(sql)", "self.entry_text(self.entry_pan, result['panID']) # self.entry_text(self.entry_designation, result['designation']) # self.entry_text(self.entry_unit, result['unit']) # self.entry_text(self.entry_emailid,", "\"BranchAdd\" : result['BranchAdd'] } content = template.render(template_vars) with open('print.html', 'w')", "webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName'] ) # self.entry_text(self.entry_EmpID, result['empID']) #", "result['address'], \"pin\" : result['pin'], \"state\" : result['state'], \"adharID\" : result['adharID'],", "# self.entry_text(self.entry_adhar, result['adharID']) # self.entry_text(self.entry_pan, result['panID']) # self.entry_text(self.entry_designation, result['designation']) #", "result['ACNo'], \"BranchAdd\" : result['BranchAdd'] } content = template.render(template_vars) with open('print.html',", "\"address\" : result['address'], \"pin\" : result['pin'], \"state\" : result['state'], \"adharID\"", "= cursor.fetchall() # print(result[0]) result = result[0] print(result) template_vars =", "self.entry_text(self.entry_department, result['depName']) # self.entry_text(self.entry_ifsc, result['IFSC']) # self.entry_text(self.enrtry_acno, result['ACNo']) # self.entry_text(self.entry_branch,", ": result['ACNo'], \"BranchAdd\" : result['BranchAdd'] } content = template.render(template_vars) with", "\"designation\" : result['designation'], \"unit\" : result['unit'], \"email\" : result['email'], \"mobile\"", "result['unit']) # self.entry_text(self.entry_emailid, result['email']) # self.entry_text(self.entry_mobile, result['mobile']) # self.entry_text(self.entry_department, result['depName'])", "\" sql += \"FROM `employees` e, `baccounts` b, `departments` d", "content = template.render(template_vars) with open('print.html', 'w') as static_file: static_file.write(content) webbrowser.open_new_tab('print.html')", "result['depName']) # self.entry_text(self.entry_ifsc, result['IFSC']) # self.entry_text(self.enrtry_acno, result['ACNo']) # self.entry_text(self.entry_branch, result['BranchAdd'])", "Environment(loader=FileSystemLoader('.')) template = env.get_template(\"src/template.html\") cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = \"SELECT", "self.entry_text(self.entry_personalno, result['empID']) # self.entry_text(self.entry_address,result['address'] ) # self.entry_text(self.entry_pin, result['pin']) # self.entry_text(self.entry_state,", "= result[0] print(result) template_vars = {\"empID\" : result['empID'], \"firstName\" :", "result['depName'], \"IFSC\" : result['IFSC'], \"ACNo\" : result['ACNo'], \"BranchAdd\" : result['BranchAdd']", "result['state']) # self.entry_text(self.entry_adhar, result['adharID']) # self.entry_text(self.entry_pan, result['panID']) # self.entry_text(self.entry_designation, result['designation'])", "template_vars = {\"empID\" : result['empID'], \"firstName\" : result['firstName'], \"lastName\" :", "sql +=\"AND e.`depDB_depID` = d.`depID` \" sql +=\"AND e.`empID` =", "b.*, d.`depName` \" sql += \"FROM `employees` e, `baccounts` b,", "\"+result['lastName']) # self.entry_text(self.entry_personalno, result['empID']) # self.entry_text(self.entry_address,result['address'] ) # self.entry_text(self.entry_pin, result['pin'])", ": result['address'], \"pin\" : result['pin'], \"state\" : result['state'], \"adharID\" :", "result['adharID'], \"panID\" : result['panID'], \"designation\" : result['designation'], \"unit\" : result['unit'],", "self.entry_text(self.entry_adhar, result['adharID']) # self.entry_text(self.entry_pan, result['panID']) # self.entry_text(self.entry_designation, result['designation']) # self.entry_text(self.entry_unit,", "= \"SELECT e.*, b.*, d.`depName` \" sql += \"FROM `employees`", "def print_report(id): env = Environment(loader=FileSystemLoader('.')) template = env.get_template(\"src/template.html\") cursor =", "self.entry_text(self.entry_emailid, result['email']) # self.entry_text(self.entry_mobile, result['mobile']) # self.entry_text(self.entry_department, result['depName']) # self.entry_text(self.entry_ifsc,", "self.entry_text(self.entry_designation, result['designation']) # self.entry_text(self.entry_unit, result['unit']) # self.entry_text(self.entry_emailid, result['email']) # self.entry_text(self.entry_mobile,", "sql +=\"WHERE e.`empID` = b.`empdb_empID` \" sql +=\"AND e.`depDB_depID` =", "\"pin\" : result['pin'], \"state\" : result['state'], \"adharID\" : result['adharID'], \"panID\"", "cursor.fetchall() # print(result[0]) result = result[0] print(result) template_vars = {\"empID\"", "self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName']) # self.entry_text(self.entry_personalno, result['empID']) # self.entry_text(self.entry_address,result['address'] ) #", "env = Environment(loader=FileSystemLoader('.')) template = env.get_template(\"src/template.html\") cursor = db.cursor(MySQLdb.cursors.DictCursor) sql", "e.`empID` = b.`empdb_empID` \" sql +=\"AND e.`depDB_depID` = d.`depID` \"", "result['lastName'], \"address\" : result['address'], \"pin\" : result['pin'], \"state\" : result['state'],", "+=\"AND e.`depDB_depID` = d.`depID` \" sql +=\"AND e.`empID` = '\"+", "`departments` d \" sql +=\"WHERE e.`empID` = b.`empdb_empID` \" sql", "template = env.get_template(\"src/template.html\") cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = \"SELECT e.*,", "# self.entry_text(self.entry_mobile, result['mobile']) # self.entry_text(self.entry_department, result['depName']) # self.entry_text(self.entry_ifsc, result['IFSC']) #", "result['pin']) # self.entry_text(self.entry_state, result['state']) # self.entry_text(self.entry_adhar, result['adharID']) # self.entry_text(self.entry_pan, result['panID'])", "sql = \"SELECT e.*, b.*, d.`depName` \" sql += \"FROM", "`baccounts` b, `departments` d \" sql +=\"WHERE e.`empID` = b.`empdb_empID`", "d.`depID` \" sql +=\"AND e.`empID` = '\"+ id +\"'\" #", "b.`empdb_empID` \" sql +=\"AND e.`depDB_depID` = d.`depID` \" sql +=\"AND", "\"ACNo\" : result['ACNo'], \"BranchAdd\" : result['BranchAdd'] } content = template.render(template_vars)", "print_report(id): env = Environment(loader=FileSystemLoader('.')) template = env.get_template(\"src/template.html\") cursor = db.cursor(MySQLdb.cursors.DictCursor)", "= Environment(loader=FileSystemLoader('.')) template = env.get_template(\"src/template.html\") cursor = db.cursor(MySQLdb.cursors.DictCursor) sql =", "<filename>src/printReport.py from __future__ import print_function from connection import * from", ": result['panID'], \"designation\" : result['designation'], \"unit\" : result['unit'], \"email\" :", "# self.entry_text(self.entry_unit, result['unit']) # self.entry_text(self.entry_emailid, result['email']) # self.entry_text(self.entry_mobile, result['mobile']) #", "e.`depDB_depID` = d.`depID` \" sql +=\"AND e.`empID` = '\"+ id", "__future__ import print_function from connection import * from jinja2 import", "# self.entry_text(self.entry_emailid, result['email']) # self.entry_text(self.entry_mobile, result['mobile']) # self.entry_text(self.entry_department, result['depName']) #", "= d.`depID` \" sql +=\"AND e.`empID` = '\"+ id +\"'\"", "\" sql +=\"AND e.`depDB_depID` = d.`depID` \" sql +=\"AND e.`empID`", "self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName'] ) # self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+\"", "print_function from connection import * from jinja2 import Environment, FileSystemLoader", "self.entry_text(self.entry_pin, result['pin']) # self.entry_text(self.entry_state, result['state']) # self.entry_text(self.entry_adhar, result['adharID']) # self.entry_text(self.entry_pan,", "# self.entry_text(self.entry_pan, result['panID']) # self.entry_text(self.entry_designation, result['designation']) # self.entry_text(self.entry_unit, result['unit']) #", "print(result) template_vars = {\"empID\" : result['empID'], \"firstName\" : result['firstName'], \"lastName\"", ": result['state'], \"adharID\" : result['adharID'], \"panID\" : result['panID'], \"designation\" :", "= db.cursor(MySQLdb.cursors.DictCursor) sql = \"SELECT e.*, b.*, d.`depName` \" sql", "# self.entry_text(self.entry_address,result['address'] ) # self.entry_text(self.entry_pin, result['pin']) # self.entry_text(self.entry_state, result['state']) #", ": result['adharID'], \"panID\" : result['panID'], \"designation\" : result['designation'], \"unit\" :", "cursor.execute(sql) result = cursor.fetchall() # print(result[0]) result = result[0] print(result)", ": result['firstName'], \"lastName\" : result['lastName'], \"address\" : result['address'], \"pin\" :", "= env.get_template(\"src/template.html\") cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = \"SELECT e.*, b.*,", "static_file: static_file.write(content) webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName'] ) # self.entry_text(self.entry_EmpID,", ": result['lastName'], \"address\" : result['address'], \"pin\" : result['pin'], \"state\" :", ": result['pin'], \"state\" : result['state'], \"adharID\" : result['adharID'], \"panID\" :", ": result['IFSC'], \"ACNo\" : result['ACNo'], \"BranchAdd\" : result['BranchAdd'] } content", "import webbrowser def print_report(id): env = Environment(loader=FileSystemLoader('.')) template = env.get_template(\"src/template.html\")", "# self.entry_text(self.entry_department, result['depName']) # self.entry_text(self.entry_ifsc, result['IFSC']) # self.entry_text(self.enrtry_acno, result['ACNo']) #", "# print(sql) cursor.execute(sql) result = cursor.fetchall() # print(result[0]) result =", "as static_file: static_file.write(content) webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name, result['firstName']+\" \"+result['lastName'] ) #", "result['firstName'], \"lastName\" : result['lastName'], \"address\" : result['address'], \"pin\" : result['pin'],", "sql +=\"AND e.`empID` = '\"+ id +\"'\" # print(sql) cursor.execute(sql)", "result['firstName']+\" \"+result['lastName'] ) # self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName'])", "\"adharID\" : result['adharID'], \"panID\" : result['panID'], \"designation\" : result['designation'], \"unit\"", "result['firstName']+\" \"+result['lastName']) # self.entry_text(self.entry_personalno, result['empID']) # self.entry_text(self.entry_address,result['address'] ) # self.entry_text(self.entry_pin,", "result['empID'], \"firstName\" : result['firstName'], \"lastName\" : result['lastName'], \"address\" : result['address'],", "\" sql +=\"WHERE e.`empID` = b.`empdb_empID` \" sql +=\"AND e.`depDB_depID`", "from jinja2 import Environment, FileSystemLoader import webbrowser def print_report(id): env", "# self.entry_text(self.entry_designation, result['designation']) # self.entry_text(self.entry_unit, result['unit']) # self.entry_text(self.entry_emailid, result['email']) #", "\"state\" : result['state'], \"adharID\" : result['adharID'], \"panID\" : result['panID'], \"designation\"", "from connection import * from jinja2 import Environment, FileSystemLoader import", "result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName']) # self.entry_text(self.entry_personalno, result['empID']) # self.entry_text(self.entry_address,result['address']", ": result['empID'], \"firstName\" : result['firstName'], \"lastName\" : result['lastName'], \"address\" :", "from __future__ import print_function from connection import * from jinja2", "with open('print.html', 'w') as static_file: static_file.write(content) webbrowser.open_new_tab('print.html') # self.entry_text(self.entry_name, result['firstName']+\"", "FileSystemLoader import webbrowser def print_report(id): env = Environment(loader=FileSystemLoader('.')) template =", "self.entry_text(self.entry_unit, result['unit']) # self.entry_text(self.entry_emailid, result['email']) # self.entry_text(self.entry_mobile, result['mobile']) # self.entry_text(self.entry_department,", ": result['email'], \"mobile\" : result['mobile'], \"depName\" : result['depName'], \"IFSC\" :", "db.cursor(MySQLdb.cursors.DictCursor) sql = \"SELECT e.*, b.*, d.`depName` \" sql +=", "+\"'\" # print(sql) cursor.execute(sql) result = cursor.fetchall() # print(result[0]) result", "\"firstName\" : result['firstName'], \"lastName\" : result['lastName'], \"address\" : result['address'], \"pin\"", "result = cursor.fetchall() # print(result[0]) result = result[0] print(result) template_vars", ": result['BranchAdd'] } content = template.render(template_vars) with open('print.html', 'w') as", "= template.render(template_vars) with open('print.html', 'w') as static_file: static_file.write(content) webbrowser.open_new_tab('print.html') #", "result['panID'], \"designation\" : result['designation'], \"unit\" : result['unit'], \"email\" : result['email'],", "connection import * from jinja2 import Environment, FileSystemLoader import webbrowser", "\"mobile\" : result['mobile'], \"depName\" : result['depName'], \"IFSC\" : result['IFSC'], \"ACNo\"", "result['designation'], \"unit\" : result['unit'], \"email\" : result['email'], \"mobile\" : result['mobile'],", "\"panID\" : result['panID'], \"designation\" : result['designation'], \"unit\" : result['unit'], \"email\"", "result['IFSC'], \"ACNo\" : result['ACNo'], \"BranchAdd\" : result['BranchAdd'] } content =", "# self.entry_text(self.entry_EmpName, result['firstName']+\" \"+result['lastName']) # self.entry_text(self.entry_personalno, result['empID']) # self.entry_text(self.entry_address,result['address'] )", "self.entry_text(self.entry_state, result['state']) # self.entry_text(self.entry_adhar, result['adharID']) # self.entry_text(self.entry_pan, result['panID']) # self.entry_text(self.entry_designation,", "result['designation']) # self.entry_text(self.entry_unit, result['unit']) # self.entry_text(self.entry_emailid, result['email']) # self.entry_text(self.entry_mobile, result['mobile'])", "\"email\" : result['email'], \"mobile\" : result['mobile'], \"depName\" : result['depName'], \"IFSC\"", "sql += \"FROM `employees` e, `baccounts` b, `departments` d \"", "print(sql) cursor.execute(sql) result = cursor.fetchall() # print(result[0]) result = result[0]", "# print(result[0]) result = result[0] print(result) template_vars = {\"empID\" :", "e, `baccounts` b, `departments` d \" sql +=\"WHERE e.`empID` =", "Environment, FileSystemLoader import webbrowser def print_report(id): env = Environment(loader=FileSystemLoader('.')) template", "result['unit'], \"email\" : result['email'], \"mobile\" : result['mobile'], \"depName\" : result['depName'],", ": result['depName'], \"IFSC\" : result['IFSC'], \"ACNo\" : result['ACNo'], \"BranchAdd\" :", "webbrowser def print_report(id): env = Environment(loader=FileSystemLoader('.')) template = env.get_template(\"src/template.html\") cursor", "cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = \"SELECT e.*, b.*, d.`depName` \"", "e.*, b.*, d.`depName` \" sql += \"FROM `employees` e, `baccounts`", "self.entry_text(self.entry_address,result['address'] ) # self.entry_text(self.entry_pin, result['pin']) # self.entry_text(self.entry_state, result['state']) # self.entry_text(self.entry_adhar,", "= b.`empdb_empID` \" sql +=\"AND e.`depDB_depID` = d.`depID` \" sql", "\"IFSC\" : result['IFSC'], \"ACNo\" : result['ACNo'], \"BranchAdd\" : result['BranchAdd'] }", "import Environment, FileSystemLoader import webbrowser def print_report(id): env = Environment(loader=FileSystemLoader('.'))", ": result['unit'], \"email\" : result['email'], \"mobile\" : result['mobile'], \"depName\" :", ": result['designation'], \"unit\" : result['unit'], \"email\" : result['email'], \"mobile\" :", "result[0] print(result) template_vars = {\"empID\" : result['empID'], \"firstName\" : result['firstName'],", "result['mobile'], \"depName\" : result['depName'], \"IFSC\" : result['IFSC'], \"ACNo\" : result['ACNo'],", ") # self.entry_text(self.entry_pin, result['pin']) # self.entry_text(self.entry_state, result['state']) # self.entry_text(self.entry_adhar, result['adharID'])" ]
[ "= ','.join(schema.render(renderer=renderer, value=item, workload=workload, incognito=True)) # and put it on", "not appropriate here; the user may want {None} as the", "are sequences of other types \"\"\" # constants typename =", "class for type declarators that are sequences of other types", "class Container(Schema): \"\"\" The base class for type declarators that", "yield renderer.trait(name=self.name, value='') # go through the items for item", "not supplied: use a TYPE (in this # case object)", "value, **kwds): \"\"\" Convert {value} into an iterable \"\"\" #", "into my container type and return it return self.container(self._coerce(value=value, **kwds))", "all end up using the same global container # checking", "{container} type\".format(type(self))) # interface def coerce(self, value, **kwds): \"\"\" Convert", "# get my schema schema = self.schema # render just", "incognito=True)) # and put it on a separate line yield", "\"class {.__name__} must define a {container} type\".format(type(self))) # interface def", "schema = self.schema # render just my name yield renderer.trait(name=self.name,", "declaration class Container(Schema): \"\"\" The base class for type declarators", "= True @property def container(self): \"\"\" The default container represented", "my name yield renderer.trait(name=self.name, value='') # go through the items", "line yield renderer.value(value=f\"{entry},\") # all done return # meta-methods def", "same global container # checking for {None} is not appropriate", "# -*- coding: utf-8 -*- # # <NAME> # orthologue", "end up using the same global container # checking for", "object else default # chain up with my default super().__init__(default=default,", "# save my schema self.schema = schema # all done", "schema self.schema = schema # all done return # end", "as the marker default = self.container() if default is object", "entry = ','.join(schema.render(renderer=renderer, value=item, workload=workload, incognito=True)) # and put it", "= self.container() if default is object else default # chain", "# orthologue # (c) 1998-2021 all rights reserved # #", "define a {container} type\".format(type(self))) # interface def coerce(self, value, **kwds):", "the worker to build an iterable, cast it into my", "one entry = ','.join(schema.render(renderer=renderer, value=item, workload=workload, incognito=True)) # and put", "# case object) as the marker default = self.container() if", "may want {None} as the default # value; we need", "case object) as the marker default = self.container() if default", "the name of my type isContainer = True @property def", "Render {value} using {renderer} \"\"\" # get my schema schema", "# value; we need a way to know that {default}", "up using the same global container # checking for {None}", "\"\"\" # constants typename = 'container' # the name of", "item in value: # ask my schema to render each", "was not supplied: use a TYPE (in this # case", "to build an iterable, cast it into my container type", "# superclass from .Schema import Schema # declaration class Container(Schema):", "this schema \"\"\" # complain that the subclass is not", "default is object else default # chain up with my", "as the default # value; we need a way to", "coding: utf-8 -*- # # <NAME> # orthologue # (c)", "into an iterable \"\"\" # get the worker to build", "it return self.container(self._coerce(value=value, **kwds)) def render(self, renderer, value, workload): \"\"\"", "workload=workload, incognito=True)) # and put it on a separate line", "an iterable \"\"\" # get the worker to build an", "# interface def coerce(self, value, **kwds): \"\"\" Convert {value} into", "self.container(self._coerce(value=value, **kwds)) def render(self, renderer, value, workload): \"\"\" Render {value}", "my schema to render each one entry = ','.join(schema.render(renderer=renderer, value=item,", "rights reserved # # superclass from .Schema import Schema #", "the default; carefully, so we don't all end up using", "all rights reserved # # superclass from .Schema import Schema", "way to know that {default} was not supplied: use a", "iterable, cast it into my container type and return it", "that {default} was not supplied: use a TYPE (in this", "**kwds): # adjust the default; carefully, so we don't all", "the marker default = self.container() if default is object else", "# chain up with my default super().__init__(default=default, **kwds) # save", "a way to know that {default} was not supplied: use", "value; we need a way to know that {default} was", "# the name of my type isContainer = True @property", "use a TYPE (in this # case object) as the", "self.container() if default is object else default # chain up", "The base class for type declarators that are sequences of", "renderer.trait(name=self.name, value='') # go through the items for item in", "ask my schema to render each one entry = ','.join(schema.render(renderer=renderer,", "super().__init__(default=default, **kwds) # save my schema self.schema = schema #", "\"\"\" The base class for type declarators that are sequences", "# go through the items for item in value: #", "# adjust the default; carefully, so we don't all end", "schema schema = self.schema # render just my name yield", "render(self, renderer, value, workload): \"\"\" Render {value} using {renderer} \"\"\"", "= self.schema # render just my name yield renderer.trait(name=self.name, value='')", "{.__name__} must define a {container} type\".format(type(self))) # interface def coerce(self,", "default container represented by this schema \"\"\" # complain that", "it on a separate line yield renderer.value(value=f\"{entry},\") # all done", "this # case object) as the marker default = self.container()", "Convert {value} into an iterable \"\"\" # get the worker", "type declarators that are sequences of other types \"\"\" #", "def coerce(self, value, **kwds): \"\"\" Convert {value} into an iterable", "on a separate line yield renderer.value(value=f\"{entry},\") # all done return", "render each one entry = ','.join(schema.render(renderer=renderer, value=item, workload=workload, incognito=True)) #", "# render just my name yield renderer.trait(name=self.name, value='') # go", "','.join(schema.render(renderer=renderer, value=item, workload=workload, incognito=True)) # and put it on a", "my default super().__init__(default=default, **kwds) # save my schema self.schema =", "of my type isContainer = True @property def container(self): \"\"\"", "(c) 1998-2021 all rights reserved # # superclass from .Schema", "properly raise NotImplementedError( \"class {.__name__} must define a {container} type\".format(type(self)))", "a {container} type\".format(type(self))) # interface def coerce(self, value, **kwds): \"\"\"", "interface def coerce(self, value, **kwds): \"\"\" Convert {value} into an", "my container type and return it return self.container(self._coerce(value=value, **kwds)) def", "container type and return it return self.container(self._coerce(value=value, **kwds)) def render(self,", "my type isContainer = True @property def container(self): \"\"\" The", "The default container represented by this schema \"\"\" # complain", "schema to render each one entry = ','.join(schema.render(renderer=renderer, value=item, workload=workload,", "default # chain up with my default super().__init__(default=default, **kwds) #", "to render each one entry = ','.join(schema.render(renderer=renderer, value=item, workload=workload, incognito=True))", "# constants typename = 'container' # the name of my", "a TYPE (in this # case object) as the marker", "# get the worker to build an iterable, cast it", "the user may want {None} as the default # value;", "from .Schema import Schema # declaration class Container(Schema): \"\"\" The", "user may want {None} as the default # value; we", "coerce(self, value, **kwds): \"\"\" Convert {value} into an iterable \"\"\"", "Schema # declaration class Container(Schema): \"\"\" The base class for", "build an iterable, cast it into my container type and", "{None} as the default # value; we need a way", "marker default = self.container() if default is object else default", "\"\"\" The default container represented by this schema \"\"\" #", "utf-8 -*- # # <NAME> # orthologue # (c) 1998-2021", "value: # ask my schema to render each one entry", "each one entry = ','.join(schema.render(renderer=renderer, value=item, workload=workload, incognito=True)) # and", "we don't all end up using the same global container", "'container' # the name of my type isContainer = True", "an iterable, cast it into my container type and return", "if default is object else default # chain up with", "save my schema self.schema = schema # all done return", "of other types \"\"\" # constants typename = 'container' #", "return # meta-methods def __init__(self, default=object, schema=Schema(), **kwds): # adjust", "__init__(self, default=object, schema=Schema(), **kwds): # adjust the default; carefully, so", "# checking for {None} is not appropriate here; the user", "name yield renderer.trait(name=self.name, value='') # go through the items for", "\"\"\" # get my schema schema = self.schema # render", "is object else default # chain up with my default", "base class for type declarators that are sequences of other", "constructed properly raise NotImplementedError( \"class {.__name__} must define a {container}", "all done return # meta-methods def __init__(self, default=object, schema=Schema(), **kwds):", "type and return it return self.container(self._coerce(value=value, **kwds)) def render(self, renderer,", "items for item in value: # ask my schema to", "\"\"\" Render {value} using {renderer} \"\"\" # get my schema", "supplied: use a TYPE (in this # case object) as", "default = self.container() if default is object else default #", "orthologue # (c) 1998-2021 all rights reserved # # superclass", "chain up with my default super().__init__(default=default, **kwds) # save my", "superclass from .Schema import Schema # declaration class Container(Schema): \"\"\"", "container # checking for {None} is not appropriate here; the", "cast it into my container type and return it return", "using {renderer} \"\"\" # get my schema schema = self.schema", "in value: # ask my schema to render each one", "default; carefully, so we don't all end up using the", "default super().__init__(default=default, **kwds) # save my schema self.schema = schema", "{renderer} \"\"\" # get my schema schema = self.schema #", "get my schema schema = self.schema # render just my", "import Schema # declaration class Container(Schema): \"\"\" The base class", "# and put it on a separate line yield renderer.value(value=f\"{entry},\")", "\"\"\" # complain that the subclass is not constructed properly", "need a way to know that {default} was not supplied:", "default # value; we need a way to know that", "render just my name yield renderer.trait(name=self.name, value='') # go through", "global container # checking for {None} is not appropriate here;", "get the worker to build an iterable, cast it into", "meta-methods def __init__(self, default=object, schema=Schema(), **kwds): # adjust the default;", "schema \"\"\" # complain that the subclass is not constructed", "# <NAME> # orthologue # (c) 1998-2021 all rights reserved", "that the subclass is not constructed properly raise NotImplementedError( \"class", "represented by this schema \"\"\" # complain that the subclass", "here; the user may want {None} as the default #", "the default # value; we need a way to know", "# complain that the subclass is not constructed properly raise", "**kwds): \"\"\" Convert {value} into an iterable \"\"\" # get", "# ask my schema to render each one entry =", ".Schema import Schema # declaration class Container(Schema): \"\"\" The base", "my schema schema = self.schema # render just my name", "# all done return # meta-methods def __init__(self, default=object, schema=Schema(),", "-*- coding: utf-8 -*- # # <NAME> # orthologue #", "the same global container # checking for {None} is not", "other types \"\"\" # constants typename = 'container' # the", "name of my type isContainer = True @property def container(self):", "True @property def container(self): \"\"\" The default container represented by", "put it on a separate line yield renderer.value(value=f\"{entry},\") # all", "{None} is not appropriate here; the user may want {None}", "we need a way to know that {default} was not", "return self.container(self._coerce(value=value, **kwds)) def render(self, renderer, value, workload): \"\"\" Render", "{value} using {renderer} \"\"\" # get my schema schema =", "don't all end up using the same global container #", "just my name yield renderer.trait(name=self.name, value='') # go through the", "\"\"\" # get the worker to build an iterable, cast", "renderer.value(value=f\"{entry},\") # all done return # meta-methods def __init__(self, default=object,", "is not constructed properly raise NotImplementedError( \"class {.__name__} must define", "self.schema = schema # all done return # end of", "the subclass is not constructed properly raise NotImplementedError( \"class {.__name__}", "@property def container(self): \"\"\" The default container represented by this", "iterable \"\"\" # get the worker to build an iterable,", "declarators that are sequences of other types \"\"\" # constants", "sequences of other types \"\"\" # constants typename = 'container'", "value=item, workload=workload, incognito=True)) # and put it on a separate", "types \"\"\" # constants typename = 'container' # the name", "# # superclass from .Schema import Schema # declaration class", "through the items for item in value: # ask my", "checking for {None} is not appropriate here; the user may", "workload): \"\"\" Render {value} using {renderer} \"\"\" # get my", "1998-2021 all rights reserved # # superclass from .Schema import", "isContainer = True @property def container(self): \"\"\" The default container", "= schema # all done return # end of file", "container(self): \"\"\" The default container represented by this schema \"\"\"", "and return it return self.container(self._coerce(value=value, **kwds)) def render(self, renderer, value,", "TYPE (in this # case object) as the marker default", "appropriate here; the user may want {None} as the default", "self.schema # render just my name yield renderer.trait(name=self.name, value='') #", "# meta-methods def __init__(self, default=object, schema=Schema(), **kwds): # adjust the", "not constructed properly raise NotImplementedError( \"class {.__name__} must define a", "it into my container type and return it return self.container(self._coerce(value=value,", "# # <NAME> # orthologue # (c) 1998-2021 all rights", "with my default super().__init__(default=default, **kwds) # save my schema self.schema", "so we don't all end up using the same global", "go through the items for item in value: # ask", "and put it on a separate line yield renderer.value(value=f\"{entry},\") #", "def container(self): \"\"\" The default container represented by this schema", "adjust the default; carefully, so we don't all end up", "{value} into an iterable \"\"\" # get the worker to", "type isContainer = True @property def container(self): \"\"\" The default", "a separate line yield renderer.value(value=f\"{entry},\") # all done return #", "worker to build an iterable, cast it into my container", "done return # meta-methods def __init__(self, default=object, schema=Schema(), **kwds): #", "schema=Schema(), **kwds): # adjust the default; carefully, so we don't", "using the same global container # checking for {None} is", "{default} was not supplied: use a TYPE (in this #", "else default # chain up with my default super().__init__(default=default, **kwds)", "my schema self.schema = schema # all done return #", "the items for item in value: # ask my schema", "**kwds) # save my schema self.schema = schema # all", "def __init__(self, default=object, schema=Schema(), **kwds): # adjust the default; carefully,", "know that {default} was not supplied: use a TYPE (in", "Container(Schema): \"\"\" The base class for type declarators that are", "yield renderer.value(value=f\"{entry},\") # all done return # meta-methods def __init__(self,", "**kwds)) def render(self, renderer, value, workload): \"\"\" Render {value} using", "for {None} is not appropriate here; the user may want", "NotImplementedError( \"class {.__name__} must define a {container} type\".format(type(self))) # interface", "up with my default super().__init__(default=default, **kwds) # save my schema", "must define a {container} type\".format(type(self))) # interface def coerce(self, value,", "-*- # # <NAME> # orthologue # (c) 1998-2021 all", "that are sequences of other types \"\"\" # constants typename", "\"\"\" Convert {value} into an iterable \"\"\" # get the", "# declaration class Container(Schema): \"\"\" The base class for type", "for item in value: # ask my schema to render", "reserved # # superclass from .Schema import Schema # declaration", "value='') # go through the items for item in value:", "constants typename = 'container' # the name of my type", "return it return self.container(self._coerce(value=value, **kwds)) def render(self, renderer, value, workload):", "(in this # case object) as the marker default =", "by this schema \"\"\" # complain that the subclass is", "raise NotImplementedError( \"class {.__name__} must define a {container} type\".format(type(self))) #", "to know that {default} was not supplied: use a TYPE", "<NAME> # orthologue # (c) 1998-2021 all rights reserved #", "is not appropriate here; the user may want {None} as", "want {None} as the default # value; we need a", "renderer, value, workload): \"\"\" Render {value} using {renderer} \"\"\" #", "value, workload): \"\"\" Render {value} using {renderer} \"\"\" # get", "complain that the subclass is not constructed properly raise NotImplementedError(", "typename = 'container' # the name of my type isContainer", "carefully, so we don't all end up using the same", "type\".format(type(self))) # interface def coerce(self, value, **kwds): \"\"\" Convert {value}", "separate line yield renderer.value(value=f\"{entry},\") # all done return # meta-methods", "# (c) 1998-2021 all rights reserved # # superclass from", "container represented by this schema \"\"\" # complain that the", "for type declarators that are sequences of other types \"\"\"", "default=object, schema=Schema(), **kwds): # adjust the default; carefully, so we", "object) as the marker default = self.container() if default is", "= 'container' # the name of my type isContainer =", "subclass is not constructed properly raise NotImplementedError( \"class {.__name__} must", "def render(self, renderer, value, workload): \"\"\" Render {value} using {renderer}" ]
[ "optimization_step final = section.get('scf_iteration', [None])[-1] final = section.get('optimization_step', [None])[-1] if", "to un-shift the band structure to # the original scale", "= np.where(dist == dist[0])[0][1] self._distances = dist[:n_k_points] return self._distances @property", "= xstype sec_method.x_exciting_xs_broadening = self.input_xml_parser.get( 'xs/broad', 0.01, 'hartree') sec_method.x_exciting_xs_gqmax =", "name.split('_')[-2] setattr(sec_method, metainfo_name, threshold) # additionally, set threshold to global", "self.total_dos[0]]) if self.energy_unit is not None: self._energies = self._energies *", "'structure/crystal/basevect', np.eye(3)) species = self.input_xml_parser.get('structure/species/speciesfile') if positions is None or", "one of the files bs_files = ['dos.xml', 'TDOS.OUT'] for fname", "default): mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = default.rsplit('.',", "== 'EPSILON' and ext == 'FXC': sec_scc = sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values", "\\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr), ]), repeats=False))", "'TET' if tetradf else None, 'AC' if nwacont else None,", "def _get_dos(self, diagram): dos = np.array( [point.attrib.get(self._dos_key) for point in", "i)teration number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity( 'final', r'(?:Convergence targets", "sec_system.x_exciting_potential_mixing = potential_mixing return sec_system def parse_configurations(self): sec_run = self.archive.run[-1]", "self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity, ext): # all files related to quantity", "kwargs.get('energy_unit', None) def init_parameters(self): self._nspin = None self._distances = None", "int(val[0]) mesh = np.array(val[1].split(), dtype=int) origin = np.array(val[2].split(), dtype=float) vector", "'band_energies': # TODO I am not certain about the format", "smearing_kind[0] smearing_kind = smearing_kind_map[smearing_kind] sec_smearing.kind = smearing_kind smearing_width = self.info_parser.get_initialization_parameter('smearing_width')", "e in file_ext_list if e]) # read q points qpoints", "where the mainfile is stored. \"\"\" mainfile = os.path.basename(self.info_parser.mainfile) suffix", "qpoints files = self.get_exciting_files('%s_%s%s%s.OUT' % (quantity, file_ext, ext, fxctype)) data", "energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic energy',", "charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic charge *: *({re_float})',", "Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree, repeats=True)) class ExcitingEigenvalueParser(TextParser): def __init__(self):", "the DOS to # the original scale in which also", "data]) if None in energy: return energy return np.array([d[1].get(key) for", "self.root.findall('./%s/%s' % (self._totaldos_key, self._diagram_key)) return self._total_dos @property def partial_dos(self): if", "is None: continue if '_X_' in name: sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_'", "'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic energy', 'core", "= np.dot(positions, lattice_vectors) * ureg.bohr lattice_vectors = lattice_vectors * ureg.bohr", "% (target[0], suffix) if target[1:]: filepath = '%s.%s' % (filepath,", "License for the specific language governing permissions and # limitations", "val) # energy, moment, charge contributions parse_scf(final, sec_scc) # forces", "= self.get_exciting_files('%s_%s%s%s.OUT' % (quantity, file_ext, ext, fxctype)) data = [[],", "['GGA_C_PBE', 'GGA_X_PBE'], 21: ['GGA_C_PBE', 'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE',", "start.lower() == 'gamma' else start, '\\u0393' if end.lower() == 'gamma'", "str(i + 1).rjust(3, '0'))] for f in files_q: self.data_xs_parser.mainfile =", "= self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax = pwm * gmb * gmaxvr", "origin, vector] self._quantities.append( Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False)) self._quantities.append( Quantity(", "number_of_spin_channels(self): if self._nspin is None: self._nspin = np.shape(np.transpose(self.data))[0] - 6", "ext in ['FXC', 'NLF_FXC']: data = get_data(quantity, ext) if not", "for band in bands_atom: self._bands.append(band.findall('./%s' % self._band_key)) return self._bands @property", "len(res[0]) // len(data))) if key == 'eigenvalues': res = res", "for n in range(len(files)): parser.mainfile = files[n] parser_function(section) # free", "'nspin' self._totaldos_key = 'totaldos' self._partialdos_key = 'partialdos' self._diagram_key = 'diagram'", "parser_function = self._parse_bandstructure elif name.startswith('EIGVAL') and name.endswith('OUT'): parser = self.eigval_parser", "= np.where(data[0] == data[0][0])[0][1] bands = data[1:] bands = np.reshape(bands,", "sec_scc = sec_run.m_create(Calculation) sccs.append(sec_scc) else: sec_scc = sccs[i] if sec_scc", "np.transpose(np.vstack(data)) n_sigma = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape( data[0],", "convert=False), Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False)] self._miscellaneous_keys_mapping =", "int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance = self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001) gmb =", "= self.get('%s_scf_iteration' % name) if quantity is None: return #", "last scf_iteration or optimization_step final = section.get('scf_iteration', [None])[-1] final =", "else: return files = self.get_exciting_files(name) if len(files) > 1: self.logger.warn('Found", "1 else v[1] if species is None: species = v[0][2]", "eigs_gw[0] is None: return nspin = self.info_parser.get_number_of_spin_channels() def reshape(data): if", "input_file = self.get_exciting_files('input.xml') if not input_file: return self.input_xml_parser.mainfile = input_file[0]", "= 'single_point' structure_optimization = self.info_parser.get('structure_optimization') if structure_optimization is not None:", "number sec_method.gw.frequency_values = frequency_data.get('values') sec_method.gw.frequency_weights = frequency_data.get('weights') fundamental_band_gap = self.info_gw_parser.get('direct_band_gap',", "None: continue # add data to scc # TODO add", "0, 0]) if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get( 'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge", "unit=1 / ureg.bohr, repeats=False, convert=False), ] self._system_keys_mapping = { 'x_exciting_unit_cell_volume':", "in filenames if os.access(f, os.F_OK)] return filenames def file_exists(self, filename):", "self._parse_xs_bse() elif xstype.lower() == 'tddft': self._parse_xs_tddft() def _parse_input_gw(self, sec_method): sec_gw", "(n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape( data[3], (n_components, n_excitons))", "1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1] else: setattr(msection, key,", "OF ANY KIND, either express or implied. # See the", "['Fermi energy', 'Fermi'], 'energy_kinetic_electronic': ['Kinetic energy', 'electronic kinetic'], 'energy_coulomb': ['Coulomb", "None) for d in data]) if None in energy: return", "number_of_dos(self): if self._ndos is None: total_dos = self.root.find('./%s/%s' % (self._totaldos_key,", "dtype=float, unit=ureg.hartree), Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False, convert=False), Quantity(", "self.root.find('./axis') if axis is None: return self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1)", "r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True)) def str_to_eigenvalues(val_in): val = val_in[:val_in.rfind('\\n \\n')].strip() val", "dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin radius *: *({re_float})', dtype=np.float64, unit=ureg.bohr), Quantity('radial_points',", "None if 'charge' in val_in: unit = ureg.elementary_charge elif 'moment'", "np.transpose(data, axes=(2, 0, 1)) sec_dos.energies = data[0][0] * ureg.hartree +", "r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True)) class BandstructureDatParser(DataTextParser): def __init__(self, **kwargs):", "key_unit[0], unit=key_unit[1], repeats=False) ) for name, key_unit in self._method_keys_mapping.items(): initialization_quantities.append(", "True return False def _parse_dos(self, sec_scc): if self.dos_parser.get('totaldos', None) is", "def bands(self): if self._bands is None: bands = self.root.findall('./%s' %", "of eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective potential energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb potential energy',", "str_to_atom_properties_dict(val_in): unit = None if 'charge' in val_in: unit =", "'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get(", "= self.archive.m_create(Run) sec_run.program = Program( name='exciting', version=self.info_parser.get('program_version', '').strip()) # method", "sec_gw.bare_coulomb_gmax = pwm * gmb * gmaxvr sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get(", "key: if not self.total_dos: return res = np.zeros((self.number_of_spin_channels, self.number_of_dos)) for", "None @property def band_energies(self): if self._band_energies is None: if self.data", "'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get( 'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get(", "np.reshape( data[1], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape( data[2],", "sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get( 'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get( 'xs/tddft/aresfxc', True)", "repeats=False)) module_quantities = [ Quantity( 'scf_iteration', r'(?:I| i)teration number :([\\s\\S]+?)(?:\\n", "else: sec_system.x_exciting_clathrates = False potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing is", "# TODO Read also input parameters here if input_GW.xml does", "def str_to_atom_properties_dict(val_in): unit = None if 'charge' in val_in: unit", "band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3] fermi_energy = self.fermisurf_parser.get('fermi_energy', None) if fermi_energy", "if os.path.isfile(filename): return [filename] filename = os.path.join(self.info_parser.maindir, default) if not", "charge', ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total core charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total valence", "bands: self._bands.append(bands) # add atom-resolved bands_atom = self.root.findall('./*/%s' % self._atom_key)", "find an example bandstructure file # atom-resolved bandstructure are added", "self._nlm = 0 l_list = set([int(e.attrib.get(self._l_key)) for e in self.partial_dos])", "about the format for the spin polarized case # I", "not use this file except in compliance with the License.", "'x_exciting_wigner_radius': (r'Effective Wigner radius, r\\_s', ureg.bohr), 'x_exciting_empty_states': ('Number of empty", "= self.eigval_parser.get('eigenvalues_occupancies') # reshaping is not necessary as this is", "self._band_k_points = [] start = 0 for nkpts_segment in self.number_of_k_points_per_segment:", "positions is None: return positions = np.array(positions) positions_format = positions_format", "if self.file_exists(fname): exciting_files.append(fname) break for f in exciting_files: self.parse_file(f, sec_scc)", "len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape( data[1],", "start + nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end]) start = end return self._band_k_points", "= self.input_xml_parser.get( 'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get( 'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype", "and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3] elif quantity ==", "val) # convergence values for name in self.info_parser._convergence_keys_mapping.keys(): val =", "= self.input_xml_parser.get( 'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get( 'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies", "positions = np.array(positions) positions_format = positions_format if positions_format is not", "ExcitingInfoParser() self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser = ExcitingEigenvalueParser()", "sec_k_band_segment.value = band_energies[nb] + energy_fermi def parse_file(self, name, section): #", "get_data(key): if key == 'k_points': return np.array([d[0][:3] for d in", "'spherical' sec_dos_values.lm = lm_values[lm] sec_dos_values.spin = spin sec_dos_values.atom_index = atom", "1 val_l = self.partial_dos[i].attrib.get(self._l_key, None) val_m = self.partial_dos[i].attrib.get(self._m_key, None) if", "= kwargs.get('energy_unit', None) def init_parameters(self): self._nspin = None self._nkpts_segment =", "elif key == 'energies': return self.energies else: res = None", "= f positions = self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors = self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3))", "val = None for name in names: val = moment_contributions.get(name,", "unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic mass *: *({re_float})', dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin", "val[-2] nspin = 2 if occs[0] == 1. else 1", "options.sort() filenames = [os.path.join(self.info_parser.maindir, f) for f in options] else:", "= set([int(e.attrib.get(self._l_key)) for e in self.partial_dos]) for li in l_list:", "self.logger def reuse_parser(self, parser): self.info_parser.quantities = parser.info_parser.quantities self.eigval_parser.quantities = parser.eigval_parser.quantities", "self._nkpts_segment is None: self._nkpts_segment = [] count = 1 for", "setting metainfo.') # species species = self.info_parser.get_initialization_parameter('species', []) for specie", "str_operation=str_to_quantity_tolerances, unit=ureg.hartree / ureg.bohr, repeats=False, dtype=float), Quantity( 'energy_total', r'Total energy", "not None: sec_scc.system_ref = sec_system sec_scc.method_ref = sec_run.method[-1] return sec_scc", "def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data = np.transpose(self.data) self._neigs_segment", "if structure_optimization is not None: sec_worfklow.type = 'geometry_optimization' sec_geometry_opt =", "def distances(self): if self._distances is None: if not self.bands: return", "self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax = rgkmax sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff", "= sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value = totaldos[spin] partialdos", "= (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi =", "self.input_xml_parser.mainfile = f correlation = self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation) exchange =", "continue if key == 'x_exciting_section_MT_moment_atom': for n in range(len(val)): sec_mt_moment_atom", "import ( Calculation, Dos, DosValues, BandStructure, BandEnergies, Energy, EnergyEntry, Charges,", "Calculation.dos_electronic) sec_dos.n_energies = len(data) // nspin data = np.reshape(data, (nspin,", "sec_scc): if self.eigval_parser.get('eigenvalues_occupancies', None) is None: return nspin = self.info_parser.get_number_of_spin_channels()", "self._system_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) )", "sec_scc.system_ref = sec_system sec_scc.method_ref = sec_run.method[-1] return sec_scc # groundstate", "info. # # Licensed under the Apache License, Version 2.0", "sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands = len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints = len(eigs_gw)", "is None: continue lattice_vectors = np.array(lattice_vectors, dtype=float) lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale',", "'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get( 'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get(", "spin_treatment.lower() == 'spin-unpolarised' else 2 return n_spin def get_unit_cell_volume(self): return", "= val[-2] nspin = 2 if occs[0] == 1. else", "and input-gw.xml for f in ['input_gw.xml', 'input-gw.xml', 'input.xml']: self.parse_file(f, sec_method)", "= ['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf'] # Parse DFT DOS from one", "**kwargs): super().__init__(None) self._nspin_key = 'nspin' self._totaldos_key = 'totaldos' self._partialdos_key =", "'x_exciting_gmaxvr': (r'Maximum \\|G\\| for potential and density', 1 / ureg.bohr),", "R\\^MT\\_min', None), 'x_exciting_gkmax': (r'Maximum \\|G\\+k\\| for APW functions', 1 /", "file_ext = '_'.join([e for e in file_ext_list if e]) #", "options = [ f for f in os.listdir( self.info_parser.maindir) if", "used to un-shift the DOS to # the original scale", "TODO implement reading of parameters from input.xml for normal calculations", "are added as separate section_k_band res = [] for n", "def init_quantities(self): self._quantities = [] def str_to_frequency(val_in): val = [v.split()", "by concatenating species symbols species = self.get('initialization', {}).get('species', []) labels", "else val return np.array(val, dtype=float) def str_to_atom_properties_dict(val_in): unit = None", "for v in val_in.strip().split('\\n')] val = val[0] if len(val) ==", "data[0])[0]) return self._neigs_segment class BandstructureXMLParser(XMLParser): def __init__(self, **kwargs): # TODO", "} def get_exciting_files(self, default): mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT')", "False) sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get( 'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get( 'xs/BSE/sciavqwg',", ":([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity( 'final', r'(?:Convergence targets achieved\\. Performing", "'gw': return sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref =", "self._quantities.append( Quantity( 'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False)) def str_to_band_parameters(val_in): val", "= self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax", "repeats=False), Quantity( 'atomic_positions', r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'imized", "input.xml input_file = self.get_exciting_files('input.xml') for f in input_file: self.input_xml_parser.mainfile =", "None), 'x_exciting_spin_treatment': ('Spin treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number of Bravais lattice", "= sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands = len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints =", "sec_scc = parse_configuration(structure_optimization) if sec_scc is None: return # volume", "started([\\s\\S]+?)Hybrids module stopped', sub_parser=TextParser(quantities=module_quantities) )) def get_atom_labels(self, section): labels =", "end = start + nkpts_segment band_energy = np.array([ np.transpose(energy)[start:end] for", "f in files: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None:", "sec_run = self.archive.run[-1] fxctype = self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf = self.input_xml_parser.get('xs/tetra/tetradf',", "energy dos_up dos_down nspin = self.info_parser.get_number_of_spin_channels() sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic)", "None: continue if name == 'time': msection.time_calculation = val else:", "'final', r'Force convergence target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(imized", "sec_scc = sec_run.m_create(Calculation) sec_scc.method_ref = sec_method if sec_run.system: sec_scc.system_ref =", "self.info_parser.get_unit_cell_volume() dos = data[1] * (1 / ureg.hartree) * volume.to('m**3').magnitude", "overwritten when setting mainfile self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_parser.get('band_energies',", "for f in files_q: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is", "'linearization' sec_gw.max_frequency = self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type = self.input_xml_parser.get( 'gw/freqgrid/fgrid',", "for the spin polarized case # I cannot find an", "energy_fermi is None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band", "= None def _parse_input_xs(self, sec_method): xstype = self.input_xml_parser.get('xs/xstype', None) if", "specie in species: sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number", "sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1] else: setattr(msection, key, val) # convergence values", "zone volume', 1 / ureg.bohr ** 3), 'x_exciting_number_of_atoms': ('Total number", "get_exciting_files(self, default): mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target =", "False) sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlbse', [0, 0, 0, 0]) if", "self.distances[i - 1]: self._nkpts_segment .append(count) count = 1 else: count", "/ ureg.bohr), ]), repeats=False)) self._quantities.append(Quantity( 'hybrids', r'Hybrids module started([\\s\\S]+?)Hybrids module", "kinetic energy', 'core electron kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion correction'] }", "energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic energy', 'core electron kinetic'], 'x_exciting_dft_d2_dispersion_correction':", "if quantity is None: return # this is really problematic", "= self.root.find('./axis') if axis is None: return self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(),", "// self.number_of_lm else: spin = int(spin) - 1 val_l =", "= nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.energies = band_energies[nb] + energy_fermi", "is not None: sec_worfklow.type = 'geometry_optimization' sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization) threshold_force", "if partialdos is None: return partialdos = partialdos.to('1/joule').magnitude lm_values =", "None: sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get( 'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get( 'xs/tddft/ahc',", "v in x.split(':')]), Quantity( 'parameters', r'\\n *(.+?:.+)', repeats=True, str_operation=lambda x:", "Calculation, Dos, DosValues, BandStructure, BandEnergies, Energy, EnergyEntry, Charges, Forces, ForcesEntry,", "0) sec_gw.core_treatment = self.input_xml_parser.get( 'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states = int( self.input_xml_parser.get('gw/nempty',", "len(data) // nspin, len(data[0]))) sec_gw_eigenvalues = sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk'))", "= ['dos.xml', 'TDOS.OUT'] for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname)", "from input.xml for normal calculations # in addition to INFO.OUT", "f if self.data_xs_parser.data is None: continue data_q.append(self.data_xs_parser.data) if not data_q:", "file is part of NOMAD. # See https://nomad-lab.eu for further", "(n_components, n_loss)) * ureg.hartree sec_scc.x_exciting_xs_bse_loss = np.reshape( data[1], (n_components, n_loss))", "'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3] elif quantity == 'SIGMA' and ext", "= self.get_initialization_parameter('species', []) if species: positions = np.vstack([s.get('positions') for s", "charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic mass *: *({re_float})',", "'x_exciting_spin_treatment': sub_sec = sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment = val elif name ==", "repeats=False) ) self._quantities.append( Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append(", "if self._vertices is None: self._vertices = self.root.findall('./%s' % self._vertex_key) return", "None), 'x_exciting_gkmax': (r'Maximum \\|G\\+k\\| for APW functions', 1 / ureg.bohr),", "None: continue if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_', '')), EnergyEntry(value=val)) else:", "optimizations volume_index = 1 while True: info_volume = self.get_exciting_files('run_dir%s/INFO.OUT' %", "res sec_eigenvalues = sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints = self.eigval_parser.get('k_points') sec_eigenvalues.occupations = get_data('occupancies')", "to quantity at all qpoints files = self.get_exciting_files('%s_%s%s%s.OUT' % (quantity,", "= self._parse_fermisurface elif name.startswith('EVALQP') and (name.endswith('DAT') or name.endswith('TXT')): parser =", "self.logger.warn( 'Mismatch in EXCITON and file type', data=dict(file=quantity)) sec_scc =", "@property def number_of_spin_channels(self): if self._nspin is None: self._nspin = np.shape(np.transpose(self.data))[0]", "optimization_step.get('method') is not None: sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method') if optimization_step.get('step') is", "= xc_functional.get('name_reference', [None, None])[1] sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels() if self._calculation_type ==", "= self.info_parser.get_initialization_parameter('species', []) for specie in species: sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group)", "re import logging from nomad.units import ureg from nomad.parsing.file_parser import", "self.number_of_lm else: lm = int(val_l) ** 2 + int(val_m) +", "killing me! if metainfo_name == 'x_exciting_scf_threshold_energy_change': sec_method.scf = Scf(threshold_energy_change=threshold) xc_functional_names", "init_parameters(self): self._nspin = None self._distances = None self._band_energies = None", "= sec_electronic.m_create(Smearing) smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind is not None:", "self.input_xml_parser.get( 'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get( 'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype =", "if self._distances is None: dist = np.transpose(self.data)[0] n_k_points = np.where(dist", "cannot find an example bandstructure file # atom-resolved bandstructure are", "sec_method.x_exciting_xs_bse_rgkmax = rgkmax sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get( 'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd =", "int(max(data[1])) bands = data[6:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues,", "= self.logger self.data_clathrate_parser.logger = self.logger def reuse_parser(self, parser): self.info_parser.quantities =", "other metainfo for name in self.info_parser._miscellaneous_keys_mapping.keys(): val = iteration.get(name) if", "2: continue energies[v[0].strip()] = float(v[1]) * ureg.hartree return energies self._quantities", "is not None else section.get('final') if final is None: #", "kwargs.get('energy_unit', None) self._units_mapping = dict(hartree=ureg.hartree) def init_parameters(self): self._ndos = None", "parser = self.band_out_parser parser_function = self._parse_band_out elif name.startswith('input') and name.endswith('xml'):", "name in names: val = moment_contributions.get(name, None) if val is", "= np.transpose(self.data)[0] n_k_points = np.where(dist == dist[0])[0][1] self._distances = dist[:n_k_points]", "really correct, i.e. columns are supposed # to be what", "None: break return positions_format def get_atom_positions(self, section={}, positions=None, positions_format=None): positions", "names: val = charge_contributions.get(name, None) if val is not None:", "if x_exciting_dos_fermi is not None: setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi) # energy", "energy_fermi nkpts_segment = self.band_out_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment =", "and name.endswith('OUT'): parser = self.dos_out_parser parser_function = self._parse_dos_out elif name.startswith('bandstructure')", "key, val) # convergence values for name in self.info_parser._convergence_keys_mapping.keys(): val", "self.data_xs_parser.data is None: continue data.append(self.data_xs_parser.data) return data def parse_exciton(data, sec_scc):", "nomad.datamodel.metainfo.simulation.method import ( Method, DFT, Electronic, Smearing, XCFunctional, Functional, GW", "= atom sec_dos_values.value = partialdos[lm][spin][atom] def _parse_bandstructure(self, sec_scc): # we", "implied. # See the License for the specific language governing", "406: ['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']} xc_functional = self.get('initialization', {}).get('xc_functional', None) if", "sec_run.m_create(Calculation) if quantity == 'EXCITON': parse_function = parse_exciton elif quantity", "repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])), Quantity( 'forces', r'Total", "name.endswith('TXT')): parser = self.evalqp_parser parser_function = self._parse_evalqp elif name.startswith('TDOS') and", "self.energy_unit is not None: self._energies = self._energies * self.energy_unit return", "= self.logger def reuse_parser(self, parser): self.info_parser.quantities = parser.info_parser.quantities self.eigval_parser.quantities =", "# This is the case when there is a mismatch", "for i in range(len(self.partial_dos)): spin = self.partial_dos[i].attrib.get(self._nspin_key, None) if spin", "number = frequency_data.get('number') sec_method.gw.number_of_frequencies = len(number) sec_method.gw.frequency_number = number sec_method.gw.frequency_values", "the License. # import numpy as np import os import", "GeometryOptimization from .metainfo.exciting import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float", "None: sec_gap.value_optical = optical_band_gap def parse_miscellaneous(self): sec_worfklow = self.archive.m_create(Workflow) sec_worfklow.type", "module started)([\\s\\S]+?)Groundstate module stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities = [ Quantity(", "muffin-tin *: *({re_float})', dtype=np.int32), Quantity('positions_format', r'atomic positions \\((.+?)\\)', flatten=False), Quantity(", "= frequency_data.get('number') sec_method.gw.number_of_frequencies = len(number) sec_method.gw.frequency_number = number sec_method.gw.frequency_values =", "'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])), Quantity(", "0, 0]) rgkmax = self.input_xml_parser.get('xs/screening/rgkmax', None) if rgkmax is None:", "band_energy = band_energy * self._energy_unit res_n.append(band_energy) start = end res.append(res_n)", "self.evalqp_parser.get('kpoints_eigenvalues') if data is None: return def get_data(key): if key", "sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get( 'xs/tddft/intraband', False)", "# read q points qpoints = self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity, ext):", "bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies = []", "= self._parse_bandstructure elif name.startswith('EIGVAL') and name.endswith('OUT'): parser = self.eigval_parser parser_function", "spin sec_dos_values.atom_index = atom sec_dos_values.value = partialdos[lm][spin][atom] def _parse_bandstructure(self, sec_scc):", "sec_smearing = sec_electronic.m_create(Smearing) smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind is not", "elif quantity == 'SIGMA' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field =", "the specific language governing permissions and # limitations under the", "self.vertices[i].attrib.get(self._coord_key).split() end = self.vertices[i + 1].attrib.get(self._coord_key).split() res.append([start, end]) else: res", "in effective potential \\(target\\)', ureg.hartree), 'x_exciting_energy_convergence': ( r'Absolute change in", "'xs' # inconsistency in the naming convention for xs input", "self._partial_dos is None: self._partial_dos = self.root.findall('./%s/%s' % (self._partialdos_key, self._diagram_key)) return", "Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True)) class BandstructureDatParser(DataTextParser): def", "np.transpose(np.vstack(data)) n_loss = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_loss_energies = np.reshape( data[0],", "self.eigval_parser.get('eigenvalues_occupancies') # reshaping is not necessary as this is done", "= self.archive.run[-1] # two versions of gw info files gw_info_files", "ureg.bohr lattice_vectors = lattice_vectors * ureg.bohr atoms = self.input_xml_parser.get('structure/species/atom') atom_labels", "else: vi = [float(vii) for vii in v[1].split()] vi =", "== 'gamma' else end]) elif key == 'band_segm_start_end': res =", "suffix = mainfile.strip('INFO.OUT') target = filename.rsplit('.', 1) filepath = '%s%s'", "sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration) return sec_scc def parse_system(self, section): sec_run =", "= [] for bse_type in bse_types: for scr_type in scr_types:", "'hartree') sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get( 'xs/gqmax', 0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw',", "self._nspin is None: self._nspin = np.shape(np.transpose(self.data))[0] - 6 return self._nspin", "self.archive.run[-1] positions = self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels =", "if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax =", "versions of gw info files gw_info_files = ['GW_INFO.OUT', 'GWINFO.OUT'] for", "XCFunctional, Functional, GW as GWMethod, Scf, BasisSet ) from nomad.datamodel.metainfo.simulation.system", "self._energy_key = 'eval' self._vertex_key = 'vertex' self._band_key = 'band' self._atom_key", "def init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point',", "break for f in exciting_files: self.parse_file(f, sec_scc) # structure optimization", "un-shift the band structure to # the original scale in", "are reported. energy_fermi = 0.0 * ureg.hartree if sec_scc.energy is", "end return self._band_energies @property def band_k_points(self): if self._band_k_points is None:", "sec_scc.calculations_ref = [sec_scc_ref] # parse properties gw_info_files = self.get_exciting_files(gw_info_file) if", "'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree, repeats=True)) class ExcitingEigenvalueParser(TextParser): def __init__(self): super().__init__(None)", "in options if f.endswith(file_ext)] options.sort() filenames = [os.path.join(self.info_parser.maindir, f) for", "sec_system def parse_configurations(self): sec_run = self.archive.run[-1] def parse_configuration(section): if not", "parameters xc_functional = self.info_parser.get('initialization', {}).get('xc_functional') if xc_functional is not None:", "of (?:total)* scf iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'force_convergence', r'Maximum force", "np.transpose(val) occs = val[-1] eigs = val[-2] nspin = 2", "band_energies(self): if self._band_energies is None: if self.data is None: return", "properties = dict() atom_resolved = [] species = None for", "None self._nkpts_segment = None self._neigs_segment = None self._bands = None", "len(eigs_gw) sec_gw_eigenvalues.kpoints = get_data('k_points') sec_gw_eigenvalues.energies = reshape(eigs_gw) sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx'))", "/ ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum \\|G\\| for potential and density', 1", "n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape( data[4], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape(", "0.) sec_method.x_exciting_xs_rgkmax = rgkmax sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff =", "None) if fermi_energy is not None: sec_scc.energy = Energy(fermi=fermi_energy) gw_files", "for d in data]) else: energy = np.array([d[1].get(key, None) for", "if logger is not None else logging self._calculation_type = None", "res = [] for n in range(len(self.bands)): res_n = []", "* ureg.hartree).to('joule') # TODO smearing with should have units of", "'eigenvalues_occupancies', r'\\(state\\, eigenvalue and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues, repeats=True)) class", "[] for bse_type in bse_types: for scr_type in scr_types: files", "if not self.bands: return if key == 'band_energies': # TODO", "if self._energy_unit: band_energy = band_energy * self._energy_unit self._band_energies.append(band_energy) start =", "= [] for specie in species: labels += [specie.get('symbol')] *", "number of k\\-points', None), 'x_exciting_rgkmax': (r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max \\(rgkmax\\)', None),", "forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree /", "end return self._band_k_points @property def distances(self): if self._distances is None:", "f correlation = self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation) exchange = self.input_xml_parser.get('libxc/exchange', None)", "data = np.transpose(np.vstack(data)) n_epsilon = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_energy_points =", "properties['atom_resolved'] = atom_resolved return properties def str_to_quantity_tolerances(val_in): return val_in.strip().replace('(', '').replace(')',", "'forces', r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array,", "get_unit_cell_volume(self): return self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0 * ureg.bohr ** 3) def", "self._coord_key = 'coord' self._energy_key = 'eval' self._vertex_key = 'vertex' self._band_key", "res class ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities =", "'LDA_X_PZ'], 4: ['LDA_C_XALPHA'], 5: ['LDA_C_VBH'], 20: ['GGA_C_PBE', 'GGA_X_PBE'], 21: ['GGA_C_PBE',", "= n_excitons sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape( data[1], (n_components, n_excitons)) * ureg.hartree", "ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3] elif quantity == 'LOSS'", "dtype=float)) eigs = {keys[i]: eigs[i] for i in range(len(keys))} return", "if energy_fermi is None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree')", "= None self._distances = None self._band_energies = None self._neigs_segment =", "self.root.findall('./%s' % self._partialdos_key) self._natoms = len(partial_dos) return self._natoms @property def", "while True: info_volume = self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2, '0')) if not", "{}).get(key, default) class ExcitingParser: def __init__(self): self.info_parser = ExcitingInfoParser() self.dos_parser", "sec_smearing.kind = smearing_kind smearing_width = self.info_parser.get_initialization_parameter('smearing_width') if smearing_width is not", "(filename, target[1]) filename = os.path.join(self.info_parser.maindir, filename) if os.path.isfile(filename): return [filename]", "scheme', None), 'smearing_width': ('Smearing width', None)} for name, key_unit in", "dtype=float) return dos def parse(self, key): if self._results is None:", "None: # get it from last scf_iteration or optimization_step final", "parser_function(section) # free up memory parser.mainfile = None def _parse_input_xs(self,", "True self.data_clathrate_parser.mainfile = clathrate_file[0] if self.data_clathrate_parser.data: data = np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates", "to set nspin again as this is overwritten when setting", "is not None: sec_gap.value_optical = optical_band_gap def parse_miscellaneous(self): sec_worfklow =", "= [] start = 0 for nkpts_segment in self.number_of_k_points_per_segment: end", "/ ureg.bohr, repeats=False, dtype=float), Quantity( 'energy_total', r'Total energy at this", "self._calculation_type = 'gw' gw_info_file = f break if not self._calculation_type", "1)[0].replace('INFO', '') options = [ f for f in os.listdir(", "= data[5][:int(max(data[1]))] return self._distances @property def number_of_spin_channels(self): if self._nspin is", "None: if self.data is None: return data = np.transpose(self.data) n_kpoints", "= partialdos.to('1/joule').magnitude lm_values = np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32))) for lm in", "sec_run.system: sec_scc.system_ref = sec_run.system[-1] sec_scc_ref = sec_run.calculation[0] sec_scc.starting_calculation_ref = sec_scc_ref", "parse_gw(self): sec_run = self.archive.run[-1] # two versions of gw info", "final = section.get('scf_iteration', [None])[-1] final = section.get('optimization_step', [None])[-1] if final", "band structure to # the original scale in which also", "done in parser, however nspin is # determined from occupancies", "= self.info_parser.get_number_of_spin_channels() def get_data(key): data = self.eigval_parser.get('eigenvalues_occupancies') # reshaping is", "parse_epsilon elif quantity == 'SIGMA': parse_function = parse_sigma elif quantity", "def _parse_xs_tddft(self): sec_run = self.archive.run[-1] fxctype = self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf", "('Spin treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number of Bravais lattice symmetries', None),", "= self.root.findall('./*/%s' % self._atom_key) for band in bands_atom: self._bands.append(band.findall('./%s' %", "in self.number_of_k_points_per_segment: end = start + nkpts_segment band_energy = np.array([", "= self.input_xml_parser.get( 'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get( 'xs/screening/ngridk', [0, 0,", "'x_exciting_valence_charge_initial': ('Total valence charge', ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective Wigner radius, r\\_s',", "= self.input_xml_parser.get( 'xs/BSE/nstlbse', [0, 0, 0, 0]) if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom", "= reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation = eigs_gw_C sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc')) def _parse_dos_out(self,", "val = energy_contributions.get(name, None) if val is not None: break", "'correlation'], 'x_exciting_correlation_energy': ['Correlation energy', 'correlation'], 'energy_sum_eigenvalues': ['Sum of eigenvalues', 'sum", "val is None: continue if key == 'x_exciting_section_MT_charge_atom': for n", "= sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.value = band_energies[nb] + energy_fermi", "0 for nkpts_segment in self.number_of_k_points_per_segment: end = start + nkpts_segment", "not None: sec_worfklow.type = 'geometry_optimization' sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization) threshold_force =", "self._ndos @property def number_of_lm(self): if self._nlm is None: if self.partial_dos", "really problematic if some scf steps dont have the quantity", "None else section.get('positions') if positions is None: species = self.get_initialization_parameter('species',", "= self.vertices[i + 1].attrib.get('label') res.append([ '\\u0393' if start.lower() == 'gamma'", "= self._get_dos(self.partial_dos[i]) if self.energy_unit is not None: res = res", "flatten=False)] initialization_quantities = [ Quantity( 'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr,", "nspin is # determined from occupancies which is problematic sometimes", "energy', 'Coulomb'], 'energy_exchange': ['Exchange energy', 'exchange'], 'x_exciting_exchange_energy': ['Exchange energy', 'exchange'],", "in xc_functional_names: if name is None: continue if '_X_' in", "is used to un-shift the band structure to # the", "len(data[0]) // n_components sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape( data[0], (n_components, n_sigma)) *", "[] for i in range(len(self.number_of_k_points_per_segment)): start = self.vertices[i].attrib.get(self._coord_key).split() end =", "in ['FXC', 'NLF_FXC']: data = get_data(quantity, ext) if not data[0]:", "= self.logger self.input_xml_parser.logger = self.logger self.data_xs_parser.logger = self.logger self.data_clathrate_parser.logger =", "sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value = dos[spin] # TODO", "gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment = self.input_xml_parser.get( 'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states", "dist = np.transpose(self.data)[0] n_k_points = np.where(dist == dist[0])[0][1] self._distances =", "G\\-vectors', None), 'x_exciting_lmaxapw': (r' APW functions', None), 'x_exciting_nuclear_charge': ('Total nuclear", "+ energy_fermi def parse_file(self, name, section): # TODO add support", "r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) for name, key_unit in", "nwacont else None, 'NAR' if not aresdf else None] file_ext", "parse_configuration(structure_optimization) if sec_scc is None: return # volume optimizations volume_index", "val[n][1].magnitude for n in range(len(val))] * val[0][1].units sec_charges.total = charge_contributions.get('total", "of energy sec_smearing.width = smearing_width.magnitude for name in self.info_parser._convergence_keys_mapping.keys(): threshold", "sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft = sec_method.m_create(DFT) sec_electronic = sec_method.m_create(Electronic) sec_electronic.method =", "n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape( data[2], (n_components, n_excitons)) *", "+(\\S+)'), Quantity( 'name_reference', r'\\n *(.+?,.+)', str_operation=lambda x: [v.strip() for v", "= gw_info_files[0] fermi_energy = self.info_gw_parser.get('fermi_energy', None) if fermi_energy is not", "ext, fxctype)) data = [[], [], []] for i in", "sec_scf_iteration) return sec_scc def parse_system(self, section): sec_run = self.archive.run[-1] positions", "forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False, str_operation=str_to_array, convert=False, unit=ureg.hartree /", "def parse_system(self, section): sec_run = self.archive.run[-1] positions = self.info_parser.get_atom_positions(section.get('atomic_positions', {}))", "is not None else section.get('positions') if positions is None: species", "if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_', '')), EnergyEntry(value=val)) else: setattr(msection, key,", "= input_file[0] xstype = self.input_xml_parser.get('xs/xstype', '') if xstype.lower() == 'bse':", "return self._vertices @property def number_of_spin_channels(self): if self._nspin is None: self._nspin", "if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax =", "= [float(vii) for vii in v[1].split()] vi = vi[0] if", "self._distances is None: dist = np.transpose(self.data)[0] n_k_points = np.where(dist ==", "= np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32))) for lm in range(len(partialdos)): for spin", "# # Copyright The NOMAD Authors. # # This file", "= DataTextParser() self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser = BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser =", "if len(sec_run.system) > 1: return sec_system for name in self.info_parser._system_keys_mapping.keys():", "if quantity == 'EPSILON' and ext == 'FXC': sec_scc =", "in names: val = energy_contributions.get(name, None) if val is not", "= self.bandstructure_parser parser_function = self._parse_bandstructure elif name.startswith('EIGVAL') and name.endswith('OUT'): parser", "if sec_scc is None: return sec_system = self.parse_system(section) if sec_system", "module started([\\s\\S]+?)Hybrids module stopped', sub_parser=TextParser(quantities=module_quantities) )) def get_atom_labels(self, section): labels", "not None: sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method') if optimization_step.get('step') is not None:", "# reshaping is not necessary as this is done in", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "for f in os.listdir( self.info_parser.maindir) if target[0] in f and", "float)) return dict( number=np.array(val[0], dtype=int), values=val[1] * ureg.hartree, weights=val[2]) #", "'EPSILON' and ext == 'FXC': sec_scc = sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values =", "return partialdos = partialdos.to('1/joule').magnitude lm_values = np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32))) for", "energy: it is used to un-shift the DOS to #", "= n_components n_excitons = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons", "(r'Estimated fundamental gap', ureg.hartree), 'time': (r'Wall time \\(seconds\\)', ureg.s)} for", "r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float,", "band_energies = self.bandstructure_dat_parser.band_energies if band_energies is None: return # Get", "files[n] parser_function(section) # free up memory parser.mainfile = None def", "self._total_dos @property def partial_dos(self): if self._partial_dos is None: self._partial_dos =", "positions \\((.+?)\\)', flatten=False), Quantity( 'positions', rf'\\d+ : *({re_float}) *({re_float}) *({re_float})',", "None: species = self.get_initialization_parameter('species', []) for specie in species: positions_format", "Quantity( 'method', r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str), Quantity( 'n_scf_iterations', r'Number of (?:total)*", "== 'xs': parser_function = self._parse_input_xs else: # TODO implement reading", "self._bands = [] if bands: self._bands.append(bands) # add atom-resolved bands_atom", "import TextParser, Quantity, XMLParser, DataTextParser from nomad.datamodel.metainfo.simulation.run import Run, Program", "= 'spherical' sec_dos_values.lm = lm_values[lm] sec_dos_values.spin = spin sec_dos_values.atom_index =", "]+) potential mixing', repeats=False, flatten=False) ) initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n", "problematic if some scf steps dont have the quantity #", "= sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value = dos[spin] #", "'\\u0393' if start.lower() == 'gamma' else start, '\\u0393' if end.lower()", "in range(len(val))] * val[0][1].units sec_charges.total = charge_contributions.get('total charge') elif key", "self._neigs_segment class BandstructureXMLParser(XMLParser): def __init__(self, **kwargs): # TODO make a", "unit=ureg.hartree, repeats=True)) class ExcitingEigenvalueParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities", "= val[0] if len(val) == 1 else val return np.array(val,", "accessible in the same folder where the mainfile is stored.", "def get_exciting_files(self, default): mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target", "unit=ureg.bohr, repeats=False, convert=False), Quantity( 'lattice_vectors_reciprocal', r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1", "parser_function = self._parse_dos_out elif name.startswith('bandstructure') and name.endswith('dat'): parser = self.bandstructure_dat_parser", "is part of NOMAD. # See https://nomad-lab.eu for further info.", "is None: if not self.total_dos: return self._nspin = len(self.total_dos) return", "= smearing_kind_map[smearing_kind] sec_smearing.kind = smearing_kind smearing_width = self.info_parser.get_initialization_parameter('smearing_width') if smearing_width", "int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states =", "'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False)) self._quantities.append( Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree,", "check if format of files are really correct, i.e. columns", "elif key == 'Znk': return np.array([d[1].get(key, None) for d in", "// n_components sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape( data[0], (n_components,", "* ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape( data[1], (n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im =", "None) if val is not None: break if val is", "charge_contributions.get('total charge') elif key == 'charge_total': pass else: setattr(msection, key,", "'.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point = xc_functional_name sec_scc = sec_run.m_create(Calculation) sec_scc.method_ref = sec_method", "if self._neigs_segment is None: data = np.transpose(self.data)[0] self._neigs_segment = len(np.where(data", "v[1] if species is None: species = v[0][2] atom_resolved.append(((species, v[1]", "sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = len(data) // nspin data", "= re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in): val = [v.split(':')[-1].split() for v in", "= self.root.find('./%s/%s' % (self._totaldos_key, self._diagram_key)) self._ndos = len(total_dos) return self._ndos", "clathrate_file = self.get_exciting_files('str.out') if clathrate_file: sec_system.x_exciting_clathrates = True self.data_clathrate_parser.mainfile =", "self.info_parser.get('structure_optimization', {}) for optimization_step in structure_optimization.get('optimization_step', []): sec_scc = parse_configuration(optimization_step)", "repeats=True, dtype=float)])), Quantity( 'forces', r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n", "return self._nlm = 0 l_list = set([int(e.attrib.get(self._l_key)) for e in", "the License is distributed on an \"AS IS\" BASIS, #", "['atom_resolved'] } def get_exciting_files(self, default): mainfile = os.path.basename(self.info_parser.mainfile) suffix =", "for name, key_unit in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0],", "self.get('initialization', {}).get('species', []) labels = [] for specie in species:", "not None: sec_gap.value_optical = optical_band_gap def parse_miscellaneous(self): sec_worfklow = self.archive.m_create(Workflow)", "Calculation.dos_electronic) sec_dos.n_energies = self.dos_parser.number_of_dos sec_dos.energies = self.dos_parser.energies + energy_fermi volume", "* ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape( data[3], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re =", "= data[1:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies", "= xc_functional.get('name_reference', [None, None])[0] sec_xc_functional.reference = xc_functional.get('name_reference', [None, None])[1] sec_electronic.n_spin_channels", "self.distances[i - 1]: self._nkpts_segment.append(count) count = 1 else: count +=", "name, [None, None])[-1] def get_scf_quantity(self, name): n_scf = len(self.get('energy_total_scf_iteration', []))", "in bs_files: if self.file_exists(fname): gw_files.append(fname) break for f in gw_files:", "= float(v[1]) * ureg.hartree return energies self._quantities = [Quantity( 'program_version',", "Dos.atom_projected) sec_dos_values.m_kind = 'spherical' sec_dos_values.lm = lm_values[lm] sec_dos_values.spin = spin", "range(1, len(self.distances)): if self.distances[i] == self.distances[i - 1]: self._nkpts_segment .append(count)", "charge_contributions = iteration.get('charge_contributions', {}) for key, names in self._electron_charge_keys_mapping.items(): val", "if eigs_gw[0] is None: return nspin = self.info_parser.get_number_of_spin_channels() def reshape(data):", "continue try: parse_function(data, sec_scc) except Exception: self.logger.error('Error setting xs data',", "data[2], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape( data[3], (n_components,", "3 # TODO confirm no cell optimization in exciting sec_atoms.lattice_vectors", "'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get( 'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra = self.input_xml_parser.get(", "self.logger.warn('Found multiple GW info files, will read only first!') self.info_gw_parser.mainfile", "# energy contributions energy_contributions = iteration.get('energy_contributions', {}) for key, names", "'xs/BSE/nstlbse', [0, 0, 0, 0]) if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get(", "a the given filename exists and is accessible in the", "'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get(", "dtype=int), Quantity( 'force_convergence', r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree /", "res[i] = self._get_dos(self._total_dos[i]) if self.energy_unit is not None: res =", "int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment =", "self.number_of_lm else: spin = int(spin) - 1 val_l = self.partial_dos[i].attrib.get(self._l_key,", "positions_format is not None else self.get_positions_format(section) if positions_format == 'lattice':", "= None self._vertices = None self._distances = None self._species =", "= self.logger self.bandstructure_dat_parser.logger = self.logger self.band_out_parser.logger = self.logger self.info_gw_parser.logger =", "logger is not None else logging self._calculation_type = None self.init_parser()", "= self.root.findall('./%s/%s' % (self._totaldos_key, self._diagram_key)) return self._total_dos @property def partial_dos(self):", "range(len(self.vertices) - 1): start = self.vertices[i].attrib.get('label') end = self.vertices[i +", "\\|G\\| for potential and density', 1 / ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector", "np.array(val[0].split(), dtype=float) keys = val[1].split() eigs = np.transpose(np.array([v.split() for v", "is None: if not self.bands: return self._distances = [ point.attrib.get(self._distance_key)", "self.file_exists(fname): gw_files.append(fname) break for f in gw_files: self.parse_file(f, sec_scc) frequency_data", "reshaping is not necessary as this is done in parser,", "= dict() for v in val: v = v.split(':') if", "xc_functional_map = { 2: ['LDA_C_PZ', 'LDA_X_PZ'], 3: ['LDA_C_PW', 'LDA_X_PZ'], 4:", "target = default.rsplit('.', 1) filename = '%s%s' % (target[0], suffix)", "* gmb * gmaxvr sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average", "['Hartree energy', 'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy', 'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear", "[v.strip() for v in x.split(':')])])) ) self._quantities.append(Quantity( 'initialization', r'(?:All units", "this file except in compliance with the License. # You", "'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']} xc_functional = self.get('initialization', {}).get('xc_functional', None)", "def get_number_of_spin_channels(self): spin_treatment = self.get('initialization', {}).get( 'x_exciting_spin_treatment', 'spin-unpolarised') n_spin =", "reshape(get_data('Vxc')) def _parse_dos_out(self, sec_scc): data = self.dos_out_parser.data if data is", "== data[0][0])[0][1] bands = data[1:] bands = np.reshape(bands, ( self.number_of_spin_channels,", "at Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=1 / ureg.hartree), Quantity(", "sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc')) def _parse_dos_out(self, sec_scc): data = self.dos_out_parser.data if", "crystal symmetries', None), 'x_exciting_kpoint_grid': (r'k\\-point grid', None), 'x_exciting_kpoint_offset': (r'k\\-point offset',", "elif name.startswith('EIGVAL') and name.endswith('OUT'): parser = self.eigval_parser parser_function = self._parse_eigenvalues", "self.logger self.input_xml_parser.logger = self.logger self.data_xs_parser.logger = self.logger self.data_clathrate_parser.logger = self.logger", "'time': (r'Wall time \\(seconds\\)', ureg.s)} for name, key_unit in self._miscellaneous_keys_mapping.items():", "aresdf = self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list = [ 'TET' if tetradf", "and name.endswith('xml'): parser = self.input_xml_parser if self._calculation_type == 'gw': parser_function", "species = self.input_xml_parser.get('structure/species/speciesfile') if positions is None or lattice_vectors is", "% self._band_key) self._bands = [] if bands: self._bands.append(bands) # add", "= np.shape(np.transpose(self.data)[1:])[0] return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is", "**kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None)", "self.number_of_dos)) for i in range(len(self.total_dos)): spin = self.total_dos[i].attrib.get(self._nspin_key, i) res[i]", "self._calculation_type == 'volume_optimization': sec_method.x_exciting_volume_optimization = True def parse_scc(self, section): sec_run", "return self._neigs_segment class BandstructureXMLParser(XMLParser): def __init__(self, **kwargs): # TODO make", "self.bands: return self._distances = [ point.attrib.get(self._distance_key) for point in self.bands[0][0]]", "_parse_band_out(self, sec_scc): self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.band_out_parser.band_energies if band_energies", "= 'xs' # inconsistency in the naming convention for xs", "self.input_xml_parser.get( 'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlxas', [0, 0]) if", "for point in self.bands[0][0]] self._distances = np.array(self._distances, dtype=float) return self._distances", "(r'Maximum number of plane\\-waves', None), 'x_exciting_lo': (r'Total number of local\\-orbitals',", "0]) if self.input_xml_parser.get('xs/tddft') is not None: sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get( 'xs/tddft/acont',", "sec_scc = sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0] *", "default=None): return self.get('initialization', {}).get(key, default) class ExcitingParser: def __init__(self): self.info_parser", "val = moment_contributions.get(name, None) if val is not None: break", "= self.input_xml_parser.get( 'xs/gqmax', 0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states", "nwacont = self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf = self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list =", "initialization_quantities.append(Quantity( 'potential_mixing', r'Using ([\\w ]+) potential mixing', repeats=False, flatten=False) )", "add data to scc # TODO add support for more", "sec_scc.system_ref = sec_run.system[-1] sec_scc_ref = sec_run.calculation[0] sec_scc.starting_calculation_ref = sec_scc_ref sec_scc.calculations_ref", "_parse_input_xs(self, sec_method): xstype = self.input_xml_parser.get('xs/xstype', None) if xstype is not", "n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape( data[3], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re", "to be what they are. What is the fourth column", "Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) class ExcitingEvalqpParser(TextParser): def __init__(self):", "= atom_resolved return properties def str_to_quantity_tolerances(val_in): return val_in.strip().replace('(', '').replace(')', '').split()", "np.reshape( data[0], (n_components, n_sigma)) * ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re = np.reshape( data[1],", "structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence', [0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance = threshold_force def parse_method(self):", "# different names for different versions of exciting self._energy_keys_mapping =", "(target[0], suffix) if target[1:]: filepath = '%s.%s' % (filepath, target[1])", "for name in xc_functional_names: if name is None: continue if", "None self._species = None @property def distances(self): if self._distances is", "self.data_xs_parser = DataTextParser() self.data_clathrate_parser = DataTextParser(dtype=str) # different names for", "n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape( data[5], (n_components, n_excitons)) def parse_epsilon(data, sec_scc):", "sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_parser.get('band_k_points') nkpts_segment =", "None: return partialdos = partialdos.to('1/joule').magnitude lm_values = np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32)))", "* ureg.hartree + energy_fermi volume = self.info_parser.get_unit_cell_volume() dos = data[1]", "this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions at this step\\s*\\(([a-z]+)\\)'),", "sec_run.m_create(Calculation) sec_scc.method_ref = sec_method if sec_run.system: sec_scc.system_ref = sec_run.system[-1] sec_scc_ref", "= None self._nkpts_segment = None @property def band_energies(self): if self._band_energies", "input.xml for normal calculations # in addition to INFO.OUT return", "(n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape( data[5], (n_components, n_excitons)) def parse_epsilon(data,", "v[1] = [float(vi) for vi in v[1].split()] v[1] = v[1][0]", "repeats=False, flatten=False) ) initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[ Quantity('type',", "= self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf = self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont = self.input_xml_parser.get('xs/tddft/nwacont',", "r'(?:I| i)teration number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity( 'final', r'(?:Convergence", "final is None else final if final is None: return", "if self._calculation_type == 'gw': parser_function = self._parse_input_gw elif self._calculation_type ==", "sec_method.x_exciting_xs_rgkmax = rgkmax sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff',", "is None: return def get_data(key): if key == 'k_points': return", "== 'charge_total': pass else: setattr(msection, key, val) # moment contributions", "'band_segm_start_end': res = [] for i in range(len(self.number_of_k_points_per_segment)): start =", "self._get_dos(self._total_dos[i]) if self.energy_unit is not None: res = res *", "in the naming convention for xs input xml file sec_method", "file_ext, ext, fxctype)) data = [[], [], []] for i", "structure from one of the files: bs_files = ['bandstructure-qp.dat', 'BAND-QP.OUT']", "sec_k_band_segment.energies = band_energies[n][nb] + energy_fermi def _parse_eigenvalues(self, sec_scc): if self.eigval_parser.get('eigenvalues_occupancies',", "= [] def str_to_eigenvalue(val_in): val = val_in.strip().split('\\n') kpts = np.array(val[0].split(),", "final SCF iteration|Reached self-consistent loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity(", "== 'FXC': sec_scc = sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies =", "# other metainfo for name in self.info_parser._miscellaneous_keys_mapping.keys(): val = iteration.get(name)", "labels def get_positions_format(self, section): positions_format = section.get('positions_format') if positions_format is", "== 'energies': return self.energies else: res = None self._results[key] =", "smearing_kind_map[smearing_kind] sec_smearing.kind = smearing_kind smearing_width = self.info_parser.get_initialization_parameter('smearing_width') if smearing_width is", "np.transpose(self.data) self._distances = data[5][:int(max(data[1]))] return self._distances @property def number_of_spin_channels(self): if", "None), 'x_exciting_kpoint_grid': (r'k\\-point grid', None), 'x_exciting_kpoint_offset': (r'k\\-point offset', None), 'x_exciting_number_kpoints':", "(n_scf - len(quantity)) + quantity return quantity def get_xc_functional_name(self): #", "sec_dos_values.spin = spin sec_dos_values.atom_index = atom sec_dos_values.value = partialdos[lm][spin][atom] def", "parse(self, key): if self._results is None: self._results = dict() if", "3], float)) return dict( number=np.array(val[0], dtype=int), values=val[1] * ureg.hartree, weights=val[2])", "val # charge contributions charge_contributions = iteration.get('charge_contributions', {}) for key,", "return res = np.zeros(( self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos)) for i", "val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1] sec_charges = msection.m_create(Charges) sec_charges.value = [", "**kwargs): # TODO make a parent class for dos and", "% key_unit[0], unit=key_unit[1], repeats=False) ) initialization_quantities.append(Quantity( 'species', rf'(Species : *\\d+", "partialdos.to('1/joule').magnitude lm_values = np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32))) for lm in range(len(partialdos)):", "start = self.vertices[i].attrib.get('label') end = self.vertices[i + 1].attrib.get('label') res.append([ '\\u0393'", "= parser.info_parser.quantities self.eigval_parser.quantities = parser.eigval_parser.quantities self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities self.evalqp_parser.quantities =", "np.transpose( np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels = list(data[3]) else: sec_system.x_exciting_clathrates = False", "data]) else: energy = np.array([d[1].get(key, None) for d in data])", "not certain if screening/BSE are children of xs if self.input_xml_parser.get('xs/screening')", "GW band structure from one of the files: bs_files =", "muffin-tins', 'total in muffin-tins'], 'charge_total': ['total charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved'] }", "data = self.evalqp_parser.get('kpoints_eigenvalues') if data is None: return def get_data(key):", "for v in val_in.split('\\n')] val = np.transpose(np.array([v for v in", "n_components sec_scc.x_exciting_xs_bse_loss_energies = np.reshape( data[0], (n_components, n_loss)) * ureg.hartree sec_scc.x_exciting_xs_bse_loss", "end = self.vertices[i + 1].attrib.get('label') res.append([ '\\u0393' if start.lower() ==", "5: ['LDA_C_VBH'], 20: ['GGA_C_PBE', 'GGA_X_PBE'], 21: ['GGA_C_PBE', 'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL',", "return quantity def get_xc_functional_name(self): # TODO expand list to include", "str_to_energy_dict(val_in): val = val_in.strip().split('\\n') energies = dict() for v in", "scf steps dont have the quantity # the only thing", "energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb potential energy', 'Coulomb potential'], 'energy_xc_potential': ['xc potential", "None: # get it from input.xml for f in input_file:", "filenames if os.access(f, os.F_OK)] return filenames def file_exists(self, filename): \"\"\"Checks", "files = self.get_exciting_files(name) if len(files) > 1: self.logger.warn('Found multiple files.", "r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=ureg.hartree), Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict,", "'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge': ['total charge in muffin-tins', 'total in muffin-tins'],", "= sec_scc.m_create(Forces) sec_forces.total = ForcesEntry(value=forces) # scf iterations scf_iterations =", "== data[0])[0]) return self._neigs_segment class BandstructureXMLParser(XMLParser): def __init__(self, **kwargs): #", "volume.to('m**3').magnitude for spin in range(len(totaldos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin", "positions=None, positions_format=None): positions = positions if positions is not None", "in muffin-tins'], 'charge_total': ['total charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved'] } self._moment_keys_mapping =", "not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface =", "x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser): def __init__(self):", "[0, 0, 0, 0]) if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get( 'xs/BSE/xasatom',", "in self.total_dos[0]]) if self.energy_unit is not None: self._energies = self._energies", "return energies self._quantities = [Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False, dtype=str,", "r'name *: *(.+)'), Quantity('nuclear_charge', rf'nuclear charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge),", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "*[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False), Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False,", "= iteration.get(name) if val is None: continue setattr(msection, name, val)", "quantity == 'EXCITON': sec_scc = sec_run.m_create(Calculation) sccs.append(sec_scc) else: sec_scc =", "self.number_of_atoms, self.number_of_dos)) for i in range(len(self.partial_dos)): spin = self.partial_dos[i].attrib.get(self._nspin_key, None)", "self._results[key] = res class DOSXMLParser(XMLParser): def __init__(self, **kwargs): super().__init__(None) self._nspin_key", "self.energy_unit is not None: res = res * (1 /", "= smearing_kind[0] smearing_kind = smearing_kind_map[smearing_kind] sec_smearing.kind = smearing_kind smearing_width =", "np.array( [float(point.attrib.get(self._energy_key)) for point in self.total_dos[0]]) if self.energy_unit is not", "moment in muffin-tins'], 'x_exciting_total_moment': ['total moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved'] } def", "repeats=True), Quantity( 'final', r'(?:Convergence targets achieved\\. Performing final SCF iteration|Reached", "when setting mainfile self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_parser.get('band_energies', [])", "key): if self._results is None: self._results = dict() if 'total'", "self._quantities.append( Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'optical_band_gap',", "'unit' self._energy_unit = kwargs.get('energy_unit', None) self._units_mapping = dict(hartree=ureg.hartree) def init_parameters(self):", "repeats=False, dtype=float), Quantity( 'energy_total', r'Total energy at this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)',", "= len(partial_dos) return self._natoms @property def number_of_dos(self): if self._ndos is", "= len(data) data = np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components = n_components n_excitons =", "repeats=False, str_operation=str_to_array, convert=False, unit=ureg.hartree / ureg.bohr), Quantity( 'step', r'Optimization step\\s*(\\d+)',", "positions_format is None: species = self.get_initialization_parameter('species', []) for specie in", "def total_dos(self): if self._total_dos is None: self._total_dos = self.root.findall('./%s/%s' %", "return self.get('initialization', {}).get(key, default) class ExcitingParser: def __init__(self): self.info_parser =", "Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical", "Method, DFT, Electronic, Smearing, XCFunctional, Functional, GW as GWMethod, Scf,", "def init_quantities(self): re_symbol = re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in): val = [v.split(':')[-1].split()", "force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree / ureg.bohr, repeats=False, dtype=float), Quantity(", "is None: return data = np.transpose(self.data) n_kpoints = int(max(data[1])) bands", "*\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[ Quantity('number', r'Species : *(\\d+)',", "return sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref", "for point in self.total_dos[0]]) if self.energy_unit is not None: self._energies", "self.vertices[i].attrib.get('label') end = self.vertices[i + 1].attrib.get('label') res.append([ '\\u0393' if start.lower()", "XMLParser() self.data_xs_parser = DataTextParser() self.data_clathrate_parser = DataTextParser(dtype=str) # different names", "1]: self._nkpts_segment .append(count) count = 1 else: count += 1", "( System, Atoms ) from nomad.datamodel.metainfo.simulation.calculation import ( Calculation, Dos,", "not exist self._quantities.append( Quantity( 'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False) )", "ureg.bohr), 'x_exciting_empty_states': ('Number of empty states', None), 'x_exciting_valence_states': ('Total number", "self._nspin = 1 return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment", "dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])), Quantity( 'forces', r'Total atomic", "end]) elif key == 'band_segm_start_end': res = [] for i", "self._neigs_segment class BandOutParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin',", "kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): # TODO", "sec_scc_ref sec_scc.calculations_ref = [sec_scc_ref] # parse properties gw_info_files = self.get_exciting_files(gw_info_file)", "= self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get( 'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands", "np.reshape(data, (nspin, len(data) // nspin, len(data[0]))) sec_gw_eigenvalues = sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor", "stopped', sub_parser=TextParser(quantities=[ Quantity( 'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent in this", "= sec_scc.energy.fermi if energy_fermi is None: continue energy_fermi = energy_fermi.to(\"hartree\")", "vertices(self): if self._vertices is None: self._vertices = self.root.findall('./%s' % self._vertex_key)", "r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' % key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False)) module_quantities = [", "for nkpts_segment in self.number_of_k_points_per_segment: end = start + nkpts_segment self._band_k_points.append(", "if positions is None: species = self.get_initialization_parameter('species', []) if species:", "is None: if self.partial_dos is None: return self._nlm = 0", "TODO make a parent class for dos and bandstructure super().__init__(None)", "'%s%s' % (target[0], suffix) if target[1:]: filepath = '%s.%s' %", "= sec_method.m_create(DFT) sec_electronic = sec_method.m_create(Electronic) sec_electronic.method = 'DFT' smearing_kind_map =", "name.startswith('bandstructure') and name.endswith('dat'): parser = self.bandstructure_dat_parser parser_function = self._parse_bandstructure_dat elif", "res.append([ '\\u0393' if start.lower() == 'gamma' else start, '\\u0393' if", "positions_format is not None: break return positions_format def get_atom_positions(self, section={},", "self.bandstructure_parser parser_function = self._parse_bandstructure elif name.startswith('EIGVAL') and name.endswith('OUT'): parser =", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "files self.logger.warn( 'Mismatch in EXCITON and file type', data=dict(file=quantity)) sec_scc", "x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser):", "fermi energy: it is used to un-shift the DOS to", "key == 'Znk': return np.array([d[1].get(key, None) for d in data])", "* unit properties['atom_resolved'] = atom_resolved return properties def str_to_quantity_tolerances(val_in): return", "there is a mismatch between files self.logger.warn( 'Mismatch in EXCITON", "(r'Effective Wigner radius, r\\_s', ureg.bohr), 'x_exciting_empty_states': ('Number of empty states',", "ext == 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1] elif quantity == 'LOSS'", "self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser = BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser = GWInfoParser() self.input_xml_parser", "# TODO make a parent clas for bandstructure dat and", "properties exciting_files = ['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf'] # Parse DFT DOS", "not None: sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step') force_convergence = optimization_step.get('force_convergence') if force_convergence", "band_k_points[nb] sec_k_band_segment.endpoints_labels = band_seg_labels[nb] sec_k_band_segment.energies = band_energies[n][nb] + energy_fermi def", "return np.array([d[0][:3] for d in data]) elif key == 'Znk':", "sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = self.dos_parser.number_of_dos sec_dos.energies = self.dos_parser.energies", "'_C_' in name: sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB' in name: sec_xc_functional.hybrid.append(Functional(name=name)) else:", "@property def energies(self): if self._energies is None: if self.total_dos is", "parser = self.dos_out_parser parser_function = self._parse_dos_out elif name.startswith('bandstructure') and name.endswith('dat'):", "spin sec_dos_values.value = dos[spin] # TODO add PDOS def _parse_bandstructure_dat(self,", "'energy_total': ['Total energy', 'total energy'], 'x_exciting_fermi_energy': ['Fermi energy', 'Fermi'], 'energy_kinetic_electronic':", "= None self._neigs_segment = None self._bands = None self._vertices =", "'%s.%s' % (filename, target[1]) filename = os.path.join(self.info_parser.maindir, filename) if os.path.isfile(filename):", "self._calculation_type == 'gw': parser_function = self._parse_input_gw elif self._calculation_type == 'xs':", "else: setattr(msection, key, val) # convergence values for name in", "= sec_system sec_scc.method_ref = sec_run.method[-1] return sec_scc # groundstate and", "ureg.elementary_charge elif 'moment' in val_in: unit = ureg.elementary_charge * ureg.bohr", "= self.input_xml_parser.get('xs/xstype', None) if xstype is not None: sec_method.x_exciting_xs_xstype =", "len(self.get('energy_total_scf_iteration', [])) quantity = self.get('%s_scf_iteration' % name) if quantity is", "- len(quantity)) + quantity return quantity def get_xc_functional_name(self): # TODO", "for name, key_unit in self._system_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' %", "e in self.partial_dos]) for li in l_list: self._nlm += 2", "repeats=False, convert=False), Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False)] self._miscellaneous_keys_mapping", "kpts = np.array(val[0].split(), dtype=float) keys = val[1].split() eigs = np.transpose(np.array([v.split()", "@property def band_k_points(self): if self._band_k_points is None: data = np.transpose(self.data)", "band_energies = self.band_out_parser.band_energies if band_energies is None: return # Get", "[ Quantity( 'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr, repeats=False, convert=False), Quantity(", "data[1], (n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape( data[2], (n_components, n_epsilon)) def", "self._bands @property def vertices(self): if self._vertices is None: self._vertices =", "= DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser = ExcitingEigenvalueParser() self.fermisurf_parser =", "- 1]: self._nkpts_segment.append(count) count = 1 else: count += 1", "Charges, Forces, ForcesEntry, ScfIteration, BandGap ) from nomad.datamodel.metainfo.workflow import Workflow,", "energy contributions energy_contributions = iteration.get('energy_contributions', {}) for key, names in", "default) if not os.path.isfile(filename): file_ext = default.split('.')[-1] mainfile_base = mainfile.rsplit('.',", "sec_run.m_create(System) sec_atoms = sec_system.m_create(Atoms) sec_atoms.positions = positions sec_atoms.labels = atom_labels", "BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser = ExcitingEigenvalueParser() self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser() self.evalqp_parser = ExcitingEvalqpParser()", "def parse_exciton(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components", "['GGA_C_BGCP', 'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']} xc_functional = self.get('initialization', {}).get('xc_functional',", "= band_energies[nb] + energy_fermi def parse_file(self, name, section): # TODO", "= ExcitingFermiSurfaceBxsfParser() self.evalqp_parser = ExcitingEvalqpParser() self.dos_out_parser = DataTextParser() self.bandstructure_dat_parser =", "repeats=False) ) for name, key_unit in self._method_keys_mapping.items(): initialization_quantities.append( Quantity( name,", "input_file: return self.input_xml_parser.mainfile = input_file[0] xstype = self.input_xml_parser.get('xs/xstype', '') if", "range(len(band_energies[n])): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb]", "distances(self): if self._distances is None: data = np.transpose(self.data) self._distances =", "iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi is not None: setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi) #", "energy_fermi = 0.0 * ureg.hartree if sec_scc.energy is not None:", "radius *: *({re_float})', dtype=np.float64, unit=ureg.bohr), Quantity('radial_points', rf'radial points in muffin-tin", "None: sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step') force_convergence = optimization_step.get('force_convergence') if force_convergence is", "'0')) if not info_volume: break sec_scc.calculations_path.append(info_volume[0]) def init_parser(self): self.info_parser.mainfile =", "quantity == 'LOSS' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1]", "setattr(msection, key, val) if key == 'x_exciting_fermi_energy': sec_energy.fermi = val", "parse_scc(self, section): sec_run = self.archive.run[-1] final = section if section.get('energy_total')", "continue data_q.append(self.data_xs_parser.data) if not data_q: continue data_q = np.transpose(data_q, axes=(2,", "= np.reshape(data, (nspin, len(data) // nspin, 2)) data = np.transpose(data,", "return positions = np.dot(positions, cell.magnitude) return positions * ureg.bohr def", "r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str), Quantity( 'n_scf_iterations', r'Number of (?:total)* scf iterations\\s*\\:\\s*(\\d+)',", "class DOSXMLParser(XMLParser): def __init__(self, **kwargs): super().__init__(None) self._nspin_key = 'nspin' self._totaldos_key", "charge in muffin-tins', 'total in muffin-tins'], 'charge_total': ['total charge'], 'x_exciting_section_MT_charge_atom':", "np.reshape( data[3], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape( data[4], (n_components, n_excitons))", "['total moment in muffin-tins'], 'x_exciting_total_moment': ['total moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved'] }", "*Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr), ]), repeats=False)) self._quantities.append(Quantity(", "n_loss)) # TODO check if format of files are really", "'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False), Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n", "'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get( 'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get(", "Parse DFT band structure from one of the files bs_files", "+= [specie.get('symbol')] * len(specie.get('positions')) return labels def get_positions_format(self, section): positions_format", "DFT, Electronic, Smearing, XCFunctional, Functional, GW as GWMethod, Scf, BasisSet", "dtype=np.float64, unit=ureg.bohr), Quantity('radial_points', rf'radial points in muffin-tin *: *({re_float})', dtype=np.int32),", "case! I assume it is # energy dos_up dos_down nspin", "* ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi nkpts_segment", "gw info files gw_info_files = ['GW_INFO.OUT', 'GWINFO.OUT'] for f in", "is not None else logging self._calculation_type = None self.init_parser() sec_run", "r'Atomic positions at this step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str),", "from one of the files bs_files = ['dos.xml', 'TDOS.OUT'] for", "def parse_file(self, name, section): # TODO add support for info.xml,", "str_operation=str_to_atom_properties_dict, repeats=False, convert=False), Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False)]", "'charge' in val_in: unit = ureg.elementary_charge elif 'moment' in val_in:", "band_energy = np.array([ np.transpose(energy)[start:end] for energy in band_energies]) if self._energy_unit", "specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius')", "sec_electronic = sec_method.m_create(Electronic) sec_electronic.method = 'DFT' smearing_kind_map = { 'Gaussian':", "isinstance(smearing_kind, str): smearing_kind = smearing_kind[0] smearing_kind = smearing_kind_map[smearing_kind] sec_smearing.kind =", "self._moment_keys_mapping = { 'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment': ['total moment in muffin-tins'],", "import numpy as np import os import re import logging", "if frequency_data is not None: number = frequency_data.get('number') sec_method.gw.number_of_frequencies =", "= self.info_parser.get_xc_functional_name() if not xc_functional_names: # get it from input.xml", "'gw/scrcoul/scrtype', 'rpa') def parse_gw(self): sec_run = self.archive.run[-1] # two versions", "= get_files(quantity) for i in range(len(files)): data = get_data(files[i]) if", "self.filepath = filepath self.archive = archive self.logger = logger if", "wannier.out if name.startswith('dos') and name.endswith('xml'): parser = self.dos_parser parser_function =", "None self._total_dos = None self._partial_dos = None @property def energy_unit(self):", "initialization_quantities = [ Quantity( 'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr, repeats=False,", "number of G\\-vectors', None), 'x_exciting_lmaxapw': (r' APW functions', None), 'x_exciting_nuclear_charge':", "positions = specie.get('positions') positions = self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions =", "'x_exciting_section_MT_moment_atom': for n in range(len(val)): sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index =", "get_data('eigenvalues') def _parse_fermisurface(self, sec_scc): fermi_surface = self.fermisurf_parser.get('fermi_surface', [None])[0] if fermi_surface", "quantity def get_xc_functional_name(self): # TODO expand list to include other", "Quantity( 'atomic_positions', r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'imized atomic", "None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface def _parse_evalqp(self, sec_scc):", "sec_dos.energies = self.dos_parser.energies + energy_fermi volume = self.info_parser.get_unit_cell_volume() totaldos =", "'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3] def parse_xs(self): sec_run = self.archive.run[-1] xs_info_files", "steps dont have the quantity # the only thing that", "'energy_correlation': ['Correlation energy', 'correlation'], 'x_exciting_correlation_energy': ['Correlation energy', 'correlation'], 'energy_sum_eigenvalues': ['Sum", "sec_dos_values = sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind = 'spherical' sec_dos_values.lm = lm_values[lm]", "r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])), Quantity( 'forces', r'Total atomic forces including IBS", "are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities = [", "lattice_vectors * ureg.bohr atoms = self.input_xml_parser.get('structure/species/atom') atom_labels = [] for", "key == 'band_energies': # TODO I am not certain about", "'xs/nempty', 5) sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq', [1, 1, 1]) sec_method.x_exciting_xs_ngridk =", "# get it from input.xml for f in input_file: self.input_xml_parser.mainfile", "= self.get_exciting_files('input.xml') if positions is None: # get it from", "[sec_method_ref] self.parse_file('input.xml', sec_method) # parse properties input_file = self.get_exciting_files('input.xml') if", "'x_exciting_dos_fermi', x_exciting_dos_fermi) # energy contributions energy_contributions = iteration.get('energy_contributions', {}) for", "None: if self.total_dos is None: return self._energies = np.array( [float(point.attrib.get(self._energy_key))", "is not None: if not isinstance(smearing_kind, str): smearing_kind = smearing_kind[0]", "(r'Total number of k\\-points', None), 'x_exciting_rgkmax': (r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max \\(rgkmax\\)',", "= int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment", "else 1 data = dict() data['occupancies'] = np.reshape(occs, (nspin, len(occs)", "self.input_xml_parser.get( 'xs/screening/ngridk', [0, 0, 0]) rgkmax = self.input_xml_parser.get('xs/screening/rgkmax', None) if", "data = get_data(quantity, ext) if not data[0]: continue if quantity", "= sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.endpoints_labels =", "self._band_key) self._bands = [] if bands: self._bands.append(bands) # add atom-resolved", "in range(len(keys))} return [kpts, eigs] self._quantities.append( Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([", "or optimization_step final = section.get('scf_iteration', [None])[-1] final = section.get('optimization_step', [None])[-1]", "return sec_scc # groundstate and hybrids calculation for module in", "writing, software # distributed under the License is distributed on", "name: sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_' in name: sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB' in", "sec_method.x_exciting_xs_xstype = xstype sec_method.x_exciting_electronic_structure_method = xstype sec_method.x_exciting_xs_broadening = self.input_xml_parser.get( 'xs/broad',", "logging self._calculation_type = None self.init_parser() sec_run = self.archive.m_create(Run) sec_run.program =", "res.append([start, end]) else: res = None self._results[key] = res class", "# forces forces = section.get('forces') if forces is not None:", "'energy_exchange': ['Exchange energy', 'exchange'], 'x_exciting_exchange_energy': ['Exchange energy', 'exchange'], 'energy_correlation': ['Correlation", "'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy', 'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy', 'nuclear-nuclear'],", "return self._partial_dos @property def energies(self): if self._energies is None: if", "are reported. energy_fermi = sec_scc.energy.fermi if energy_fermi is None: return", "[f for f in filenames if os.access(f, os.F_OK)] return filenames", "0.0001) gmb = self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax = gmb * gmaxvr", "self.input_xml_parser.get('structure/species/atom') atom_labels = [] for n in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] *", "self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont = self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf = self.input_xml_parser.get('xs/tddft/aresdf', True)", "do is to assume that the first steps are the", "= sec_run.m_create(System) sec_atoms = sec_system.m_create(Atoms) sec_atoms.positions = positions sec_atoms.labels =", "self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' % key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False))", "sec_method.m_create(DFT) sec_electronic = sec_method.m_create(Electronic) sec_electronic.method = 'DFT' smearing_kind_map = {", "band_energies[nb] + energy_fermi def _parse_band_out(self, sec_scc): self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies", "format for the spin polarized case # I cannot find", "not data_q: continue data_q = np.transpose(data_q, axes=(2, 0, 1)) for", "self.input_xml_parser.get( 'xs/broad', 0.01, 'hartree') sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get( 'xs/gqmax', 0.0, '1/bohr')", "r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) initialization_quantities.append(Quantity( 'species', rf'(Species :", "None: return # volume optimizations volume_index = 1 while True:", "= None @property def band_energies(self): if self._band_energies is None: if", "to assume that the first steps are the # ones", "sec_dos_values.value = partialdos[lm][spin][atom] def _parse_bandstructure(self, sec_scc): # we need to", "dict() atom_resolved = [] species = None for v in", "class ExcitingInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): re_symbol = re.compile(r'([A-Z][a-z]?)')", "when there is a mismatch between files self.logger.warn( 'Mismatch in", "def get_files(name): bse_types = ['IP', 'singlet', 'triplet', 'RPA'] scr_types =", "'x_exciting_valence_states': ('Total number of valence states', None), 'x_exciting_hamiltonian_size': ('Maximum Hamiltonian", "(r'k\\-point offset', None), 'x_exciting_number_kpoints': (r'Total number of k\\-points', None), 'x_exciting_rgkmax':", "val_in.strip().split('\\n') properties = dict() atom_resolved = [] species = None", "'x_exciting_madelung_energy': ['Madelung energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic energy', 'core electron", "dist[0])[0][1] self._distances = dist[:n_k_points] return self._distances @property def number_of_spin_channels(self): if", "= val[-1] eigs = val[-2] nspin = 2 if occs[0]", "for li in l_list: self._nlm += 2 * li +", "= 'partialdos' self._diagram_key = 'diagram' self._l_key = 'l' self._m_key =", "if labels is None: # we get it by concatenating", "groundstate and hybrids calculation for module in ['groundstate', 'hybrids']: sec_scc", "self._parse_fermisurface elif name.startswith('EVALQP') and (name.endswith('DAT') or name.endswith('TXT')): parser = self.evalqp_parser", "None self._nkpts_segment = None self._neigs_segment = None self._vertices = None", "return self._natoms @property def number_of_dos(self): if self._ndos is None: total_dos", "nkpts_segment[nb] sec_k_band_segment.value = band_energies[nb] + energy_fermi def parse_file(self, name, section):", "is None: # get it from last scf_iteration or optimization_step", "return self._energy_unit @property def number_of_spin_channels(self): if self._nspin is None: if", "np import os import re import logging from nomad.units import", "contributions energy_contributions = iteration.get('energy_contributions', {}) for key, names in self._energy_keys_mapping.items():", "str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr), ]), repeats=False)) self._quantities.append(Quantity( 'hybrids', r'Hybrids", "sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n + 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol =", "weights=val[2]) # TODO Read also input parameters here if input_GW.xml", "end = start + nkpts_segment band_energy = np.array([np.transpose(band)[start:end] for band", "= positions_format positions = specie.get('positions') positions = self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m')", "li in l_list: self._nlm += 2 * li + 1", "potential'], 'energy_electrostatic': ['Hartree energy', 'Hartree'], 'x_exciting_hartree_energy': ['Hartree energy', 'Hartree'], 'x_exciting_electron_nuclear_energy':", "# parse input xml file, there seems to be two", "dtype=int), Quantity( 'method', r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str), Quantity( 'n_scf_iterations', r'Number of", "@property def distances(self): if self._distances is None: data = np.transpose(self.data)", "parse_file(self, name, section): # TODO add support for info.xml, wannier.out", "= iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi is not None: setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi)", "lattice_vectors = np.array(lattice_vectors, dtype=float) lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale', 1.0) positions =", "/ ureg.bohr), Quantity( 'step', r'Optimization step\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'method',", "'1/bohr') sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get( 'xs/nempty', 5)", "smearing_width is not None: smearing_width = (smearing_width * ureg.hartree).to('joule') #", "lattice_vectors = lattice_vectors * ureg.bohr atoms = self.input_xml_parser.get('structure/species/atom') atom_labels =", "dat and xml self._nspin = None self._nkpts_segment = None self._neigs_segment", "Authors. # # This file is part of NOMAD. #", "[0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel =", "get_files(quantity) for i in range(len(files)): data = get_data(files[i]) if not", "= None self._results[key] = res class ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self): super().__init__(None)", "self.info_gw_parser.get('optical_band_gap', None) if optical_band_gap is not None: sec_gap.value_optical = optical_band_gap", "else: res = None self._results[key] = res class ExcitingFermiSurfaceBxsfParser(TextParser): def", "setattr(sec_system, name, ' '.join([str(v) for v in val])) else: try:", "{ 'x_exciting_effective_potential_convergence': ( r'RMS change in effective potential \\(target\\)', ureg.hartree),", "False) sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get( 'xs/BSE/xas',", "sec_run.m_create(Calculation) def parse_scf(iteration, msection): energy_total = iteration.get('energy_total') sec_energy = msection.m_create(Energy)", "= sec_run.m_create(Calculation) sec_scc.method_ref = sec_method if sec_run.system: sec_scc.system_ref = sec_run.system[-1]", "ureg.joule).to('hartree') # TODO I am not sure about format for", "bse_type in bse_types: for scr_type in scr_types: files = self.get_exciting_files(", "self.input_xml_parser.get('xs/xstype', '') if xstype.lower() == 'bse': self._parse_xs_bse() elif xstype.lower() ==", "support for info.xml, wannier.out if name.startswith('dos') and name.endswith('xml'): parser =", "= self._parse_input_gw elif self._calculation_type == 'xs': parser_function = self._parse_input_xs else:", "'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb = self.input_xml_parser.get(", "vector] self._quantities.append( Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False)) self._quantities.append( Quantity( 'fermi_surface',", "self._nkpts_segment.append(count) return self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None:", "= section.get('forces') if forces is not None: sec_forces = sec_scc.m_create(Forces)", "sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic')", "r'atomic positions \\((.+?)\\)', flatten=False), Quantity( 'positions', rf'\\d+ : *({re_float}) *({re_float})", "f in input_file: self.input_xml_parser.mainfile = f positions = self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors", "self._parse_bandstructure_dat elif name.startswith('BAND') and name.endswith('OUT'): parser = self.band_out_parser parser_function =", "= sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft = sec_method.m_create(DFT) sec_electronic = sec_method.m_create(Electronic) sec_electronic.method", "= self.input_xml_parser if self._calculation_type == 'gw': parser_function = self._parse_input_gw elif", "sec_gw.max_frequency = self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type = self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2')", "* ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re = np.reshape( data[1], (n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im =", "Quantity( 'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity(", "r'(?:Convergence targets achieved\\. Performing final SCF iteration|Reached self-consistent loops maximum)([\\s\\S]+?)(\\n", "None: self._neigs_segment = len(self.bands[0]) // self.number_of_spin_channels return self._neigs_segment def parse(self,", "elif v[0].startswith('species'): species = re.search(re_symbol, v[-1]).group(1) elif v[0].startswith('atom'): v[0] =", "if not xc_functional_names: # simply write parameters xc_functional = self.info_parser.get('initialization',", "self._distances @property def bands(self): if self._bands is None: bands =", "the missing quantity if len(quantity) < n_scf: quantity = [None]", "'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) class ExcitingEvalqpParser(TextParser): def __init__(self): super().__init__(None)", "sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get( 'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get( 'xs/BSE/xasspecies', 0)", "is None: data = np.transpose(self.data) n_kpoints = np.where(data[0] == data[0][0])[0][1]", "dict() if 'total' in key: if not self.total_dos: return res", "None) nwacont = self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf = self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list", "= start + nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end]) start = end return", "band_parameters = self.fermisurf_parser.get('band_parameters', None) if band_parameters is not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface", "'RPA'] scr_types = ['full', 'diag', 'noinvdiag', 'longrange'] bse_files = []", "for name, key_unit in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' %", "the only thing that we can do is to assume", "= sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap is not None: sec_gap.value_fundamental = fundamental_band_gap", "data self._quantities.append( Quantity( 'eigenvalues_occupancies', r'\\(state\\, eigenvalue and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))',", "gmaxvr pwm = self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax = pwm * gmb", "[] for i in range(len(self.number_of_k_points_per_segment)): start = np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float)", "\\n')].strip() val = np.array([v.split() for v in val.split('\\n')], dtype=float) val", "self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos)) for i in range(len(self.partial_dos)): spin =", "Smearing, XCFunctional, Functional, GW as GWMethod, Scf, BasisSet ) from", "moment_contributions.get(name, None) if val is not None: break if val", "of the files bs_files = ['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat'] for fname", "val = val_in[:val_in.rfind('\\n \\n')].strip() val = np.array([v.split() for v in", "in the same folder where the mainfile is stored. \"\"\"", "sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.endpoints_labels = band_seg_labels[nb] sec_k_band_segment.energies = band_energies[n][nb] +", "= 'totaldos' self._partialdos_key = 'partialdos' self._diagram_key = 'diagram' self._l_key =", "val])) else: try: setattr(sec_system, name, val) except Exception: self.logger.warn('Error setting", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "threshold) # additionally, set threshold to global metainfo. This is", "if len(v) < 2: continue elif v[0].startswith('species'): species = re.search(re_symbol,", "sec_system.x_exciting_clathrates = False potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing is not", "init_quantities(self): self._quantities = [] def str_to_eigenvalue(val_in): val = val_in.strip().split('\\n') kpts", "['xc potential energy', 'xc potential'], 'energy_electrostatic': ['Hartree energy', 'Hartree'], 'x_exciting_hartree_energy':", "['Exchange energy', 'exchange'], 'energy_correlation': ['Correlation energy', 'correlation'], 'x_exciting_correlation_energy': ['Correlation energy',", "input_file = self.get_exciting_files('input.xml') for f in input_file: self.input_xml_parser.mainfile = f", "self.eigval_parser.get('k_points') sec_eigenvalues.occupations = get_data('occupancies') sec_eigenvalues.energies = get_data('eigenvalues') def _parse_fermisurface(self, sec_scc):", "under the Apache License, Version 2.0 (the \"License\"); # you", "= sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = self.dos_parser.number_of_dos sec_dos.energies = self.dos_parser.energies +", "self._distance_key = 'distance' self._coord_key = 'coord' self._energy_key = 'eval' self._vertex_key", "= self.evalqp_parser parser_function = self._parse_evalqp elif name.startswith('TDOS') and name.endswith('OUT'): parser", "dispersion correction'] } self._electron_charge_keys_mapping = { 'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage': ['core", "name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0], repeats=False, unit=key_unit[1])) self._convergence_keys_mapping = { 'x_exciting_effective_potential_convergence':", "None])[0] sec_xc_functional.reference = xc_functional.get('name_reference', [None, None])[1] sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels() if", "'e' self._dos_key = 'dos' self._unit_key = 'unit' self._energy_unit = kwargs.get('energy_unit',", "self-consistent loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n',", "'x_exciting_exchange_energy': ['Exchange energy', 'exchange'], 'energy_correlation': ['Correlation energy', 'correlation'], 'x_exciting_correlation_energy': ['Correlation", "'gw/mixbasis/epsmb', 0.0001) gmb = self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax = gmb *", "def _parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_dat_parser.band_energies if", "name.endswith('dat'): parser = self.bandstructure_dat_parser parser_function = self._parse_bandstructure_dat elif name.startswith('BAND') and", "= np.transpose(np.vstack(data)) n_epsilon = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon", "return nspin = self.info_parser.get_number_of_spin_channels() def reshape(data): if data[0] is None:", "# species species = self.info_parser.get_initialization_parameter('species', []) for specie in species:", "self._distances = None self._band_energies = None self._band_k_points = None @property", "sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:] elif quantity == 'EPSILON' and ext ==", "final is None: # get it from last scf_iteration or", "of files are really correct, i.e. columns are supposed #", "end res.append(res_n) elif key == 'band_k_points': res = [] for", "if positions is None or lattice_vectors is None or species", "= Scf(threshold_energy_change=threshold) xc_functional_names = self.info_parser.get_xc_functional_name() if not xc_functional_names: # get", "self.logger self.data_clathrate_parser.logger = self.logger def reuse_parser(self, parser): self.info_parser.quantities = parser.info_parser.quantities", "self.energy_unit return self._energies def _get_dos(self, diagram): dos = np.array( [point.attrib.get(self._dos_key)", "k\\-points', None), 'x_exciting_rgkmax': (r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max \\(rgkmax\\)', None), 'x_exciting_species_rtmin': (r'Species", "sec_run = self.archive.run[-1] xs_info_files = self.get_exciting_files('INFOXS.OUT') if not xs_info_files: return", "initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities = [ Quantity( 'energy_total', r'[Tt]*otal", "import re import logging from nomad.units import ureg from nomad.parsing.file_parser", "# to be what they are. What is the fourth", "[] for i in range(len(self.vertices) - 1): start = self.vertices[i].attrib.get('label')", "= optimization_step.get('method') if optimization_step.get('step') is not None: sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step')", "None), 'x_exciting_number_of_crystal_symmetries': ('Number of crystal symmetries', None), 'x_exciting_kpoint_grid': (r'k\\-point grid',", "None), 'x_exciting_hamiltonian_size': ('Maximum Hamiltonian size', None), 'x_exciting_pw': (r'Maximum number of", "if start.lower() == 'gamma' else start, '\\u0393' if end.lower() ==", "self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return self._energy_unit @property def number_of_spin_channels(self): if", "gw_info_file = f break if not self._calculation_type == 'gw': return", "== 'x_exciting_spin_treatment': sub_sec = sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment = val elif name", "self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment = self.input_xml_parser.get( 'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states = int(", "sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value = totaldos[spin] partialdos =", "= vi * unit properties['atom_resolved'] = atom_resolved return properties def", "@property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: self._neigs_segment = len(self.bands[0])", "n_excitons = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons sec_scc.x_exciting_xs_bse_exciton_energies =", "files, will read only first!') self.info_gw_parser.mainfile = gw_info_files[0] fermi_energy =", "// nspin data = np.reshape(data, (nspin, len(data) // nspin, 2))", "6 return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is None:", ".append(count) count = 1 else: count += 1 self._nkpts_segment.append(count) return", "None: species = v[0][2] atom_resolved.append(((species, v[1] * unit))) else: vi", "positions = np.dot(positions, cell.magnitude) return positions * ureg.bohr def get_scf_threshold(self,", "= 1 else: count += 1 self._nkpts_segment.append(count) return self._nkpts_segment @property", "'parameters', r'\\n *(.+?:.+)', repeats=True, str_operation=lambda x: [v.strip() for v in", "= np.array([np.transpose(band)[start:end] for band in bands]) if self._energy_unit: band_energy =", "in input_file: self.input_xml_parser.mainfile = f correlation = self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation)", "sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get( 'xs/tddft/nwacont', 0)", "self._nspin = np.shape(np.transpose(self.data))[0] - 6 return self._nspin @property def number_of_k_points_per_segment(self):", "in range(len(data)): data[j].append(data_q[j]) return data for quantity in ['EPSILON', 'LOSS',", "self._calculation_type = None self.init_parser() sec_run = self.archive.m_create(Run) sec_run.program = Program(", "one of the files: bs_files = ['bandstructure-qp.dat', 'BAND-QP.OUT'] for fname", "we get it by concatenating species symbols species = self.get('initialization',", "frequency_data.get('weights') fundamental_band_gap = self.info_gw_parser.get('direct_band_gap', None) if fundamental_band_gap is None: fundamental_band_gap", "def __init__(self, **kwargs): super().__init__(None) self._nspin_key = 'nspin' self._totaldos_key = 'totaldos'", "step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False, dtype=float) ] self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization", "data[1:3] elif quantity == 'SIGMA' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field", "= gmb * gmaxvr pwm = self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax =", "in val_in: unit = ureg.elementary_charge * ureg.bohr val = val_in.strip().split('\\n')", "'atomic_positions', r'(Atomic positions at this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic", "*: *({re_float})', dtype=np.float64, unit=ureg.bohr), Quantity('radial_points', rf'radial points in muffin-tin *:", "either express or implied. # See the License for the", "msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n + 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value", "self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14) rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax', None) if rgkmax is", "= dict() if not self.bands: return if key == 'band_energies':", "charge', ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective Wigner radius, r\\_s', ureg.bohr), 'x_exciting_empty_states': ('Number", "sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape( data[0], (n_components, n_epsilon)) * ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re =", "# energy dos_up dos_down nspin = self.info_parser.get_number_of_spin_channels() sec_dos = sec_scc.m_create(Dos,", "% (target[0], suffix) if target[1:]: filename = '%s.%s' % (filename,", "sec_xc_functional = sec_dft.m_create(XCFunctional) for name in xc_functional_names: if name is", "species]) if positions is None: return positions = np.array(positions) positions_format", "if tetradf else None, 'AC' if nwacont else None, 'NAR'", "res[lm][spin][atom] = self._get_dos(self.partial_dos[i]) if self.energy_unit is not None: res =", "'structure_optimization', r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization module stopped', sub_parser=TextParser(quantities=[ Quantity( 'optimization_step', r'(Optimization", "sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] #", "DataTextParser() self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser = BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser = GWInfoParser()", "sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get( 'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get( 'xs/BSE/xasedge',", "spin_treatment = self.get('initialization', {}).get( 'x_exciting_spin_treatment', 'spin-unpolarised') n_spin = 1 if", "fundamental_band_gap optical_band_gap = self.info_gw_parser.get('optical_band_gap', None) if optical_band_gap is not None:", "(r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max \\(rgkmax\\)', None), 'x_exciting_species_rtmin': (r'Species with R\\^MT\\_min', None),", "= sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.energies =", "Quantity( 'final', r'Force convergence target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions',", "int(spin) - 1 val_l = self.partial_dos[i].attrib.get(self._l_key, None) val_m = self.partial_dos[i].attrib.get(self._m_key,", "'%s%s' % (target[0], suffix) if target[1:]: filename = '%s.%s' %", "for f in files if f.endswith('QMT%s.OUT' % str(i + 1).rjust(3,", "self.get('initialization', {}).get( 'x_exciting_spin_treatment', 'spin-unpolarised') n_spin = 1 if spin_treatment.lower() ==", "self.logger self.evalqp_parser.logger = self.logger self.dos_out_parser.logger = self.logger self.bandstructure_dat_parser.logger = self.logger", "def init_parameters(self): self._ndos = None self._natoms = None self._nspin =", "None) if optical_band_gap is not None: sec_gap.value_optical = optical_band_gap def", "= { 'Gaussian': 'gaussian', 'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac': 'fermi', 'Extended': 'tetrahedra'}", "def __init__(self): self.info_parser = ExcitingInfoParser() self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser =", "None: self._nspin = np.shape(np.transpose(self.data)[1:])[0] return self._nspin @property def number_of_k_points_per_segment(self): if", "= kwargs.get('energy_unit', None) self._units_mapping = dict(hartree=ureg.hartree) def init_parameters(self): self._ndos =", "dtype=float) res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i])) elif key == 'band_segm_labels': res =", "data = get_data(files[i]) if not data: sccs.append(None) continue if quantity", "ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum \\|G\\| for potential and density', 1 /", "(1 / ureg.hartree) * volume.to('m**3').magnitude for spin in range(len(dos)): sec_dos_values", "dtype=float) end = np.array( self.vertices[i + 1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start, end,", "self.data_clathrate_parser = DataTextParser(dtype=str) # different names for different versions of", "= energy_contributions.get(name, None) if val is not None: break if", "= np.array(positions) positions_format = positions_format if positions_format is not None", "which is not parsed? sccs = [] for quantity in", "] self._system_keys_mapping = { 'x_exciting_unit_cell_volume': ('Unit cell volume', ureg.bohr **", "sec_charges.value = [ val[n][1].magnitude for n in range(len(val))] * val[0][1].units", "max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree / ureg.bohr)} for name, key_unit in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity(", "number of local\\-orbitals', None)} self._method_keys_mapping = { 'smearing_kind': ('Smearing scheme',", "not None: break if val is None: continue if key.startswith('energy_'):", "sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1] sec_scc = parse_configuration(structure_optimization) if sec_scc is None:", "def _parse_bandstructure(self, sec_scc): # we need to set nspin again", "in gw_files: self.parse_file(f, sec_scc) frequency_data = self.info_gw_parser.get('frequency_data', None) if frequency_data", "np.where(data[0] == data[0][0])[0][1] bands = data[1:] bands = np.reshape(bands, (", "val = [v.split(':')[-1].split() for v in val_in.strip().split('\\n')] val = val[0]", "None: # we get it by concatenating species symbols species", "= self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' % (name, bse_type, scr_type)) bse_files.append(files) return bse_files", "== 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3] elif quantity == 'SIGMA' and", "* ureg.hartree eigs_gw = get_data('E_GW') if eigs_gw[0] is None: return", "np.reshape( data[5], (n_components, n_excitons)) def parse_epsilon(data, sec_scc): n_components = len(data)", "try: setattr(sec_system, name, val) except Exception: self.logger.warn('Error setting metainfo.') #", "% self._partialdos_key) self._natoms = len(partial_dos) return self._natoms @property def number_of_dos(self):", "(r'Species with R\\^MT\\_min', None), 'x_exciting_gkmax': (r'Maximum \\|G\\+k\\| for APW functions',", "sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.energies", "different names for different versions of exciting self._energy_keys_mapping = {", "None) if band_parameters is not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface", "= f correlation = self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation) exchange = self.input_xml_parser.get('libxc/exchange',", "self._bands.append(band.findall('./%s' % self._band_key)) return self._bands @property def vertices(self): if self._vertices", "'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr, repeats=False, convert=False), Quantity( 'lattice_vectors_reciprocal', r'Reciprocal", "self._vertices = None self._distances = None self._band_energies = None self._band_k_points", "name.startswith('dos') and name.endswith('xml'): parser = self.dos_parser parser_function = self._parse_dos elif", "input_gw.xml and input-gw.xml for f in ['input_gw.xml', 'input-gw.xml', 'input.xml']: self.parse_file(f,", "sec_scc.x_exciting_xs_bse_sigma_im = np.reshape( data[2], (n_components, n_sigma)) def parse_loss(data, sec_scc): n_components", "[] if bands: self._bands.append(bands) # add atom-resolved bands_atom = self.root.findall('./*/%s'", "energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') # TODO I am not", "(self._totaldos_key, self._diagram_key)) return self._total_dos @property def partial_dos(self): if self._partial_dos is", "initialization_quantities.append(Quantity( 'species', rf'(Species : *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[", "= data[6:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies", "= self.get_exciting_files('input.xml') for f in input_file: self.input_xml_parser.mainfile = f correlation", "section.get('final') if final is None: # get it from last", "val[-1] eigs = val[-2] nspin = 2 if occs[0] ==", "unit=ureg.hartree / ureg.bohr) ] self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent loop started|Groundstate module", "I assume it is # energy dos_up dos_down nspin =", "return self._band_energies @property def distances(self): if self._distances is None: dist", "if name == 'x_exciting_spin_treatment': sub_sec = sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment = val", "= rgkmax sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff', [0.,", "is None: return nspin = self.info_parser.get_number_of_spin_channels() def get_data(key): data =", "self._energy_unit self._band_energies.append(band_energy) start = end return self._band_energies @property def band_k_points(self):", "'core electron kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion correction'] } self._electron_charge_keys_mapping =", "{}).get('xc_functional') if xc_functional is not None: sec_xc_functional.name = xc_functional.get('name_reference', [None,", "nspin = self.info_parser.get_number_of_spin_channels() def reshape(data): if data[0] is None: return", "if spin is None: spin = (i % (self.number_of_spin_channels *", "self.get('groundstate', self.get('hybrids', {})) return reference.get('scf_iteration', [{}])[-1].get( name, [None, None])[-1] def", "use this file except in compliance with the License. #", "['Madelung energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic energy', 'core electron kinetic'],", "get it from input.xml input_file = self.get_exciting_files('input.xml') for f in", "= len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints = len(eigs_gw) sec_gw_eigenvalues.kpoints = get_data('k_points') sec_gw_eigenvalues.energies =", "'k_points': return np.array([d[0][:3] for d in data]) elif key ==", "if not xc_functional_names: # get it from input.xml input_file =", "ureg.bohr, repeats=False, dtype=float), Quantity( 'energy_total', r'Total energy at this optimization", "module in ['groundstate', 'hybrids']: sec_scc = parse_configuration(self.info_parser.get(module)) if sec_scc is", "in muffin-tins', 'total in muffin-tins'], 'charge_total': ['total charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved']", "memory parser.mainfile = None def _parse_input_xs(self, sec_method): xstype = self.input_xml_parser.get('xs/xstype',", "'Coulomb'], 'energy_exchange': ['Exchange energy', 'exchange'], 'x_exciting_exchange_energy': ['Exchange energy', 'exchange'], 'energy_correlation':", "name: sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name)) if not xc_functional_names: # simply write", "\\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=1 / ureg.hartree), Quantity( 'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n", "sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape( data[1], (n_components, n_excitons)) *", "support for more output files and properties exciting_files = ['EIGVAL.OUT',", "fermi_energy = self.info_gw_parser.get('fermi_energy', None) if fermi_energy is not None: sec_scc.energy", "started|Groundstate module started)([\\s\\S]+?)Groundstate module stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities = [", "'exchange'], 'energy_correlation': ['Correlation energy', 'correlation'], 'x_exciting_correlation_energy': ['Correlation energy', 'correlation'], 'energy_sum_eigenvalues':", "calculations # in addition to INFO.OUT return else: return files", "self.get_positions_format(section) if positions_format == 'lattice': cell = self.get_initialization_parameter('lattice_vectors') if cell", "[Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False) ) self._quantities.append( Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False)", "self._dos_key = 'dos' self._unit_key = 'unit' self._energy_unit = kwargs.get('energy_unit', None)", "parser = self.bandstructure_parser parser_function = self._parse_bandstructure elif name.startswith('EIGVAL') and name.endswith('OUT'):", "for ext in ['FXC', 'NLF_FXC']: data = get_data(quantity, ext) if", "is not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface def", "None: sec_energy.total = EnergyEntry(value=energy_total) x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi is", "= self.bandstructure_dat_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints", "in val: v = v.split(':') if len(v) < 2: continue", "None: return self._energies = np.array( [float(point.attrib.get(self._energy_key)) for point in self.total_dos[0]])", "def _parse_evalqp(self, sec_scc): data = self.evalqp_parser.get('kpoints_eigenvalues') if data is None:", "(r'Maximum \\|G\\| for potential and density', 1 / ureg.bohr), 'x_exciting_gvector_size':", "self.info_parser.get_number_of_spin_channels() band_energies = self.band_out_parser.band_energies if band_energies is None: return #", "key == 'band_segm_labels': res = [] for i in range(len(self.vertices)", "in range(len(totaldos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value", "charge_contributions.get(name, None) if val is not None: break if val", "name: sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB' in name: sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name)) if", "repeats=False) ) class ExcitingEvalqpParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities", "msection.m_create(Energy) if energy_total is not None: sec_energy.total = EnergyEntry(value=energy_total) x_exciting_dos_fermi", "Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False)) def str_to_band_parameters(val_in): val = val_in.strip().split('\\n') nbands =", "sec_run = self.archive.m_create(Run) sec_run.program = Program( name='exciting', version=self.info_parser.get('program_version', '').strip()) #", "data = self.eigval_parser.get('eigenvalues_occupancies') # reshaping is not necessary as this", "r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0], repeats=False, unit=key_unit[1])) self._convergence_keys_mapping = { 'x_exciting_effective_potential_convergence': (", "mainfile self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_parser.get('band_energies', []) for n", "from input.xml for f in input_file: self.input_xml_parser.mainfile = f positions", "if sec_scc is None: # This is the case when", "ureg.hartree + energy_fermi volume = self.info_parser.get_unit_cell_volume() dos = data[1] *", "positions = self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors = self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3)) species =", "v[1].split()] v[1] = v[1][0] if len(v[1]) == 1 else v[1]", "data[1], (n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im = np.reshape( data[2], (n_components, n_sigma)) def", "v in data]) res = res.reshape((len(res), len(data), len(res[0]) // len(data)))", "get_data(quantity, ext): # all files related to quantity at all", "xml self._nspin = None self._nkpts_segment = None self._neigs_segment = None", "self._results is None: self._results = dict() if 'total' in key:", "'x_exciting_fermi_energy': sec_energy.fermi = val # charge contributions charge_contributions = iteration.get('charge_contributions',", "xc_functional_names: if name is None: continue if '_X_' in name:", "is None: continue if key == 'x_exciting_section_MT_moment_atom': for n in", "# determined from occupancies which is problematic sometimes res =", "% self.number_of_spin_channels][i] = np.array( [e.attrib.get(self._energy_key) for e in self.bands[n][i]]) for", "is None: return sec_scc = sec_run.m_create(Calculation) def parse_scf(iteration, msection): energy_total", "number of atoms per unit cell', None), 'x_exciting_spin_treatment': ('Spin treatment',", "parser.fermisurf_parser.quantities self.evalqp_parser.quantities = parser.evalqp_parser.quantities self.info_gw_parser.quantities = parser.info_gw_parser.quantities def parse(self, filepath,", "'single_point' structure_optimization = self.info_parser.get('structure_optimization') if structure_optimization is not None: sec_worfklow.type", "ureg.bohr, repeats=False, convert=False), ] self._system_keys_mapping = { 'x_exciting_unit_cell_volume': ('Unit cell", "try: parse_function(data, sec_scc) except Exception: self.logger.error('Error setting xs data', data=dict(file=quantity))", "sec_scc # groundstate and hybrids calculation for module in ['groundstate',", "data = np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components = n_components n_excitons = len(data[0]) //", "and bandstructure super().__init__(None) self._distance_key = 'distance' self._coord_key = 'coord' self._energy_key", "str_operation=str_to_array, unit=ureg.bohr, repeats=False, convert=False), Quantity( 'lattice_vectors_reciprocal', r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array,", "in self._energy_keys_mapping.items(): val = None for name in names: val", "[float(point.attrib.get(self._energy_key)) for point in self.total_dos[0]]) if self.energy_unit is not None:", "band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2]", "self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax =", "* volume.to('m**3').magnitude for spin in range(len(totaldos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total)", "sec_charges.total = charge_contributions.get('total charge') elif key == 'charge_total': pass else:", "(r'Total number of G\\-vectors', None), 'x_exciting_lmaxapw': (r' APW functions', None),", "False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get( 'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get( 'xs/tddft/drude',", "'TDOS-QP.OUT'] # Parse GW band structure from one of the", "stopped', sub_parser=TextParser(quantities=module_quantities) )) def get_atom_labels(self, section): labels = section.get('symbols') if", "== self.distances[i - 1]: self._nkpts_segment.append(count) count = 1 else: count", "for name in names: val = charge_contributions.get(name, None) if val", "name, key_unit in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' % key_unit[0],", "self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list = [ 'TET' if tetradf else None,", "self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb = self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa') def parse_gw(self):", "Quantity( 'energy_total', r'Total energy at this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False,", "= True def parse_scc(self, section): sec_run = self.archive.run[-1] final =", "self._energies is None: if self.total_dos is None: return self._energies =", "including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False, str_operation=str_to_array, convert=False, unit=ureg.hartree / ureg.bohr),", "not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface def _parse_evalqp(self,", "= self.input_xml_parser.get( 'xs/screening/ngridk', [0, 0, 0]) rgkmax = self.input_xml_parser.get('xs/screening/rgkmax', None)", "range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] * len(atoms[n])) if positions is None or atom_labels", "= get_data('E_GW') if eigs_gw[0] is None: return nspin = self.info_parser.get_number_of_spin_channels()", "specie.get('muffin_tin_radius') positions_format = specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format = positions_format positions = specie.get('positions')", "different versions of exciting self._energy_keys_mapping = { 'energy_total': ['Total energy',", "for f in input_file: self.input_xml_parser.mainfile = f correlation = self.input_xml_parser.get('libxc/correlation',", "parser.eigval_parser.quantities self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities self.evalqp_parser.quantities = parser.evalqp_parser.quantities self.info_gw_parser.quantities = parser.info_gw_parser.quantities", "in data]) if None in energy: return energy return np.array([d[1].get(key)", "Quantity( 'forces', r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False,", "'xs/screening/ngridk', [0, 0, 0]) rgkmax = self.input_xml_parser.get('xs/screening/rgkmax', None) if rgkmax", "# Copyright The NOMAD Authors. # # This file is", "if name.startswith('dos') and name.endswith('xml'): parser = self.dos_parser parser_function = self._parse_dos", "0.01, 'hartree') sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get( 'xs/gqmax', 0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw =", "dos_down nspin = self.info_parser.get_number_of_spin_channels() sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies =", "self.file_exists(fname): exciting_files.append(fname) break for f in exciting_files: self.parse_file(f, sec_scc) #", "[[], [], []] for i in range(len(qpoints)): data_q = []", "info clathrate_file = self.get_exciting_files('str.out') if clathrate_file: sec_system.x_exciting_clathrates = True self.data_clathrate_parser.mainfile", "Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=1 / ureg.hartree), Quantity( 'charge_contributions',", "(quantity, file_ext, ext, fxctype)) data = [[], [], []] for", "dos_up dos_down nspin = self.info_parser.get_number_of_spin_channels() sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies", "'mixed' sec_gw.qp_equation_treatment = 'linearization' sec_gw.max_frequency = self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type", "if some scf steps dont have the quantity # the", "one of the files bs_files = ['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat'] for", "sec_dos.n_energies = len(data) // nspin data = np.reshape(data, (nspin, len(data)", "structure from one of the files bs_files = ['bandstructure.xml', 'BAND.OUT',", "self.input_xml_parser.get( 'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get( 'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands =", "None self._distances = None self._band_energies = None self._neigs_segment = None", "data = np.reshape(data, (nspin, len(data) // nspin, 2)) data =", "r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False)) def str_to_band_parameters(val_in): val = val_in.strip().split('\\n') nbands", "is None: self._nspin = np.shape(np.transpose(self.data)[1:])[0] return self._nspin @property def number_of_k_points_per_segment(self):", "input_file = self.get_exciting_files('input.xml') if positions is None: # get it", "The NOMAD Authors. # # This file is part of", "('Total number of atoms per unit cell', None), 'x_exciting_spin_treatment': ('Spin", "scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' % key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False)) module_quantities", "r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])), Quantity( 'forces',", "lm = i % self.number_of_lm else: lm = int(val_l) **", "if not self.total_dos: return res = np.zeros((self.number_of_spin_channels, self.number_of_dos)) for i", "Quantity( 'name_reference', r'\\n *(.+?,.+)', str_operation=lambda x: [v.strip() for v in", "> 1: self.logger.warn('Found multiple files. Will read all!', data=dict(file=name)) for", "= val[n][1] else: setattr(msection, key, val) # convergence values for", "# additionally, set threshold to global metainfo. This is killing", "can do is to assume that the first steps are", "'x_exciting_number_of_atoms': ('Total number of atoms per unit cell', None), 'x_exciting_spin_treatment':", "return self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: self._neigs_segment", "sec_method.x_exciting_electronic_structure_method = xstype sec_method.x_exciting_xs_broadening = self.input_xml_parser.get( 'xs/broad', 0.01, 'hartree') sec_method.x_exciting_xs_gqmax", "return properties def str_to_quantity_tolerances(val_in): return val_in.strip().replace('(', '').replace(')', '').split() def str_to_energy_dict(val_in):", "self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff', [0., 0., 0.]) # TODO", "# add data to scc # TODO add support for", "in EXCITON and file type', data=dict(file=quantity)) sec_scc = sec_run.m_create(Calculation) if", "self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get( 'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra =", "quantity if len(quantity) < n_scf: quantity = [None] * (n_scf", "sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.endpoints_labels", "name.endswith('xml'): parser = self.input_xml_parser if self._calculation_type == 'gw': parser_function =", "Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file', r'parameters loaded from *: *(.+)'), Quantity('name', r'name", "= data[1] elif quantity == 'SIGMA' and ext == 'FXC':", "sec_energy.total = EnergyEntry(value=energy_total) x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi is not", "# I cannot find an example bandstructure file # atom-resolved", "3), 'x_exciting_number_of_atoms': ('Total number of atoms per unit cell', None),", "val_in.strip().split('\\n') kpts = np.array(val[0].split(), dtype=float) keys = val[1].split() eigs =", "['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE', 'GGA_X_WC'], 30: ['GGA_C_AM05', 'GGA_C_AM05'], 300: ['GGA_C_BGCP',", "// n_components sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape( data[0], (n_components, n_sigma)) * ureg.hartree", "self._band_k_points @property def distances(self): if self._distances is None: data =", "str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False)) module_quantities = [ Quantity( 'scf_iteration', r'(?:I| i)teration", "(r'Maximum \\|G\\+k\\| for APW functions', 1 / ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum", "sec_atoms.labels = atom_labels sec_atoms.periodic = [True] * 3 # TODO", "= self.input_xml_parser.get( 'xs/nempty', 5) sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq', [1, 1, 1])", "len(atoms[n])) if positions is None or atom_labels is None: return", "for i in range(len(self.vertices) - 1): start = self.vertices[i].attrib.get('label') end", "scr_type)) bse_files.append(files) return bse_files def get_data(files): data = [] for", "sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape( data[1], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies =", "30: ['GGA_C_AM05', 'GGA_C_AM05'], 300: ['GGA_C_BGCP', 'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']}", "energy', 'exchange'], 'energy_correlation': ['Correlation energy', 'correlation'], 'x_exciting_correlation_energy': ['Correlation energy', 'correlation'],", "species is None: continue lattice_vectors = np.array(lattice_vectors, dtype=float) lattice_vectors *=", "exciting_files.append(fname) break for f in exciting_files: self.parse_file(f, sec_scc) # structure", "super().__init__(None) def init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'fermi_energy', r'Fermi", "parse_scf(iteration, msection): energy_total = iteration.get('energy_total') sec_energy = msection.m_create(Energy) if energy_total", "in files if f.endswith('QMT%s.OUT' % str(i + 1).rjust(3, '0'))] for", "= parse_loss else: continue try: parse_function(data, sec_scc) except Exception: self.logger.error('Error", "return self._nspin @property def number_of_atoms(self): if self._natoms is None: partial_dos", "energy_contributions = iteration.get('energy_contributions', {}) for key, names in self._energy_keys_mapping.items(): val", "name in names: val = charge_contributions.get(name, None) if val is", "= reshape(get_data('Sc')) if eigs_gw_C is None: eigs_gw_C = reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation", "self.input_xml_parser.get( 'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get( 'xs/screening/ngridk', [0, 0, 0])", "vi = [float(vii) for vii in v[1].split()] vi = vi[0]", "if quantity == 'EXCITON': sec_scc = sec_run.m_create(Calculation) sccs.append(sec_scc) else: sec_scc", "'\\u0393' if end.lower() == 'gamma' else end]) elif key ==", "flatten=False) ) initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation", "plane\\-waves', None), 'x_exciting_lo': (r'Total number of local\\-orbitals', None)} self._method_keys_mapping =", "sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get( 'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get( 'xs/tddft/ahc', False)", "= val_in.strip().split('\\n') properties = dict() atom_resolved = [] species =", "addition to INFO.OUT return else: return files = self.get_exciting_files(name) if", "= len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0] * ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:]", "scf iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'force_convergence', r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)',", "0) sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get( 'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get( 'xs/BSE/xasspecies',", "in species: sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number =", "positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True,", "which also other energies are reported. energy_fermi = sec_scc.energy.fermi if", "reported. energy_fermi = 0.0 * ureg.hartree if sec_scc.energy is not", "'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1] elif quantity == 'SIGMA' and ext", "unit=key_unit[1], repeats=False) ) for name, key_unit in self._method_keys_mapping.items(): initialization_quantities.append( Quantity(", "@property def number_of_spin_channels(self): if self._nspin is None: self._nspin = 1", "self._distances = data[5][:int(max(data[1]))] return self._distances @property def number_of_spin_channels(self): if self._nspin", "occs = val[-1] eigs = val[-2] nspin = 2 if", "1.0) positions = np.dot(positions, lattice_vectors) * ureg.bohr lattice_vectors = lattice_vectors", "sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape( data[5], (n_components, n_excitons)) def parse_epsilon(data, sec_scc): n_components", "= [] count = 1 for i in range(1, len(self.distances)):", "None), 'x_exciting_number_kpoints': (r'Total number of k\\-points', None), 'x_exciting_rgkmax': (r'R\\^MT\\_min \\*", "limitations under the License. # import numpy as np import", "sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n + 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value =", "([\\w ]+) potential mixing', repeats=False, flatten=False) ) initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation", "threshold to global metainfo. This is killing me! if metainfo_name", "get_data('k_points') sec_gw_eigenvalues.energies = reshape(eigs_gw) sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx')) eigs_gw_C = reshape(get_data('Sc'))", "0.0) sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff', [0., 0., 0.]) # TODO I", "dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing', r'Using ([\\w ]+) potential mixing', repeats=False, flatten=False)", "sec_method.gw.starting_point = xc_functional_name sec_scc = sec_run.m_create(Calculation) sec_scc.method_ref = sec_method if", "correlation = self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation) exchange = self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange)", "IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr) ]", "for spin-polarized case! I assume it is # energy dos_up", "[None])[-1] final = section.get('optimization_step', [None])[-1] if final is None else", "__init__(self): self.info_parser = ExcitingInfoParser() self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree)", "n_sigma)) * ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re = np.reshape( data[1], (n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im", "and ext == 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1] elif quantity ==", "= self.info_parser.get_scf_threshold(name) if threshold is None: continue metainfo_name = 'x_exciting_scf_threshold_%s_change'", "class BandstructureXMLParser(XMLParser): def __init__(self, **kwargs): # TODO make a parent", "in bs_files: if self.file_exists(fname): exciting_files.append(fname) break # Parse DFT band", "0.]) # TODO I am not certain if screening/BSE are", "'NAR' if not aresdf else None] file_ext = '_'.join([e for", "= force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1] sec_scc = parse_configuration(structure_optimization) if sec_scc", "and xml self._nspin = None self._nkpts_segment = None self._neigs_segment =", "val_in.strip().split('\\n') nbands = int(val[0]) mesh = np.array(val[1].split(), dtype=int) origin =", "if species is None: species = v[0][2] atom_resolved.append(((species, v[1] *", "in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints =", "in muffin-tins'], 'x_exciting_total_moment': ['total moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved'] } def get_exciting_files(self,", "if sec_scc is None: continue # add data to scc", "= energy_fermi nkpts_segment = self.band_out_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment", "= sec_method.m_create(GWMethod) sec_gw.type = 'G0W0' gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment", "sec_system.m_create(Atoms) sec_atoms.positions = positions sec_atoms.labels = atom_labels sec_atoms.periodic = [True]", "self._quantities = [] def str_to_eigenvalue(val_in): val = val_in.strip().split('\\n') kpts =", "in val_in.strip().split('\\n')] val = val[0] if len(val) == 1 else", "quantity # the only thing that we can do is", "if bands: self._bands.append(bands) # add atom-resolved bands_atom = self.root.findall('./*/%s' %", "self._miscellaneous_keys_mapping = { 'x_exciting_gap': (r'Estimated fundamental gap', ureg.hartree), 'time': (r'Wall", "= self._parse_input_xs else: # TODO implement reading of parameters from", "_parse_xs_tddft(self): sec_run = self.archive.run[-1] fxctype = self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf =", "\"\"\"Checks if a the given filename exists and is accessible", "for name in self.info_parser._system_keys_mapping.keys(): val = self.info_parser.get_initialization_parameter(name) if val is", "for vii in v[1].split()] vi = vi[0] if len(vi) ==", "# TODO add support for more output files and properties", "'all') sec_gw.polarizability_number_of_empty_states = int( self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq', [1,", "= self.bandstructure_dat_parser parser_function = self._parse_bandstructure_dat elif name.startswith('BAND') and name.endswith('OUT'): parser", "np.reshape(occs, (nspin, len(occs) // nspin)) data['eigenvalues'] = np.reshape(eigs, (nspin, len(eigs)", "unit=ureg.bohr), Quantity('radial_points', rf'radial points in muffin-tin *: *({re_float})', dtype=np.int32), Quantity('positions_format',", "str_operation=str_to_frequency, repeats=False) ) self._quantities.append( Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False)", "number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data = np.transpose(self.data)[0] self._neigs_segment =", "self._nspin is None: self._nspin = np.shape(np.transpose(self.data)[1:])[0] return self._nspin @property def", "len(data[0]))) sec_gw_eigenvalues = sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands = len(eigs_gw[0])", "section): # TODO add support for info.xml, wannier.out if name.startswith('dos')", "= positions if positions is not None else section.get('positions') if", "self.input_xml_parser.get( 'xs/gqmax', 0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states =", "is None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band =", "key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_', '')), EnergyEntry(value=val)) else: setattr(msection, key, val)", "None self._bands = None self._vertices = None self._distances = None", "exchange = self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange) sec_xc_functional = sec_dft.m_create(XCFunctional) for name", "len(data) data = np.transpose(np.vstack(data)) n_epsilon = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_energy_points", "len(partial_dos) return self._natoms @property def number_of_dos(self): if self._ndos is None:", "if potential_mixing is not None: sec_system.x_exciting_potential_mixing = potential_mixing return sec_system", "the quantity # the only thing that we can do", "'diag', 'noinvdiag', 'longrange'] bse_files = [] for bse_type in bse_types:", "continue if quantity == 'EPSILON' and ext == 'FXC': sec_scc", "> 1: return sec_system for name in self.info_parser._system_keys_mapping.keys(): val =", "'RPA') tetradf = self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont = self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf", "unit=ureg.hartree / ureg.bohr), Quantity( 'step', r'Optimization step\\s*(\\d+)', repeats=False, dtype=int), Quantity(", "= rgkmax sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get( 'xs/screening/screentype', 'full') if self.input_xml_parser.get('xs/BSE') is", "data['occupancies'] = np.reshape(occs, (nspin, len(occs) // nspin)) data['eigenvalues'] = np.reshape(eigs,", "data for quantity in ['EPSILON', 'LOSS', 'SIGMA']: for ext in", "*: *(.+)'), Quantity('name', r'name *: *(.+)'), Quantity('nuclear_charge', rf'nuclear charge *:", "'isotropic') sec_gw.screened_Coulomb = self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa') def parse_gw(self): sec_run =", "= 0 band_energies = np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float) for", "'singlet', 'triplet', 'RPA'] scr_types = ['full', 'diag', 'noinvdiag', 'longrange'] bse_files", "change in effective potential \\(target\\)', ureg.hartree), 'x_exciting_energy_convergence': ( r'Absolute change", "lattice_vectors is None or species is None: continue lattice_vectors =", "are children of xs if self.input_xml_parser.get('xs/screening') is not None: sec_method.x_exciting_xs_screening_number_of_empty_states", "parser.info_gw_parser.quantities def parse(self, filepath, archive, logger): self.filepath = filepath self.archive", "options if f.endswith(file_ext)] options.sort() filenames = [os.path.join(self.info_parser.maindir, f) for f", "init_parser(self): self.info_parser.mainfile = self.filepath self.info_parser.logger = self.logger self.dos_parser.logger = self.logger", "the mainfile is stored. \"\"\" mainfile = os.path.basename(self.info_parser.mainfile) suffix =", "r'Total energy at this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False, dtype=float), Quantity(", "ext == 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3] elif quantity == 'SIGMA'", "in val_in.split('\\n')] val = np.transpose(np.array([v for v in val if", "= specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format = positions_format positions = specie.get('positions') positions =", "== 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3] def parse_xs(self): sec_run = self.archive.run[-1]", "is None: partial_dos = self.root.findall('./%s' % self._partialdos_key) self._natoms = len(partial_dos)", "= None self._neigs_segment = None self._vertices = None self._distances =", "distances(self): if self._distances is None: if not self.bands: return self._distances", "band_k_points = self.bandstructure_dat_parser.band_k_points nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment for nb in range(len(band_energies)):", "self._vertices = None self._distances = None self._species = None @property", "sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1] sec_scc = parse_configuration(structure_optimization) if", "energies = dict() for v in val: v = v.split(':')", "get_scf_threshold(self, name): reference = self.get('groundstate', self.get('hybrids', {})) return reference.get('scf_iteration', [{}])[-1].get(", "self._nkpts_segment = None self._neigs_segment = None self._vertices = None self._distances", "if cell is None: return positions = np.dot(positions, cell.magnitude) return", "self._distances = np.array(self._distances, dtype=float) return self._distances @property def bands(self): if", "self._vertices = self.root.findall('./%s' % self._vertex_key) return self._vertices @property def number_of_spin_channels(self):", "band_k_points = self.bandstructure_parser.get('band_k_points') nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels = self.bandstructure_parser.get('band_segm_labels') for", "volume_index = 1 while True: info_volume = self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2,", "force_convergence[1] sec_scc = parse_configuration(structure_optimization) if sec_scc is None: return #", "input-gw.xml for f in ['input_gw.xml', 'input-gw.xml', 'input.xml']: self.parse_file(f, sec_method) xc_functional_name", "np.reshape( data[4], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape( data[5], (n_components, n_excitons))", "sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get( 'xs/screening/screentype', 'full') if self.input_xml_parser.get('xs/BSE') is not None:", "= Energy(fermi=fermi_energy) gw_files = ['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT'] # Parse GW", "rf'electronic charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic mass *:", "'sum of eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective potential energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb potential", "sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step') force_convergence = optimization_step.get('force_convergence') if force_convergence is not", "val return np.array(val, dtype=float) def str_to_atom_properties_dict(val_in): unit = None if", "self.root.findall('./%s' % self._band_key) self._bands = [] if bands: self._bands.append(bands) #", "# the only thing that we can do is to", "self._quantities.append( Quantity( 'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False) ) self._quantities.append( Quantity(", "charge') elif key == 'charge_total': pass else: setattr(msection, key, val)", "names: val = moment_contributions.get(name, None) if val is not None:", "mass *: *({re_float})', dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin radius *: *({re_float})',", "rgkmax = self.input_xml_parser.get('xs/rgkmax', None) if rgkmax is None: rgkmax =", "* ureg.bohr def get_scf_threshold(self, name): reference = self.get('groundstate', self.get('hybrids', {}))", "# You may obtain a copy of the License at", "= end res.append(res_n) elif key == 'band_k_points': res = []", "iteration.get(name) if val is None: continue setattr(msection, name, val) #", "== 'band_segm_start_end': res = [] for i in range(len(self.number_of_k_points_per_segment)): start", "v.split(':') if len(v) < 2: continue energies[v[0].strip()] = float(v[1]) *", "np.array([d[0][:3] for d in data]) elif key == 'Znk': return", "1)) sec_dos.energies = data[0][0] * ureg.hartree + energy_fermi volume =", "== 'lattice': cell = self.get_initialization_parameter('lattice_vectors') if cell is None: return", "= os.path.join(self.info_parser.maindir, filepath) if os.path.isfile(filepath) and os.access(filepath, os.F_OK): return True", "= self.get('initialization', {}).get('xc_functional', None) if xc_functional is None: return []", "None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax = rgkmax sec_method.x_exciting_xs_bse_sciavbd =", "return [filename] filename = os.path.join(self.info_parser.maindir, default) if not os.path.isfile(filename): file_ext", "return files = self.get_exciting_files(name) if len(files) > 1: self.logger.warn('Found multiple", "def parse_scc(self, section): sec_run = self.archive.run[-1] final = section if", "None: if not self.total_dos: return self._nspin = len(self.total_dos) return self._nspin", "species: positions = np.vstack([s.get('positions') for s in species]) if positions", "key: if not self.partial_dos: return res = np.zeros(( self.number_of_lm, self.number_of_spin_channels,", "0, 1)) for j in range(len(data)): data[j].append(data_q[j]) return data for", "['full', 'diag', 'noinvdiag', 'longrange'] bse_files = [] for bse_type in", "= [] for quantity in ['EXCITON', 'EPSILON', 'SIGMA', 'LOSS']: files", "from nomad.units import ureg from nomad.parsing.file_parser import TextParser, Quantity, XMLParser,", "self._quantities.append(Quantity( 'initialization', r'(?:All units are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities))", "used to un-shift the band structure to # the original", "= lattice_vectors_reciprocal if len(sec_run.system) > 1: return sec_system for name", "for v in val])) else: try: setattr(sec_system, name, val) except", "'rpa') def parse_gw(self): sec_run = self.archive.run[-1] # two versions of", "= None self.init_parser() sec_run = self.archive.m_create(Run) sec_run.program = Program( name='exciting',", "self._parse_xs_tddft() def _parse_input_gw(self, sec_method): sec_gw = sec_method.m_create(GWMethod) sec_gw.type = 'G0W0'", "self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal if len(sec_run.system) > 1: return", "if final is None: return sec_scc = sec_run.m_create(Calculation) def parse_scf(iteration,", "atom_labels.extend([species[n].split('.')[0]] * len(atoms[n])) if positions is None or atom_labels is", "None or atom_labels is None: return sec_system = sec_run.m_create(System) sec_atoms", "first steps are the # ones with the missing quantity", "self.number_of_spin_channels) res[lm][spin][atom] = self._get_dos(self.partial_dos[i]) if self.energy_unit is not None: res", "nkpts_segment in self.number_of_k_points_per_segment: end = start + nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end])", "self.eigval_parser parser_function = self._parse_eigenvalues elif (name.startswith('FERMISURF') or name.startswith('FS')) and name.endswith('bxsf'):", "1 data = dict() data['occupancies'] = np.reshape(occs, (nspin, len(occs) //", "class ExcitingParser: def __init__(self): self.info_parser = ExcitingInfoParser() self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree)", "len(data) data = np.transpose(np.vstack(data)) n_loss = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_loss_energies", "two versions of gw info files gw_info_files = ['GW_INFO.OUT', 'GWINFO.OUT']", "np.shape(np.transpose(self.data))[0] - 6 return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment", "self.band_out_parser = BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser = GWInfoParser() self.input_xml_parser = XMLParser() self.data_xs_parser", "positions is None or lattice_vectors is None or species is", "ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:] elif quantity == 'EPSILON' and ext", "{}) for key, names in self._energy_keys_mapping.items(): val = None for", "initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) for", "self.input_xml_parser.get( 'xs/BSE/nstlxas', [0, 0]) if self.input_xml_parser.get('xs/tddft') is not None: sec_method.x_exciting_xs_tddft_analytic_continuation", "positions_format == 'lattice': cell = self.get_initialization_parameter('lattice_vectors') if cell is None:", "sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.value = band_energies[nb] + energy_fermi def", "= frequency_data.get('weights') fundamental_band_gap = self.info_gw_parser.get('direct_band_gap', None) if fundamental_band_gap is None:", "self.data is None: return data = np.transpose(self.data) n_kpoints = int(max(data[1]))", "2.0 (the \"License\"); # you may not use this file", "smearing_width = self.info_parser.get_initialization_parameter('smearing_width') if smearing_width is not None: smearing_width =", "parser = self.eigval_parser parser_function = self._parse_eigenvalues elif (name.startswith('FERMISURF') or name.startswith('FS'))", "None: # This is the case when there is a", "if smearing_kind is not None: if not isinstance(smearing_kind, str): smearing_kind", ": *(\\d+)', dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file', r'parameters loaded from *:", "self.input_xml_parser.logger = self.logger self.data_xs_parser.logger = self.logger self.data_clathrate_parser.logger = self.logger def", "0.) sec_method.x_exciting_xs_screening_rgkmax = rgkmax sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get( 'xs/screening/screentype', 'full') if", "return self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return self._energy_unit @property def number_of_spin_channels(self):", "'total energy'], 'x_exciting_fermi_energy': ['Fermi energy', 'Fermi'], 'energy_kinetic_electronic': ['Kinetic energy', 'electronic", "about format for spin-polarized case! I assume it is #", "= self._parse_band_out elif name.startswith('input') and name.endswith('xml'): parser = self.input_xml_parser if", "None: continue lattice_vectors = np.array(lattice_vectors, dtype=float) lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale', 1.0)", "sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get( 'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical')", "sec_scc.m_create(Forces) sec_forces.total = ForcesEntry(value=forces) # scf iterations scf_iterations = section.get('scf_iteration',", "n_kpoints)) self._band_energies = [] start = 0 for nkpts_segment in", "v = v.split(':') if len(v) < 2: continue energies[v[0].strip()] =", "sec_gw_eigenvalues.n_bands = len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints = len(eigs_gw) sec_gw_eigenvalues.kpoints = get_data('k_points') sec_gw_eigenvalues.energies", "= self.input_xml_parser.get( 'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get( 'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd", "len(v) < 2: continue elif v[0].startswith('species'): species = re.search(re_symbol, v[-1]).group(1)", "reference = self.get('groundstate', self.get('hybrids', {})) return reference.get('scf_iteration', [{}])[-1].get( name, [None,", "if positions is not None else section.get('positions') if positions is", "self._results = dict() if 'total' in key: if not self.total_dos:", "in range(len(partialdos)): for spin in range(len(partialdos[lm])): for atom in range(len(partialdos[lm][spin])):", "parser = self.input_xml_parser if self._calculation_type == 'gw': parser_function = self._parse_input_gw", "= smearing_width.magnitude for name in self.info_parser._convergence_keys_mapping.keys(): threshold = self.info_parser.get_scf_threshold(name) if", "'x_exciting_section_MT_charge_atom': ['atom_resolved'] } self._moment_keys_mapping = { 'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment': ['total", "is the case when there is a mismatch between files", "self.bands[n][i]]) for nkpts_segment in self.number_of_k_points_per_segment: end = start + nkpts_segment", "val[n][1] sec_charges = msection.m_create(Charges) sec_charges.value = [ val[n][1].magnitude for n", "if eigs_gw_C is None: eigs_gw_C = reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation = eigs_gw_C", "if optimization_step.get('step') is not None: sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step') force_convergence =", "len(val) == 1 else val return np.array(val, dtype=float) def str_to_atom_properties_dict(val_in):", "self.info_parser._convergence_keys_mapping.keys(): threshold = self.info_parser.get_scf_threshold(name) if threshold is None: continue metainfo_name", "sec_gw = sec_method.m_create(GWMethod) sec_gw.type = 'G0W0' gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0)", "quantity = self.get('%s_scf_iteration' % name) if quantity is None: return", "= self.partial_dos[i].attrib.get(self._l_key, None) val_m = self.partial_dos[i].attrib.get(self._m_key, None) if val_l is", "def band_energies(self): if self._band_energies is None: if self.data is None:", "return def get_data(key): if key == 'k_points': return np.array([d[0][:3] for", "TODO I am not certain about the format for the", "name, key_unit in self._method_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0],", "self.get_exciting_files('str.out') if clathrate_file: sec_system.x_exciting_clathrates = True self.data_clathrate_parser.mainfile = clathrate_file[0] if", "repeats=False)) self._quantities.append(Quantity( 'hybrids', r'Hybrids module started([\\s\\S]+?)Hybrids module stopped', sub_parser=TextParser(quantities=module_quantities) ))", "self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude # clathrate info clathrate_file", "val: v = v.strip().split(':') if len(v) < 2: continue elif", "dict() if not self.bands: return if key == 'band_energies': #", "sec_scc.method_ref = sec_method if sec_run.system: sec_scc.system_ref = sec_run.system[-1] sec_scc_ref =", "return self._band_energies @property def band_k_points(self): if self._band_k_points is None: data", "None else self.get_positions_format(section) if positions_format == 'lattice': cell = self.get_initialization_parameter('lattice_vectors')", "'optimization_step', [{}])[0].get('force_convergence', [0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance = threshold_force def parse_method(self): sec_run", "nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies)", "(r'Wall time \\(seconds\\)', ureg.s)} for name, key_unit in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity(", "if clathrate_file: sec_system.x_exciting_clathrates = True self.data_clathrate_parser.mainfile = clathrate_file[0] if self.data_clathrate_parser.data:", "energy in band_energies]) if self._energy_unit is not None: band_energy =", "sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get( 'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14)", "data = np.transpose(self.data) n_kpoints = np.where(data[0] == data[0][0])[0][1] bands =", "names in self._electron_charge_keys_mapping.items(): val = None for name in names:", "for e in file_ext_list if e]) # read q points", "# in addition to INFO.OUT return else: return files =", "def number_of_spin_channels(self): if self._nspin is None: if not self.total_dos: return", "# moment contributions moment_contributions = iteration.get('moment_contributions', {}) for key, names", "= self.input_xml_parser.get( 'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment", "positions_format=None): positions = positions if positions is not None else", "'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get( 'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get(", "bs_files = ['bandstructure-qp.dat', 'BAND-QP.OUT'] for fname in bs_files: if self.file_exists(fname):", "is None or species is None: continue lattice_vectors = np.array(lattice_vectors,", "('Total nuclear charge', ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total electronic charge', ureg.elementary_charge), 'x_exciting_core_charge_initial':", "self.input_xml_parser.get( 'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get( 'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd =", "energy_fermi = sec_scc.energy.fermi if energy_fermi is None: continue energy_fermi =", "if not data: sccs.append(None) continue if quantity == 'EXCITON': sec_scc", "parse_loss(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_loss =", "band in bands_atom: self._bands.append(band.findall('./%s' % self._band_key)) return self._bands @property def", "quantity == 'EXCITON': parse_function = parse_exciton elif quantity == 'EPSILON':", ") from nomad.datamodel.metainfo.simulation.calculation import ( Calculation, Dos, DosValues, BandStructure, BandEnergies,", "else: energy = np.array([d[1].get(key, None) for d in data]) if", "None self._neigs_segment = None self._nkpts_segment = None @property def band_energies(self):", "which also other energies are reported. energy_fermi = 0.0 *", "name, val) except Exception: self.logger.warn('Error setting metainfo.') # species species", "'LOSS' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1] elif quantity", "np.transpose(self.data)[0] self._neigs_segment = len(np.where(data == data[0])[0]) return self._neigs_segment class BandstructureXMLParser(XMLParser):", "See the License for the specific language governing permissions and", "= band_parameters[3] fermi_energy = self.fermisurf_parser.get('fermi_energy', None) if fermi_energy is not", "- 1): start = self.vertices[i].attrib.get('label') end = self.vertices[i + 1].attrib.get('label')", "self.root.findall('./%s/%s' % (self._partialdos_key, self._diagram_key)) return self._partial_dos @property def energies(self): if", "to in writing, software # distributed under the License is", "return self._energies def _get_dos(self, diagram): dos = np.array( [point.attrib.get(self._dos_key) for", "= len(data) data = np.transpose(np.vstack(data)) n_epsilon = len(data[0]) // n_components", "v[1][0] if len(v[1]) == 1 else v[1] if species is", "positions_format def get_atom_positions(self, section={}, positions=None, positions_format=None): positions = positions if", "= sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration) return sec_scc def parse_system(self, section): sec_run", "# Parse DFT band structure from one of the files", "are supposed # to be what they are. What is", "= [v.split(':')[-1].split() for v in val_in.strip().split('\\n')] val = val[0] if", "at all qpoints files = self.get_exciting_files('%s_%s%s%s.OUT' % (quantity, file_ext, ext,", "is None: continue if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_', '')), EnergyEntry(value=val))", "(i % (self.number_of_spin_channels * self.number_of_lm)) // self.number_of_lm else: spin =", "= val elif name == 'x_exciting_species_rtmin': setattr(sec_system, name, ' '.join([str(v)", "in range(len(self.number_of_k_points_per_segment)): start = self.vertices[i].attrib.get(self._coord_key).split() end = self.vertices[i + 1].attrib.get(self._coord_key).split()", "self.dos_out_parser = DataTextParser() self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser = BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser", "np.array( [point.attrib.get(self._dos_key) for point in diagram], dtype=float) return dos def", "file_exists(self, filename): \"\"\"Checks if a the given filename exists and", "if not data[0]: continue if quantity == 'EPSILON' and ext", "v[0].startswith('atom'): v[0] = v[0].split() v[1] = [float(vi) for vi in", "[nbands, mesh, origin, vector] self._quantities.append( Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False))", "optical_band_gap def parse_miscellaneous(self): sec_worfklow = self.archive.m_create(Workflow) sec_worfklow.type = 'single_point' structure_optimization", "['total charge in muffin-tins', 'total in muffin-tins'], 'charge_total': ['total charge'],", "compliance with the License. # You may obtain a copy", "False def _parse_dos(self, sec_scc): if self.dos_parser.get('totaldos', None) is None: return", "suffix = mainfile.strip('INFO.OUT') target = default.rsplit('.', 1) filename = '%s%s'", "[kpts, eigs] self._quantities.append( Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True))", "only thing that we can do is to assume that", "in self.bands[0][0]] self._distances = np.array(self._distances, dtype=float) return self._distances @property def", "if self._total_dos is None: self._total_dos = self.root.findall('./%s/%s' % (self._totaldos_key, self._diagram_key))", "eigs_gw_C is None: eigs_gw_C = reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation = eigs_gw_C sec_gw_eigenvalues.value_xc_potential", "np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels = list(data[3]) else: sec_system.x_exciting_clathrates = False potential_mixing", "sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0] * ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field =", "= xc_functional_name sec_scc = sec_run.m_create(Calculation) sec_scc.method_ref = sec_method if sec_run.system:", "be two versions, input_gw.xml and input-gw.xml for f in ['input_gw.xml',", "Parse DFT DOS from one of the files bs_files =", "self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing is not None: sec_system.x_exciting_potential_mixing = potential_mixing return", "self._nspin = None self._distances = None self._band_energies = None self._neigs_segment", "loop started|Groundstate module started)([\\s\\S]+?)Groundstate module stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities =", "['interstitial'], 'x_exciting_total_MT_charge': ['total charge in muffin-tins', 'total in muffin-tins'], 'charge_total':", "partialdos is None: return partialdos = partialdos.to('1/joule').magnitude lm_values = np.column_stack((np.arange(len(partialdos)),", "'tddft': self._parse_xs_tddft() def _parse_input_gw(self, sec_method): sec_gw = sec_method.m_create(GWMethod) sec_gw.type =", "r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False) ) self._quantities.append( Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s',", "unit cell', None), 'x_exciting_spin_treatment': ('Spin treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number of", "( r'RMS change in effective potential \\(target\\)', ureg.hartree), 'x_exciting_energy_convergence': (", "energy: return energy return np.array([d[1].get(key) for d in data]) *", "xstype = self.input_xml_parser.get('xs/xstype', '') if xstype.lower() == 'bse': self._parse_xs_bse() elif", "threshold = self.info_parser.get_scf_threshold(name) if threshold is None: continue metainfo_name =", "r'Charge distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence': ( r'Abs\\. change in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree", "atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'imized atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols',", "return dos def parse(self, key): if self._results is None: self._results", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "return self._neigs_segment class BandOutParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin =", "sccs = [] for quantity in ['EXCITON', 'EPSILON', 'SIGMA', 'LOSS']:", "data_q = [] files_q = [f for f in files", "dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic mass *: *({re_float})', dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius',", "4: ['LDA_C_XALPHA'], 5: ['LDA_C_VBH'], 20: ['GGA_C_PBE', 'GGA_X_PBE'], 21: ['GGA_C_PBE', 'GGA_X_PBE_R'],", "None self._distances = None self._band_energies = None self._band_k_points = None", "elif 'moment' in val_in: unit = ureg.elementary_charge * ureg.bohr val", "filepath) if os.path.isfile(filepath) and os.access(filepath, os.F_OK): return True return False", "if smearing_width is not None: smearing_width = (smearing_width * ureg.hartree).to('joule')", "states', None), 'x_exciting_hamiltonian_size': ('Maximum Hamiltonian size', None), 'x_exciting_pw': (r'Maximum number", "self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file", "= None self._bands = None self._vertices = None self._distances =", "not xc_functional_names: # simply write parameters xc_functional = self.info_parser.get('initialization', {}).get('xc_functional')", "from input.xml input_file = self.get_exciting_files('input.xml') for f in input_file: self.input_xml_parser.mainfile", "sec_method): sec_gw = sec_method.m_create(GWMethod) sec_gw.type = 'G0W0' gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr',", "= v.strip().split(':') if len(v) < 2: continue elif v[0].startswith('species'): species", "sec_atoms = sec_system.m_create(Atoms) sec_atoms.positions = positions sec_atoms.labels = atom_labels sec_atoms.periodic", "files bs_files = ['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat'] for fname in bs_files:", "self.info_parser.get_number_of_spin_channels() def get_data(key): data = self.eigval_parser.get('eigenvalues_occupancies') # reshaping is not", "number_of_atoms(self): if self._natoms is None: partial_dos = self.root.findall('./%s' % self._partialdos_key)", "return positions = np.array(positions) positions_format = positions_format if positions_format is", "@property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data = np.transpose(self.data)[0]", "'energy_electrostatic': ['Hartree energy', 'Hartree'], 'x_exciting_hartree_energy': ['Hartree energy', 'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear", "return val_in.strip().replace('(', '').replace(')', '').split() def str_to_energy_dict(val_in): val = val_in.strip().split('\\n') energies", ") self._quantities.append( Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity(", "is None: self._results = dict() if 'total' in key: if", "is None: continue if name == 'time': msection.time_calculation = val", "energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies", "\\|G\\+k\\| for APW functions', 1 / ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum \\|G\\|", "= self.input_xml_parser.get('xs/BSE/rgkmax', None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax',", "n_components = len(data) data = np.transpose(np.vstack(data)) n_epsilon = len(data[0]) //", "parser): self.info_parser.quantities = parser.info_parser.quantities self.eigval_parser.quantities = parser.eigval_parser.quantities self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities", "is None or atom_labels is None: return sec_system = sec_run.m_create(System)", "self.parse_file(f, sec_scc) # structure optimization structure_optimization = self.info_parser.get('structure_optimization', {}) for", "'Hartree'], 'x_exciting_hartree_energy': ['Hartree energy', 'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy', 'electron-nuclear '],", "in muffin-tin *: *({re_float})', dtype=np.int32), Quantity('positions_format', r'atomic positions \\((.+?)\\)', flatten=False),", "eigenvalue and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues, repeats=True)) class ExcitingGWOutParser(TextParser): def", "the band structure to # the original scale in which", "False) def _parse_xs_bse(self): sec_run = self.archive.run[-1] # TODO read from", "sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1] sec_charges = msection.m_create(Charges) sec_charges.value = [ val[n][1].magnitude", "data[2], (n_components, n_epsilon)) def parse_sigma(data, sec_scc): n_components = len(data) data", "self._nspin = np.shape(np.transpose(self.data)[1:])[0] return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment", "range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb]", "'x_exciting_section_MT_charge_atom': for n in range(len(val)): sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index =", "['Exchange energy', 'exchange'], 'x_exciting_exchange_energy': ['Exchange energy', 'exchange'], 'energy_correlation': ['Correlation energy',", "filepath = '%s.%s' % (filepath, target[1]) filepath = os.path.join(self.info_parser.maindir, filepath)", "not self.bands: return self._distances = [ point.attrib.get(self._distance_key) for point in", "v in val: v = v.strip().split(':') if len(v) < 2:", "optimization structure_optimization = self.info_parser.get('structure_optimization', {}) for optimization_step in structure_optimization.get('optimization_step', []):", "+ energy_fermi def _parse_eigenvalues(self, sec_scc): if self.eigval_parser.get('eigenvalues_occupancies', None) is None:", "if self._nspin is None: if not self.total_dos: return self._nspin =", "= specie.get('muffin_tin_radius') positions_format = specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format = positions_format positions =", "specie in species: positions_format = specie.get('positions_format', None) if positions_format is", "data[6:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies =", "per unit cell', None), 'x_exciting_spin_treatment': ('Spin treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number", "quantity == 'EPSILON' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3]", "self._band_energies is None: if self.data is None: return data =", "# volume optimizations volume_index = 1 while True: info_volume =", "sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape( data[2], (n_components, n_epsilon)) def parse_sigma(data, sec_scc): n_components", "super().__init__(None) def init_quantities(self): self._quantities = [] def str_to_eigenvalue(val_in): val =", "in self._electron_charge_keys_mapping.items(): val = None for name in names: val", "np.transpose(np.vstack(data)) n_epsilon = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies", "xstype sec_method.x_exciting_xs_broadening = self.input_xml_parser.get( 'xs/broad', 0.01, 'hartree') sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get(", "xc_functional is None: return [] name = xc_functional_map.get(xc_functional.type, []) return", "if format of files are really correct, i.e. columns are", "(filepath, target[1]) filepath = os.path.join(self.info_parser.maindir, filepath) if os.path.isfile(filepath) and os.access(filepath,", "res = np.zeros((self.number_of_spin_channels, self.number_of_dos)) for i in range(len(self.total_dos)): spin =", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "if threshold is None: continue metainfo_name = 'x_exciting_scf_threshold_%s_change' % name.split('_')[-2]", "None: return nspin = self.info_parser.get_number_of_spin_channels() def reshape(data): if data[0] is", "n_components sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape( data[0], (n_components, n_epsilon))", "def _parse_xs_bse(self): sec_run = self.archive.run[-1] # TODO read from xml", "'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung energy', 'Madelung'],", "is not None: sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step') force_convergence = optimization_step.get('force_convergence') if", "= sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points =", "sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities = [ Quantity( 'atomic_positions', r'(Atomic positions at", "info files gw_info_files = ['GW_INFO.OUT', 'GWINFO.OUT'] for f in gw_info_files:", "in val_in: unit = ureg.elementary_charge elif 'moment' in val_in: unit", "= np.array( [point.attrib.get(self._dos_key) for point in diagram], dtype=float) return dos", "self.info_parser.get_number_of_spin_channels() def reshape(data): if data[0] is None: return return np.reshape(data,", "name.startswith('FS')) and name.endswith('bxsf'): parser = self.fermisurf_parser parser_function = self._parse_fermisurface elif", "also other energies are reported. energy_fermi = sec_scc.energy.fermi if energy_fermi", "None self._partial_dos = None @property def energy_unit(self): if self._energy_unit is", "not xs_info_files: return self._calculation_type = 'xs' # inconsistency in the", "= sec_run.m_create(Calculation) sccs.append(sec_scc) else: sec_scc = sccs[i] if sec_scc is", "'input-gw.xml', 'input.xml']: self.parse_file(f, sec_method) xc_functional_name = ' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point =", "repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr) ] self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent", "if len(vi) == 1 else vi properties[v[0].strip()] = vi *", "None: sec_method.x_exciting_xs_xstype = xstype sec_method.x_exciting_electronic_structure_method = xstype sec_method.x_exciting_xs_broadening = self.input_xml_parser.get(", "def parse_method(self): sec_run = self.archive.run[-1] sec_method = sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft", "= self.input_xml_parser.get('xs/rgkmax', None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax',", "GWMethod, Scf, BasisSet ) from nomad.datamodel.metainfo.simulation.system import ( System, Atoms", "= self.bandstructure_parser.get('band_k_points') nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels = self.bandstructure_parser.get('band_segm_labels') for nb", "energy_total = iteration.get('energy_total') sec_energy = msection.m_create(Energy) if energy_total is not", "# clathrate info clathrate_file = self.get_exciting_files('str.out') if clathrate_file: sec_system.x_exciting_clathrates =", "'energies': return self.energies else: res = None self._results[key] = res", "name, val) # other metainfo for name in self.info_parser._miscellaneous_keys_mapping.keys(): val", "moment_contributions = iteration.get('moment_contributions', {}) for key, names in self._moment_keys_mapping.items(): val", "r\\_s', ureg.bohr), 'x_exciting_empty_states': ('Number of empty states', None), 'x_exciting_valence_states': ('Total", "sec_xc_functional.contributions.append(Functional(name=name)) if not xc_functional_names: # simply write parameters xc_functional =", "in val])) else: try: setattr(sec_system, name, val) except Exception: self.logger.warn('Error", "None: self._results = dict() if 'total' in key: if not", "pwm * gmb * gmaxvr sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none')", "'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s',", "self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_dat_parser.band_energies if band_energies is None: return #", "self.get_initialization_parameter('species', []) for specie in species: positions_format = specie.get('positions_format', None)", "self.energy_unit) elif 'partial' in key: if not self.partial_dos: return res", "EnergyEntry, Charges, Forces, ForcesEntry, ScfIteration, BandGap ) from nomad.datamodel.metainfo.workflow import", "sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb = self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa')", "= band_k_points[nb] sec_k_band_segment.energies = band_energies[nb] + energy_fermi def _parse_band_out(self, sec_scc):", "positions_format = positions_format if positions_format is not None else self.get_positions_format(section)", "class BandstructureDatParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None)", "= iteration.get(name) if val is None: continue if name ==", "'forces', r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False, str_operation=str_to_array,", "= self.archive.run[-1] positions = self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels", "self._species = None @property def distances(self): if self._distances is None:", "section={}, positions=None, positions_format=None): positions = positions if positions is not", "len(data))) if key == 'eigenvalues': res = res * ureg.hartree", "= { 'energy_total': ['Total energy', 'total energy'], 'x_exciting_fermi_energy': ['Fermi energy',", "= val # charge contributions charge_contributions = iteration.get('charge_contributions', {}) for", "KIND, either express or implied. # See the License for", "= int(val_l) ** 2 + int(val_m) + int(val_l) atom =", "sec_gw.mixed_basis_gmax = gmb * gmaxvr pwm = self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax", "val) # other metainfo for name in self.info_parser._miscellaneous_keys_mapping.keys(): val =", "for v in val: v = v.strip().split(':') if len(v) <", "= data[0][0][0] * ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:] elif quantity ==", "data]) elif key == 'Znk': return np.array([d[1].get(key, None) for d", "v in val[3:6]], dtype=float) return [nbands, mesh, origin, vector] self._quantities.append(", "parse_function(data, sec_scc) except Exception: self.logger.error('Error setting xs data', data=dict(file=quantity)) def", "energy_fermi def _parse_eigenvalues(self, sec_scc): if self.eigval_parser.get('eigenvalues_occupancies', None) is None: return", "is None: self._vertices = self.root.findall('./%s' % self._vertex_key) return self._vertices @property", "key == 'band_k_points': res = [] for i in range(len(self.number_of_k_points_per_segment)):", "this is done in parser, however nspin is # determined", "self._nkpts_segment.append(count) count = 1 else: count += 1 self._nkpts_segment.append(count) return", "sec_dos_values.spin = spin sec_dos_values.value = totaldos[spin] partialdos = self.dos_parser.get('partialdos') if", "(the \"License\"); # you may not use this file except", "nspin)) for v in data]) res = res.reshape((len(res), len(data), len(res[0])", "positions sec_atoms.labels = atom_labels sec_atoms.periodic = [True] * 3 #", "return filenames def file_exists(self, filename): \"\"\"Checks if a the given", "None self._natoms = None self._nspin = None self._nlm = None", "q points qpoints = self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity, ext): # all", "None: sec_forces = sec_scc.m_create(Forces) sec_forces.total = ForcesEntry(value=forces) # scf iterations", "Will read all!', data=dict(file=name)) for n in range(len(files)): parser.mainfile =", "count = 1 for i in range(1, len(self.distances)): if self.distances[i]", "energy', 'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung energy',", "is None: continue metainfo_name = 'x_exciting_scf_threshold_%s_change' % name.split('_')[-2] setattr(sec_method, metainfo_name,", "# # Unless required by applicable law or agreed to", "self._energies = self._energies * self.energy_unit return self._energies def _get_dos(self, diagram):", "= sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind = 'spherical' sec_dos_values.lm = lm_values[lm] sec_dos_values.spin", "len(v) < 2: continue energies[v[0].strip()] = float(v[1]) * ureg.hartree return", "self.partial_dos[i].attrib.get(self._nspin_key, None) if spin is None: spin = (i %", "np.array(val, dtype=float) def str_to_atom_properties_dict(val_in): unit = None if 'charge' in", "of the files bs_files = ['dos.xml', 'TDOS.OUT'] for fname in", "'EVALQP.TXT', 'TDOS-QP.OUT'] # Parse GW band structure from one of", "for atom in range(len(partialdos[lm][spin])): sec_dos_values = sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind =", "sec_forces.total = ForcesEntry(value=forces) # scf iterations scf_iterations = section.get('scf_iteration', [])", "gw_info_files = self.get_exciting_files(gw_info_file) if len(gw_info_files) > 1: self.logger.warn('Found multiple GW", "[] for n in range(len(self.bands)): res_n = [] start =", "unit properties['atom_resolved'] = atom_resolved return properties def str_to_quantity_tolerances(val_in): return val_in.strip().replace('(',", "target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[", "specie.get('positions') positions = self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude #", "= sec_scc.energy.fermi if energy_fermi is None: return energy_fermi = (energy_fermi.magnitude", "np.array([d[1].get(key, None) for d in data]) else: energy = np.array([d[1].get(key,", "'x_exciting_kpoint_grid': (r'k\\-point grid', None), 'x_exciting_kpoint_offset': (r'k\\-point offset', None), 'x_exciting_number_kpoints': (r'Total", "else: res = None self._results[key] = res class DOSXMLParser(XMLParser): def", "files_q = [f for f in files if f.endswith('QMT%s.OUT' %", "parser.mainfile = files[n] parser_function(section) # free up memory parser.mainfile =", "'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance = self.input_xml_parser.get(", "sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get( 'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get( 'xs/BSE/xasedge', 'K')", "= '%s%s' % (target[0], suffix) if target[1:]: filename = '%s.%s'", "self._neigs_segment is None: self._neigs_segment = len(self.bands[0]) // self.number_of_spin_channels return self._neigs_segment", "*Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr) ] self._quantities.append(Quantity( 'groundstate',", "am not certain about the format for the spin polarized", "None: sec_gap.value_fundamental = fundamental_band_gap optical_band_gap = self.info_gw_parser.get('optical_band_gap', None) if optical_band_gap", "def get_data(files): data = [] for f in files: self.data_xs_parser.mainfile", "if self.eigval_parser.get('eigenvalues_occupancies', None) is None: return nspin = self.info_parser.get_number_of_spin_channels() def", "0)) sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq', [1, 1, 1]) sec_gw.basis_set = 'mixed'", "parse(self, filepath, archive, logger): self.filepath = filepath self.archive = archive", "= self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14) rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax', None) if rgkmax", "sec_scc.starting_calculation_ref = sec_scc_ref sec_scc.calculations_ref = [sec_scc_ref] # parse properties gw_info_files", "val = charge_contributions.get(name, None) if val is not None: break", "'SIGMA': parse_function = parse_sigma elif quantity == 'LOSS': parse_function =", "in file_ext_list if e]) # read q points qpoints =", "= self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation) exchange = self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange) sec_xc_functional", "= positions.magnitude # clathrate info clathrate_file = self.get_exciting_files('str.out') if clathrate_file:", "None), 'x_exciting_gvector_total': (r'Total number of G\\-vectors', None), 'x_exciting_lmaxapw': (r' APW", "parameters here if input_GW.xml does not exist self._quantities.append( Quantity( 'frequency_data',", "sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.endpoints_labels = band_seg_labels[nb]", "(r'Total number of local\\-orbitals', None)} self._method_keys_mapping = { 'smearing_kind': ('Smearing", "is not None: sec_gap.value_fundamental = fundamental_band_gap optical_band_gap = self.info_gw_parser.get('optical_band_gap', None)", "= spin sec_dos_values.value = dos[spin] # TODO add PDOS def", "set([int(e.attrib.get(self._l_key)) for e in self.partial_dos]) for li in l_list: self._nlm", "is # energy dos_up dos_down nspin = self.info_parser.get_number_of_spin_channels() sec_dos =", "'gaussian', 'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac': 'fermi', 'Extended': 'tetrahedra'} sec_smearing = sec_electronic.m_create(Smearing)", "= BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser = BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser = GWInfoParser() self.input_xml_parser =", "in range(len(self.bands[n])): band_energies[i % self.number_of_spin_channels][i] = np.array( [e.attrib.get(self._energy_key) for e", "import ureg from nomad.parsing.file_parser import TextParser, Quantity, XMLParser, DataTextParser from", "None), 'x_exciting_pw': (r'Maximum number of plane\\-waves', None), 'x_exciting_lo': (r'Total number", "sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions at this step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols',", "self.input_xml_parser.get( 'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get( 'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg =", "as GWMethod, Scf, BasisSet ) from nomad.datamodel.metainfo.simulation.system import ( System,", "self._bands.append(bands) # add atom-resolved bands_atom = self.root.findall('./*/%s' % self._atom_key) for", "'EXCITON': sec_scc = sec_run.m_create(Calculation) sccs.append(sec_scc) else: sec_scc = sccs[i] if", ") initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation type", "data[1] elif quantity == 'SIGMA' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field", "np.where(dist == dist[0])[0][1] self._distances = dist[:n_k_points] return self._distances @property def", "self.vertices[i + 1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i])) elif key ==", "r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)',", "sec_gw.polarizability_number_of_empty_states = int( self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq', [1, 1,", "np.array([d[1].get(key, None) for d in data]) if None in energy:", "= self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff', [0., 0., 0.]) #", "dtype=float), Quantity( 'time', r'Time spent in this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s,", "Atoms ) from nomad.datamodel.metainfo.simulation.calculation import ( Calculation, Dos, DosValues, BandStructure,", "= data[1:3] elif quantity == 'LOSS' and ext == 'FXC':", "- 6 return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is", "potential'], 'energy_xc_potential': ['xc potential energy', 'xc potential'], 'energy_electrostatic': ['Hartree energy',", "sec_gw_eigenvalues.value_correlation = eigs_gw_C sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc')) def _parse_dos_out(self, sec_scc): data", "there seems to be two versions, input_gw.xml and input-gw.xml for", "[0, 0, 0]) rgkmax = self.input_xml_parser.get('xs/screening/rgkmax', None) if rgkmax is", "positions.magnitude # clathrate info clathrate_file = self.get_exciting_files('str.out') if clathrate_file: sec_system.x_exciting_clathrates", "key, names in self._energy_keys_mapping.items(): val = None for name in", "val_in.strip().split('\\n') energies = dict() for v in val: v =", "sec_scc.x_exciting_xs_bse_number_of_components = n_components n_excitons = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_excitons =", "self._m_key = 'm' self._energy_key = 'e' self._dos_key = 'dos' self._unit_key", "nkpts_segment band_energy = np.array([np.transpose(band)[start:end] for band in bands]) if self._energy_unit:", "def get_data(key): data = self.eigval_parser.get('eigenvalues_occupancies') # reshaping is not necessary", "= data[1:] elif quantity == 'EPSILON' and ext == 'NLF_FXC':", "self.band_out_parser parser_function = self._parse_band_out elif name.startswith('input') and name.endswith('xml'): parser =", "sec_scc): data = self.dos_out_parser.data if data is None: return #", "elif key == 'band_segm_labels': res = [] for i in", "TODO expand list to include other xcf xc_functional_map = {", "if self.total_dos is None: return self._energies = np.array( [float(point.attrib.get(self._energy_key)) for", "for v in val if len(v) == 3], float)) return", "for info.xml, wannier.out if name.startswith('dos') and name.endswith('xml'): parser = self.dos_parser", "'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlxas', [0, 0]) if self.input_xml_parser.get('xs/tddft')", "return n_spin def get_unit_cell_volume(self): return self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0 * ureg.bohr", "= 'G0W0' gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment = self.input_xml_parser.get( 'gw/coreflag',", "= self._parse_evalqp elif name.startswith('TDOS') and name.endswith('OUT'): parser = self.dos_out_parser parser_function", "not None: if not isinstance(smearing_kind, str): smearing_kind = smearing_kind[0] smearing_kind", "= self.input_xml_parser.get( 'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get( 'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands", "[] self._quantities.append( Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True)) def str_to_eigenvalues(val_in): val", "% self.number_of_lm else: lm = int(val_l) ** 2 + int(val_m)", "self._parse_band_out elif name.startswith('input') and name.endswith('xml'): parser = self.input_xml_parser if self._calculation_type", "None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number of Bravais lattice symmetries', None), 'x_exciting_number_of_crystal_symmetries': ('Number", "self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind is not None: if not isinstance(smearing_kind, str):", "res = None self._results[key] = res class ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self):", "# TODO add PDOS def _parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels()", "for i in range(len(qpoints)): data_q = [] files_q = [f", "self._distances is None: data = np.transpose(self.data) self._distances = data[5][:int(max(data[1]))] return", "'x_exciting_charge_convergence': ( r'Charge distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence': ( r'Abs\\. change in", "r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False) ) self._quantities.append( Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s',", "dtype=float) return [nbands, mesh, origin, vector] self._quantities.append( Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)',", "= self.dos_parser.number_of_dos sec_dos.energies = self.dos_parser.energies + energy_fermi volume = self.info_parser.get_unit_cell_volume()", "= np.array(lattice_vectors, dtype=float) lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale', 1.0) positions = np.dot(positions,", "self._diagram_key)) self._ndos = len(total_dos) return self._ndos @property def number_of_lm(self): if", "= int( self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq', [1, 1, 1])", "os.access(f, os.F_OK)] return filenames def file_exists(self, filename): \"\"\"Checks if a", "'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get( 'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get(", "None self._results[key] = res class DOSXMLParser(XMLParser): def __init__(self, **kwargs): super().__init__(None)", "None: continue if key == 'x_exciting_section_MT_moment_atom': for n in range(len(val)):", "key, val) if key == 'x_exciting_fermi_energy': sec_energy.fermi = val #", "DOSXMLParser(XMLParser): def __init__(self, **kwargs): super().__init__(None) self._nspin_key = 'nspin' self._totaldos_key =", "to be two versions, input_gw.xml and input-gw.xml for f in", "band structure from one of the files: bs_files = ['bandstructure-qp.dat',", "np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies = [] start =", "elif (name.startswith('FERMISURF') or name.startswith('FS')) and name.endswith('bxsf'): parser = self.fermisurf_parser parser_function", "for potential and density', 1 / ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector grid", "os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = filename.rsplit('.', 1) filepath =", "= self.input_xml_parser.get( 'xs/tetra/tetradf', False) def _parse_xs_bse(self): sec_run = self.archive.run[-1] #", "sec_scc.x_exciting_xs_bse_loss = np.reshape( data[1], (n_components, n_loss)) # TODO check if", "= np.array(val[0].split(), dtype=float) keys = val[1].split() eigs = np.transpose(np.array([v.split() for", "ExcitingFermiSurfaceBxsfParser() self.evalqp_parser = ExcitingEvalqpParser() self.dos_out_parser = DataTextParser() self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree)", "reshape(eigs_gw) sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx')) eigs_gw_C = reshape(get_data('Sc')) if eigs_gw_C is", "continue if name == 'time': msection.time_calculation = val else: setattr(msection,", "np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32))) for lm in range(len(partialdos)): for spin in", "__init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit',", "[] name = xc_functional_map.get(xc_functional.type, []) return name @property def n_optimization_steps(self):", "energy', 'Fermi'], 'energy_kinetic_electronic': ['Kinetic energy', 'electronic kinetic'], 'energy_coulomb': ['Coulomb energy',", "sec_scc): data = self.evalqp_parser.get('kpoints_eigenvalues') if data is None: return def", "'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14) rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax',", "np.dot(positions, cell.magnitude) return positions * ureg.bohr def get_scf_threshold(self, name): reference", "end = np.array( self.vertices[i + 1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i]))", "str_to_quantity_tolerances(val_in): return val_in.strip().replace('(', '').replace(')', '').split() def str_to_energy_dict(val_in): val = val_in.strip().split('\\n')", "= [f for f in filenames if os.access(f, os.F_OK)] return", "'LOSS', 'SIGMA']: for ext in ['FXC', 'NLF_FXC']: data = get_data(quantity,", "exist self._quantities.append( Quantity( 'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False) ) self._quantities.append(", "= self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude # clathrate info", "def parse_scf(iteration, msection): energy_total = iteration.get('energy_total') sec_energy = msection.m_create(Energy) if", "is None: self._neigs_segment = len(self.bands[0]) // self.number_of_spin_channels return self._neigs_segment def", "species is None: species = v[0][2] atom_resolved.append(((species, v[1] * unit)))", "add support for info.xml, wannier.out if name.startswith('dos') and name.endswith('xml'): parser", "if not data_q: continue data_q = np.transpose(data_q, axes=(2, 0, 1))", "band_energy = band_energy * self._energy_unit self._band_energies.append(band_energy) start = end return", "'LOSS': parse_function = parse_loss else: continue try: parse_function(data, sec_scc) except", "energy', 'xc potential'], 'energy_electrostatic': ['Hartree energy', 'Hartree'], 'x_exciting_hartree_energy': ['Hartree energy',", "eigenvalues', 'sum of eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective potential energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb", "= iteration.get('charge_contributions', {}) for key, names in self._electron_charge_keys_mapping.items(): val =", "is None: return sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters = self.fermisurf_parser.get('band_parameters', None)", "is None: species = v[0][2] atom_resolved.append(((species, v[1] * unit))) else:", "loaded from *: *(.+)'), Quantity('name', r'name *: *(.+)'), Quantity('nuclear_charge', rf'nuclear", "the format for the spin polarized case # I cannot", "None: return # this is really problematic if some scf", "'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1] elif quantity == 'LOSS' and ext", "spin = self.total_dos[i].attrib.get(self._nspin_key, i) res[i] = self._get_dos(self._total_dos[i]) if self.energy_unit is", "in ['EPSILON', 'LOSS', 'SIGMA']: for ext in ['FXC', 'NLF_FXC']: data", "sccs.append(sec_scc) else: sec_scc = sccs[i] if sec_scc is None: #", "= None self._distances = None self._species = None @property def", "= band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface =", "sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq', [1, 1, 1]) sec_gw.basis_set = 'mixed' sec_gw.qp_equation_treatment", "None: return self._nlm = 0 l_list = set([int(e.attrib.get(self._l_key)) for e", "energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi", "int(val_l) atom = i // (self.number_of_lm * self.number_of_spin_channels) res[lm][spin][atom] =", "is None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_dos =", "are the # ones with the missing quantity if len(quantity)", "= default.split('.')[-1] mainfile_base = mainfile.rsplit('.', 1)[0].replace('INFO', '') options = [", "r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False)] self._miscellaneous_keys_mapping = { 'x_exciting_gap': (r'Estimated", "potential energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb potential energy', 'Coulomb potential'], 'energy_xc_potential': ['xc", "= f if self.data_xs_parser.data is None: continue data_q.append(self.data_xs_parser.data) if not", "[1, 1, 1]) sec_gw.basis_set = 'mixed' sec_gw.qp_equation_treatment = 'linearization' sec_gw.max_frequency", "val[0] if len(val) == 1 else val return np.array(val, dtype=float)", "== 'bse': self._parse_xs_bse() elif xstype.lower() == 'tddft': self._parse_xs_tddft() def _parse_input_gw(self,", "nomad.datamodel.metainfo.simulation.system import ( System, Atoms ) from nomad.datamodel.metainfo.simulation.calculation import (", "None: return sec_system = self.parse_system(section) if sec_system is not None:", "quantity == 'SIGMA' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3]", "= self.get('groundstate', self.get('hybrids', {})) return reference.get('scf_iteration', [{}])[-1].get( name, [None, None])[-1]", "bands = data[1:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints))", "None: return nspin = self.info_parser.get_number_of_spin_channels() def get_data(key): data = self.eigval_parser.get('eigenvalues_occupancies')", "for i in range(len(self.number_of_k_points_per_segment)): start = np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end", "band_energies]) if self._energy_unit is not None: band_energy = band_energy *", "number_of_spin_channels(self): if self._nspin is None: self._nspin = np.shape(np.transpose(self.data)[1:])[0] return self._nspin", "totaldos = self.dos_parser.get('totaldos') * volume.to('m**3').magnitude for spin in range(len(totaldos)): sec_dos_values", "nspin)) return data self._quantities.append( Quantity( 'eigenvalues_occupancies', r'\\(state\\, eigenvalue and occupancy", "'x_exciting_total_moment': ['total moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved'] } def get_exciting_files(self, default): mainfile", "seems to be two versions, input_gw.xml and input-gw.xml for f", "energy_fermi.to(\"hartree\") sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points =", "partial_dos(self): if self._partial_dos is None: self._partial_dos = self.root.findall('./%s/%s' % (self._partialdos_key,", "bse_files def get_data(files): data = [] for f in files:", "def vertices(self): if self._vertices is None: self._vertices = self.root.findall('./%s' %", "= spin sec_dos_values.atom_index = atom sec_dos_values.value = partialdos[lm][spin][atom] def _parse_bandstructure(self,", "i in range(len(self.total_dos)): spin = self.total_dos[i].attrib.get(self._nspin_key, i) res[i] = self._get_dos(self._total_dos[i])", "= val_in.strip().split('\\n') energies = dict() for v in val: v", "multiple files. Will read all!', data=dict(file=name)) for n in range(len(files)):", "== 'band_segm_labels': res = [] for i in range(len(self.vertices) -", "(self.number_of_lm * self.number_of_spin_channels) res[lm][spin][atom] = self._get_dos(self.partial_dos[i]) if self.energy_unit is not", "False potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing is not None: sec_system.x_exciting_potential_mixing", "data = [[], [], []] for i in range(len(qpoints)): data_q", "= smearing_kind smearing_width = self.info_parser.get_initialization_parameter('smearing_width') if smearing_width is not None:", "for dos and bandstructure super().__init__(None) self._distance_key = 'distance' self._coord_key =", "= np.array(val[1].split(), dtype=int) origin = np.array(val[2].split(), dtype=float) vector = np.array([v.split()", "spin in range(len(dos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin", "= self.input_xml_parser.get( 'xs/screening/screentype', 'full') if self.input_xml_parser.get('xs/BSE') is not None: sec_method.x_exciting_xs_bse_antiresonant", "exciting self._energy_keys_mapping = { 'energy_total': ['Total energy', 'total energy'], 'x_exciting_fermi_energy':", "lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale', 1.0) positions = np.dot(positions, lattice_vectors) * ureg.bohr", "[]): sec_scc = parse_configuration(optimization_step) if optimization_step.get('method') is not None: sec_scc.x_exciting_geometry_optimization_method", "= self.total_dos[i].attrib.get(self._nspin_key, i) res[i] = self._get_dos(self._total_dos[i]) if self.energy_unit is not", "continue elif v[0].startswith('species'): species = re.search(re_symbol, v[-1]).group(1) elif v[0].startswith('atom'): v[0]", "normal calculations # in addition to INFO.OUT return else: return", "0) sec_method.x_exciting_xs_tetra = self.input_xml_parser.get( 'xs/tetra/tetradf', False) def _parse_xs_bse(self): sec_run =", "/ ureg.bohr)} for name, key_unit in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee", "n_components sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape( data[0], (n_components, n_sigma)) * ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re", "sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get( 'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get( 'xs/tddft/drude', [0.,", "sec_run = self.archive.run[-1] final = section if section.get('energy_total') is not", "[] def str_to_eigenvalue(val_in): val = val_in.strip().split('\\n') kpts = np.array(val[0].split(), dtype=float)", "dtype=float)])), Quantity( 'forces', r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic',", "default) class ExcitingParser: def __init__(self): self.info_parser = ExcitingInfoParser() self.dos_parser =", "= self.root.findall('./%s' % self._vertex_key) return self._vertices @property def number_of_spin_channels(self): if", "quantity == 'EPSILON' and ext == 'FXC': sec_scc = sec_run.m_create(Calculation)", "= self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal if len(sec_run.system) > 1:", "'potential_mixing', r'Using ([\\w ]+) potential mixing', repeats=False, flatten=False) ) initialization_quantities.append(Quantity(", "files = get_files(quantity) for i in range(len(files)): data = get_data(files[i])", "sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude # clathrate info clathrate_file = self.get_exciting_files('str.out') if", "self.eigval_parser.get('eigenvalues_occupancies', None) is None: return nspin = self.info_parser.get_number_of_spin_channels() def get_data(key):", "in band_energies]) if self._energy_unit is not None: band_energy = band_energy", "None: continue energy_fermi = energy_fermi.to(\"hartree\") sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi", "data = np.transpose(np.vstack(data)) n_loss = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_loss_energies =", "band_parameters[3] fermi_energy = self.fermisurf_parser.get('fermi_energy', None) if fermi_energy is not None:", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "nspin = self.info_parser.get_number_of_spin_channels() def get_data(key): data = self.eigval_parser.get('eigenvalues_occupancies') # reshaping", "data: sccs.append(None) continue if quantity == 'EXCITON': sec_scc = sec_run.m_create(Calculation)", "if f.endswith('QMT%s.OUT' % str(i + 1).rjust(3, '0'))] for f in", "{keys[i]: eigs[i] for i in range(len(keys))} return [kpts, eigs] self._quantities.append(", "\\(seconds\\)', ureg.s)} for name, key_unit in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)'", "language governing permissions and # limitations under the License. #", "sec_dos_values.lm = lm_values[lm] sec_dos_values.spin = spin sec_dos_values.atom_index = atom sec_dos_values.value", "if os.access(f, os.F_OK)] return filenames def file_exists(self, filename): \"\"\"Checks if", "energy_unit(self): if self._energy_unit is None: axis = self.root.find('./axis') if axis", "None self._nlm = None self._energies = None self._total_dos = None", "* ureg.bohr val = val_in.strip().split('\\n') properties = dict() atom_resolved =", "n + 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1] else:", "input xml file, there seems to be two versions, input_gw.xml", "None: break if val is None: continue if key ==", "def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] def str_to_eigenvalue(val_in):", "= np.dot(positions, cell.magnitude) return positions * ureg.bohr def get_scf_threshold(self, name):", "= parse_exciton elif quantity == 'EPSILON': parse_function = parse_epsilon elif", "if self._energies is None: if self.total_dos is None: return self._energies", "# TODO add support for info.xml, wannier.out if name.startswith('dos') and", "= charge_contributions.get(name, None) if val is not None: break if", "= section.get('positions_format') if positions_format is None: species = self.get_initialization_parameter('species', [])", "super().__init__(None) self._distance_key = 'distance' self._coord_key = 'coord' self._energy_key = 'eval'", "lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal if len(sec_run.system) >", "None: band_energy = band_energy * self._energy_unit res_n.append(band_energy) start = end", "in self.bands[n][i]]) for nkpts_segment in self.number_of_k_points_per_segment: end = start +", "int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation =", "sec_run.calculation[0] sec_scc.starting_calculation_ref = sec_scc_ref sec_scc.calculations_ref = [sec_scc_ref] # parse properties", "partial_dos = self.root.findall('./%s' % self._partialdos_key) self._natoms = len(partial_dos) return self._natoms", "26: ['GGA_C_PBE', 'GGA_X_WC'], 30: ['GGA_C_AM05', 'GGA_C_AM05'], 300: ['GGA_C_BGCP', 'GGA_X_PBE'], 406:", "self.input_xml_parser.get('xs/rgkmax', None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.)", "in name: sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB' in name: sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name))", "= self.dos_parser.get('totaldos') * volume.to('m**3').magnitude for spin in range(len(totaldos)): sec_dos_values =", "['total charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved'] } self._moment_keys_mapping = { 'x_exciting_interstitial_moment': ['interstitial'],", "@property def number_of_spin_channels(self): if self._nspin is None: if not self.total_dos:", "if 'charge' in val_in: unit = ureg.elementary_charge elif 'moment' in", "self.evalqp_parser = ExcitingEvalqpParser() self.dos_out_parser = DataTextParser() self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser", "res_n.append(band_energy) start = end res.append(res_n) elif key == 'band_k_points': res", "https://nomad-lab.eu for further info. # # Licensed under the Apache", "= Program( name='exciting', version=self.info_parser.get('program_version', '').strip()) # method goes first since", "self.input_xml_parser.get('xs/ngridq', [1, 1, 1]) sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk', [1, 1, 1])", "= self.logger self.info_gw_parser.logger = self.logger self.input_xml_parser.logger = self.logger self.data_xs_parser.logger =", "self._band_key = 'band' self._atom_key = 'atom' self._nspin = kwargs.get('nspin', None)", "sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_', '')), EnergyEntry(value=val)) else: setattr(msection, key, val) if", "= v.split(':') if len(v) < 2: continue energies[v[0].strip()] = float(v[1])", "def parse(self, filepath, archive, logger): self.filepath = filepath self.archive =", "for name in self.info_parser._convergence_keys_mapping.keys(): val = iteration.get(name) if val is", "f] options = [f for f in options if f.endswith(file_ext)]", "the spin polarized case # I cannot find an example", "nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end]) start = end return self._band_k_points @property def", "if self.input_xml_parser.get('xs/screening') is not None: sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get( 'xs/screening/nempty', 0)", "self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: self._neigs_segment =", "str_operation=lambda x: [v.strip() for v in x.split(':')]), Quantity( 'parameters', r'\\n", "is None: # get it from input.xml for f in", "np.transpose(self.data) n_kpoints = int(max(data[1])) bands = data[6:] bands = np.reshape(bands,", "= None self._neigs_segment = None self._nkpts_segment = None @property def", "section.get('energy_total') is not None else section.get('final') if final is None:", "sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0)", "key == 'x_exciting_fermi_energy': sec_energy.fermi = val # charge contributions charge_contributions", "effective potential \\(target\\)', ureg.hartree), 'x_exciting_energy_convergence': ( r'Absolute change in total", "end, self.number_of_k_points_per_segment[i])) elif key == 'band_segm_labels': res = [] for", "smearing_kind_map = { 'Gaussian': 'gaussian', 'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac': 'fermi', 'Extended':", "parser.mainfile = None def _parse_input_xs(self, sec_method): xstype = self.input_xml_parser.get('xs/xstype', None)", "metainfo_name == 'x_exciting_scf_threshold_energy_change': sec_method.scf = Scf(threshold_energy_change=threshold) xc_functional_names = self.info_parser.get_xc_functional_name() if", "def init_parser(self): self.info_parser.mainfile = self.filepath self.info_parser.logger = self.logger self.dos_parser.logger =", "info files, will read only first!') self.info_gw_parser.mainfile = gw_info_files[0] fermi_energy", "= energy_fermi band_k_points = self.bandstructure_dat_parser.band_k_points nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment for nb", "super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None) def", "= self._get_dos(self._total_dos[i]) if self.energy_unit is not None: res = res", "= len(total_dos) return self._ndos @property def number_of_lm(self): if self._nlm is", "0)) sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get( 'gw/selfenergy/actype',", "['Correlation energy', 'correlation'], 'x_exciting_correlation_energy': ['Correlation energy', 'correlation'], 'energy_sum_eigenvalues': ['Sum of", "False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get( 'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get( 'xs/tddft/aresfxc',", "charge contributions parse_scf(final, sec_scc) # forces forces = section.get('forces') if", "= None for name in names: val = charge_contributions.get(name, None)", "[{}])[-1].get( name, [None, None])[-1] def get_scf_quantity(self, name): n_scf = len(self.get('energy_total_scf_iteration',", "key, default=None): return self.get('initialization', {}).get(key, default) class ExcitingParser: def __init__(self):", "if band_energies is None: return # Get fermi energy: it", "len(total_dos) return self._ndos @property def number_of_lm(self): if self._nlm is None:", "self.archive.run[-1] fxctype = self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf = self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont", "started)([\\s\\S]+?)Groundstate module stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities = [ Quantity( 'atomic_positions',", "not xc_functional_names: # get it from input.xml input_file = self.get_exciting_files('input.xml')", "name == 'time': msection.time_calculation = val else: setattr(msection, name, val)", "is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax = rgkmax sec_method.x_exciting_xs_screening_type", "ext) if not data[0]: continue if quantity == 'EPSILON' and", "== 'Znk': return np.array([d[1].get(key, None) for d in data]) else:", "charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total valence charge', ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective Wigner", "spin in range(len(partialdos[lm])): for atom in range(len(partialdos[lm][spin])): sec_dos_values = sec_dos.m_create(DosValues,", "stored. \"\"\" mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target =", "self._electron_charge_keys_mapping = { 'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage': ['core leakage'], 'x_exciting_valence_charge': ['valence'],", "# get it from last scf_iteration or optimization_step final =", "'x_exciting_gkmax': (r'Maximum \\|G\\+k\\| for APW functions', 1 / ureg.bohr), 'x_exciting_gmaxvr':", "1, 1]) rgkmax = self.input_xml_parser.get('xs/rgkmax', None) if rgkmax is None:", "law or agreed to in writing, software # distributed under", "self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float) for i in range(len(self.bands[n])): band_energies[i %", "bse_files = [] for bse_type in bse_types: for scr_type in", "= self._parse_bandstructure_dat elif name.startswith('BAND') and name.endswith('OUT'): parser = self.band_out_parser parser_function", "= len(data) // nspin data = np.reshape(data, (nspin, len(data) //", "sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3] elif quantity == 'SIGMA' and ext ==", "= None self._nkpts_segment = None self._neigs_segment = None self._vertices =", "point.attrib.get(self._distance_key) for point in self.bands[0][0]] self._distances = np.array(self._distances, dtype=float) return", "ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape( data[1], (n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape(", "'atom' self._nspin = kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None) def", "None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_dos = sec_scc.m_create(Dos,", "self._vertex_key) return self._vertices @property def number_of_spin_channels(self): if self._nspin is None:", "self._method_keys_mapping = { 'smearing_kind': ('Smearing scheme', None), 'smearing_width': ('Smearing width',", "sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3] fermi_energy", "16)) sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get( 'gw/selfenergy/nempty',", "'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get( 'xs/screening/ngridk', [0, 0, 0]) rgkmax", "= None self._vertices = None self._distances = None self._band_energies =", "sec_method) xc_functional_name = ' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point = xc_functional_name sec_scc =", "= self.info_gw_parser.get('fundamental_band_gap', None) sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap is not", "setting xs data', data=dict(file=quantity)) def _parse_xs_tddft(self): sec_run = self.archive.run[-1] fxctype", "is None: spin = (i % (self.number_of_spin_channels * self.number_of_lm)) //", "self.get_exciting_files(gw_info_file) if len(gw_info_files) > 1: self.logger.warn('Found multiple GW info files,", "'FXC': sec_scc = sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0]", "'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True)) def str_to_eigenvalues(val_in): val = val_in[:val_in.rfind('\\n \\n')].strip()", "rf'(Species : *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[ Quantity('number', r'Species", "data = self.dos_out_parser.data if data is None: return # Get", "def reshape(data): if data[0] is None: return return np.reshape(data, (nspin,", "sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_epsilon = len(data[0])", "'x_exciting_empty_states': ('Number of empty states', None), 'x_exciting_valence_states': ('Total number of", "if forces is not None: sec_forces = sec_scc.m_create(Forces) sec_forces.total =", "DosValues, BandStructure, BandEnergies, Energy, EnergyEntry, Charges, Forces, ForcesEntry, ScfIteration, BandGap", "get_files(name): bse_types = ['IP', 'singlet', 'triplet', 'RPA'] scr_types = ['full',", "if data is None: return def get_data(key): if key ==", "in x.split(':')])])) ) self._quantities.append(Quantity( 'initialization', r'(?:All units are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending", "e in self.bands[n][i]]) for nkpts_segment in self.number_of_k_points_per_segment: end = start", "= self.eigval_parser.get('k_points') sec_eigenvalues.occupations = get_data('occupancies') sec_eigenvalues.energies = get_data('eigenvalues') def _parse_fermisurface(self,", "key_unit in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' % key_unit[0], str_operation=str_to_quantity_tolerances,", "points qpoints = self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity, ext): # all files", "key == 'energies': return self.energies else: res = None self._results[key]", "= np.reshape( data[4], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape( data[5], (n_components,", "in range(len(self.number_of_k_points_per_segment)): start = np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end = np.array(", "r'DOS at Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=1 / ureg.hartree),", "implement reading of parameters from input.xml for normal calculations #", "lattice_vectors_reciprocal if len(sec_run.system) > 1: return sec_system for name in", "'_'.join([e for e in file_ext_list if e]) # read q", "parse_configuration(self.info_parser.get(module)) if sec_scc is None: continue # add data to", "xc_functional_names.append(exchange) sec_xc_functional = sec_dft.m_create(XCFunctional) for name in xc_functional_names: if name", "2 return n_spin def get_unit_cell_volume(self): return self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0 *", "if not input_file: return self.input_xml_parser.mainfile = input_file[0] xstype = self.input_xml_parser.get('xs/xstype',", "self.archive.run[-1] xs_info_files = self.get_exciting_files('INFOXS.OUT') if not xs_info_files: return self._calculation_type =", "= self.get_initialization_parameter('species', []) for specie in species: positions_format = specie.get('positions_format',", "fermi_energy is not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface", "name.startswith('TDOS') and name.endswith('OUT'): parser = self.dos_out_parser parser_function = self._parse_dos_out elif", "'positions_format', r'imized atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity(", "sec_gw.mixed_basis_tolerance = self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001) gmb = self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax", "repeats=False, convert=False), ] self._system_keys_mapping = { 'x_exciting_unit_cell_volume': ('Unit cell volume',", "for name in names: val = moment_contributions.get(name, None) if val", "in names: val = moment_contributions.get(name, None) if val is not", "continue lattice_vectors = np.array(lattice_vectors, dtype=float) lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale', 1.0) positions", "return self.energies else: res = None self._results[key] = res class", "self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data =", "is None: eigs_gw_C = reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation = eigs_gw_C sec_gw_eigenvalues.value_xc_potential =", "import Run, Program from nomad.datamodel.metainfo.simulation.method import ( Method, DFT, Electronic,", "self.get_exciting_files('INFOXS.OUT') if not xs_info_files: return self._calculation_type = 'xs' # inconsistency", "# TODO make a parent class for dos and bandstructure", "= sec_scc_ref sec_scc.calculations_ref = [sec_scc_ref] # parse properties gw_info_files =", "for xs input xml file sec_method = sec_run.m_create(Method) sec_method_ref =", "parameters from input.xml for normal calculations # in addition to", "fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break for f in", "* ureg.joule).to('hartree') # TODO I am not sure about format", "= reshape(get_data('Vxc')) def _parse_dos_out(self, sec_scc): data = self.dos_out_parser.data if data", "setting mainfile self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_parser.get('band_energies', []) for", "name.startswith('BAND') and name.endswith('OUT'): parser = self.band_out_parser parser_function = self._parse_band_out elif", "or implied. # See the License for the specific language", "np.zeros(( self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos)) for i in range(len(self.partial_dos)): spin", "= [Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False, dtype=str, flatten=False)] initialization_quantities =", "total energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence': ( r'Charge distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence': (", "n_components sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape( data[1], (n_components, n_excitons))", "d in data]) if None in energy: return energy return", "in self._moment_keys_mapping.items(): val = None for name in names: val", "% self._band_key)) return self._bands @property def vertices(self): if self._vertices is", "*{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[ Quantity('number', r'Species : *(\\d+)', dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'),", "convert=False), Quantity( 'x_exciting_dos_fermi', r'DOS at Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float,", "metainfo_name, threshold) # additionally, set threshold to global metainfo. This", "return reference.get('scf_iteration', [{}])[-1].get( name, [None, None])[-1] def get_scf_quantity(self, name): n_scf", "DataTextParser from nomad.datamodel.metainfo.simulation.run import Run, Program from nomad.datamodel.metainfo.simulation.method import (", "= 'mixed' sec_gw.qp_equation_treatment = 'linearization' sec_gw.max_frequency = self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0)", "sec_method.scf = Scf(threshold_energy_change=threshold) xc_functional_names = self.info_parser.get_xc_functional_name() if not xc_functional_names: #", "False) sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get( 'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get( 'xs/BSE/sciavtype',", "for f in options] else: filenames = [filename] filenames =", "'Fermi'], 'energy_kinetic_electronic': ['Kinetic energy', 'electronic kinetic'], 'energy_coulomb': ['Coulomb energy', 'Coulomb'],", "v[1] = v[1][0] if len(v[1]) == 1 else v[1] if", "'xs': parser_function = self._parse_input_xs else: # TODO implement reading of", "up memory parser.mainfile = None def _parse_input_xs(self, sec_method): xstype =", "sec_system.x_exciting_clathrates_atom_labels = list(data[3]) else: sec_system.x_exciting_clathrates = False potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing')", "ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total electronic charge', ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total core charge',", "[ Quantity( 'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=ureg.hartree), Quantity( 'energy_contributions',", "DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser = ExcitingEigenvalueParser() self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser()", "default.split('.')[-1] mainfile_base = mainfile.rsplit('.', 1)[0].replace('INFO', '') options = [ f", "fermi_energy sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface def _parse_evalqp(self, sec_scc): data = self.evalqp_parser.get('kpoints_eigenvalues')", "def _parse_input_xs(self, sec_method): xstype = self.input_xml_parser.get('xs/xstype', None) if xstype is", "msection.time_calculation = val else: setattr(msection, name, val) # energy, moment,", "res = [] for i in range(len(self.number_of_k_points_per_segment)): start = self.vertices[i].attrib.get(self._coord_key).split()", "1.0 * ureg.bohr ** 3) def get_initialization_parameter(self, key, default=None): return", "# groundstate and hybrids calculation for module in ['groundstate', 'hybrids']:", "number_of_k_points_per_segment(self): if self._nkpts_segment is None: self._nkpts_segment = [] count =", "dtype=float, unit=ureg.hartree / ureg.bohr) ] self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent loop started|Groundstate", "data[1] elif quantity == 'LOSS' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field", "= val[n][1] sec_charges = msection.m_create(Charges) sec_charges.value = [ val[n][1].magnitude for", "bands]) if self._energy_unit: band_energy = band_energy * self._energy_unit self._band_energies.append(band_energy) start", "os.path.isfile(filepath) and os.access(filepath, os.F_OK): return True return False def _parse_dos(self,", "gmaxvr sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get( 'gw/scrcoul/sciavtype',", "*({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic mass *: *({re_float})', dtype=np.float64, unit=ureg.electron_mass),", "= filename.rsplit('.', 1) filepath = '%s%s' % (target[0], suffix) if", "val = iteration.get(name) if val is None: continue setattr(msection, name,", "= [ Quantity( 'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr, repeats=False, convert=False),", "self.logger = logger if logger is not None else logging", "Quantity( 'n_scf_iterations', r'Number of (?:total)* scf iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int), Quantity(", "['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']} xc_functional = self.get('initialization', {}).get('xc_functional', None) if xc_functional", "ureg.hartree if sec_scc.energy is not None: energy_fermi = sec_scc.energy.fermi energy_fermi", "= parse_configuration(structure_optimization) if sec_scc is None: return # volume optimizations", "parser.evalqp_parser.quantities self.info_gw_parser.quantities = parser.info_gw_parser.quantities def parse(self, filepath, archive, logger): self.filepath", "start, '\\u0393' if end.lower() == 'gamma' else end]) elif key", "ext == 'FXC': sec_scc = sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies", "in key: if not self.partial_dos: return res = np.zeros(( self.number_of_lm,", "in val[3:6]], dtype=float) return [nbands, mesh, origin, vector] self._quantities.append( Quantity(", "(name, bse_type, scr_type)) bse_files.append(files) return bse_files def get_data(files): data =", "* li + 1 return self._nlm @property def total_dos(self): if", "DFT band structure from one of the files bs_files =", "'LOSS' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1] elif quantity", "'atomic_positions', r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'imized atomic positions\\s*\\(([a-z]+)\\)'),", "= parse_configuration(self.info_parser.get(module)) if sec_scc is None: continue # add data", "return sec_system for name in self.info_parser._system_keys_mapping.keys(): val = self.info_parser.get_initialization_parameter(name) if", "= self.info_parser.get_number_of_spin_channels() if self._calculation_type == 'volume_optimization': sec_method.x_exciting_volume_optimization = True def", "xc_functional.get('name_reference', [None, None])[1] sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels() if self._calculation_type == 'volume_optimization':", "GW info files, will read only first!') self.info_gw_parser.mainfile = gw_info_files[0]", "unit=ureg.hartree), Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False, convert=False), Quantity( 'x_exciting_dos_fermi',", "is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax = rgkmax sec_method.x_exciting_xs_scissor", "'gaule2') sec_gw.number_of_frequencies = int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get( 'gw/selfenergy/npol',", "< 2: continue elif v[0].startswith('species'): species = re.search(re_symbol, v[-1]).group(1) elif", "= self.info_gw_parser.get('direct_band_gap', None) if fundamental_band_gap is None: fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap',", "[] for quantity in ['EXCITON', 'EPSILON', 'SIGMA', 'LOSS']: files =", "started([\\s\\S]+?)Structure\\-optimization module stopped', sub_parser=TextParser(quantities=[ Quantity( 'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent", "= self._parse_eigenvalues elif (name.startswith('FERMISURF') or name.startswith('FS')) and name.endswith('bxsf'): parser =", "in range(len(band_energies)): # Get fermi energy: it is used to", "self._nspin = None self._nlm = None self._energies = None self._total_dos", "if optimization_step.get('method') is not None: sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method') if optimization_step.get('step')", "None) if fundamental_band_gap is None: fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap', None) sec_gap", "self._neigs_segment = None self._nkpts_segment = None @property def band_energies(self): if", "pass else: setattr(msection, key, val) # moment contributions moment_contributions =", "None: if self.partial_dos is None: return self._nlm = 0 l_list", "n_epsilon)) * ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape( data[1], (n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im", "= len(self.total_dos) return self._nspin @property def number_of_atoms(self): if self._natoms is", "self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser() self.evalqp_parser = ExcitingEvalqpParser() self.dos_out_parser = DataTextParser() self.bandstructure_dat_parser", "import logging from nomad.units import ureg from nomad.parsing.file_parser import TextParser,", "np.zeros((self.number_of_spin_channels, self.number_of_dos)) for i in range(len(self.total_dos)): spin = self.total_dos[i].attrib.get(self._nspin_key, i)", "= self.archive.run[-1] xs_info_files = self.get_exciting_files('INFOXS.OUT') if not xs_info_files: return self._calculation_type", "spin polarized case # I cannot find an example bandstructure", "= ['full', 'diag', 'noinvdiag', 'longrange'] bse_files = [] for bse_type", "files: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None: continue data.append(self.data_xs_parser.data)", "'], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy':", "= self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_dat_parser.band_energies if band_energies is None: return", "of exciting self._energy_keys_mapping = { 'energy_total': ['Total energy', 'total energy'],", "self._bands = None self._vertices = None self._distances = None self._species", "mainfile.strip('INFO.OUT') target = default.rsplit('.', 1) filename = '%s%s' % (target[0],", "return sec_scc def parse_system(self, section): sec_run = self.archive.run[-1] positions =", "= sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi nkpts_segment = self.band_out_parser.number_of_k_points_per_segment for", "= msection.m_create(Energy) if energy_total is not None: sec_energy.total = EnergyEntry(value=energy_total)", "is not parsed? sccs = [] for quantity in ['EXCITON',", "'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get( 'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get(", "val is not None: break if val is None: continue", "= sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0] * ureg.hartree", "in files: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None: continue", "parser = self.dos_parser parser_function = self._parse_dos elif name.startswith('bandstructure') and name.endswith('xml'):", "= self.input_xml_parser.get( 'xs/tddft/drude', [0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001,", "np.transpose(data_q, axes=(2, 0, 1)) for j in range(len(data)): data[j].append(data_q[j]) return", "= parser.info_gw_parser.quantities def parse(self, filepath, archive, logger): self.filepath = filepath", "if band_parameters is not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface =", "and os.access(filepath, os.F_OK): return True return False def _parse_dos(self, sec_scc):", "self.band_out_parser.logger = self.logger self.info_gw_parser.logger = self.logger self.input_xml_parser.logger = self.logger self.data_xs_parser.logger", "'exchange'], 'x_exciting_exchange_energy': ['Exchange energy', 'exchange'], 'energy_correlation': ['Correlation energy', 'correlation'], 'x_exciting_correlation_energy':", "the License for the specific language governing permissions and #", "str_operation=str_to_array, unit=1 / ureg.bohr, repeats=False, convert=False), ] self._system_keys_mapping = {", "'SIGMA']: for ext in ['FXC', 'NLF_FXC']: data = get_data(quantity, ext)", "in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] * len(atoms[n])) if positions is None or", "super().__init__(None) def init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\-", "== 'tddft': self._parse_xs_tddft() def _parse_input_gw(self, sec_method): sec_gw = sec_method.m_create(GWMethod) sec_gw.type", "[]) labels = [] for specie in species: labels +=", "# the original scale in which also other energies are", "return self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data", "None self._results[key] = res class ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self): super().__init__(None) def", "if len(files) > 1: self.logger.warn('Found multiple files. Will read all!',", "xstype = self.input_xml_parser.get('xs/xstype', None) if xstype is not None: sec_method.x_exciting_xs_xstype", "= { 'smearing_kind': ('Smearing scheme', None), 'smearing_width': ('Smearing width', None)}", "def get_data(quantity, ext): # all files related to quantity at", "self.get_exciting_files('input.xml') for f in input_file: self.input_xml_parser.mainfile = f correlation =", "None: partial_dos = self.root.findall('./%s' % self._partialdos_key) self._natoms = len(partial_dos) return", "is not None else self.get_positions_format(section) if positions_format == 'lattice': cell", "'x_exciting_electronic_charge': ('Total electronic charge', ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total core charge', ureg.elementary_charge),", "self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_dat_parser.band_energies if band_energies is None:", "BandGap ) from nomad.datamodel.metainfo.workflow import Workflow, GeometryOptimization from .metainfo.exciting import", "in this optimization step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity( 'final', r'Force", "= self.partial_dos[i].attrib.get(self._nspin_key, None) if spin is None: spin = (i", "optimization_step in structure_optimization.get('optimization_step', []): sec_scc = parse_configuration(optimization_step) if optimization_step.get('method') is", "scale in which also other energies are reported. energy_fermi =", "species = self.info_parser.get_initialization_parameter('species', []) for specie in species: sec_atoms_group =", "self._units_mapping = dict(hartree=ureg.hartree) def init_parameters(self): self._ndos = None self._natoms =", "elif quantity == 'SIGMA' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field =", "len(self.distances)): if self.distances[i] == self.distances[i - 1]: self._nkpts_segment .append(count) count", "file_ext_list if e]) # read q points qpoints = self.input_xml_parser.get('xs/qpointset/qpoint')", "'energy_total', r'Total energy at this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False, dtype=float),", "= '%s.%s' % (filename, target[1]) filename = os.path.join(self.info_parser.maindir, filename) if", "'x_exciting_species_rtmin': (r'Species with R\\^MT\\_min', None), 'x_exciting_gkmax': (r'Maximum \\|G\\+k\\| for APW", "setattr(sec_system, name, val) except Exception: self.logger.warn('Error setting metainfo.') # species", "range(len(totaldos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value =", "potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing is not None: sec_system.x_exciting_potential_mixing =", "= dict() if 'total' in key: if not self.total_dos: return", "n_sigma)) def parse_loss(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data))", "'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb = self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa') def parse_gw(self): sec_run", "# distributed under the License is distributed on an \"AS", "in range(len(qpoints)): data_q = [] files_q = [f for f", "str_to_array(val_in): val = [v.split(':')[-1].split() for v in val_in.strip().split('\\n')] val =", "= [] for i in range(len(self.number_of_k_points_per_segment)): start = np.array( self.vertices[i].attrib.get(self._coord_key).split(),", "self.root.findall('./%s' % self._vertex_key) return self._vertices @property def number_of_spin_channels(self): if self._nspin", "= self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing is not None: sec_system.x_exciting_potential_mixing = potential_mixing", "smearing_kind = smearing_kind_map[smearing_kind] sec_smearing.kind = smearing_kind smearing_width = self.info_parser.get_initialization_parameter('smearing_width') if", "ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3] def parse_xs(self): sec_run =", "= band_energies[nb] + energy_fermi def _parse_band_out(self, sec_scc): self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels()", "repeats=False)) self._quantities.append( Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree, repeats=True)) class ExcitingEigenvalueParser(TextParser):", "class GWInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = []", "species: labels += [specie.get('symbol')] * len(specie.get('positions')) return labels def get_positions_format(self,", "is None: # we get it by concatenating species symbols", "iteration.get('charge_contributions', {}) for key, names in self._electron_charge_keys_mapping.items(): val = None", "xc_functional_name = ' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point = xc_functional_name sec_scc = sec_run.m_create(Calculation)", "['input_gw.xml', 'input-gw.xml', 'input.xml']: self.parse_file(f, sec_method) xc_functional_name = ' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point", "for lm in range(len(partialdos)): for spin in range(len(partialdos[lm])): for atom", "5) sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq', [1, 1, 1]) sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk',", "self._natoms @property def number_of_dos(self): if self._ndos is None: total_dos =", "def parse_configuration(section): if not section: return sec_scc = self.parse_scc(section) if", "I cannot find an example bandstructure file # atom-resolved bandstructure", "from nomad.datamodel.metainfo.simulation.system import ( System, Atoms ) from nomad.datamodel.metainfo.simulation.calculation import", "iteration|Reached self-consistent loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(Atomic", "f) for f in options] else: filenames = [filename] filenames", "potential energy', 'xc potential'], 'energy_electrostatic': ['Hartree energy', 'Hartree'], 'x_exciting_hartree_energy': ['Hartree", "nomad.datamodel.metainfo.workflow import Workflow, GeometryOptimization from .metainfo.exciting import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin,", "self._quantities.append( Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False)) self._quantities.append( Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n", "('Total valence charge', ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective Wigner radius, r\\_s', ureg.bohr),", "mismatch between files self.logger.warn( 'Mismatch in EXCITON and file type',", "None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') # TODO I", "'.join([str(v) for v in val])) else: try: setattr(sec_system, name, val)", "parse_exciton elif quantity == 'EPSILON': parse_function = parse_epsilon elif quantity", "def band_energies(self): if self._band_energies is None: data = np.transpose(self.data) n_kpoints", "= self.band_out_parser.band_energies if band_energies is None: return # Get fermi", "parse_xs(self): sec_run = self.archive.run[-1] xs_info_files = self.get_exciting_files('INFOXS.OUT') if not xs_info_files:", "with R\\^MT\\_min', None), 'x_exciting_gkmax': (r'Maximum \\|G\\+k\\| for APW functions', 1", "energy_fermi band_k_points = self.bandstructure_parser.get('band_k_points') nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels = self.bandstructure_parser.get('band_segm_labels')", "if val is None: continue if name == 'time': msection.time_calculation", "bs_files: if self.file_exists(fname): gw_files.append(fname) break for f in gw_files: self.parse_file(f,", "self.input_xml_parser.get( 'xs/tetra/tetradf', False) def _parse_xs_bse(self): sec_run = self.archive.run[-1] # TODO", "None: return sec_system = sec_run.m_create(System) sec_atoms = sec_system.m_create(Atoms) sec_atoms.positions =", "val[n][1] else: setattr(msection, key, val) # convergence values for name", "self.number_of_k_points_per_segment[i])) elif key == 'band_segm_labels': res = [] for i", "file, there seems to be two versions, input_gw.xml and input-gw.xml", "'Extended': 'tetrahedra'} sec_smearing = sec_electronic.m_create(Smearing) smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind", "val[1].split() eigs = np.transpose(np.array([v.split() for v in val[2:]], dtype=float)) eigs", "= [sec_method_ref] # parse input xml file, there seems to", "sec_run.m_create(Calculation) sccs.append(sec_scc) else: sec_scc = sccs[i] if sec_scc is None:", "n_components n_excitons = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons sec_scc.x_exciting_xs_bse_exciton_energies", "core charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total valence charge', ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective", "sec_scc.calculations_path.append(info_volume[0]) def init_parser(self): self.info_parser.mainfile = self.filepath self.info_parser.logger = self.logger self.dos_parser.logger", "under the License is distributed on an \"AS IS\" BASIS,", "None: continue if name == 'x_exciting_spin_treatment': sub_sec = sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment", "1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1] sec_charges = msection.m_create(Charges)", "None: return [] name = xc_functional_map.get(xc_functional.type, []) return name @property", "repeats=True, sub_parser=TextParser(quantities=[ Quantity('number', r'Species : *(\\d+)', dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file',", "i) res[i] = self._get_dos(self._total_dos[i]) if self.energy_unit is not None: res", "BasisSet ) from nomad.datamodel.metainfo.simulation.system import ( System, Atoms ) from", "self.info_parser.get_xc_functional_name() if not xc_functional_names: # get it from input.xml input_file", "def _parse_input_gw(self, sec_method): sec_gw = sec_method.m_create(GWMethod) sec_gw.type = 'G0W0' gmaxvr", "None: sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get( 'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get( 'xs/screening/ngridk',", "class for dos and bandstructure super().__init__(None) self._distance_key = 'distance' self._coord_key", "*\\n)', sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation type +: +(\\S+)'), Quantity( 'name_reference', r'\\n", "energy', 'Coulomb potential'], 'energy_xc_potential': ['xc potential energy', 'xc potential'], 'energy_electrostatic':", "= [v.split() for v in val_in.split('\\n')] val = np.transpose(np.array([v for", "Quantity('atomic_mass', rf'atomic mass *: *({re_float})', dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin radius", "sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name)) if not xc_functional_names: # simply write parameters", "i in range(len(keys))} return [kpts, eigs] self._quantities.append( Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point", "= self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return self._energy_unit @property def number_of_spin_channels(self): if self._nspin", "= np.array([ np.transpose(energy)[start:end] for energy in band_energies]) if self._energy_unit is", "for key, names in self._energy_keys_mapping.items(): val = None for name", "metainfo for name in self.info_parser._miscellaneous_keys_mapping.keys(): val = iteration.get(name) if val", "end = self.vertices[i + 1].attrib.get(self._coord_key).split() res.append([start, end]) else: res =", "[True] * 3 # TODO confirm no cell optimization in", "< 2: continue energies[v[0].strip()] = float(v[1]) * ureg.hartree return energies", "'Gaussian': 'gaussian', 'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac': 'fermi', 'Extended': 'tetrahedra'} sec_smearing =", "parse_function = parse_loss else: continue try: parse_function(data, sec_scc) except Exception:", "repeats=False) ) self._quantities.append( Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append(", "= i // (self.number_of_lm * self.number_of_spin_channels) res[lm][spin][atom] = self._get_dos(self.partial_dos[i]) if", "total_dos = self.root.find('./%s/%s' % (self._totaldos_key, self._diagram_key)) self._ndos = len(total_dos) return", "self.logger self.fermisurf_parser.logger = self.logger self.evalqp_parser.logger = self.logger self.dos_out_parser.logger = self.logger", "species symbols species = self.get('initialization', {}).get('species', []) labels = []", "Wigner radius, r\\_s', ureg.bohr), 'x_exciting_empty_states': ('Number of empty states', None),", "iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'force_convergence', r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances,", "= self.info_parser.get_initialization_parameter(name) if val is None: continue if name ==", "smearing_kind = smearing_kind[0] smearing_kind = smearing_kind_map[smearing_kind] sec_smearing.kind = smearing_kind smearing_width", "= None for v in val: v = v.strip().split(':') if", ": *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[ Quantity('number', r'Species :", "positions_format = specie.get('positions_format', None) if positions_format is not None: break", "self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float) for i in range(len(self.bands[n])): band_energies[i % self.number_of_spin_channels][i]", "electronic charge', ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total core charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total", "= self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file = self.get_exciting_files('input.xml') if", "self.info_parser._convergence_keys_mapping.keys(): val = iteration.get(name) if val is None: continue setattr(msection,", "os.path.isfile(filename): file_ext = default.split('.')[-1] mainfile_base = mainfile.rsplit('.', 1)[0].replace('INFO', '') options", "filename): \"\"\"Checks if a the given filename exists and is", "elif name.startswith('EVALQP') and (name.endswith('DAT') or name.endswith('TXT')): parser = self.evalqp_parser parser_function", "= self.parse_scc(section) if sec_scc is None: return sec_system = self.parse_system(section)", "the License. # You may obtain a copy of the", "gw_files.append(fname) break for f in gw_files: self.parse_file(f, sec_scc) frequency_data =", "if not section: return sec_scc = self.parse_scc(section) if sec_scc is", "self._neigs_segment is None: data = np.transpose(self.data) self._neigs_segment = int(max(data[0])) return", "'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True)) class BandstructureDatParser(DataTextParser): def __init__(self,", "filepath, archive, logger): self.filepath = filepath self.archive = archive self.logger", "np.array(lattice_vectors, dtype=float) lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale', 1.0) positions = np.dot(positions, lattice_vectors)", "repeats=False, dtype=float) ] self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization module stopped',", "(n_components, n_epsilon)) * ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape( data[1], (n_components, n_epsilon))", "% (quantity, file_ext, ext, fxctype)) data = [[], [], []]", "= band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3] fermi_energy =", "= self.info_parser.get_number_of_spin_channels() def reshape(data): if data[0] is None: return return", "data[0] is None: return return np.reshape(data, (nspin, len(data) // nspin,", "sec_method.m_create(GWMethod) sec_gw.type = 'G0W0' gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment =", "name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) for name, key_unit", "iteration.get('moment_contributions', {}) for key, names in self._moment_keys_mapping.items(): val = None", "= get_data(quantity, ext) if not data[0]: continue if quantity ==", "self._energies def _get_dos(self, diagram): dos = np.array( [point.attrib.get(self._dos_key) for point", "mainfile.rsplit('.', 1)[0].replace('INFO', '') options = [ f for f in", "is None: self._partial_dos = self.root.findall('./%s/%s' % (self._partialdos_key, self._diagram_key)) return self._partial_dos", "tetradf = self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont = self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf =", "l_list = set([int(e.attrib.get(self._l_key)) for e in self.partial_dos]) for li in", "'') options = [ f for f in os.listdir( self.info_parser.maindir)", "elif key == 'band_segm_start_end': res = [] for i in", "n in range(len(band_energies)): # Get fermi energy: it is used", "def _parse_band_out(self, sec_scc): self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.band_out_parser.band_energies if", "files_q: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None: continue data_q.append(self.data_xs_parser.data)", "np.array( [e.attrib.get(self._energy_key) for e in self.bands[n][i]]) for nkpts_segment in self.number_of_k_points_per_segment:", "module_quantities = [ Quantity( 'scf_iteration', r'(?:I| i)teration number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})',", "x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser): def __init__(self): super().__init__(None)", "filenames = [os.path.join(self.info_parser.maindir, f) for f in options] else: filenames", "sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap is not None: sec_gap.value_fundamental = fundamental_band_gap optical_band_gap", "== 'SIGMA': parse_function = parse_sigma elif quantity == 'LOSS': parse_function", "1) filepath = '%s%s' % (target[0], suffix) if target[1:]: filepath", "initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities = [ Quantity( 'energy_total',", "[] start = 0 band_energies = np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)),", "None @property def band_energies(self): if self._band_energies is None: data =", "self.archive.run[-1] def parse_configuration(section): if not section: return sec_scc = self.parse_scc(section)", "is None: # This is the case when there is", "= dict() atom_resolved = [] species = None for v", "energy_fermi def parse_file(self, name, section): # TODO add support for", "quantity return quantity def get_xc_functional_name(self): # TODO expand list to", "of NOMAD. # See https://nomad-lab.eu for further info. # #", "] self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent loop started|Groundstate module started)([\\s\\S]+?)Groundstate module stopped',", "self._calculation_type = 'xs' # inconsistency in the naming convention for", "= msection.m_create(Charges) sec_charges.value = [ val[n][1].magnitude for n in range(len(val))]", "return sec_system = self.parse_system(section) if sec_system is not None: sec_scc.system_ref", "System, Atoms ) from nomad.datamodel.metainfo.simulation.calculation import ( Calculation, Dos, DosValues,", "xstype.lower() == 'bse': self._parse_xs_bse() elif xstype.lower() == 'tddft': self._parse_xs_tddft() def", "not os.path.isfile(filename): file_ext = default.split('.')[-1] mainfile_base = mainfile.rsplit('.', 1)[0].replace('INFO', '')", "number of plane\\-waves', None), 'x_exciting_lo': (r'Total number of local\\-orbitals', None)}", "elif quantity == 'LOSS': parse_function = parse_loss else: continue try:", "/ ureg.bohr) ] self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent loop started|Groundstate module started)([\\s\\S]+?)Groundstate", "def get_positions_format(self, section): positions_format = section.get('positions_format') if positions_format is None:", "= (i % (self.number_of_spin_channels * self.number_of_lm)) // self.number_of_lm else: spin", "None: res = res * (1 / self.energy_unit) elif 'partial'", "ureg.hartree), 'time': (r'Wall time \\(seconds\\)', ureg.s)} for name, key_unit in", "== 'time': msection.time_calculation = val else: setattr(msection, name, val) #", "= [] for n in range(len(self.bands)): res_n = [] start", "TODO add PDOS def _parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies", "l_list: self._nlm += 2 * li + 1 return self._nlm", "filenames = [f for f in filenames if os.access(f, os.F_OK)]", "['Electron-nuclear energy', 'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung", "ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi nkpts_segment =", "and file type', data=dict(file=quantity)) sec_scc = sec_run.m_create(Calculation) if quantity ==", "= np.array( self.vertices[i + 1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i])) elif", "'x_exciting_number_kpoints': (r'Total number of k\\-points', None), 'x_exciting_rgkmax': (r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max", "self.data_xs_parser.data is None: continue data_q.append(self.data_xs_parser.data) if not data_q: continue data_q", "None: continue if key == 'x_exciting_section_MT_charge_atom': for n in range(len(val)):", "len(self.distances)): if self.distances[i] == self.distances[i - 1]: self._nkpts_segment.append(count) count =", "Energy(fermi=fermi_energy) gw_files = ['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT'] # Parse GW band", "if self.data_clathrate_parser.data: data = np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates = np.transpose( np.array(data[:3], dtype=float))", "to # the original scale in which also other energies", "[filename] filename = os.path.join(self.info_parser.maindir, default) if not os.path.isfile(filename): file_ext =", "= pwm * gmb * gmaxvr sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get( 'gw/barecoul/cutofftype',", "target[0] in f and mainfile_base in f] options = [f", "and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1] elif quantity ==", "= int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states", "return len(self.get('structure_optimization', {}).get('optimization_step', [])) def get_number_of_spin_channels(self): spin_treatment = self.get('initialization', {}).get(", "ForcesEntry(value=forces) # scf iterations scf_iterations = section.get('scf_iteration', []) for scf_iteration", "= start + nkpts_segment band_energy = np.array([np.transpose(band)[start:end] for band in", "for i in range(1, len(self.distances)): if self.distances[i] == self.distances[i -", "screening/BSE are children of xs if self.input_xml_parser.get('xs/screening') is not None:", "forces is not None: sec_forces = sec_scc.m_create(Forces) sec_forces.total = ForcesEntry(value=forces)", "np.reshape( data[0], (n_components, n_loss)) * ureg.hartree sec_scc.x_exciting_xs_bse_loss = np.reshape( data[1],", "'G0W0' gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment = self.input_xml_parser.get( 'gw/coreflag', 'all')", "continue if key == 'x_exciting_section_MT_charge_atom': for n in range(len(val)): sec_mt_charge_atom", "== 1 else v[1] if species is None: species =", "fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap', None) sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap is", "@property def distances(self): if self._distances is None: if not self.bands:", "dont have the quantity # the only thing that we", "np.array([ np.transpose(energy)[start:end] for energy in band_energies]) if self._energy_unit is not", "elif name.startswith('TDOS') and name.endswith('OUT'): parser = self.dos_out_parser parser_function = self._parse_dos_out", "if '_X_' in name: sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_' in name: sec_xc_functional.correlation.append(Functional(name=name))", "if val is None: continue setattr(msection, name, val) # other", "[ 'TET' if tetradf else None, 'AC' if nwacont else", "'x_exciting_core_charge_initial': ('Total core charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total valence charge', ureg.elementary_charge),", "'x_exciting_rgkmax': (r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max \\(rgkmax\\)', None), 'x_exciting_species_rtmin': (r'Species with R\\^MT\\_min',", "is not None: sec_energy.total = EnergyEntry(value=energy_total) x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi') if", "else start, '\\u0393' if end.lower() == 'gamma' else end]) elif", "data.append(self.data_xs_parser.data) return data def parse_exciton(data, sec_scc): n_components = len(data) data", "mainfile, logger): super().__init__(mainfile, logger=logger) def init_quantities(self): self._quantities = [] class", "== 'k_points': return np.array([d[0][:3] for d in data]) elif key", "sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get( 'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get( 'xs/BSE/sciavqwg', False)", "logger=logger) def init_quantities(self): self._quantities = [] class ExcitingInfoParser(TextParser): def __init__(self):", "re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self):", "is None: continue if name == 'x_exciting_spin_treatment': sub_sec = sec_system.m_create(x_exciting_section_spin)", "res * ureg.hartree return res sec_eigenvalues = sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints =", "def parse_sigma(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_sigma", "x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser): def", "= re.search(re_symbol, v[-1]).group(1) elif v[0].startswith('atom'): v[0] = v[0].split() v[1] =", "is None: self._nkpts_segment = [] count = 1 for i", "os import re import logging from nomad.units import ureg from", "size', None), 'x_exciting_pw': (r'Maximum number of plane\\-waves', None), 'x_exciting_lo': (r'Total", "['IP', 'singlet', 'triplet', 'RPA'] scr_types = ['full', 'diag', 'noinvdiag', 'longrange']", "structure_optimization.get('optimization_step', []): sec_scc = parse_configuration(optimization_step) if optimization_step.get('method') is not None:", "[]) return name @property def n_optimization_steps(self): return len(self.get('structure_optimization', {}).get('optimization_step', []))", "self.band_out_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints =", "sec_k_band_segment.endpoints_labels = band_seg_labels[nb] sec_k_band_segment.energies = band_energies[n][nb] + energy_fermi def _parse_eigenvalues(self,", "nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.energies = band_energies[nb] + energy_fermi def", "= '_'.join([e for e in file_ext_list if e]) # read", "exciting_files: self.parse_file(f, sec_scc) # structure optimization structure_optimization = self.info_parser.get('structure_optimization', {})", "self.parse_file(f, sec_scc) frequency_data = self.info_gw_parser.get('frequency_data', None) if frequency_data is not", "not None: sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get( 'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get(", "f in options if f.endswith(file_ext)] options.sort() filenames = [os.path.join(self.info_parser.maindir, f)", "*: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic charge *: *({re_float})', dtype=np.float64,", "= force_convergence[1] sec_scc = parse_configuration(structure_optimization) if sec_scc is None: return", "necessary as this is done in parser, however nspin is", "not None: sec_system.x_exciting_potential_mixing = potential_mixing return sec_system def parse_configurations(self): sec_run", "repeats=False), Quantity( 'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'),", "= [ Quantity( 'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=ureg.hartree), Quantity(", "parse properties gw_info_files = self.get_exciting_files(gw_info_file) if len(gw_info_files) > 1: self.logger.warn('Found", "for more output files and properties exciting_files = ['EIGVAL.OUT', 'FERMISURF.bxsf',", "+ 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1] else: setattr(msection,", "dtype=np.int32))) for lm in range(len(partialdos)): for spin in range(len(partialdos[lm])): for", "% str(i + 1).rjust(3, '0'))] for f in files_q: self.data_xs_parser.mainfile", "no cell optimization in exciting sec_atoms.lattice_vectors = lattice_vectors lattice_vectors_reciprocal =", "for i in range(len(self.total_dos)): spin = self.total_dos[i].attrib.get(self._nspin_key, i) res[i] =", "self.info_parser._miscellaneous_keys_mapping.keys(): val = iteration.get(name) if val is None: continue if", "name in self.info_parser._convergence_keys_mapping.keys(): threshold = self.info_parser.get_scf_threshold(name) if threshold is None:", "sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities = [ Quantity( 'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False,", "self._partialdos_key) self._natoms = len(partial_dos) return self._natoms @property def number_of_dos(self): if", "specific language governing permissions and # limitations under the License.", "width', None)} for name, key_unit in self._system_keys_mapping.items(): initialization_quantities.append( Quantity( name,", "*\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[ Quantity('number', r'Species : *(\\d+)', dtype=np.int32),", "self._nspin = None self._nkpts_segment = None self._neigs_segment = None self._bands", "unit=ureg.s, repeats=False, dtype=float) ] self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization module", "is None: return partialdos = partialdos.to('1/joule').magnitude lm_values = np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos),", "positions = np.dot(positions, lattice_vectors) * ureg.bohr lattice_vectors = lattice_vectors *", "self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None: continue data.append(self.data_xs_parser.data) return", "self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals =", "None: self._results = dict() if not self.bands: return if key", "else: setattr(msection, key, val) # moment contributions moment_contributions = iteration.get('moment_contributions',", "None: return positions = np.array(positions) positions_format = positions_format if positions_format", "= specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius') positions_format = specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format =", "= self.get_exciting_files(name) if len(files) > 1: self.logger.warn('Found multiple files. Will", "in species]) if positions is None: return positions = np.array(positions)", "if key == 'x_exciting_section_MT_charge_atom': for n in range(len(val)): sec_mt_charge_atom =", "init_quantities(self): self._quantities = [] class ExcitingInfoParser(TextParser): def __init__(self): super().__init__(None) def", "in self.number_of_k_points_per_segment: end = start + nkpts_segment band_energy = np.array([np.transpose(band)[start:end]", "energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=ureg.hartree), Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False,", "self.data_clathrate_parser.data: data = np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates = np.transpose( np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels", "1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i])) elif key == 'band_segm_labels': res", "or name.startswith('FS')) and name.endswith('bxsf'): parser = self.fermisurf_parser parser_function = self._parse_fermisurface", "(r'k\\-point grid', None), 'x_exciting_kpoint_offset': (r'k\\-point offset', None), 'x_exciting_number_kpoints': (r'Total number", "setattr(sec_method, metainfo_name, threshold) # additionally, set threshold to global metainfo.", "= frequency_data.get('values') sec_method.gw.frequency_weights = frequency_data.get('weights') fundamental_band_gap = self.info_gw_parser.get('direct_band_gap', None) if", "r'Abs\\. change in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree / ureg.bohr)} for name, key_unit", "sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx')) eigs_gw_C = reshape(get_data('Sc')) if eigs_gw_C is None:", "is accessible in the same folder where the mainfile is", "DOS to # the original scale in which also other", "*({re_float})', dtype=np.float64, unit=ureg.bohr), Quantity('radial_points', rf'radial points in muffin-tin *: *({re_float})',", "= self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] # parse", "_parse_fermisurface(self, sec_scc): fermi_surface = self.fermisurf_parser.get('fermi_surface', [None])[0] if fermi_surface is None:", "target[1]) filepath = os.path.join(self.info_parser.maindir, filepath) if os.path.isfile(filepath) and os.access(filepath, os.F_OK):", "r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False, convert=False), Quantity( 'x_exciting_dos_fermi', r'DOS at Fermi", "sccs.append(None) continue if quantity == 'EXCITON': sec_scc = sec_run.m_create(Calculation) sccs.append(sec_scc)", "dtype=float) ] self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization module stopped', sub_parser=TextParser(quantities=[", "not certain about the format for the spin polarized case", "r'Optimization step\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'method', r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str), Quantity(", "states', None), 'x_exciting_valence_states': ('Total number of valence states', None), 'x_exciting_hamiltonian_size':", "= 0 l_list = set([int(e.attrib.get(self._l_key)) for e in self.partial_dos]) for", "else v[1] if species is None: species = v[0][2] atom_resolved.append(((species,", "= self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax = rgkmax sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get( 'xs/BSE/sciavbd',", "quantity == 'SIGMA' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3]", "len(data), len(res[0]) // len(data))) if key == 'eigenvalues': res =", "self.dos_parser.get('partialdos') if partialdos is None: return partialdos = partialdos.to('1/joule').magnitude lm_values", "mainfile is stored. \"\"\" mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT')", "None self._band_k_points = None @property def band_energies(self): if self._band_energies is", "number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: self._neigs_segment = len(self.bands[0]) // self.number_of_spin_channels", "== 'LOSS' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1] elif", "names in self._moment_keys_mapping.items(): val = None for name in names:", "# TODO I am not certain if screening/BSE are children", "{}) for key, names in self._moment_keys_mapping.items(): val = None for", "BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) class ExcitingEvalqpParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self):", "= self.get_exciting_files('input.xml') if not input_file: return self.input_xml_parser.mainfile = input_file[0] xstype", "self._vertex_key = 'vertex' self._band_key = 'band' self._atom_key = 'atom' self._nspin", "== 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1] elif quantity == 'SIGMA' and", "Hamiltonian size', None), 'x_exciting_pw': (r'Maximum number of plane\\-waves', None), 'x_exciting_lo':", "and mainfile_base in f] options = [f for f in", "reshape(data): if data[0] is None: return return np.reshape(data, (nspin, len(data)", "bands = self.root.findall('./%s' % self._band_key) self._bands = [] if bands:", "res.append(res_n) elif key == 'band_k_points': res = [] for i", "= self.get('initialization', {}).get('species', []) labels = [] for specie in", "sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value = totaldos[spin]", "'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])), Quantity( 'forces', r'Total atomic forces including", "(n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape( data[2], (n_components, n_epsilon)) def parse_sigma(data,", "val = np.transpose(val) occs = val[-1] eigs = val[-2] nspin", "( r'Abs\\. change in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree / ureg.bohr)} for name,", "type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation type +: +(\\S+)'), Quantity( 'name_reference',", "sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get( 'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get( 'xs/screening/ngridk', [0,", "'x_exciting_gap': (r'Estimated fundamental gap', ureg.hartree), 'time': (r'Wall time \\(seconds\\)', ureg.s)}", "given filename exists and is accessible in the same folder", "for bse_type in bse_types: for scr_type in scr_types: files =", "'time': msection.time_calculation = val else: setattr(msection, name, val) # energy,", "sec_scc.energy.fermi energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic)", "sec_scc) # structure optimization structure_optimization = self.info_parser.get('structure_optimization', {}) for optimization_step", "None: species = self.get_initialization_parameter('species', []) if species: positions = np.vstack([s.get('positions')", "= r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities", "nspin)) data['eigenvalues'] = np.reshape(eigs, (nspin, len(eigs) // nspin)) return data", "= self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity, ext): # all files related to", "res = [] for i in range(len(self.number_of_k_points_per_segment)): start = np.array(", "super().__init__(None) self._nspin_key = 'nspin' self._totaldos_key = 'totaldos' self._partialdos_key = 'partialdos'", "self.total_dos: return self._nspin = len(self.total_dos) return self._nspin @property def number_of_atoms(self):", "= EnergyEntry(value=energy_total) x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi is not None:", "self.input_xml_parser.get( 'xs/BSE/nstlbse', [0, 0, 0, 0]) if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom =", "ureg.bohr val = val_in.strip().split('\\n') properties = dict() atom_resolved = []", "fermi_surface def _parse_evalqp(self, sec_scc): data = self.evalqp_parser.get('kpoints_eigenvalues') if data is", "self._parse_input_gw elif self._calculation_type == 'xs': parser_function = self._parse_input_xs else: #", "if fundamental_band_gap is None: fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap', None) sec_gap =", "self.input_xml_parser.get('xs/ngridk', [1, 1, 1]) rgkmax = self.input_xml_parser.get('xs/rgkmax', None) if rgkmax", "= data[1] elif quantity == 'LOSS' and ext == 'NLF_FXC':", "self.distances[i] == self.distances[i - 1]: self._nkpts_segment.append(count) count = 1 else:", "if self._nlm is None: if self.partial_dos is None: return self._nlm", "continue data.append(self.data_xs_parser.data) return data def parse_exciton(data, sec_scc): n_components = len(data)", "'0'))] for f in files_q: self.data_xs_parser.mainfile = f if self.data_xs_parser.data", "self._neigs_segment is None: data = np.transpose(self.data)[0] self._neigs_segment = len(np.where(data ==", "potential_mixing is not None: sec_system.x_exciting_potential_mixing = potential_mixing return sec_system def", "get_atom_positions(self, section={}, positions=None, positions_format=None): positions = positions if positions is", "self._atom_key) for band in bands_atom: self._bands.append(band.findall('./%s' % self._band_key)) return self._bands", "else 2 return n_spin def get_unit_cell_volume(self): return self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0", "'BAND-QP.OUT'] for fname in bs_files: if self.file_exists(fname): gw_files.append(fname) break for", "self.number_of_k_points_per_segment: end = start + nkpts_segment band_energy = np.array([ np.transpose(energy)[start:end]", "None for name in names: val = charge_contributions.get(name, None) if", "nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.endpoints_labels = band_seg_labels[nb] sec_k_band_segment.energies = band_energies[n][nb]", "0 band_energies = np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float) for i", "None: continue data_q.append(self.data_xs_parser.data) if not data_q: continue data_q = np.transpose(data_q,", "bands_atom: self._bands.append(band.findall('./%s' % self._band_key)) return self._bands @property def vertices(self): if", "distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence': ( r'Abs\\. change in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree /", "quantity is None: return # this is really problematic if", "self.info_parser.get_number_of_spin_channels() sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = len(data) // nspin", "convergence values for name in self.info_parser._convergence_keys_mapping.keys(): val = iteration.get(name) if", "points in muffin-tin *: *({re_float})', dtype=np.int32), Quantity('positions_format', r'atomic positions \\((.+?)\\)',", "'energy_sum_eigenvalues': ['Sum of eigenvalues', 'sum of eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective potential", "self._quantities.append( Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True)) def str_to_eigenvalues(val_in): val =", "xc_functional_map.get(xc_functional.type, []) return name @property def n_optimization_steps(self): return len(self.get('structure_optimization', {}).get('optimization_step',", "fermi_surface is None: return sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters = self.fermisurf_parser.get('band_parameters',", "self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0], repeats=False, unit=key_unit[1])) self._convergence_keys_mapping =", "class BandOutParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None)", "set nspin again as this is overwritten when setting mainfile", "sec_method.methods_ref = [sec_method_ref] # parse input xml file, there seems", "properties gw_info_files = self.get_exciting_files(gw_info_file) if len(gw_info_files) > 1: self.logger.warn('Found multiple", "is not None: sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method') if optimization_step.get('step') is not", "['total moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved'] } def get_exciting_files(self, default): mainfile =", "is to assume that the first steps are the #", "sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff', [0., 0., 0.]) # TODO I am", "if 'total' in key: if not self.total_dos: return res =", "= { 'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage': ['core leakage'], 'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge':", "self._parse_eigenvalues elif (name.startswith('FERMISURF') or name.startswith('FS')) and name.endswith('bxsf'): parser = self.fermisurf_parser", "is None: continue setattr(msection, name, val) # other metainfo for", "[]) if species: positions = np.vstack([s.get('positions') for s in species])", "positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'imized atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)',", "data[5], (n_components, n_excitons)) def parse_epsilon(data, sec_scc): n_components = len(data) data", "format for spin-polarized case! I assume it is # energy", "epsilon which is not parsed? sccs = [] for quantity", "self.energy_unit) elif key == 'energies': return self.energies else: res =", "and (name.endswith('DAT') or name.endswith('TXT')): parser = self.evalqp_parser parser_function = self._parse_evalqp", "band_energy * self._energy_unit self._band_energies.append(band_energy) start = end return self._band_energies @property", "optical_band_gap is not None: sec_gap.value_optical = optical_band_gap def parse_miscellaneous(self): sec_worfklow", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "None: data = np.transpose(self.data) self._band_k_points = [] start = 0", "def number_of_atoms(self): if self._natoms is None: partial_dos = self.root.findall('./%s' %", "xc_functional_names: # simply write parameters xc_functional = self.info_parser.get('initialization', {}).get('xc_functional') if", "self.input_xml_parser.get( 'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment =", "ureg.bohr def get_scf_threshold(self, name): reference = self.get('groundstate', self.get('hybrids', {})) return", "output files and properties exciting_files = ['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf'] #", "the same folder where the mainfile is stored. \"\"\" mainfile", "goes first since reference needed for sec_scc self.parse_method() self.parse_configurations() self.parse_gw()", "is None: continue data_q.append(self.data_xs_parser.data) if not data_q: continue data_q =", "number_of_spin_channels(self): if self._nspin is None: self._nspin = 1 return self._nspin", "= [filename] filenames = [f for f in filenames if", "('Smearing scheme', None), 'smearing_width': ('Smearing width', None)} for name, key_unit", "else section.get('final') if final is None: # get it from", "not None: sec_gap.value_fundamental = fundamental_band_gap optical_band_gap = self.info_gw_parser.get('optical_band_gap', None) if", "if key == 'eigenvalues': res = res * ureg.hartree return", "' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point = xc_functional_name sec_scc = sec_run.m_create(Calculation) sec_scc.method_ref =", "= self.input_xml_parser.get('xs/screening/rgkmax', None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax',", "and properties exciting_files = ['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf'] # Parse DFT", "is None: self._nspin = np.shape(np.transpose(self.data))[0] - 6 return self._nspin @property", "sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get( 'xs/nempty', 5) sec_method.x_exciting_xs_ngridq", "self._energy_unit res_n.append(band_energy) start = end res.append(res_n) elif key == 'band_k_points':", "eigs_gw_C sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc')) def _parse_dos_out(self, sec_scc): data = self.dos_out_parser.data", "if self.data is None: return data = np.transpose(self.data) n_kpoints =", "positions is not None else section.get('positions') if positions is None:", "== 'x_exciting_section_MT_moment_atom': for n in range(len(val)): sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index", "= sec_run.m_create(Calculation) if quantity == 'EXCITON': parse_function = parse_exciton elif", "What is the fourth column in epsilon which is not", "positions = self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude # clathrate", "= number sec_method.gw.frequency_values = frequency_data.get('values') sec_method.gw.frequency_weights = frequency_data.get('weights') fundamental_band_gap =", "self.logger self.info_gw_parser.logger = self.logger self.input_xml_parser.logger = self.logger self.data_xs_parser.logger = self.logger", "+ energy_fermi volume = self.info_parser.get_unit_cell_volume() dos = data[1] * (1", "'scf_iteration', r'(?:I| i)teration number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity( 'final',", "* (1 / self.energy_unit) elif key == 'energies': return self.energies", "res = res * (1 / self.energy_unit) elif 'partial' in", "energy_fermi volume = self.info_parser.get_unit_cell_volume() dos = data[1] * (1 /", "# we get it by concatenating species symbols species =", "totaldos[spin] partialdos = self.dos_parser.get('partialdos') if partialdos is None: return partialdos", "return np.array(val, dtype=float) def str_to_atom_properties_dict(val_in): unit = None if 'charge'", "axes=(2, 0, 1)) sec_dos.energies = data[0][0] * ureg.hartree + energy_fermi", "None, 'AC' if nwacont else None, 'NAR' if not aresdf", "for d in data]) * ureg.hartree eigs_gw = get_data('E_GW') if", "== 'LOSS' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1] elif", "data[1:3] elif quantity == 'LOSS' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field", "in exciting sec_atoms.lattice_vectors = lattice_vectors lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal", "None) def init_parameters(self): self._nspin = None self._distances = None self._band_energies", "def _parse_fermisurface(self, sec_scc): fermi_surface = self.fermisurf_parser.get('fermi_surface', [None])[0] if fermi_surface is", "for e in self.partial_dos]) for li in l_list: self._nlm +=", "d in data]) * ureg.hartree eigs_gw = get_data('E_GW') if eigs_gw[0]", "step\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'method', r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str), Quantity( 'n_scf_iterations',", "import ( Method, DFT, Electronic, Smearing, XCFunctional, Functional, GW as", "'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False, dtype=str, flatten=False)] initialization_quantities = [ Quantity(", "'GGA_X_PBE'], 21: ['GGA_C_PBE', 'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE', 'GGA_X_WC'],", "self.bands: return if key == 'band_energies': # TODO I am", "# TODO I am not certain about the format for", "else: setattr(msection, name, val) # energy, moment, charge contributions parse_scf(final,", "= np.reshape( data[0], (n_components, n_loss)) * ureg.hartree sec_scc.x_exciting_xs_bse_loss = np.reshape(", "[filename] filenames = [f for f in filenames if os.access(f,", "= band_k_points[nb] sec_k_band_segment.endpoints_labels = band_seg_labels[nb] sec_k_band_segment.energies = band_energies[n][nb] + energy_fermi", "class ExcitingEigenvalueParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = []", "frequency_data.get('values') sec_method.gw.frequency_weights = frequency_data.get('weights') fundamental_band_gap = self.info_gw_parser.get('direct_band_gap', None) if fundamental_band_gap", "'EPSILON', 'SIGMA', 'LOSS']: files = get_files(quantity) for i in range(len(files)):", "self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get( 'xs/nempty', 5) sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq',", "3) def get_initialization_parameter(self, key, default=None): return self.get('initialization', {}).get(key, default) class", "= self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2, '0')) if not info_volume: break sec_scc.calculations_path.append(info_volume[0])", "= [] self._quantities.append( Quantity( 'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False)) def", "'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=ureg.hartree), Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)',", "self.number_of_k_points_per_segment: end = start + nkpts_segment band_energy = np.array([np.transpose(band)[start:end] for", "None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax = rgkmax sec_method.x_exciting_xs_screening_type =", "n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape( data[0], (n_components, n_epsilon)) * ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re", "v in x.split(':')])])) ) self._quantities.append(Quantity( 'initialization', r'(?:All units are atomic|Starting", "filename exists and is accessible in the same folder where", "f break if not self._calculation_type == 'gw': return sec_method =", "# two versions of gw info files gw_info_files = ['GW_INFO.OUT',", "parse_scf(final, sec_scc) # forces forces = section.get('forces') if forces is", "// len(data))) if key == 'eigenvalues': res = res *", "at this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions at this", "from nomad.parsing.file_parser import TextParser, Quantity, XMLParser, DataTextParser from nomad.datamodel.metainfo.simulation.run import", "is used to un-shift the DOS to # the original", "_parse_input_gw(self, sec_method): sec_gw = sec_method.m_create(GWMethod) sec_gw.type = 'G0W0' gmaxvr =", "['Kinetic energy', 'electronic kinetic'], 'energy_coulomb': ['Coulomb energy', 'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb", "= reshape(get_data('Sx')) eigs_gw_C = reshape(get_data('Sc')) if eigs_gw_C is None: eigs_gw_C", "if fermi_surface is None: return sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters =", "species = None for v in val: v = v.strip().split(':')", "sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_loss = len(data[0])", "sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius') positions_format", "aresdf else None] file_ext = '_'.join([e for e in file_ext_list", "= sec_method_ref sec_method.methods_ref = [sec_method_ref] self.parse_file('input.xml', sec_method) # parse properties", "data = np.transpose(self.data) self._neigs_segment = int(max(data[0])) return self._neigs_segment class BandOutParser(DataTextParser):", "sec_scc.energy.fermi if energy_fermi is None: continue energy_fermi = energy_fermi.to(\"hartree\") sec_k_band", "is None: dist = np.transpose(self.data)[0] n_k_points = np.where(dist == dist[0])[0][1]", "= res class DOSXMLParser(XMLParser): def __init__(self, **kwargs): super().__init__(None) self._nspin_key =", "ureg.elementary_charge * ureg.bohr val = val_in.strip().split('\\n') properties = dict() atom_resolved", "Scf(threshold_energy_change=threshold) xc_functional_names = self.info_parser.get_xc_functional_name() if not xc_functional_names: # get it", "sec_dft = sec_method.m_create(DFT) sec_electronic = sec_method.m_create(Electronic) sec_electronic.method = 'DFT' smearing_kind_map", "= self.get_exciting_files(gw_info_file) if len(gw_info_files) > 1: self.logger.warn('Found multiple GW info", "software # distributed under the License is distributed on an", "= kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): #", "[] species = None for v in val: v =", "= self.input_xml_parser.get( 'xs/BSE/nstlxas', [0, 0]) if self.input_xml_parser.get('xs/tddft') is not None:", "self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa') def parse_gw(self): sec_run = self.archive.run[-1] # two", "mesh, origin, vector] self._quantities.append( Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False)) self._quantities.append(", "sec_method.m_create(Electronic) sec_electronic.method = 'DFT' smearing_kind_map = { 'Gaussian': 'gaussian', 'Methfessel-Paxton':", "is None: continue energy_fermi = energy_fermi.to(\"hartree\") sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic)", "'none') sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb = self.input_xml_parser.get( 'gw/scrcoul/scrtype',", "lm in range(len(partialdos)): for spin in range(len(partialdos[lm])): for atom in", "sec_method.gw.frequency_number = number sec_method.gw.frequency_values = frequency_data.get('values') sec_method.gw.frequency_weights = frequency_data.get('weights') fundamental_band_gap", "initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation type +:", "'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get(", "self.total_dos is None: return self._energies = np.array( [float(point.attrib.get(self._energy_key)) for point", "val_l is None or val_m is None: lm = i", "as np import os import re import logging from nomad.units", "grid sizes', None), 'x_exciting_gvector_total': (r'Total number of G\\-vectors', None), 'x_exciting_lmaxapw':", "between files self.logger.warn( 'Mismatch in EXCITON and file type', data=dict(file=quantity))", "= val_in.strip().split('\\n') kpts = np.array(val[0].split(), dtype=float) keys = val[1].split() eigs", "labels = [] for specie in species: labels += [specie.get('symbol')]", "name.endswith('xml'): parser = self.bandstructure_parser parser_function = self._parse_bandstructure elif name.startswith('EIGVAL') and", "is None: return nspin = self.info_parser.get_number_of_spin_channels() def reshape(data): if data[0]", "'SIGMA' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3] def parse_xs(self):", "2 + int(val_m) + int(val_l) atom = i // (self.number_of_lm", "data=dict(file=name)) for n in range(len(files)): parser.mainfile = files[n] parser_function(section) #", "for specie in species: labels += [specie.get('symbol')] * len(specie.get('positions')) return", "in addition to INFO.OUT return else: return files = self.get_exciting_files(name)", "from .metainfo.exciting import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float =", "is None: self._nspin = 1 return self._nspin @property def number_of_k_points_per_segment(self):", "0.]) sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get(", "= self._parse_dos elif name.startswith('bandstructure') and name.endswith('xml'): parser = self.bandstructure_parser parser_function", "ureg.hartree sec_scc.x_exciting_xs_bse_loss = np.reshape( data[1], (n_components, n_loss)) # TODO check", "energy', 'exchange'], 'x_exciting_exchange_energy': ['Exchange energy', 'exchange'], 'energy_correlation': ['Correlation energy', 'correlation'],", "None: continue data.append(self.data_xs_parser.data) return data def parse_exciton(data, sec_scc): n_components =", "for name, key_unit in self._method_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' %", "magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree / ureg.bohr, repeats=False, dtype=float), Quantity( 'energy_total',", "xs input xml file sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0]", "= '%s.%s' % (filepath, target[1]) filepath = os.path.join(self.info_parser.maindir, filepath) if", "data = [] for f in files: self.data_xs_parser.mainfile = f", "parse_configurations(self): sec_run = self.archive.run[-1] def parse_configuration(section): if not section: return", "if self._distances is None: if not self.bands: return self._distances =", "supposed # to be what they are. What is the", "self.input_xml_parser.get( 'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get( 'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric =", "f.endswith('QMT%s.OUT' % str(i + 1).rjust(3, '0'))] for f in files_q:", "sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.value = band_energies[nb] +", "'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get( 'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get(", "else: sec_scc = sccs[i] if sec_scc is None: # This", "@property def vertices(self): if self._vertices is None: self._vertices = self.root.findall('./%s'", "data[1] * (1 / ureg.hartree) * volume.to('m**3').magnitude for spin in", "range(len(band_energies)): # Get fermi energy: it is used to un-shift", "atom-resolved bandstructure are added as separate section_k_band res = []", "self.logger self.band_out_parser.logger = self.logger self.info_gw_parser.logger = self.logger self.input_xml_parser.logger = self.logger", "None: total_dos = self.root.find('./%s/%s' % (self._totaldos_key, self._diagram_key)) self._ndos = len(total_dos)", "eigs_gw_C = reshape(get_data('Sc')) if eigs_gw_C is None: eigs_gw_C = reshape(get_data('Re(Sc)'))", "= np.reshape( data[1], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape(", "np.dot(positions, lattice_vectors) * ureg.bohr lattice_vectors = lattice_vectors * ureg.bohr atoms", "self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities self.evalqp_parser.quantities = parser.evalqp_parser.quantities self.info_gw_parser.quantities = parser.info_gw_parser.quantities def", "= default.rsplit('.', 1) filename = '%s%s' % (target[0], suffix) if", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "section.get('scf_iteration', [None])[-1] final = section.get('optimization_step', [None])[-1] if final is None", "mainfile_base = mainfile.rsplit('.', 1)[0].replace('INFO', '') options = [ f for", "f in os.listdir( self.info_parser.maindir) if target[0] in f and mainfile_base", "Quantity('name', r'name *: *(.+)'), Quantity('nuclear_charge', rf'nuclear charge *: *({re_float})', dtype=np.float64,", "gmb = self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax = gmb * gmaxvr pwm", "more output files and properties exciting_files = ['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf']", "]+)' % key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False)) module_quantities = [ Quantity(", "change in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree / ureg.bohr)} for name, key_unit in", "self.bandstructure_parser.get('band_energies', []) for n in range(len(band_energies)): # Get fermi energy:", "part of NOMAD. # See https://nomad-lab.eu for further info. #", "scf_iterations = section.get('scf_iteration', []) for scf_iteration in scf_iterations: sec_scf_iteration =", "if xc_functional is None: return [] name = xc_functional_map.get(xc_functional.type, [])", "self._partial_dos = None @property def energy_unit(self): if self._energy_unit is None:", "['atom_resolved'] } self._moment_keys_mapping = { 'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment': ['total moment", "* ureg.hartree return energies self._quantities = [Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started',", "'energy_xc_potential': ['xc potential energy', 'xc potential'], 'energy_electrostatic': ['Hartree energy', 'Hartree'],", "0, 1)) sec_dos.energies = data[0][0] * ureg.hartree + energy_fermi volume", "if not aresdf else None] file_ext = '_'.join([e for e", "'GGA_X_WC'], 30: ['GGA_C_AM05', 'GGA_C_AM05'], 300: ['GGA_C_BGCP', 'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'], 408:", "= 'distance' self._coord_key = 'coord' self._energy_key = 'eval' self._vertex_key =", "self._nspin_key = 'nspin' self._totaldos_key = 'totaldos' self._partialdos_key = 'partialdos' self._diagram_key", "% key_unit[0], unit=key_unit[1], repeats=False) ) for name, key_unit in self._method_keys_mapping.items():", "dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass',", "sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_sigma = len(data[0])", "it from input.xml input_file = self.get_exciting_files('input.xml') for f in input_file:", "filepath self.archive = archive self.logger = logger if logger is", "if val_l is None or val_m is None: lm =", "to scc # TODO add support for more output files", "@property def number_of_dos(self): if self._ndos is None: total_dos = self.root.find('./%s/%s'", "is not None: break return positions_format def get_atom_positions(self, section={}, positions=None,", "# Parse DFT DOS from one of the files bs_files", "name, key_unit in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0], repeats=False,", "['Coulomb energy', 'Coulomb'], 'energy_exchange': ['Exchange energy', 'exchange'], 'x_exciting_exchange_energy': ['Exchange energy',", "['Effective potential energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb potential energy', 'Coulomb potential'], 'energy_xc_potential':", "unit = None if 'charge' in val_in: unit = ureg.elementary_charge", "else None, 'NAR' if not aresdf else None] file_ext =", "if positions_format is None: species = self.get_initialization_parameter('species', []) for specie", "len(quantity)) + quantity return quantity def get_xc_functional_name(self): # TODO expand", "range(len(files)): data = get_data(files[i]) if not data: sccs.append(None) continue if", "None) xc_functional_names.append(exchange) sec_xc_functional = sec_dft.m_create(XCFunctional) for name in xc_functional_names: if", "parse_configuration(optimization_step) if optimization_step.get('method') is not None: sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method') if", "None) if fermi_energy is not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy sec_fermisurface.x_exciting_values_fermi_surface", "= sec_run.calculation[0] sec_scc.starting_calculation_ref = sec_scc_ref sec_scc.calculations_ref = [sec_scc_ref] # parse", "atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False, str_operation=str_to_array, convert=False, unit=ureg.hartree", "values for name in self.info_parser._convergence_keys_mapping.keys(): val = iteration.get(name) if val", "self.parse_scc(section) if sec_scc is None: return sec_system = self.parse_system(section) if", "Get fermi energy: it is used to un-shift the band", "f in ['input_gw.xml', 'input-gw.xml', 'input.xml']: self.parse_file(f, sec_method) xc_functional_name = '", "r'\\((\\w+)\\)'), Quantity('file', r'parameters loaded from *: *(.+)'), Quantity('name', r'name *:", "input xml file sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref", "BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) )", "** 3), 'x_exciting_brillouin_zone_volume': ('Brillouin zone volume', 1 / ureg.bohr **", "'eval' self._vertex_key = 'vertex' self._band_key = 'band' self._atom_key = 'atom'", "assume that the first steps are the # ones with", "dos[spin] # TODO add PDOS def _parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin =", "GWInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] def", "n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape( data[2], (n_components, n_epsilon)) def parse_sigma(data, sec_scc):", "x_exciting_section_atoms_group re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser): def __init__(self): super().__init__(None) def", "'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE', 'GGA_X_WC'], 30: ['GGA_C_AM05', 'GGA_C_AM05'],", "data = np.transpose(self.data) self._band_k_points = [] start = 0 for", "= None self._partial_dos = None @property def energy_unit(self): if self._energy_unit", "INFO.OUT return else: return files = self.get_exciting_files(name) if len(files) >", "in val[2:]], dtype=float)) eigs = {keys[i]: eigs[i] for i in", "if target[0] in f and mainfile_base in f] options =", "not None else self.get_positions_format(section) if positions_format == 'lattice': cell =", "not None: sec_energy.total = EnergyEntry(value=energy_total) x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi", "['core leakage'], 'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge': ['total charge in", "True def parse_scc(self, section): sec_run = self.archive.run[-1] final = section", "ureg.hartree / ureg.bohr)} for name, key_unit in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name,", "polarized case # I cannot find an example bandstructure file", "target[1]) filename = os.path.join(self.info_parser.maindir, filename) if os.path.isfile(filename): return [filename] filename", "unit=key_unit[1], repeats=False) ) initialization_quantities.append(Quantity( 'species', rf'(Species : *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float}", "str_operation=str_to_eigenvalue, repeats=True)) class BandstructureDatParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin =", "number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data = np.transpose(self.data) self._neigs_segment =", "return True return False def _parse_dos(self, sec_scc): if self.dos_parser.get('totaldos', None)", "expand list to include other xcf xc_functional_map = { 2:", "[v.split() for v in val_in.split('\\n')] val = np.transpose(np.array([v for v", "sec_method): xstype = self.input_xml_parser.get('xs/xstype', None) if xstype is not None:", "sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_dat_parser.band_k_points nkpts_segment =", "np.eye(3)) species = self.input_xml_parser.get('structure/species/speciesfile') if positions is None or lattice_vectors", "self.input_xml_parser.get( 'xs/screening/screentype', 'full') if self.input_xml_parser.get('xs/BSE') is not None: sec_method.x_exciting_xs_bse_antiresonant =", "self.input_xml_parser.get('gw/ngridq', [1, 1, 1]) sec_gw.basis_set = 'mixed' sec_gw.qp_equation_treatment = 'linearization'", "/ ureg.hartree), Quantity( 'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False),", "'smearing_width': ('Smearing width', None)} for name, key_unit in self._system_keys_mapping.items(): initialization_quantities.append(", "to INFO.OUT return else: return files = self.get_exciting_files(name) if len(files)", "am not certain if screening/BSE are children of xs if", "get it from last scf_iteration or optimization_step final = section.get('scf_iteration',", "** 3) def get_initialization_parameter(self, key, default=None): return self.get('initialization', {}).get(key, default)", "format of files are really correct, i.e. columns are supposed", "self.dos_out_parser.data if data is None: return # Get fermi energy:", "np.reshape( data[1], (n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im = np.reshape( data[2], (n_components, n_sigma))", "force_convergence is not None: sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1]", "= res * ureg.hartree return res sec_eigenvalues = sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints", "*({re_float}) *({re_float})', repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing', r'Using ([\\w ]+) potential", "is overwritten when setting mainfile self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies =", "= BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser = GWInfoParser() self.input_xml_parser = XMLParser() self.data_xs_parser =", "metainfo.') # species species = self.info_parser.get_initialization_parameter('species', []) for specie in", "== 1 else vi properties[v[0].strip()] = vi * unit properties['atom_resolved']", "res = res.reshape((len(res), len(data), len(res[0]) // len(data))) if key ==", "(energy_fermi.magnitude * ureg.joule).to('hartree') sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = self.dos_parser.number_of_dos", "else: sec_xc_functional.contributions.append(Functional(name=name)) if not xc_functional_names: # simply write parameters xc_functional", "self.info_parser.maindir) if target[0] in f and mainfile_base in f] options", "elif quantity == 'LOSS' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field =", "from one of the files: bs_files = ['bandstructure-qp.dat', 'BAND-QP.OUT'] for", "input.xml for f in input_file: self.input_xml_parser.mainfile = f positions =", "range(len(self.number_of_k_points_per_segment)): start = self.vertices[i].attrib.get(self._coord_key).split() end = self.vertices[i + 1].attrib.get(self._coord_key).split() res.append([start,", "if self._distances is None: data = np.transpose(self.data) self._distances = data[5][:int(max(data[1]))]", "2 if occs[0] == 1. else 1 data = dict()", "'Fermi-Dirac': 'fermi', 'Extended': 'tetrahedra'} sec_smearing = sec_electronic.m_create(Smearing) smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind')", "including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr),", "= self.vertices[i + 1].attrib.get(self._coord_key).split() res.append([start, end]) else: res = None", "def init_parameters(self): self._nspin = None self._nkpts_segment = None self._neigs_segment =", "'moment' in val_in: unit = ureg.elementary_charge * ureg.bohr val =", "= 0 for nkpts_segment in self.number_of_k_points_per_segment: end = start +", "None: self._energies = self._energies * self.energy_unit return self._energies def _get_dos(self,", "self.logger.warn('Error setting metainfo.') # species species = self.info_parser.get_initialization_parameter('species', []) for", "'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states = int( self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq',", "self._quantities = [] self._quantities.append( Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True)) def", "nspin data = np.reshape(data, (nspin, len(data) // nspin, 2)) data", "'correlation'], 'energy_sum_eigenvalues': ['Sum of eigenvalues', 'sum of eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective", "self._natoms is None: partial_dos = self.root.findall('./%s' % self._partialdos_key) self._natoms =", "bse_types: for scr_type in scr_types: files = self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' %", "= { 'x_exciting_effective_potential_convergence': ( r'RMS change in effective potential \\(target\\)',", "input_file[0] xstype = self.input_xml_parser.get('xs/xstype', '') if xstype.lower() == 'bse': self._parse_xs_bse()", "self.bandstructure_parser.get('band_k_points') nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels = self.bandstructure_parser.get('band_segm_labels') for nb in", "\\* \\|G\\+k\\|\\_max \\(rgkmax\\)', None), 'x_exciting_species_rtmin': (r'Species with R\\^MT\\_min', None), 'x_exciting_gkmax':", "// nspin, 2)) data = np.transpose(data, axes=(2, 0, 1)) sec_dos.energies", "Functional, GW as GWMethod, Scf, BasisSet ) from nomad.datamodel.metainfo.simulation.system import", "I am not certain if screening/BSE are children of xs", "nbands = int(val[0]) mesh = np.array(val[1].split(), dtype=int) origin = np.array(val[2].split(),", "= eigs_gw_C sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc')) def _parse_dos_out(self, sec_scc): data =", "energy at this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False, dtype=float), Quantity( 'time',", "= self.input_xml_parser.get('structure/species/atom') atom_labels = [] for n in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]]", "None: self._total_dos = self.root.findall('./%s/%s' % (self._totaldos_key, self._diagram_key)) return self._total_dos @property", "if positions is None: return positions = np.array(positions) positions_format =", "fermi_surface = self.fermisurf_parser.get('fermi_surface', [None])[0] if fermi_surface is None: return sec_fermisurface", "= 'linearization' sec_gw.max_frequency = self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type = self.input_xml_parser.get(", "'x_exciting_energy_convergence': ( r'Absolute change in total energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence': (", "def str_to_band_parameters(val_in): val = val_in.strip().split('\\n') nbands = int(val[0]) mesh =", "= self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb", "v in val if len(v) == 3], float)) return dict(", "module stopped', sub_parser=TextParser(quantities=[ Quantity( 'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent in", "class ExcitingEvalqpParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = []", "== 'EPSILON' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3] elif", "sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi nkpts_segment = self.band_out_parser.number_of_k_points_per_segment", "= sec_method if sec_run.system: sec_scc.system_ref = sec_run.system[-1] sec_scc_ref = sec_run.calculation[0]", "xc_functional_names = self.info_parser.get_xc_functional_name() if not xc_functional_names: # get it from", "// (self.number_of_lm * self.number_of_spin_channels) res[lm][spin][atom] = self._get_dos(self.partial_dos[i]) if self.energy_unit is", "= self.input_xml_parser.get( 'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get( 'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg", "[None] * (n_scf - len(quantity)) + quantity return quantity def", "= self.archive.run[-1] def parse_configuration(section): if not section: return sec_scc =", "sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1] else: setattr(msection, key, val)", "for v in x.split(':')]), Quantity( 'parameters', r'\\n *(.+?:.+)', repeats=True, str_operation=lambda", "self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax = gmb * gmaxvr pwm = self.input_xml_parser.get('gw/barecoul/pwm',", "is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax = rgkmax sec_method.x_exciting_xs_bse_sciavbd", "nkpts_segment = self.band_out_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies)", "repeats=False)) def str_to_band_parameters(val_in): val = val_in.strip().split('\\n') nbands = int(val[0]) mesh", "2: continue elif v[0].startswith('species'): species = re.search(re_symbol, v[-1]).group(1) elif v[0].startswith('atom'):", "clas for bandstructure dat and xml self._nspin = None self._nkpts_segment", "parent clas for bandstructure dat and xml self._nspin = None", "val_in.split('\\n')] val = np.transpose(np.array([v for v in val if len(v)", "if not os.path.isfile(filename): file_ext = default.split('.')[-1] mainfile_base = mainfile.rsplit('.', 1)[0].replace('INFO',", "[os.path.join(self.info_parser.maindir, f) for f in options] else: filenames = [filename]", "= None self._energies = None self._total_dos = None self._partial_dos =", "None) xc_functional_names.append(correlation) exchange = self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange) sec_xc_functional = sec_dft.m_create(XCFunctional)", "in self.info_parser._convergence_keys_mapping.keys(): threshold = self.info_parser.get_scf_threshold(name) if threshold is None: continue", "val is None: continue if name == 'time': msection.time_calculation =", "i in range(len(self.partial_dos)): spin = self.partial_dos[i].attrib.get(self._nspin_key, None) if spin is", "section.get('symbols') if labels is None: # we get it by", "= get_data('occupancies') sec_eigenvalues.energies = get_data('eigenvalues') def _parse_fermisurface(self, sec_scc): fermi_surface =", "= list(data[3]) else: sec_system.x_exciting_clathrates = False potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing') if", "self.archive.m_create(Run) sec_run.program = Program( name='exciting', version=self.info_parser.get('program_version', '').strip()) # method goes", "data = np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates = np.transpose( np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels =", "= 'coord' self._energy_key = 'eval' self._vertex_key = 'vertex' self._band_key =", "repeats=False, dtype=str, flatten=False)] initialization_quantities = [ Quantity( 'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n',", "2 * li + 1 return self._nlm @property def total_dos(self):", "= np.vstack([s.get('positions') for s in species]) if positions is None:", "band_energy * self._energy_unit res_n.append(band_energy) start = end res.append(res_n) elif key", "from last scf_iteration or optimization_step final = section.get('scf_iteration', [None])[-1] final", "< n_scf: quantity = [None] * (n_scf - len(quantity)) +", "as separate section_k_band res = [] for n in range(len(self.bands)):", "# charge contributions charge_contributions = iteration.get('charge_contributions', {}) for key, names", "== 'LOSS': parse_function = parse_loss else: continue try: parse_function(data, sec_scc)", "{}).get('species', []) labels = [] for specie in species: labels", "data[0]: continue if quantity == 'EPSILON' and ext == 'FXC':", "22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE', 'GGA_X_WC'], 30: ['GGA_C_AM05', 'GGA_C_AM05'], 300:", "Quantity('electronic_charge', rf'electronic charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic mass", "else: lm = int(val_l) ** 2 + int(val_m) + int(val_l)", "moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved'] } def get_exciting_files(self, default): mainfile = os.path.basename(self.info_parser.mainfile)", "properties input_file = self.get_exciting_files('input.xml') if not input_file: return self.input_xml_parser.mainfile =", "sec_eigenvalues = sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints = self.eigval_parser.get('k_points') sec_eigenvalues.occupations = get_data('occupancies') sec_eigenvalues.energies", "/ ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector grid sizes', None), 'x_exciting_gvector_total': (r'Total number", "name.startswith('EIGVAL') and name.endswith('OUT'): parser = self.eigval_parser parser_function = self._parse_eigenvalues elif", "def _parse_dos(self, sec_scc): if self.dos_parser.get('totaldos', None) is None: return #", "def get_unit_cell_volume(self): return self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0 * ureg.bohr ** 3)", "name, ' '.join([str(v) for v in val])) else: try: setattr(sec_system,", "in species: positions_format = specie.get('positions_format', None) if positions_format is not", "in which also other energies are reported. energy_fermi = sec_scc.energy.fermi", "axis is None: return self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return self._energy_unit", "[] self._quantities.append( Quantity( 'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False)) def str_to_band_parameters(val_in):", "= kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): self._nspin", "[] for specie in species: labels += [specie.get('symbol')] * len(specie.get('positions'))", "ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector grid sizes', None), 'x_exciting_gvector_total': (r'Total number of", "None else section.get('final') if final is None: # get it", "start = np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end = np.array( self.vertices[i +", "= self.info_parser.get_initialization_parameter('smearing_width') if smearing_width is not None: smearing_width = (smearing_width", "for APW functions', 1 / ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum \\|G\\| for", "# Get fermi energy: it is used to un-shift the", "_parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_dat_parser.band_energies if band_energies", "parser_function = self._parse_input_xs else: # TODO implement reading of parameters", "rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax = rgkmax", "= self.partial_dos[i].attrib.get(self._m_key, None) if val_l is None or val_m is", "convert=False)] self._miscellaneous_keys_mapping = { 'x_exciting_gap': (r'Estimated fundamental gap', ureg.hartree), 'time':", "if positions_format is not None else self.get_positions_format(section) if positions_format ==", "+: +(\\S+)'), Quantity( 'name_reference', r'\\n *(.+?,.+)', str_operation=lambda x: [v.strip() for", "values=val[1] * ureg.hartree, weights=val[2]) # TODO Read also input parameters", "is not None: sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1] sec_scc", "file type', data=dict(file=quantity)) sec_scc = sec_run.m_create(Calculation) if quantity == 'EXCITON':", "since reference needed for sec_scc self.parse_method() self.parse_configurations() self.parse_gw() self.parse_xs() self.parse_miscellaneous()", "self._band_energies.append(band_energy) start = end return self._band_energies @property def band_k_points(self): if", "xc_functional_names: # get it from input.xml input_file = self.get_exciting_files('input.xml') for", "the case when there is a mismatch between files self.logger.warn(", "' '.join([str(v) for v in val])) else: try: setattr(sec_system, name,", "= '%s%s' % (target[0], suffix) if target[1:]: filepath = '%s.%s'", "sec_worfklow.m_create(GeometryOptimization) threshold_force = structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence', [0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance =", "nuclear charge', ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total electronic charge', ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total", "vi = vi[0] if len(vi) == 1 else vi properties[v[0].strip()]", "structure_optimization is not None: sec_worfklow.type = 'geometry_optimization' sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization)", "gw_files: self.parse_file(f, sec_scc) frequency_data = self.info_gw_parser.get('frequency_data', None) if frequency_data is", "'x_exciting_coulomb_potential_energy': ['Coulomb potential energy', 'Coulomb potential'], 'energy_xc_potential': ['xc potential energy',", "= np.array( [e.attrib.get(self._energy_key) for e in self.bands[n][i]]) for nkpts_segment in", "['Coulomb potential energy', 'Coulomb potential'], 'energy_xc_potential': ['xc potential energy', 'xc", "= sec_dft.m_create(XCFunctional) for name in xc_functional_names: if name is None:", "self._nkpts_segment = None self._neigs_segment = None self._bands = None self._vertices", "'Znk': return np.array([d[1].get(key, None) for d in data]) else: energy", "sccs[i] if sec_scc is None: # This is the case", "if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax =", "including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr)", "os.path.join(self.info_parser.maindir, filepath) if os.path.isfile(filepath) and os.access(filepath, os.F_OK): return True return", "sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14) rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax', None) if", "= atom_labels sec_atoms.periodic = [True] * 3 # TODO confirm", "in self.partial_dos]) for li in l_list: self._nlm += 2 *", "'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies = int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get(", "self.info_gw_parser.mainfile = gw_info_files[0] fermi_energy = self.info_gw_parser.get('fermi_energy', None) if fermi_energy is", "'GWINFO.OUT'] for f in gw_info_files: if self.get_exciting_files(f): self._calculation_type = 'gw'", "self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax = pwm * gmb * gmaxvr sec_gw.bare_coulomb_cutofftype", "sec_scc.energy is not None: energy_fermi = sec_scc.energy.fermi energy_fermi = (energy_fermi.magnitude", "parser_function = self._parse_band_out elif name.startswith('input') and name.endswith('xml'): parser = self.input_xml_parser", "name in xc_functional_names: if name is None: continue if '_X_'", "range(len(self.number_of_k_points_per_segment)): start = np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end = np.array( self.vertices[i", "not None: sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get( 'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get(", "= self.logger self.eigval_parser.logger = self.logger self.fermisurf_parser.logger = self.logger self.evalqp_parser.logger =", "return dict( number=np.array(val[0], dtype=int), values=val[1] * ureg.hartree, weights=val[2]) # TODO", "None), 'x_exciting_rgkmax': (r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max \\(rgkmax\\)', None), 'x_exciting_species_rtmin': (r'Species with", "Dos.total) sec_dos_values.spin = spin sec_dos_values.value = totaldos[spin] partialdos = self.dos_parser.get('partialdos')", "unit=ureg.hartree / ureg.bohr, repeats=False, dtype=float), Quantity( 'energy_total', r'Total energy at", "this optimization step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity( 'final', r'Force convergence", "= None self._band_energies = None self._band_k_points = None @property def", "and name.endswith('dat'): parser = self.bandstructure_dat_parser parser_function = self._parse_bandstructure_dat elif name.startswith('BAND')", "r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation type +: +(\\S+)'), Quantity(", "repeats=False, convert=False), Quantity( 'lattice_vectors_reciprocal', r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1 /", "nkpts_segment in self.number_of_k_points_per_segment: end = start + nkpts_segment band_energy =", "= int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation", "= 2 if occs[0] == 1. else 1 data =", "number of valence states', None), 'x_exciting_hamiltonian_size': ('Maximum Hamiltonian size', None),", "xml file def get_files(name): bse_types = ['IP', 'singlet', 'triplet', 'RPA']", "if key == 'x_exciting_fermi_energy': sec_energy.fermi = val # charge contributions", "np.hstack([np.reshape(v[key], (nspin, np.size(v[key]) // nspin)) for v in data]) res", "int(val_l) ** 2 + int(val_m) + int(val_l) atom = i", "if fermi_energy is not None: sec_scc.energy = Energy(fermi=fermi_energy) gw_files =", "val is None: continue if name == 'x_exciting_spin_treatment': sub_sec =", "return res sec_eigenvalues = sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints = self.eigval_parser.get('k_points') sec_eigenvalues.occupations =", "repeats=True)) class ExcitingEigenvalueParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities =", "version=self.info_parser.get('program_version', '').strip()) # method goes first since reference needed for", "occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues, repeats=True)) class ExcitingGWOutParser(TextParser): def __init__(self, mainfile,", "is not None: sec_method.x_exciting_xs_xstype = xstype sec_method.x_exciting_electronic_structure_method = xstype sec_method.x_exciting_xs_broadening", "sec_scc = parse_configuration(self.info_parser.get(module)) if sec_scc is None: continue # add", "APW functions', 1 / ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum \\|G\\| for potential", "return return np.reshape(data, (nspin, len(data) // nspin, len(data[0]))) sec_gw_eigenvalues =", "self.dos_parser.get('totaldos', None) is None: return # Get fermi energy: it", "// nspin, len(data[0]))) sec_gw_eigenvalues = sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands", "self.info_parser.get_number_of_spin_channels() if self._calculation_type == 'volume_optimization': sec_method.x_exciting_volume_optimization = True def parse_scc(self,", "= energy_fermi.to(\"hartree\") sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points", "self.input_xml_parser.get('xs/screening/rgkmax', None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.)", "r'parameters loaded from *: *(.+)'), Quantity('name', r'name *: *(.+)'), Quantity('nuclear_charge',", "'hybrids', r'Hybrids module started([\\s\\S]+?)Hybrids module stopped', sub_parser=TextParser(quantities=module_quantities) )) def get_atom_labels(self,", "added as separate section_k_band res = [] for n in", "('Maximum Hamiltonian size', None), 'x_exciting_pw': (r'Maximum number of plane\\-waves', None),", "= self.input_xml_parser.get( 'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get( 'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda", "Bravais lattice symmetries', None), 'x_exciting_number_of_crystal_symmetries': ('Number of crystal symmetries', None),", "msection): energy_total = iteration.get('energy_total') sec_energy = msection.m_create(Energy) if energy_total is", "name, val) # energy, moment, charge contributions parse_scf(final, sec_scc) #", "quantity = [None] * (n_scf - len(quantity)) + quantity return", "for specie in species: positions_format = specie.get('positions_format', None) if positions_format", "potential mixing', repeats=False, flatten=False) ) initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)',", "'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False)] self._miscellaneous_keys_mapping = { 'x_exciting_gap':", "= sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters = self.fermisurf_parser.get('band_parameters', None) if band_parameters is not", "= None if 'charge' in val_in: unit = ureg.elementary_charge elif", "logger if logger is not None else logging self._calculation_type =", "example bandstructure file # atom-resolved bandstructure are added as separate", "in ['EXCITON', 'EPSILON', 'SIGMA', 'LOSS']: files = get_files(quantity) for i", "{ 'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment': ['total moment in muffin-tins'], 'x_exciting_total_moment': ['total", "= np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float) for i in range(len(self.bands[n])):", "= self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001) gmb = self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax =", "= n + 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1]", "key, val) # moment contributions moment_contributions = iteration.get('moment_contributions', {}) for", "return res = np.zeros((self.number_of_spin_channels, self.number_of_dos)) for i in range(len(self.total_dos)): spin", "r'Species : *(\\d+)', dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file', r'parameters loaded from", "data=dict(file=quantity)) def _parse_xs_tddft(self): sec_run = self.archive.run[-1] fxctype = self.input_xml_parser.get('xs/tddft/fxctype', 'RPA')", "step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions at this step\\s*\\(([a-z]+)\\)'), Quantity(", "lm_values = np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32))) for lm in range(len(partialdos)): for", "np.reshape( data[1], (n_components, n_loss)) # TODO check if format of", "spin-polarized case! I assume it is # energy dos_up dos_down", "band_energies[n][nb] + energy_fermi def _parse_eigenvalues(self, sec_scc): if self.eigval_parser.get('eigenvalues_occupancies', None) is", "data[0], (n_components, n_epsilon)) * ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape( data[1], (n_components,", "('Number of Bravais lattice symmetries', None), 'x_exciting_number_of_crystal_symmetries': ('Number of crystal", "'final', r'(?:Convergence targets achieved\\. Performing final SCF iteration|Reached self-consistent loops", "symbols species = self.get('initialization', {}).get('species', []) labels = [] for", "= self.info_parser.get('structure_optimization') if structure_optimization is not None: sec_worfklow.type = 'geometry_optimization'", "end]) else: res = None self._results[key] = res class DOSXMLParser(XMLParser):", "self.bandstructure_dat_parser.band_k_points nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment =", "os.path.join(self.info_parser.maindir, filename) if os.path.isfile(filename): return [filename] filename = os.path.join(self.info_parser.maindir, default)", "True: info_volume = self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2, '0')) if not info_volume:", "for band in bands]) if self._energy_unit: band_energy = band_energy *", "ext): # all files related to quantity at all qpoints", "ureg.hartree), Quantity( 'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False), Quantity(", "parent class for dos and bandstructure super().__init__(None) self._distance_key = 'distance'", "os.F_OK)] return filenames def file_exists(self, filename): \"\"\"Checks if a the", "i in range(1, len(self.distances)): if self.distances[i] == self.distances[i - 1]:", "parse_sigma(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_sigma =", "positions is None: species = self.get_initialization_parameter('species', []) if species: positions", "[] for f in files: self.data_xs_parser.mainfile = f if self.data_xs_parser.data", "[f for f in options if f.endswith(file_ext)] options.sort() filenames =", "1].attrib.get('label') res.append([ '\\u0393' if start.lower() == 'gamma' else start, '\\u0393'", "v[1].split()] vi = vi[0] if len(vi) == 1 else vi", "= self.bandstructure_dat_parser.band_energies if band_energies is None: return # Get fermi", "global metainfo. This is killing me! if metainfo_name == 'x_exciting_scf_threshold_energy_change':", "'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get( 'xs/tddft/drude', [0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter =", "'xs/screening/screentype', 'full') if self.input_xml_parser.get('xs/BSE') is not None: sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get(", "else None, 'AC' if nwacont else None, 'NAR' if not", "None: return self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return self._energy_unit @property def", "300: ['GGA_C_BGCP', 'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']} xc_functional = self.get('initialization',", "in range(len(files)): parser.mainfile = files[n] parser_function(section) # free up memory", "self._totaldos_key = 'totaldos' self._partialdos_key = 'partialdos' self._diagram_key = 'diagram' self._l_key", "self.fermisurf_parser.logger = self.logger self.evalqp_parser.logger = self.logger self.dos_out_parser.logger = self.logger self.bandstructure_dat_parser.logger", "None)} self._method_keys_mapping = { 'smearing_kind': ('Smearing scheme', None), 'smearing_width': ('Smearing", "np.array(val[1].split(), dtype=int) origin = np.array(val[2].split(), dtype=float) vector = np.array([v.split() for", "or agreed to in writing, software # distributed under the", "not self.bands: return if key == 'band_energies': # TODO I", "= self.info_gw_parser.get('fermi_energy', None) if fermi_energy is not None: sec_scc.energy =", "clathrate_file: sec_system.x_exciting_clathrates = True self.data_clathrate_parser.mainfile = clathrate_file[0] if self.data_clathrate_parser.data: data", "None else logging self._calculation_type = None self.init_parser() sec_run = self.archive.m_create(Run)", "self.get_exciting_files('input.xml') if not input_file: return self.input_xml_parser.mainfile = input_file[0] xstype =", "data[5][:int(max(data[1]))] return self._distances @property def number_of_spin_channels(self): if self._nspin is None:", "distances(self): if self._distances is None: dist = np.transpose(self.data)[0] n_k_points =", "files: bs_files = ['bandstructure-qp.dat', 'BAND-QP.OUT'] for fname in bs_files: if", "sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface def _parse_evalqp(self, sec_scc): data", "'band' self._atom_key = 'atom' self._nspin = kwargs.get('nspin', None) self._energy_unit =", "sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi nkpts_segment = self.band_out_parser.number_of_k_points_per_segment for nb", "int( self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq', [1, 1, 1]) sec_gw.basis_set", "sec_scc): if self.dos_parser.get('totaldos', None) is None: return # Get fermi", "__init__(self): super().__init__(None) def init_quantities(self): re_symbol = re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in): val", "smearing_kind smearing_width = self.info_parser.get_initialization_parameter('smearing_width') if smearing_width is not None: smearing_width", "in key: if not self.total_dos: return res = np.zeros((self.number_of_spin_channels, self.number_of_dos))", "in data]) elif key == 'Znk': return np.array([d[1].get(key, None) for", "range(len(partialdos[lm])): for atom in range(len(partialdos[lm][spin])): sec_dos_values = sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind", "* (1 / ureg.hartree) * volume.to('m**3').magnitude for spin in range(len(dos)):", "= nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.endpoints_labels = band_seg_labels[nb] sec_k_band_segment.energies =", "in structure_optimization.get('optimization_step', []): sec_scc = parse_configuration(optimization_step) if optimization_step.get('method') is not", "sec_system.x_exciting_clathrates = True self.data_clathrate_parser.mainfile = clathrate_file[0] if self.data_clathrate_parser.data: data =", "*: *({re_float})', dtype=np.int32), Quantity('positions_format', r'atomic positions \\((.+?)\\)', flatten=False), Quantity( 'positions',", "sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref]", "self.input_xml_parser.get( 'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra = self.input_xml_parser.get( 'xs/tetra/tetradf', False) def _parse_xs_bse(self):", "n_spin def get_unit_cell_volume(self): return self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0 * ureg.bohr **", "repeats=False, dtype=int), Quantity( 'method', r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str), Quantity( 'n_scf_iterations', r'Number", "None: energy_fermi = sec_scc.energy.fermi energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band", "self.vertices[i + 1].attrib.get('label') res.append([ '\\u0393' if start.lower() == 'gamma' else", "sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff', [0., 0., 0.])", "str_operation=str_to_array, convert=False, unit=ureg.hartree / ureg.bohr), Quantity( 'step', r'Optimization step\\s*(\\d+)', repeats=False,", "* self.energy_unit return self._energies def _get_dos(self, diagram): dos = np.array(", "self.input_xml_parser.get('structure/crystal/scale', 1.0) positions = np.dot(positions, lattice_vectors) * ureg.bohr lattice_vectors =", "None: if not self.bands: return self._distances = [ point.attrib.get(self._distance_key) for", "name in self.info_parser._miscellaneous_keys_mapping.keys(): val = iteration.get(name) if val is None:", "['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf'] # Parse DFT DOS from one of", "IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr), ]),", "NOMAD Authors. # # This file is part of NOMAD.", "self._distances = None self._band_energies = None self._neigs_segment = None self._nkpts_segment", "sec_method.gw.frequency_values = frequency_data.get('values') sec_method.gw.frequency_weights = frequency_data.get('weights') fundamental_band_gap = self.info_gw_parser.get('direct_band_gap', None)", "'x_exciting_core_leakage': ['core leakage'], 'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge': ['total charge", "None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure,", "]+)\\s*started', repeats=False, dtype=str, flatten=False)] initialization_quantities = [ Quantity( 'lattice_vectors', r'Lattice", "None: fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap', None) sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap", "* gmaxvr pwm = self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax = pwm *", "in f and mainfile_base in f] options = [f for", "__init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'fermi_energy',", "[v.strip() for v in x.split(':')]), Quantity( 'parameters', r'\\n *(.+?:.+)', repeats=True,", "\\(target\\)', ureg.hartree), 'x_exciting_energy_convergence': ( r'Absolute change in total energy\\s*\\(target\\)', ureg.hartree),", "x_exciting_dos_fermi is not None: setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi) # energy contributions", "data[1:] elif quantity == 'EPSILON' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field", "parser = self.evalqp_parser parser_function = self._parse_evalqp elif name.startswith('TDOS') and name.endswith('OUT'):", "spin is None: spin = (i % (self.number_of_spin_channels * self.number_of_lm))", "np.reshape(data, (nspin, len(data) // nspin, 2)) data = np.transpose(data, axes=(2,", "= parse_configuration(optimization_step) if optimization_step.get('method') is not None: sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method')", "'x_exciting_lmaxapw': (r' APW functions', None), 'x_exciting_nuclear_charge': ('Total nuclear charge', ureg.elementary_charge),", "sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get( 'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlbse', [0,", "sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints = self.eigval_parser.get('k_points') sec_eigenvalues.occupations = get_data('occupancies') sec_eigenvalues.energies = get_data('eigenvalues')", "sec_charges = msection.m_create(Charges) sec_charges.value = [ val[n][1].magnitude for n in", "{}) for optimization_step in structure_optimization.get('optimization_step', []): sec_scc = parse_configuration(optimization_step) if", "'x_exciting_total_MT_moment': ['total moment in muffin-tins'], 'x_exciting_total_moment': ['total moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved']", "if self._nkpts_segment is None: self._nkpts_segment = [] count = 1", "quantity == 'SIGMA': parse_function = parse_sigma elif quantity == 'LOSS':", "of G\\-vectors', None), 'x_exciting_lmaxapw': (r' APW functions', None), 'x_exciting_nuclear_charge': ('Total", "None: return positions = np.dot(positions, cell.magnitude) return positions * ureg.bohr", "if self._natoms is None: partial_dos = self.root.findall('./%s' % self._partialdos_key) self._natoms", "_parse_bandstructure(self, sec_scc): # we need to set nspin again as", "'x_exciting_hamiltonian_size': ('Maximum Hamiltonian size', None), 'x_exciting_pw': (r'Maximum number of plane\\-waves',", "x.split(':')]), Quantity( 'parameters', r'\\n *(.+?:.+)', repeats=True, str_operation=lambda x: [v.strip() for", "# get it from input.xml input_file = self.get_exciting_files('input.xml') for f", "None) is None: return # Get fermi energy: it is", "optimization_quantities = [ Quantity( 'atomic_positions', r'(Atomic positions at this step\\s*\\([\\s\\S]+?)\\n\\n',", "positions at this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions at", "is not None: setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi) # energy contributions energy_contributions", "in name: sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_' in name: sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB'", "self.info_gw_parser.quantities = parser.info_gw_parser.quantities def parse(self, filepath, archive, logger): self.filepath =", "other energies are reported. energy_fermi = sec_scc.energy.fermi if energy_fermi is", "is None: continue # add data to scc # TODO", "= parse_sigma elif quantity == 'LOSS': parse_function = parse_loss else:", "eigs[i] for i in range(len(keys))} return [kpts, eigs] self._quantities.append( Quantity(", "'n_scf_iterations', r'Number of (?:total)* scf iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'force_convergence',", "additionally, set threshold to global metainfo. This is killing me!", "not None: break if val is None: continue if key", "= data[1:3] def parse_xs(self): sec_run = self.archive.run[-1] xs_info_files = self.get_exciting_files('INFOXS.OUT')", "fxctype = self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf = self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont =", "= sccs[i] if sec_scc is None: # This is the", "self.info_parser._system_keys_mapping.keys(): val = self.info_parser.get_initialization_parameter(name) if val is None: continue if", "# we need to set nspin again as this is", "None: return def get_data(key): if key == 'k_points': return np.array([d[0][:3]", "= np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface =", "is None or val_m is None: lm = i %", "convert=False), ] self._system_keys_mapping = { 'x_exciting_unit_cell_volume': ('Unit cell volume', ureg.bohr", "def parse_miscellaneous(self): sec_worfklow = self.archive.m_create(Workflow) sec_worfklow.type = 'single_point' structure_optimization =", "% name.split('_')[-2] setattr(sec_method, metainfo_name, threshold) # additionally, set threshold to", "'EXCITON': parse_function = parse_exciton elif quantity == 'EPSILON': parse_function =", "# See https://nomad-lab.eu for further info. # # Licensed under", "self.input_xml_parser.get( 'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas =", "in range(len(partialdos[lm])): for atom in range(len(partialdos[lm][spin])): sec_dos_values = sec_dos.m_create(DosValues, Dos.atom_projected)", "os.listdir( self.info_parser.maindir) if target[0] in f and mainfile_base in f]", "multiple GW info files, will read only first!') self.info_gw_parser.mainfile =", "np.transpose(self.data) self._band_k_points = [] start = 0 for nkpts_segment in", "name = xc_functional_map.get(xc_functional.type, []) return name @property def n_optimization_steps(self): return", "('Unit cell volume', ureg.bohr ** 3), 'x_exciting_brillouin_zone_volume': ('Brillouin zone volume',", "f in files_q: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None:", "Quantity( 'eigenvalues_occupancies', r'\\(state\\, eigenvalue and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues, repeats=True))", "= len(np.where(data == data[0])[0]) return self._neigs_segment class BandstructureXMLParser(XMLParser): def __init__(self,", "None: setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi) # energy contributions energy_contributions = iteration.get('energy_contributions',", "1 return self._nlm @property def total_dos(self): if self._total_dos is None:", "data=dict(file=quantity)) sec_scc = sec_run.m_create(Calculation) if quantity == 'EXCITON': parse_function =", "= len(data) data = np.transpose(np.vstack(data)) n_loss = len(data[0]) // n_components", "[] for n in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] * len(atoms[n])) if positions", "1) return self._energy_unit @property def number_of_spin_channels(self): if self._nspin is None:", "+ energy_fermi volume = self.info_parser.get_unit_cell_volume() totaldos = self.dos_parser.get('totaldos') * volume.to('m**3').magnitude", "for name in self.info_parser._convergence_keys_mapping.keys(): threshold = self.info_parser.get_scf_threshold(name) if threshold is", "name): n_scf = len(self.get('energy_total_scf_iteration', [])) quantity = self.get('%s_scf_iteration' % name)", "sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters = self.fermisurf_parser.get('band_parameters', None) if band_parameters is not None:", "val: v = v.split(':') if len(v) < 2: continue energies[v[0].strip()]", "band_energies(self): if self._band_energies is None: data = np.transpose(self.data) n_kpoints =", "% name) if quantity is None: return # this is", "info.xml, wannier.out if name.startswith('dos') and name.endswith('xml'): parser = self.dos_parser parser_function", "= iteration.get('energy_total') sec_energy = msection.m_create(Energy) if energy_total is not None:", "len(specie.get('positions')) return labels def get_positions_format(self, section): positions_format = section.get('positions_format') if", "= self.dos_out_parser.data if data is None: return # Get fermi", "= [sec_method_ref] self.parse_file('input.xml', sec_method) # parse properties input_file = self.get_exciting_files('input.xml')", "# limitations under the License. # import numpy as np", "sec_scc = self.parse_scc(section) if sec_scc is None: return sec_system =", "os.F_OK): return True return False def _parse_dos(self, sec_scc): if self.dos_parser.get('totaldos',", "optimization_step.get('step') is not None: sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step') force_convergence = optimization_step.get('force_convergence')", "return nspin = self.info_parser.get_number_of_spin_channels() def get_data(key): data = self.eigval_parser.get('eigenvalues_occupancies') #", "(nspin, np.size(v[key]) // nspin)) for v in data]) res =", "import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class", "os.path.join(self.info_parser.maindir, default) if not os.path.isfile(filename): file_ext = default.split('.')[-1] mainfile_base =", "key, names in self._moment_keys_mapping.items(): val = None for name in", "and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues, repeats=True)) class ExcitingGWOutParser(TextParser): def __init__(self,", "for nkpts_segment in self.number_of_k_points_per_segment: end = start + nkpts_segment band_energy", "'x_exciting_section_MT_moment_atom': ['atom_resolved'] } def get_exciting_files(self, default): mainfile = os.path.basename(self.info_parser.mainfile) suffix", "*({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge),", "= os.path.join(self.info_parser.maindir, default) if not os.path.isfile(filename): file_ext = default.split('.')[-1] mainfile_base", "'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s',", "the naming convention for xs input xml file sec_method =", "continue if name == 'x_exciting_spin_treatment': sub_sec = sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment =", "kwargs.get('energy_unit', None) def init_parameters(self): # TODO make a parent clas", "sec_scc): fermi_surface = self.fermisurf_parser.get('fermi_surface', [None])[0] if fermi_surface is None: return", "I am not sure about format for spin-polarized case! I", "in range(len(self.bands)): res_n = [] start = 0 band_energies =", "'species', rf'(Species : *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[ Quantity('number',", "[v.split(':')[-1].split() for v in val_in.strip().split('\\n')] val = val[0] if len(val)", "None) if frequency_data is not None: number = frequency_data.get('number') sec_method.gw.number_of_frequencies", "= np.transpose(self.data) self._distances = data[5][:int(max(data[1]))] return self._distances @property def number_of_spin_channels(self):", "def init_quantities(self): self._quantities = [] def str_to_eigenvalue(val_in): val = val_in.strip().split('\\n')", "= optimization_step.get('step') force_convergence = optimization_step.get('force_convergence') if force_convergence is not None:", "self._quantities.append( Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'fundamental_band_gap',", "= ['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat'] for fname in bs_files: if self.file_exists(fname):", "moment, charge contributions parse_scf(final, sec_scc) # forces forces = section.get('forces')", "def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] self._quantities.append( Quantity(", "= band_seg_labels[nb] sec_k_band_segment.energies = band_energies[n][nb] + energy_fermi def _parse_eigenvalues(self, sec_scc):", "number=np.array(val[0], dtype=int), values=val[1] * ureg.hartree, weights=val[2]) # TODO Read also", "for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break for f", "= self.get_exciting_files('INFOXS.OUT') if not xs_info_files: return self._calculation_type = 'xs' #", "scf_iterations: sec_scf_iteration = sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration) return sec_scc def parse_system(self,", "ureg.joule).to('hartree') sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = self.dos_parser.number_of_dos sec_dos.energies =", "== 'x_exciting_scf_threshold_energy_change': sec_method.scf = Scf(threshold_energy_change=threshold) xc_functional_names = self.info_parser.get_xc_functional_name() if not", "sec_scc.energy = Energy(fermi=fermi_energy) gw_files = ['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT'] # Parse", "= ['bandstructure-qp.dat', 'BAND-QP.OUT'] for fname in bs_files: if self.file_exists(fname): gw_files.append(fname)", "TODO make a parent clas for bandstructure dat and xml", "for v in val[3:6]], dtype=float) return [nbands, mesh, origin, vector]", "'gw' gw_info_file = f break if not self._calculation_type == 'gw':", "np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3]", "point in self.total_dos[0]]) if self.energy_unit is not None: self._energies =", "eigs = {keys[i]: eigs[i] for i in range(len(keys))} return [kpts,", "self.info_gw_parser.get('direct_band_gap', None) if fundamental_band_gap is None: fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap', None)", "= self.input_xml_parser.get( 'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get( 'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel", "Quantity('number', r'Species : *(\\d+)', dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file', r'parameters loaded", "self.energies else: res = None self._results[key] = res class ExcitingFermiSurfaceBxsfParser(TextParser):", "None: sec_scc.system_ref = sec_system sec_scc.method_ref = sec_run.method[-1] return sec_scc #", "elif key == 'band_k_points': res = [] for i in", "rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax = rgkmax sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor',", "sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1] sec_charges = msection.m_create(Charges) sec_charges.value", "is not None: band_energy = band_energy * self._energy_unit res_n.append(band_energy) start", "sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref", "xc_functional is not None: sec_xc_functional.name = xc_functional.get('name_reference', [None, None])[0] sec_xc_functional.reference", "None: sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1] sec_scc = parse_configuration(structure_optimization)", "bands(self): if self._bands is None: bands = self.root.findall('./%s' % self._band_key)", "Run, Program from nomad.datamodel.metainfo.simulation.method import ( Method, DFT, Electronic, Smearing,", "0, 0, 0]) if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get( 'xs/BSE/xasatom', 0)", "# TODO expand list to include other xcf xc_functional_map =", "+ int(val_m) + int(val_l) atom = i // (self.number_of_lm *", "not self._calculation_type == 'gw': return sec_method = sec_run.m_create(Method) sec_method_ref =", "if end.lower() == 'gamma' else end]) elif key == 'band_segm_start_end':", "self._parse_bandstructure elif name.startswith('EIGVAL') and name.endswith('OUT'): parser = self.eigval_parser parser_function =", "nspin, 2)) data = np.transpose(data, axes=(2, 0, 1)) sec_dos.energies =", "Read also input parameters here if input_GW.xml does not exist", "if species: positions = np.vstack([s.get('positions') for s in species]) if", "in scf_iterations: sec_scf_iteration = sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration) return sec_scc def", "vi in v[1].split()] v[1] = v[1][0] if len(v[1]) == 1", "ExcitingEvalqpParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] def", "vi[0] if len(vi) == 1 else vi properties[v[0].strip()] = vi", "None), 'x_exciting_species_rtmin': (r'Species with R\\^MT\\_min', None), 'x_exciting_gkmax': (r'Maximum \\|G\\+k\\| for", "0)) sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get( 'gw/selfenergy/singularity',", "self._distances = None self._species = None @property def distances(self): if", "self.info_gw_parser.get('frequency_data', None) if frequency_data is not None: number = frequency_data.get('number')", "Unless required by applicable law or agreed to in writing,", "np.transpose(self.data)[0] n_k_points = np.where(dist == dist[0])[0][1] self._distances = dist[:n_k_points] return", "val_in: unit = ureg.elementary_charge * ureg.bohr val = val_in.strip().split('\\n') properties", "= {keys[i]: eigs[i] for i in range(len(keys))} return [kpts, eigs]", "TODO I am not sure about format for spin-polarized case!", "sec_dos_values.atom_index = atom sec_dos_values.value = partialdos[lm][spin][atom] def _parse_bandstructure(self, sec_scc): #", "*E*', unit=ureg.hartree, repeats=True)) class ExcitingEigenvalueParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self):", "sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.value = band_energies[nb] + energy_fermi def parse_file(self,", "sec_electronic.method = 'DFT' smearing_kind_map = { 'Gaussian': 'gaussian', 'Methfessel-Paxton': 'methfessel-paxton',", "muffin-tins'], 'charge_total': ['total charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved'] } self._moment_keys_mapping = {", "repeats=False) ) self._quantities.append( Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) class", "self.parse_file('input.xml', sec_method) # parse properties input_file = self.get_exciting_files('input.xml') if not", "return self._nspin = len(self.total_dos) return self._nspin @property def number_of_atoms(self): if", "'name_reference', r'\\n *(.+?,.+)', str_operation=lambda x: [v.strip() for v in x.split(':')]),", "sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get( 'xs/tddft/fxctype',", "= [ 'TET' if tetradf else None, 'AC' if nwacont", "'SIGMA', 'LOSS']: files = get_files(quantity) for i in range(len(files)): data", "if self._results is None: self._results = dict() if 'total' in", "exists and is accessible in the same folder where the", "* len(specie.get('positions')) return labels def get_positions_format(self, section): positions_format = section.get('positions_format')", "reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation = eigs_gw_C sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc')) def _parse_dos_out(self, sec_scc):", "= section.get('scf_iteration', [None])[-1] final = section.get('optimization_step', [None])[-1] if final is", "= band_energy * self._energy_unit self._band_energies.append(band_energy) start = end return self._band_energies", "folder where the mainfile is stored. \"\"\" mainfile = os.path.basename(self.info_parser.mainfile)", "os.path.isfile(filename): return [filename] filename = os.path.join(self.info_parser.maindir, default) if not os.path.isfile(filename):", "'distance' self._coord_key = 'coord' self._energy_key = 'eval' self._vertex_key = 'vertex'", "= 0.0 * ureg.hartree if sec_scc.energy is not None: energy_fermi", "for scf_iteration in scf_iterations: sec_scf_iteration = sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration) return", "return self._calculation_type = 'xs' # inconsistency in the naming convention", "len(data) data = np.transpose(np.vstack(data)) n_sigma = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_sigma_energies", "import os import re import logging from nomad.units import ureg", "Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi nkpts_segment = self.band_out_parser.number_of_k_points_per_segment for nb in", "dtype=float) for i in range(len(self.bands[n])): band_energies[i % self.number_of_spin_channels][i] = np.array(", "sec_gw_eigenvalues.energies = reshape(eigs_gw) sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx')) eigs_gw_C = reshape(get_data('Sc')) if", "[None, None])[1] sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels() if self._calculation_type == 'volume_optimization': sec_method.x_exciting_volume_optimization", "np.reshape( data[2], (n_components, n_epsilon)) def parse_sigma(data, sec_scc): n_components = len(data)", "= sec_scc.energy.fermi energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure,", "axes=(2, 0, 1)) for j in range(len(data)): data[j].append(data_q[j]) return data", "write parameters xc_functional = self.info_parser.get('initialization', {}).get('xc_functional') if xc_functional is not", "need to set nspin again as this is overwritten when", "None: return # Get fermi energy: it is used to", "= np.reshape( data[1], (n_components, n_loss)) # TODO check if format", "fundamental_band_gap is not None: sec_gap.value_fundamental = fundamental_band_gap optical_band_gap = self.info_gw_parser.get('optical_band_gap',", "sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3))", "import ( System, Atoms ) from nomad.datamodel.metainfo.simulation.calculation import ( Calculation,", "for scr_type in scr_types: files = self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' % (name,", "'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac': 'fermi', 'Extended': 'tetrahedra'} sec_smearing = sec_electronic.m_create(Smearing) smearing_kind", "sec_system sec_scc.method_ref = sec_run.method[-1] return sec_scc # groundstate and hybrids", "for i in range(len(keys))} return [kpts, eigs] self._quantities.append( Quantity( 'kpoints_eigenvalues',", "from nomad.datamodel.metainfo.simulation.calculation import ( Calculation, Dos, DosValues, BandStructure, BandEnergies, Energy,", "not data[0]: continue if quantity == 'EPSILON' and ext ==", "range(len(self.partial_dos)): spin = self.partial_dos[i].attrib.get(self._nspin_key, None) if spin is None: spin", "r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False)) self._quantities.append( Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree, repeats=True))", "frequency_data.get('number') sec_method.gw.number_of_frequencies = len(number) sec_method.gw.frequency_number = number sec_method.gw.frequency_values = frequency_data.get('values')", "init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree,", "= self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_parser.get('band_energies', []) for n in range(len(band_energies)):", "sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity( 'final', r'(?:Convergence targets achieved\\. Performing final SCF", "[])) quantity = self.get('%s_scf_iteration' % name) if quantity is None:", "if self._nspin is None: self._nspin = 1 return self._nspin @property", "Quantity( 'lattice_vectors_reciprocal', r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1 / ureg.bohr, repeats=False,", "len(np.where(data == data[0])[0]) return self._neigs_segment class BandstructureXMLParser(XMLParser): def __init__(self, **kwargs):", "a parent class for dos and bandstructure super().__init__(None) self._distance_key =", "self.archive.run[-1] # two versions of gw info files gw_info_files =", "add support for more output files and properties exciting_files =", "sec_scc = sccs[i] if sec_scc is None: # This is", "= v[0].split() v[1] = [float(vi) for vi in v[1].split()] v[1]", "None, 'NAR' if not aresdf else None] file_ext = '_'.join([e", "sec_gw.type = 'G0W0' gmaxvr = self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment = self.input_xml_parser.get(", "inconsistency in the naming convention for xs input xml file", "dtype=float) val = np.transpose(val) occs = val[-1] eigs = val[-2]", "d in data]) elif key == 'Znk': return np.array([d[1].get(key, None)", "= np.array(self._distances, dtype=float) return self._distances @property def bands(self): if self._bands", "if sec_system is not None: sec_scc.system_ref = sec_system sec_scc.method_ref =", "None])[1] sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels() if self._calculation_type == 'volume_optimization': sec_method.x_exciting_volume_optimization =", "Quantity( 'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr, repeats=False, convert=False), Quantity( 'lattice_vectors_reciprocal',", "def str_to_frequency(val_in): val = [v.split() for v in val_in.split('\\n')] val", "is None: data = np.transpose(self.data) self._band_k_points = [] start =", "14) rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax', None) if rgkmax is None: rgkmax", "2: ['LDA_C_PZ', 'LDA_X_PZ'], 3: ['LDA_C_PW', 'LDA_X_PZ'], 4: ['LDA_C_XALPHA'], 5: ['LDA_C_VBH'],", "self._parse_input_xs else: # TODO implement reading of parameters from input.xml", "np.zeros(len(partialdos), dtype=np.int32))) for lm in range(len(partialdos)): for spin in range(len(partialdos[lm])):", "You may obtain a copy of the License at #", "gap', ureg.hartree), 'time': (r'Wall time \\(seconds\\)', ureg.s)} for name, key_unit", "sec_worfklow.type = 'geometry_optimization' sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization) threshold_force = structure_optimization.get( 'optimization_step',", "= ' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point = xc_functional_name sec_scc = sec_run.m_create(Calculation) sec_scc.method_ref", "v in val: v = v.split(':') if len(v) < 2:", "units are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities =", "False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get( 'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get( 'xs/tddft/lmaxalda',", "dos def parse(self, key): if self._results is None: self._results =", "sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points", "add atom-resolved bands_atom = self.root.findall('./*/%s' % self._atom_key) for band in", "self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies = [] start = 0 for", "reshape(get_data('Sx')) eigs_gw_C = reshape(get_data('Sc')) if eigs_gw_C is None: eigs_gw_C =", "band_parameters is not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1])", "['EXCITON', 'EPSILON', 'SIGMA', 'LOSS']: files = get_files(quantity) for i in", "rf'muffin-tin radius *: *({re_float})', dtype=np.float64, unit=ureg.bohr), Quantity('radial_points', rf'radial points in", "the original scale in which also other energies are reported.", "[])) def get_number_of_spin_channels(self): spin_treatment = self.get('initialization', {}).get( 'x_exciting_spin_treatment', 'spin-unpolarised') n_spin", "= get_data('eigenvalues') def _parse_fermisurface(self, sec_scc): fermi_surface = self.fermisurf_parser.get('fermi_surface', [None])[0] if", "f if self.data_xs_parser.data is None: continue data.append(self.data_xs_parser.data) return data def", "and name.endswith('xml'): parser = self.dos_parser parser_function = self._parse_dos elif name.startswith('bandstructure')", "self.input_xml_parser = XMLParser() self.data_xs_parser = DataTextParser() self.data_clathrate_parser = DataTextParser(dtype=str) #", "self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution", "elif quantity == 'LOSS' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field =", "eigs_gw_C = reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation = eigs_gw_C sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc')) def", "sec_gap.value_fundamental = fundamental_band_gap optical_band_gap = self.info_gw_parser.get('optical_band_gap', None) if optical_band_gap is", "file def get_files(name): bse_types = ['IP', 'singlet', 'triplet', 'RPA'] scr_types", "data_q.append(self.data_xs_parser.data) if not data_q: continue data_q = np.transpose(data_q, axes=(2, 0,", "'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra = self.input_xml_parser.get( 'xs/tetra/tetradf', False) def _parse_xs_bse(self): sec_run", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "continue energies[v[0].strip()] = float(v[1]) * ureg.hartree return energies self._quantities =", "the fourth column in epsilon which is not parsed? sccs", "li + 1 return self._nlm @property def total_dos(self): if self._total_dos", "they are. What is the fourth column in epsilon which", "input_file: self.input_xml_parser.mainfile = f positions = self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors = self.input_xml_parser.get(", "% (self.number_of_spin_channels * self.number_of_lm)) // self.number_of_lm else: spin = int(spin)", "band_energies = self.bandstructure_parser.get('band_energies', []) for n in range(len(band_energies)): # Get", "energy_fermi = sec_scc.energy.fermi if energy_fermi is None: return energy_fermi =", "= reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands = len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints = len(eigs_gw) sec_gw_eigenvalues.kpoints =", "sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape( data[3], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape( data[4],", "if a the given filename exists and is accessible in", "val_in: unit = ureg.elementary_charge elif 'moment' in val_in: unit =", "'xs/gqmax', 0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get(", "= self.input_xml_parser.get( 'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlbse', [0, 0,", "and name.endswith('OUT'): parser = self.eigval_parser parser_function = self._parse_eigenvalues elif (name.startswith('FERMISURF')", "val_m is None: lm = i % self.number_of_lm else: lm", "sec_system.x_exciting_clathrates_atom_coordinates = np.transpose( np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels = list(data[3]) else: sec_system.x_exciting_clathrates", "self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos)) for i in range(len(self.partial_dos)): spin = self.partial_dos[i].attrib.get(self._nspin_key,", "if len(val) == 1 else val return np.array(val, dtype=float) def", "None: return sec_scc = sec_run.m_create(Calculation) def parse_scf(iteration, msection): energy_total =", "from xml file def get_files(name): bse_types = ['IP', 'singlet', 'triplet',", "'') if xstype.lower() == 'bse': self._parse_xs_bse() elif xstype.lower() == 'tddft':", "'vertex' self._band_key = 'band' self._atom_key = 'atom' self._nspin = kwargs.get('nspin',", "'diagram' self._l_key = 'l' self._m_key = 'm' self._energy_key = 'e'", "optimization_step.get('method') if optimization_step.get('step') is not None: sec_scc.x_exciting_geometry_optimization_step = optimization_step.get('step') force_convergence", "Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) for name,", "// nspin)) return data self._quantities.append( Quantity( 'eigenvalues_occupancies', r'\\(state\\, eigenvalue and", "sec_scc.x_exciting_xs_bse_loss_energies = np.reshape( data[0], (n_components, n_loss)) * ureg.hartree sec_scc.x_exciting_xs_bse_loss =", "= [] for i in range(len(self.number_of_k_points_per_segment)): start = self.vertices[i].attrib.get(self._coord_key).split() end", "0., 0.]) # TODO I am not certain if screening/BSE", "= np.reshape( data[1], (n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im = np.reshape( data[2], (n_components,", "@property def number_of_atoms(self): if self._natoms is None: partial_dos = self.root.findall('./%s'", "float(v[1]) * ureg.hartree return energies self._quantities = [Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\.", "data[j].append(data_q[j]) return data for quantity in ['EPSILON', 'LOSS', 'SIGMA']: for", "energy'], 'x_exciting_fermi_energy': ['Fermi energy', 'Fermi'], 'energy_kinetic_electronic': ['Kinetic energy', 'electronic kinetic'],", "j in range(len(data)): data[j].append(data_q[j]) return data for quantity in ['EPSILON',", "sec_worfklow = self.archive.m_create(Workflow) sec_worfklow.type = 'single_point' structure_optimization = self.info_parser.get('structure_optimization') if", "[sec_method_ref] # parse input xml file, there seems to be", "get it from input.xml for f in input_file: self.input_xml_parser.mainfile =", "if len(v[1]) == 1 else v[1] if species is None:", "len(data[0]) // n_components sec_scc.x_exciting_xs_bse_loss_energies = np.reshape( data[0], (n_components, n_loss)) *", "sec_scc.energy.fermi if energy_fermi is None: return energy_fermi = (energy_fermi.magnitude *", "= os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = default.rsplit('.', 1) filename", "= sec_run.m_create(Calculation) def parse_scf(iteration, msection): energy_total = iteration.get('energy_total') sec_energy =", "sec_smearing.width = smearing_width.magnitude for name in self.info_parser._convergence_keys_mapping.keys(): threshold = self.info_parser.get_scf_threshold(name)", "ureg.bohr)} for name, key_unit in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)'", "section): sec_run = self.archive.run[-1] positions = self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors =", "for v in val[2:]], dtype=float)) eigs = {keys[i]: eigs[i] for", "= BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser = ExcitingEigenvalueParser() self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser() self.evalqp_parser =", "sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get( 'xs/screening/ngridk', [0, 0, 0]) rgkmax = self.input_xml_parser.get('xs/screening/rgkmax',", "not data: sccs.append(None) continue if quantity == 'EXCITON': sec_scc =", "sec_atoms.positions = positions sec_atoms.labels = atom_labels sec_atoms.periodic = [True] *", "= ['IP', 'singlet', 'triplet', 'RPA'] scr_types = ['full', 'diag', 'noinvdiag',", "sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'imized atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True,", "is None: continue data.append(self.data_xs_parser.data) return data def parse_exciton(data, sec_scc): n_components", "else vi properties[v[0].strip()] = vi * unit properties['atom_resolved'] = atom_resolved", "energy', 'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy', 'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy',", "'x_exciting_spin_treatment', 'spin-unpolarised') n_spin = 1 if spin_treatment.lower() == 'spin-unpolarised' else", "range(len(data)): data[j].append(data_q[j]) return data for quantity in ['EPSILON', 'LOSS', 'SIGMA']:", "re_symbol = re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in): val = [v.split(':')[-1].split() for v", "[None, None])[0] sec_xc_functional.reference = xc_functional.get('name_reference', [None, None])[1] sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels()", "fermi_energy is not None: sec_scc.energy = Energy(fermi=fermi_energy) gw_files = ['EVALQP.DAT',", "scf_iteration or optimization_step final = section.get('scf_iteration', [None])[-1] final = section.get('optimization_step',", "'x_exciting_nuclear_charge': ('Total nuclear charge', ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total electronic charge', ureg.elementary_charge),", "'Mismatch in EXCITON and file type', data=dict(file=quantity)) sec_scc = sec_run.m_create(Calculation)", "sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface def _parse_evalqp(self, sec_scc): data = self.evalqp_parser.get('kpoints_eigenvalues') if", "== 'x_exciting_section_MT_charge_atom': for n in range(len(val)): sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index", "for n in range(len(val))] * val[0][1].units sec_charges.total = charge_contributions.get('total charge')", "labels is None: # we get it by concatenating species", "if self._band_energies is None: data = np.transpose(self.data) n_kpoints = np.where(data[0]", "if screening/BSE are children of xs if self.input_xml_parser.get('xs/screening') is not", "res = None self._results[key] = res class DOSXMLParser(XMLParser): def __init__(self,", "self.total_dos[i].attrib.get(self._nspin_key, i) res[i] = self._get_dos(self._total_dos[i]) if self.energy_unit is not None:", "# import numpy as np import os import re import", "sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels() if self._calculation_type == 'volume_optimization': sec_method.x_exciting_volume_optimization = True", "'spherical') sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get( 'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlbse',", "'force_convergence', r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree / ureg.bohr, repeats=False,", "f in filenames if os.access(f, os.F_OK)] return filenames def file_exists(self,", "fundamental_band_gap = self.info_gw_parser.get('direct_band_gap', None) if fundamental_band_gap is None: fundamental_band_gap =", "distributed under the License is distributed on an \"AS IS\"", "[f for f in files if f.endswith('QMT%s.OUT' % str(i +", "f for f in os.listdir( self.info_parser.maindir) if target[0] in f", "if target[1:]: filename = '%s.%s' % (filename, target[1]) filename =", "res * (1 / self.energy_unit) elif 'partial' in key: if", "below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues, repeats=True)) class ExcitingGWOutParser(TextParser): def __init__(self, mainfile, logger):", "start = end return self._band_energies @property def distances(self): if self._distances", "== 'volume_optimization': sec_method.x_exciting_volume_optimization = True def parse_scc(self, section): sec_run =", "'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE', 'GGA_X_WC'], 30: ['GGA_C_AM05', 'GGA_C_AM05'], 300: ['GGA_C_BGCP', 'GGA_X_PBE'],", "lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1 / ureg.bohr, repeats=False, convert=False), ] self._system_keys_mapping", "*(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False, convert=False), Quantity( 'x_exciting_dos_fermi', r'DOS at Fermi energy", "self.partial_dos[i].attrib.get(self._m_key, None) if val_l is None or val_m is None:", "sub_sec.x_exciting_spin_treatment = val elif name == 'x_exciting_species_rtmin': setattr(sec_system, name, '", "sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3] fermi_energy = self.fermisurf_parser.get('fermi_energy', None) if fermi_energy is", "= 'nspin' self._totaldos_key = 'totaldos' self._partialdos_key = 'partialdos' self._diagram_key =", "nomad.units import ureg from nomad.parsing.file_parser import TextParser, Quantity, XMLParser, DataTextParser", "self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies = [] start = 0 for nkpts_segment", "in files_q: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None: continue", "'_X_' in name: sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_' in name: sec_xc_functional.correlation.append(Functional(name=name)) elif", "None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax", "self._band_key)) return self._bands @property def vertices(self): if self._vertices is None:", "'x_exciting_scf_threshold_energy_change': sec_method.scf = Scf(threshold_energy_change=threshold) xc_functional_names = self.info_parser.get_xc_functional_name() if not xc_functional_names:", "= self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals", "return positions_format def get_atom_positions(self, section={}, positions=None, positions_format=None): positions = positions", "un-shift the DOS to # the original scale in which", "or lattice_vectors is None or species is None: continue lattice_vectors", "val_m = self.partial_dos[i].attrib.get(self._m_key, None) if val_l is None or val_m", "is None: total_dos = self.root.find('./%s/%s' % (self._totaldos_key, self._diagram_key)) self._ndos =", "spin sec_dos_values.value = totaldos[spin] partialdos = self.dos_parser.get('partialdos') if partialdos is", "# add atom-resolved bands_atom = self.root.findall('./*/%s' % self._atom_key) for band", "sec_dos_values.spin = spin sec_dos_values.value = dos[spin] # TODO add PDOS", "data[1], (n_components, n_loss)) # TODO check if format of files", "= val[1].split() eigs = np.transpose(np.array([v.split() for v in val[2:]], dtype=float))", "section: return sec_scc = self.parse_scc(section) if sec_scc is None: return", "if fermi_energy is not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy sec_fermisurface.x_exciting_values_fermi_surface =", "continue setattr(msection, name, val) # other metainfo for name in", "1 else val return np.array(val, dtype=float) def str_to_atom_properties_dict(val_in): unit =", "[float(vii) for vii in v[1].split()] vi = vi[0] if len(vi)", "None) aresdf = self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list = [ 'TET' if", "[ val[n][1].magnitude for n in range(len(val))] * val[0][1].units sec_charges.total =", "self._nspin = len(self.total_dos) return self._nspin @property def number_of_atoms(self): if self._natoms", "diagram): dos = np.array( [point.attrib.get(self._dos_key) for point in diagram], dtype=float)", "section.get('forces') if forces is not None: sec_forces = sec_scc.m_create(Forces) sec_forces.total", "self.input_xml_parser.get('xs/vkloff', [0., 0., 0.]) # TODO I am not certain", "read from xml file def get_files(name): bse_types = ['IP', 'singlet',", "self.info_parser.get_initialization_parameter('smearing_width') if smearing_width is not None: smearing_width = (smearing_width *", "*(.+)'), Quantity('name', r'name *: *(.+)'), Quantity('nuclear_charge', rf'nuclear charge *: *({re_float})',", "if self._band_k_points is None: data = np.transpose(self.data) self._band_k_points = []", "self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb =", "= self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax = rgkmax sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get( 'xs/screening/screentype',", "np.array(positions) positions_format = positions_format if positions_format is not None else", "in range(len(band_energies[n])): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints =", "quantity == 'EPSILON': parse_function = parse_epsilon elif quantity == 'SIGMA':", "= positions_format if positions_format is not None else self.get_positions_format(section) if", "1].attrib.get(self._coord_key).split() res.append([start, end]) else: res = None self._results[key] = res", "this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False, dtype=float) ] self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization", "'NLF_FXC']: data = get_data(quantity, ext) if not data[0]: continue if", "also input parameters here if input_GW.xml does not exist self._quantities.append(", "= np.reshape(occs, (nspin, len(occs) // nspin)) data['eigenvalues'] = np.reshape(eigs, (nspin,", "if self._energy_unit is not None: band_energy = band_energy * self._energy_unit", "str): smearing_kind = smearing_kind[0] smearing_kind = smearing_kind_map[smearing_kind] sec_smearing.kind = smearing_kind", "if self._partial_dos is None: self._partial_dos = self.root.findall('./%s/%s' % (self._partialdos_key, self._diagram_key))", "[] class ExcitingInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): re_symbol =", "repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing', r'Using ([\\w ]+) potential mixing', repeats=False,", "1 else vi properties[v[0].strip()] = vi * unit properties['atom_resolved'] =", "start = end return self._band_k_points @property def distances(self): if self._distances", "self._band_energies = None self._band_k_points = None @property def band_energies(self): if", "# ones with the missing quantity if len(quantity) < n_scf:", "return name @property def n_optimization_steps(self): return len(self.get('structure_optimization', {}).get('optimization_step', [])) def", "may obtain a copy of the License at # #", "val = np.array([v.split() for v in val.split('\\n')], dtype=float) val =", "(n_components, n_sigma)) * ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re = np.reshape( data[1], (n_components, n_sigma))", "offset', None), 'x_exciting_number_kpoints': (r'Total number of k\\-points', None), 'x_exciting_rgkmax': (r'R\\^MT\\_min", "not None else section.get('positions') if positions is None: species =", "name='exciting', version=self.info_parser.get('program_version', '').strip()) # method goes first since reference needed", "optimization_step.get('force_convergence') if force_convergence is not None: sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force", "if os.path.isfile(filepath) and os.access(filepath, os.F_OK): return True return False def", "files are really correct, i.e. columns are supposed # to", "res_n = [] start = 0 band_energies = np.zeros(( self.number_of_spin_channels,", "'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type = self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies = int(self.input_xml_parser.get(", "potential energy', 'Coulomb potential'], 'energy_xc_potential': ['xc potential energy', 'xc potential'],", "units of energy sec_smearing.width = smearing_width.magnitude for name in self.info_parser._convergence_keys_mapping.keys():", "not sure about format for spin-polarized case! I assume it", "n_loss = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_loss_energies = np.reshape( data[0], (n_components,", "= [None] * (n_scf - len(quantity)) + quantity return quantity", "kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion correction'] } self._electron_charge_keys_mapping = { 'x_exciting_core_charge':", "n in range(len(val)): sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n +", "optimization_step.get('step') force_convergence = optimization_step.get('force_convergence') if force_convergence is not None: sec_scc.x_exciting_maximum_force_magnitude", "of plane\\-waves', None), 'x_exciting_lo': (r'Total number of local\\-orbitals', None)} self._method_keys_mapping", "sec_gw.screened_Coulomb = self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa') def parse_gw(self): sec_run = self.archive.run[-1]", "with should have units of energy sec_smearing.width = smearing_width.magnitude for", "key.replace('energy_', '')), EnergyEntry(value=val)) else: setattr(msection, key, val) if key ==", "= optimization_step.get('force_convergence') if force_convergence is not None: sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0]", "in range(len(dos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value", "self._parse_dos_out elif name.startswith('bandstructure') and name.endswith('dat'): parser = self.bandstructure_dat_parser parser_function =", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "self._nspin = kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self):", "1 if spin_treatment.lower() == 'spin-unpolarised' else 2 return n_spin def", "sec_run = self.archive.run[-1] def parse_configuration(section): if not section: return sec_scc", "1 for i in range(1, len(self.distances)): if self.distances[i] == self.distances[i", "_parse_dos(self, sec_scc): if self.dos_parser.get('totaldos', None) is None: return # Get", "def __init__(self, **kwargs): # TODO make a parent class for", "spin = (i % (self.number_of_spin_channels * self.number_of_lm)) // self.number_of_lm else:", "sizes', None), 'x_exciting_gvector_total': (r'Total number of G\\-vectors', None), 'x_exciting_lmaxapw': (r'", "section.get('scf_iteration', []) for scf_iteration in scf_iterations: sec_scf_iteration = sec_scc.m_create(ScfIteration) parse_scf(scf_iteration,", "x: [v.strip() for v in x.split(':')]), Quantity( 'parameters', r'\\n *(.+?:.+)',", "is not None: number = frequency_data.get('number') sec_method.gw.number_of_frequencies = len(number) sec_method.gw.frequency_number", "% (self._totaldos_key, self._diagram_key)) self._ndos = len(total_dos) return self._ndos @property def", "'x_exciting_pw': (r'Maximum number of plane\\-waves', None), 'x_exciting_lo': (r'Total number of", "loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[", "name == 'x_exciting_species_rtmin': setattr(sec_system, name, ' '.join([str(v) for v in", "filepath = '%s%s' % (target[0], suffix) if target[1:]: filepath =", "treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number of Bravais lattice symmetries', None), 'x_exciting_number_of_crystal_symmetries':", "PDOS def _parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_dat_parser.band_energies", "n_loss)) * ureg.hartree sec_scc.x_exciting_xs_bse_loss = np.reshape( data[1], (n_components, n_loss)) #", "@property def total_dos(self): if self._total_dos is None: self._total_dos = self.root.findall('./%s/%s'", "parse_sigma elif quantity == 'LOSS': parse_function = parse_loss else: continue", "'x_exciting_number_of_crystal_symmetries': ('Number of crystal symmetries', None), 'x_exciting_kpoint_grid': (r'k\\-point grid', None),", "= specie.get('positions_format', None) if positions_format is not None: break return", "Quantity( 'time', r'Time spent in this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False,", "energy_fermi = sec_scc.energy.fermi energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band =", "reported. energy_fermi = sec_scc.energy.fermi if energy_fermi is None: continue energy_fermi", "sec_energy = msection.m_create(Energy) if energy_total is not None: sec_energy.total =", "# this is really problematic if some scf steps dont", "for d in data]) if None in energy: return energy", "val = np.transpose(np.array([v for v in val if len(v) ==", "is None: return self._nlm = 0 l_list = set([int(e.attrib.get(self._l_key)) for", "len(files) > 1: self.logger.warn('Found multiple files. Will read all!', data=dict(file=name))", "class ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = []", "not input_file: return self.input_xml_parser.mainfile = input_file[0] xstype = self.input_xml_parser.get('xs/xstype', '')", "None: return data = np.transpose(self.data) n_kpoints = int(max(data[1])) bands =", "sec_dft.m_create(XCFunctional) for name in xc_functional_names: if name is None: continue", "GW as GWMethod, Scf, BasisSet ) from nomad.datamodel.metainfo.simulation.system import (", "['bandstructure-qp.dat', 'BAND-QP.OUT'] for fname in bs_files: if self.file_exists(fname): gw_files.append(fname) break", "energy_contributions.get(name, None) if val is not None: break if val", "bs_files = ['dos.xml', 'TDOS.OUT'] for fname in bs_files: if self.file_exists(fname):", "optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False, dtype=float), Quantity( 'time', r'Time spent in", "= band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3] fermi_energy = self.fermisurf_parser.get('fermi_energy', None) if", "'lattice': cell = self.get_initialization_parameter('lattice_vectors') if cell is None: return positions", "smearing_width = (smearing_width * ureg.hartree).to('joule') # TODO smearing with should", "self.bandstructure_dat_parser.logger = self.logger self.band_out_parser.logger = self.logger self.info_gw_parser.logger = self.logger self.input_xml_parser.logger", "energies[v[0].strip()] = float(v[1]) * ureg.hartree return energies self._quantities = [Quantity(", "0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get( 'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra = self.input_xml_parser.get( 'xs/tetra/tetradf',", "optimization in exciting sec_atoms.lattice_vectors = lattice_vectors lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal')", "dtype=float) keys = val[1].split() eigs = np.transpose(np.array([v.split() for v in", "self._parse_dos elif name.startswith('bandstructure') and name.endswith('xml'): parser = self.bandstructure_parser parser_function =", "TODO check if format of files are really correct, i.e.", "self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0 * ureg.bohr ** 3) def get_initialization_parameter(self, key,", "data is None: return def get_data(key): if key == 'k_points':", "def get_scf_quantity(self, name): n_scf = len(self.get('energy_total_scf_iteration', [])) quantity = self.get('%s_scf_iteration'", "else: filenames = [filename] filenames = [f for f in", "energy_fermi is None: continue energy_fermi = energy_fermi.to(\"hartree\") sec_k_band = sec_scc.m_create(BandStructure,", "if positions_format is not None: break return positions_format def get_atom_positions(self,", "= { 'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment': ['total moment in muffin-tins'], 'x_exciting_total_moment':", "for spin in range(len(partialdos[lm])): for atom in range(len(partialdos[lm][spin])): sec_dos_values =", "final is None: return sec_scc = sec_run.m_create(Calculation) def parse_scf(iteration, msection):", "TODO confirm no cell optimization in exciting sec_atoms.lattice_vectors = lattice_vectors", "# structure optimization structure_optimization = self.info_parser.get('structure_optimization', {}) for optimization_step in", "= len(number) sec_method.gw.frequency_number = number sec_method.gw.frequency_values = frequency_data.get('values') sec_method.gw.frequency_weights =", "self._band_energies @property def distances(self): if self._distances is None: dist =", ") initialization_quantities.append(Quantity( 'species', rf'(Species : *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)', repeats=True,", "in which also other energies are reported. energy_fermi = 0.0", "} self._moment_keys_mapping = { 'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment': ['total moment in", "def __init__(self): super().__init__(None) def init_quantities(self): re_symbol = re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in):", "in input_file: self.input_xml_parser.mainfile = f positions = self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors =", "vector = np.array([v.split() for v in val[3:6]], dtype=float) return [nbands,", "in v[1].split()] vi = vi[0] if len(vi) == 1 else", "'xs/broad', 0.01, 'hartree') sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get( 'xs/gqmax', 0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw", "def init_quantities(self): self._quantities = [] class ExcitingInfoParser(TextParser): def __init__(self): super().__init__(None)", "repeats=False, dtype=str), Quantity( 'n_scf_iterations', r'Number of (?:total)* scf iterations\\s*\\:\\s*(\\d+)', repeats=False,", "= val else: setattr(msection, name, val) # energy, moment, charge", "is None: data = np.transpose(self.data) self._distances = data[5][:int(max(data[1]))] return self._distances", "name.endswith('OUT'): parser = self.eigval_parser parser_function = self._parse_eigenvalues elif (name.startswith('FERMISURF') or", "= self.dos_out_parser parser_function = self._parse_dos_out elif name.startswith('bandstructure') and name.endswith('dat'): parser", "however nspin is # determined from occupancies which is problematic", "self.parse_file(f, sec_method) xc_functional_name = ' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point = xc_functional_name sec_scc", "which is problematic sometimes res = np.hstack([np.reshape(v[key], (nspin, np.size(v[key]) //", "sec_eigenvalues.occupations = get_data('occupancies') sec_eigenvalues.energies = get_data('eigenvalues') def _parse_fermisurface(self, sec_scc): fermi_surface", "if force_convergence is not None: sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force =", "= np.zeros((self.number_of_spin_channels, self.number_of_dos)) for i in range(len(self.total_dos)): spin = self.total_dos[i].attrib.get(self._nspin_key,", "+ 1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i])) elif key == 'band_segm_labels':", "quantity == 'LOSS' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1]", "len(v[1]) == 1 else v[1] if species is None: species", "'total in muffin-tins'], 'charge_total': ['total charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved'] } self._moment_keys_mapping", "n_epsilon)) def parse_sigma(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data))", "else final if final is None: return sec_scc = sec_run.m_create(Calculation)", "ureg.hartree return energies self._quantities = [Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False,", "in bands_atom: self._bands.append(band.findall('./%s' % self._band_key)) return self._bands @property def vertices(self):", "= spin sec_dos_values.value = totaldos[spin] partialdos = self.dos_parser.get('partialdos') if partialdos", "self._parse_evalqp elif name.startswith('TDOS') and name.endswith('OUT'): parser = self.dos_out_parser parser_function =", "None) for d in data]) else: energy = np.array([d[1].get(key, None)", "data[1], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape( data[2], (n_components,", "self.data_clathrate_parser.mainfile = clathrate_file[0] if self.data_clathrate_parser.data: data = np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates =", "force_convergence = optimization_step.get('force_convergence') if force_convergence is not None: sec_scc.x_exciting_maximum_force_magnitude =", "kinetic'], 'energy_coulomb': ['Coulomb energy', 'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb energy', 'Coulomb'], 'energy_exchange':", "None), 'x_exciting_lo': (r'Total number of local\\-orbitals', None)} self._method_keys_mapping = {", "{}) for key, names in self._electron_charge_keys_mapping.items(): val = None for", "% str(volume_index).rjust(2, '0')) if not info_volume: break sec_scc.calculations_path.append(info_volume[0]) def init_parser(self):", "self.input_xml_parser.get( 'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states = int( self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq =", "self.fermisurf_parser.get('band_parameters', None) if band_parameters is not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0]", "self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax = rgkmax sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get( 'xs/BSE/sciavbd', True)", "= self.vertices[i].attrib.get(self._coord_key).split() end = self.vertices[i + 1].attrib.get(self._coord_key).split() res.append([start, end]) else:", "= 'dos' self._unit_key = 'unit' self._energy_unit = kwargs.get('energy_unit', None) self._units_mapping", "for name in self.info_parser._miscellaneous_keys_mapping.keys(): val = iteration.get(name) if val is", "sec_scf_iteration = sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration) return sec_scc def parse_system(self, section):", "positions_format if positions_format is not None else self.get_positions_format(section) if positions_format", "'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance = self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001) gmb = self.input_xml_parser.get('gw/mixbasis/gmb',", "== 'EXCITON': parse_function = parse_exciton elif quantity == 'EPSILON': parse_function", "sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.energies = band_energies[nb] + energy_fermi def _parse_band_out(self,", "elif v[0].startswith('atom'): v[0] = v[0].split() v[1] = [float(vi) for vi", "self.logger self.bandstructure_parser.logger = self.logger self.eigval_parser.logger = self.logger self.fermisurf_parser.logger = self.logger", "None: self._nspin = np.shape(np.transpose(self.data))[0] - 6 return self._nspin @property def", "self._quantities.append( Quantity( 'eigenvalues_occupancies', r'\\(state\\, eigenvalue and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues,", "self.init_parser() sec_run = self.archive.m_create(Run) sec_run.program = Program( name='exciting', version=self.info_parser.get('program_version', '').strip())", "self._quantities = [] self._quantities.append( Quantity( 'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False))", "len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints = len(eigs_gw) sec_gw_eigenvalues.kpoints = get_data('k_points') sec_gw_eigenvalues.energies = reshape(eigs_gw)", "= self.logger self.data_xs_parser.logger = self.logger self.data_clathrate_parser.logger = self.logger def reuse_parser(self,", "if self.input_xml_parser.get('xs/BSE') is not None: sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get( 'xs/BSE/aresbse', True)", "name in names: val = energy_contributions.get(name, None) if val is", "DataTextParser() self.data_clathrate_parser = DataTextParser(dtype=str) # different names for different versions", "for n in range(len(val)): sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n", "self._ndos = len(total_dos) return self._ndos @property def number_of_lm(self): if self._nlm", "'x_exciting_brillouin_zone_volume': ('Brillouin zone volume', 1 / ureg.bohr ** 3), 'x_exciting_number_of_atoms':", "== 'gw': return sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref", "'bandstructure.dat'] for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break for", "self._neigs_segment = len(np.where(data == data[0])[0]) return self._neigs_segment class BandstructureXMLParser(XMLParser): def", "len(sec_run.system) > 1: return sec_system for name in self.info_parser._system_keys_mapping.keys(): val", "if self._results is None: self._results = dict() if not self.bands:", "rf'radial points in muffin-tin *: *({re_float})', dtype=np.int32), Quantity('positions_format', r'atomic positions", "= lattice_vectors lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal if", "eigs_gw = get_data('E_GW') if eigs_gw[0] is None: return nspin =", "break sec_scc.calculations_path.append(info_volume[0]) def init_parser(self): self.info_parser.mainfile = self.filepath self.info_parser.logger = self.logger", "r'Exchange-correlation type +: +(\\S+)'), Quantity( 'name_reference', r'\\n *(.+?,.+)', str_operation=lambda x:", "continue energy_fermi = energy_fermi.to(\"hartree\") sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi =", "( r'Charge distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence': ( r'Abs\\. change in max\\-nonIBS\\-force\\s*\\(target\\)',", "suffix) if target[1:]: filepath = '%s.%s' % (filepath, target[1]) filepath", "n_components = len(data) data = np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components = n_components n_excitons", "occs[0] == 1. else 1 data = dict() data['occupancies'] =", "self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type = self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies =", "name is None: continue if '_X_' in name: sec_xc_functional.exchange.append(Functional(name=name)) elif", "= ['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT'] # Parse GW band structure from", "{ 'x_exciting_unit_cell_volume': ('Unit cell volume', ureg.bohr ** 3), 'x_exciting_brillouin_zone_volume': ('Brillouin", "free up memory parser.mainfile = None def _parse_input_xs(self, sec_method): xstype", "self._energies * self.energy_unit return self._energies def _get_dos(self, diagram): dos =", "[point.attrib.get(self._dos_key) for point in diagram], dtype=float) return dos def parse(self,", "dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file', r'parameters loaded from *: *(.+)'), Quantity('name',", "band in bands]) if self._energy_unit: band_energy = band_energy * self._energy_unit", "energy: it is used to un-shift the band structure to", "sec_forces = sec_scc.m_create(Forces) sec_forces.total = ForcesEntry(value=forces) # scf iterations scf_iterations", "= str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius') positions_format =", "@property def distances(self): if self._distances is None: dist = np.transpose(self.data)[0]", "get_data(files): data = [] for f in files: self.data_xs_parser.mainfile =", "positions = positions if positions is not None else section.get('positions')", "== 'FXC': sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1] elif quantity == 'LOSS' and", "reported. energy_fermi = sec_scc.energy.fermi if energy_fermi is None: return energy_fermi", "in range(len(val)): sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n + 1", "if e]) # read q points qpoints = self.input_xml_parser.get('xs/qpointset/qpoint') def", "atoms per unit cell', None), 'x_exciting_spin_treatment': ('Spin treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries':", "list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False) ) self._quantities.append( Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree,", "= np.shape(np.transpose(self.data))[0] - 6 return self._nspin @property def number_of_k_points_per_segment(self): if", "sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get( 'xs/tddft/drude', [0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get( 'xs/tddft/fxcbsesplit',", "dtype=str, flatten=False)] initialization_quantities = [ Quantity( 'lattice_vectors', r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array,", "r'Number of (?:total)* scf iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'force_convergence', r'Maximum", ") self._quantities.append( Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) class ExcitingEvalqpParser(TextParser):", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'eigenvalues': res = res * ureg.hartree return res sec_eigenvalues =", "sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get( 'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3)", "Performing final SCF iteration|Reached self-consistent loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False),", "self.input_xml_parser.get( 'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get( 'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude =", "= sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints = self.eigval_parser.get('k_points') sec_eigenvalues.occupations = get_data('occupancies') sec_eigenvalues.energies =", "__init__(self, mainfile, logger): super().__init__(mainfile, logger=logger) def init_quantities(self): self._quantities = []", "of valence states', None), 'x_exciting_hamiltonian_size': ('Maximum Hamiltonian size', None), 'x_exciting_pw':", "sec_atoms.periodic = [True] * 3 # TODO confirm no cell", "else: count += 1 self._nkpts_segment.append(count) return self._nkpts_segment @property def number_of_band_segment_eigenvalues(self):", "convert=False), Quantity( 'lattice_vectors_reciprocal', r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1 / ureg.bohr,", "sec_system is not None: sec_scc.system_ref = sec_system sec_scc.method_ref = sec_run.method[-1]", "self._band_k_points.append( np.transpose(data[2:5])[start:end]) start = end return self._band_k_points @property def distances(self):", "is None: return # volume optimizations volume_index = 1 while", "rgkmax sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor', 0.0) sec_method.x_exciting_xs_vkloff = self.input_xml_parser.get('xs/vkloff', [0., 0.,", "exciting_files.append(fname) break # Parse DFT band structure from one of", "else: # TODO implement reading of parameters from input.xml for", "self._nspin is None: if not self.total_dos: return self._nspin = len(self.total_dos)", "sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get( 'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlxas', [0,", "self._quantities.append( Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False) ) self._quantities.append( Quantity(", "file_ext_list = [ 'TET' if tetradf else None, 'AC' if", "self._energy_unit is not None: band_energy = band_energy * self._energy_unit res_n.append(band_energy)", "range(1, len(self.distances)): if self.distances[i] == self.distances[i - 1]: self._nkpts_segment.append(count) count", "of k\\-points', None), 'x_exciting_rgkmax': (r'R\\^MT\\_min \\* \\|G\\+k\\|\\_max \\(rgkmax\\)', None), 'x_exciting_species_rtmin':", "section.get('optimization_step', [None])[-1] if final is None else final if final", "self.data_xs_parser.mainfile = f if self.data_xs_parser.data is None: continue data_q.append(self.data_xs_parser.data) if", "return positions * ureg.bohr def get_scf_threshold(self, name): reference = self.get('groundstate',", "None for name in names: val = energy_contributions.get(name, None) if", "= (smearing_width * ureg.hartree).to('joule') # TODO smearing with should have", "parse properties input_file = self.get_exciting_files('input.xml') if not input_file: return self.input_xml_parser.mainfile", "ExcitingEigenvalueParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] self._quantities.append(", "for f in gw_info_files: if self.get_exciting_files(f): self._calculation_type = 'gw' gw_info_file", "self._moment_keys_mapping.items(): val = None for name in names: val =", "nomad.datamodel.metainfo.simulation.calculation import ( Calculation, Dos, DosValues, BandStructure, BandEnergies, Energy, EnergyEntry,", "is not None: sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get( 'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk =", "('Smearing width', None)} for name, key_unit in self._system_keys_mapping.items(): initialization_quantities.append( Quantity(", "repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr), ]), repeats=False)) self._quantities.append(Quantity( 'hybrids',", "2)) data = np.transpose(data, axes=(2, 0, 1)) sec_dos.energies = data[0][0]", "'x_exciting_species_rtmin': setattr(sec_system, name, ' '.join([str(v) for v in val])) else:", "*({re_float})', dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin radius *: *({re_float})', dtype=np.float64, unit=ureg.bohr),", "'GGA_C_AM05'], 300: ['GGA_C_BGCP', 'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']} xc_functional =", "__init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] def str_to_eigenvalue(val_in): val", "input_GW.xml does not exist self._quantities.append( Quantity( 'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency,", "atom-resolved bands_atom = self.root.findall('./*/%s' % self._atom_key) for band in bands_atom:", "in f] options = [f for f in options if", "if section.get('energy_total') is not None else section.get('final') if final is", "parser_function = self._parse_dos elif name.startswith('bandstructure') and name.endswith('xml'): parser = self.bandstructure_parser", "repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities = [ Quantity( 'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)',", "= self.logger self.dos_parser.logger = self.logger self.bandstructure_parser.logger = self.logger self.eigval_parser.logger =", "*({re_float}) *({re_float}) *({re_float})', repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing', r'Using ([\\w ]+)", "def parse_configurations(self): sec_run = self.archive.run[-1] def parse_configuration(section): if not section:", "column in epsilon which is not parsed? sccs = []", "threshold is None: continue metainfo_name = 'x_exciting_scf_threshold_%s_change' % name.split('_')[-2] setattr(sec_method,", "= self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax = gmb * gmaxvr pwm =", "= self.archive.run[-1] final = section if section.get('energy_total') is not None", "from *: *(.+)'), Quantity('name', r'name *: *(.+)'), Quantity('nuclear_charge', rf'nuclear charge", "range(len(files)): parser.mainfile = files[n] parser_function(section) # free up memory parser.mainfile", "[]) for specie in species: positions_format = specie.get('positions_format', None) if", "in v[1].split()] v[1] = v[1][0] if len(v[1]) == 1 else", "self.data_xs_parser.logger = self.logger self.data_clathrate_parser.logger = self.logger def reuse_parser(self, parser): self.info_parser.quantities", "for v in val.split('\\n')], dtype=float) val = np.transpose(val) occs =", "'xs/tetra/tetradf', False) def _parse_xs_bse(self): sec_run = self.archive.run[-1] # TODO read", "np.array(self._distances, dtype=float) return self._distances @property def bands(self): if self._bands is", "self._partial_dos @property def energies(self): if self._energies is None: if self.total_dos", "parser_function = self._parse_eigenvalues elif (name.startswith('FERMISURF') or name.startswith('FS')) and name.endswith('bxsf'): parser", "['Core-electron kinetic energy', 'core electron kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion correction']", "band_energy = np.array([np.transpose(band)[start:end] for band in bands]) if self._energy_unit: band_energy", "n_sigma = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape( data[0], (n_components,", "bandstructure super().__init__(None) self._distance_key = 'distance' self._coord_key = 'coord' self._energy_key =", "= self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange) sec_xc_functional = sec_dft.m_create(XCFunctional) for name in", "x.split(':')])])) ) self._quantities.append(Quantity( 'initialization', r'(?:All units are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)',", "# parse properties gw_info_files = self.get_exciting_files(gw_info_file) if len(gw_info_files) > 1:", "is None: if self.data is None: return data = np.transpose(self.data)", "number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity( 'final', r'(?:Convergence targets achieved\\.", "= section if section.get('energy_total') is not None else section.get('final') if", "if positions is None or atom_labels is None: return sec_system", "None self._nkpts_segment = None @property def band_energies(self): if self._band_energies is", "atom_labels = [] for n in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] * len(atoms[n]))", "sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points')", "for nb in range(len(band_energies[n])): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb]", "self.input_xml_parser.get( 'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get( 'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel =", "potential \\(target\\)', ureg.hartree), 'x_exciting_energy_convergence': ( r'Absolute change in total energy\\s*\\(target\\)',", "dos and bandstructure super().__init__(None) self._distance_key = 'distance' self._coord_key = 'coord'", "self.get_exciting_files(f): self._calculation_type = 'gw' gw_info_file = f break if not", "= 1 return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is", "if not self.total_dos: return self._nspin = len(self.total_dos) return self._nspin @property", "* 3 # TODO confirm no cell optimization in exciting", "ureg.bohr ** 3) def get_initialization_parameter(self, key, default=None): return self.get('initialization', {}).get(key,", "self._nlm is None: if self.partial_dos is None: return self._nlm =", "f in options] else: filenames = [filename] filenames = [f", "band_k_points[nb] sec_k_band_segment.energies = band_energies[nb] + energy_fermi def _parse_band_out(self, sec_scc): self.band_out_parser._nspin", "= os.path.join(self.info_parser.maindir, filename) if os.path.isfile(filename): return [filename] filename = os.path.join(self.info_parser.maindir,", "self._system_keys_mapping = { 'x_exciting_unit_cell_volume': ('Unit cell volume', ureg.bohr ** 3),", "'').split() def str_to_energy_dict(val_in): val = val_in.strip().split('\\n') energies = dict() for", "scf_iteration in scf_iterations: sec_scf_iteration = sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration) return sec_scc", "dtype=float, unit=ureg.hartree / ureg.bohr), ]), repeats=False)) self._quantities.append(Quantity( 'hybrids', r'Hybrids module", "band_seg_labels[nb] sec_k_band_segment.energies = band_energies[n][nb] + energy_fermi def _parse_eigenvalues(self, sec_scc): if", "None: data = np.transpose(self.data)[0] self._neigs_segment = len(np.where(data == data[0])[0]) return", "= n + 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1]", "sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius", "self._quantities = [] class ExcitingInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self):", "import Workflow, GeometryOptimization from .metainfo.exciting import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\", "[specie.get('symbol')] * len(specie.get('positions')) return labels def get_positions_format(self, section): positions_format =", "'').replace(')', '').split() def str_to_energy_dict(val_in): val = val_in.strip().split('\\n') energies = dict()", "an example bandstructure file # atom-resolved bandstructure are added as", "def distances(self): if self._distances is None: data = np.transpose(self.data) self._distances", "flatten=False), Quantity( 'positions', rf'\\d+ : *({re_float}) *({re_float}) *({re_float})', repeats=True, dtype=np.dtype(np.float64))])))", "data[3], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape( data[4], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im", "= self.parse_system(section) if sec_system is not None: sec_scc.system_ref = sec_system", "vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr, repeats=False, convert=False), Quantity( 'lattice_vectors_reciprocal', r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n',", "dict() for v in val: v = v.split(':') if len(v)", "dos = np.array( [point.attrib.get(self._dos_key) for point in diagram], dtype=float) return", "[], []] for i in range(len(qpoints)): data_q = [] files_q", "len(data) // nspin data = np.reshape(data, (nspin, len(data) // nspin,", "if energy_fermi is None: continue energy_fermi = energy_fermi.to(\"hartree\") sec_k_band =", "= sec_run.system[-1] sec_scc_ref = sec_run.calculation[0] sec_scc.starting_calculation_ref = sec_scc_ref sec_scc.calculations_ref =", "__init__(self, **kwargs): super().__init__(None) self._nspin_key = 'nspin' self._totaldos_key = 'totaldos' self._partialdos_key", "list(data[3]) else: sec_system.x_exciting_clathrates = False potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing", "repeats=False, dtype=float, unit=ureg.hartree), Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False, convert=False),", "BandstructureDatParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None) self._energy_unit", "for quantity in ['EXCITON', 'EPSILON', 'SIGMA', 'LOSS']: files = get_files(quantity)", "dtype=int) origin = np.array(val[2].split(), dtype=float) vector = np.array([v.split() for v", "section): positions_format = section.get('positions_format') if positions_format is None: species =", "not None: number = frequency_data.get('number') sec_method.gw.number_of_frequencies = len(number) sec_method.gw.frequency_number =", "in data]) res = res.reshape((len(res), len(data), len(res[0]) // len(data))) if", "/ ureg.bohr ** 3), 'x_exciting_number_of_atoms': ('Total number of atoms per", "sec_dos_values.m_kind = 'spherical' sec_dos_values.lm = lm_values[lm] sec_dos_values.spin = spin sec_dos_values.atom_index", "np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float) for i in range(len(self.bands[n])): band_energies[i", "rf'\\d+ : *({re_float}) *({re_float}) *({re_float})', repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing', r'Using", "name.startswith('input') and name.endswith('xml'): parser = self.input_xml_parser if self._calculation_type == 'gw':", "is not None: smearing_width = (smearing_width * ureg.hartree).to('joule') # TODO", "from occupancies which is problematic sometimes res = np.hstack([np.reshape(v[key], (nspin,", "= sec_method_ref sec_method.methods_ref = [sec_method_ref] # parse input xml file,", "ANY KIND, either express or implied. # See the License", "with the missing quantity if len(quantity) < n_scf: quantity =", "# See the License for the specific language governing permissions", "1: return sec_system for name in self.info_parser._system_keys_mapping.keys(): val = self.info_parser.get_initialization_parameter(name)", "'input.xml']: self.parse_file(f, sec_method) xc_functional_name = ' '.join(self.info_parser.get_xc_functional_name()) sec_method.gw.starting_point = xc_functional_name", "thing that we can do is to assume that the", "\\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True)) class BandstructureDatParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin", "= self.logger self.bandstructure_parser.logger = self.logger self.eigval_parser.logger = self.logger self.fermisurf_parser.logger =", "self._nkpts_segment = [] count = 1 for i in range(1,", "res = np.hstack([np.reshape(v[key], (nspin, np.size(v[key]) // nspin)) for v in", "self.archive.run[-1] final = section if section.get('energy_total') is not None else", "sec_run.system[-1] sec_scc_ref = sec_run.calculation[0] sec_scc.starting_calculation_ref = sec_scc_ref sec_scc.calculations_ref = [sec_scc_ref]", "a mismatch between files self.logger.warn( 'Mismatch in EXCITON and file", "ExcitingParser: def __init__(self): self.info_parser = ExcitingInfoParser() self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser", "_parse_evalqp(self, sec_scc): data = self.evalqp_parser.get('kpoints_eigenvalues') if data is None: return", "band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3] fermi_energy = self.fermisurf_parser.get('fermi_energy',", ") self._quantities.append( Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False) ) self._quantities.append(", "'x_exciting_dos_fermi', r'DOS at Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=1 /", "energies are reported. energy_fermi = 0.0 * ureg.hartree if sec_scc.energy", "sec_scc) except Exception: self.logger.error('Error setting xs data', data=dict(file=quantity)) def _parse_xs_tddft(self):", "= 'DFT' smearing_kind_map = { 'Gaussian': 'gaussian', 'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac':", "if target[1:]: filepath = '%s.%s' % (filepath, target[1]) filepath =", "['LDA_C_PZ', 'LDA_X_PZ'], 3: ['LDA_C_PW', 'LDA_X_PZ'], 4: ['LDA_C_XALPHA'], 5: ['LDA_C_VBH'], 20:", "None) if xstype is not None: sec_method.x_exciting_xs_xstype = xstype sec_method.x_exciting_electronic_structure_method", "in self.info_parser._convergence_keys_mapping.keys(): val = iteration.get(name) if val is None: continue", "not None: energy_fermi = sec_scc.energy.fermi energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree')", "== 'eigenvalues': res = res * ureg.hartree return res sec_eigenvalues", "BandEnergies, Energy, EnergyEntry, Charges, Forces, ForcesEntry, ScfIteration, BandGap ) from", "ureg.bohr ** 3), 'x_exciting_number_of_atoms': ('Total number of atoms per unit", "np.transpose(np.array([v for v in val if len(v) == 3], float))", "sec_run = self.archive.run[-1] sec_method = sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft = sec_method.m_create(DFT)", "sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0))", "None])[-1] def get_scf_quantity(self, name): n_scf = len(self.get('energy_total_scf_iteration', [])) quantity =", "return data self._quantities.append( Quantity( 'eigenvalues_occupancies', r'\\(state\\, eigenvalue and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n", "= self.info_parser.get_number_of_spin_channels() sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = len(data) //", "self.get('initialization', {}).get('xc_functional', None) if xc_functional is None: return [] name", "if self.distances[i] == self.distances[i - 1]: self._nkpts_segment .append(count) count =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "None), 'smearing_width': ('Smearing width', None)} for name, key_unit in self._system_keys_mapping.items():", "mainfile_base in f] options = [f for f in options", "return sec_system = sec_run.m_create(System) sec_atoms = sec_system.m_create(Atoms) sec_atoms.positions = positions", ") self._quantities.append(Quantity( 'initialization', r'(?:All units are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False,", "[float(vi) for vi in v[1].split()] v[1] = v[1][0] if len(v[1])", "lattice_vectors = self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3)) species = self.input_xml_parser.get('structure/species/speciesfile') if positions", "kwargs.get('energy_unit', None) def init_parameters(self): self._nspin = None self._nkpts_segment = None", "nomad.datamodel.metainfo.simulation.run import Run, Program from nomad.datamodel.metainfo.simulation.method import ( Method, DFT,", "in range(len(self.partial_dos)): spin = self.partial_dos[i].attrib.get(self._nspin_key, None) if spin is None:", "'l' self._m_key = 'm' self._energy_key = 'e' self._dos_key = 'dos'", "= self.input_xml_parser.get( 'gw/scrcoul/sciavtype', 'isotropic') sec_gw.screened_Coulomb = self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa') def", "volume', 1 / ureg.bohr ** 3), 'x_exciting_number_of_atoms': ('Total number of", "== 1 else val return np.array(val, dtype=float) def str_to_atom_properties_dict(val_in): unit", "of atoms per unit cell', None), 'x_exciting_spin_treatment': ('Spin treatment', None),", "'longrange'] bse_files = [] for bse_type in bse_types: for scr_type", "atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)',", "vi * unit properties['atom_resolved'] = atom_resolved return properties def str_to_quantity_tolerances(val_in):", "is None: if self.total_dos is None: return self._energies = np.array(", "def get_data(key): if key == 'k_points': return np.array([d[0][:3] for d", "data[0], (n_components, n_loss)) * ureg.hartree sec_scc.x_exciting_xs_bse_loss = np.reshape( data[1], (n_components,", "= len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape(", "fundamental_band_gap is None: fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap', None) sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap)", "unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin radius *: *({re_float})', dtype=np.float64, unit=ureg.bohr), Quantity('radial_points', rf'radial", "key, names in self._electron_charge_keys_mapping.items(): val = None for name in", "Workflow, GeometryOptimization from .metainfo.exciting import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group", "// self.number_of_spin_channels return self._neigs_segment def parse(self, key): if self._results is", "sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.endpoints_labels = band_seg_labels[nb] sec_k_band_segment.energies", "r'(Atomic positions at this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions", "self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): # TODO make a", "i in range(len(self.bands[n])): band_energies[i % self.number_of_spin_channels][i] = np.array( [e.attrib.get(self._energy_key) for", "parse_method(self): sec_run = self.archive.run[-1] sec_method = sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft =", "sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get( 'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra = self.input_xml_parser.get( 'xs/tetra/tetradf', False)", "sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_parser.get('band_k_points')", "self.input_xml_parser.mainfile = f positions = self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors = self.input_xml_parser.get( 'structure/crystal/basevect',", "= None self._total_dos = None self._partial_dos = None @property def", "labels = section.get('symbols') if labels is None: # we get", "= v[0][2] atom_resolved.append(((species, v[1] * unit))) else: vi = [float(vii)", "self._quantities.append(Quantity( 'hybrids', r'Hybrids module started([\\s\\S]+?)Hybrids module stopped', sub_parser=TextParser(quantities=module_quantities) )) def", "parser.info_parser.quantities self.eigval_parser.quantities = parser.eigval_parser.quantities self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities self.evalqp_parser.quantities = parser.evalqp_parser.quantities", "= self.fermisurf_parser.get('fermi_surface', [None])[0] if fermi_surface is None: return sec_fermisurface =", "None self._vertices = None self._distances = None self._band_energies = None", "in range(1, len(self.distances)): if self.distances[i] == self.distances[i - 1]: self._nkpts_segment.append(count)", "volume = self.info_parser.get_unit_cell_volume() totaldos = self.dos_parser.get('totaldos') * volume.to('m**3').magnitude for spin", "re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in): val = [v.split(':')[-1].split() for v in val_in.strip().split('\\n')]", "under the License. # import numpy as np import os", "repeats=False, dtype=float), Quantity( 'time', r'Time spent in this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds',", "res class DOSXMLParser(XMLParser): def __init__(self, **kwargs): super().__init__(None) self._nspin_key = 'nspin'", "['GGA_C_AM05', 'GGA_C_AM05'], 300: ['GGA_C_BGCP', 'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'], 408: ['HYB_GGA_XC_HSE03']} xc_functional", "sec_method.methods_ref = [sec_method_ref] self.parse_file('input.xml', sec_method) # parse properties input_file =", "sure about format for spin-polarized case! I assume it is", "repeats=False, unit=key_unit[1])) self._convergence_keys_mapping = { 'x_exciting_effective_potential_convergence': ( r'RMS change in", "dtype=str), Quantity( 'n_scf_iterations', r'Number of (?:total)* scf iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int),", "None: number = frequency_data.get('number') sec_method.gw.number_of_frequencies = len(number) sec_method.gw.frequency_number = number", "['Total energy', 'total energy'], 'x_exciting_fermi_energy': ['Fermi energy', 'Fermi'], 'energy_kinetic_electronic': ['Kinetic", "sec_method = sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft = sec_method.m_create(DFT) sec_electronic = sec_method.m_create(Electronic)", "for optimization_step in structure_optimization.get('optimization_step', []): sec_scc = parse_configuration(optimization_step) if optimization_step.get('method')", "self.number_of_dos)) for i in range(len(self.partial_dos)): spin = self.partial_dos[i].attrib.get(self._nspin_key, None) if", "[e.attrib.get(self._energy_key) for e in self.bands[n][i]]) for nkpts_segment in self.number_of_k_points_per_segment: end", "v[-1]).group(1) elif v[0].startswith('atom'): v[0] = v[0].split() v[1] = [float(vi) for", "r'imized atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions',", "def str_to_eigenvalue(val_in): val = val_in.strip().split('\\n') kpts = np.array(val[0].split(), dtype=float) keys", "val_l = self.partial_dos[i].attrib.get(self._l_key, None) val_m = self.partial_dos[i].attrib.get(self._m_key, None) if val_l", "= 'l' self._m_key = 'm' self._energy_key = 'e' self._dos_key =", "f.endswith(file_ext)] options.sort() filenames = [os.path.join(self.info_parser.maindir, f) for f in options]", "if self.get_exciting_files(f): self._calculation_type = 'gw' gw_info_file = f break if", "+ nkpts_segment band_energy = np.array([np.transpose(band)[start:end] for band in bands]) if", "contributions charge_contributions = iteration.get('charge_contributions', {}) for key, names in self._electron_charge_keys_mapping.items():", "+ 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1] sec_charges =", "len(self.get('structure_optimization', {}).get('optimization_step', [])) def get_number_of_spin_channels(self): spin_treatment = self.get('initialization', {}).get( 'x_exciting_spin_treatment',", "len(number) sec_method.gw.frequency_number = number sec_method.gw.frequency_values = frequency_data.get('values') sec_method.gw.frequency_weights = frequency_data.get('weights')", "of empty states', None), 'x_exciting_valence_states': ('Total number of valence states',", "= val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1] sec_charges = msection.m_create(Charges) sec_charges.value =", "convert=False, unit=ureg.hartree / ureg.bohr), Quantity( 'step', r'Optimization step\\s*(\\d+)', repeats=False, dtype=int),", "Quantity( 'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent in this optimization step\\s*:\\s*[\\d\\.]+", "section): labels = section.get('symbols') if labels is None: # we", "# parse properties input_file = self.get_exciting_files('input.xml') if not input_file: return", "f in gw_info_files: if self.get_exciting_files(f): self._calculation_type = 'gw' gw_info_file =", "read q points qpoints = self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity, ext): #", "self._quantities = [] def str_to_frequency(val_in): val = [v.split() for v", "name in self.info_parser._convergence_keys_mapping.keys(): val = iteration.get(name) if val is None:", "(r'G\\-vector grid sizes', None), 'x_exciting_gvector_total': (r'Total number of G\\-vectors', None),", ") class ExcitingEvalqpParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities =", "= [] for i in range(len(self.vertices) - 1): start =", "step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False, dtype=float), Quantity( 'time', r'Time spent in this", "sec_dos_values.value = dos[spin] # TODO add PDOS def _parse_bandstructure_dat(self, sec_scc):", "children of xs if self.input_xml_parser.get('xs/screening') is not None: sec_method.x_exciting_xs_screening_number_of_empty_states =", "BandstructureXMLParser(XMLParser): def __init__(self, **kwargs): # TODO make a parent class", "is not necessary as this is done in parser, however", "sec_scc) frequency_data = self.info_gw_parser.get('frequency_data', None) if frequency_data is not None:", "None) val_m = self.partial_dos[i].attrib.get(self._m_key, None) if val_l is None or", "+ int(val_l) atom = i // (self.number_of_lm * self.number_of_spin_channels) res[lm][spin][atom]", "@property def bands(self): if self._bands is None: bands = self.root.findall('./%s'", "in range(len(partialdos[lm][spin])): sec_dos_values = sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind = 'spherical' sec_dos_values.lm", "r'Lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=ureg.bohr, repeats=False, convert=False), Quantity( 'lattice_vectors_reciprocal', r'Reciprocal lattice", "['interstitial'], 'x_exciting_total_MT_moment': ['total moment in muffin-tins'], 'x_exciting_total_moment': ['total moment'], 'x_exciting_section_MT_moment_atom':", "section if section.get('energy_total') is not None else section.get('final') if final", "= 'diagram' self._l_key = 'l' self._m_key = 'm' self._energy_key =", "atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities = [ Quantity(", "self.input_xml_parser.get( 'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14) rgkmax =", "Quantity('file', r'parameters loaded from *: *(.+)'), Quantity('name', r'name *: *(.+)'),", "name.endswith('OUT'): parser = self.band_out_parser parser_function = self._parse_band_out elif name.startswith('input') and", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "f positions = self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors = self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3)) species", "n_excitons)) def parse_epsilon(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data))", "Quantity, XMLParser, DataTextParser from nomad.datamodel.metainfo.simulation.run import Run, Program from nomad.datamodel.metainfo.simulation.method", "self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation) exchange = self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange) sec_xc_functional =", "r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?' class GWInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities =", "in diagram], dtype=float) return dos def parse(self, key): if self._results", "+= 2 * li + 1 return self._nlm @property def", "def get_atom_positions(self, section={}, positions=None, positions_format=None): positions = positions if positions", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "'x_exciting_gvector_size': (r'G\\-vector grid sizes', None), 'x_exciting_gvector_total': (r'Total number of G\\-vectors',", "fermi energy: it is used to un-shift the band structure", "not None: break return positions_format def get_atom_positions(self, section={}, positions=None, positions_format=None):", "the # ones with the missing quantity if len(quantity) <", "return sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters = self.fermisurf_parser.get('band_parameters', None) if band_parameters", "ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1] elif quantity == 'SIGMA'", "ureg.elementary_charge), 'x_exciting_IBS_force_convergence': ( r'Abs\\. change in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree / ureg.bohr)}", "Quantity('type', r'Exchange-correlation type +: +(\\S+)'), Quantity( 'name_reference', r'\\n *(.+?,.+)', str_operation=lambda", "if self._calculation_type == 'volume_optimization': sec_method.x_exciting_volume_optimization = True def parse_scc(self, section):", "self.dos_out_parser parser_function = self._parse_dos_out elif name.startswith('bandstructure') and name.endswith('dat'): parser =", "for module in ['groundstate', 'hybrids']: sec_scc = parse_configuration(self.info_parser.get(module)) if sec_scc", "= self.input_xml_parser.get( 'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get( 'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude", "self._neigs_segment = len(self.bands[0]) // self.number_of_spin_channels return self._neigs_segment def parse(self, key):", "properties def str_to_quantity_tolerances(val_in): return val_in.strip().replace('(', '').replace(')', '').split() def str_to_energy_dict(val_in): val", "= self.root.findall('./%s' % self._band_key) self._bands = [] if bands: self._bands.append(bands)", "mixing', repeats=False, flatten=False) ) initialization_quantities.append(Quantity( 'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[", "= logger if logger is not None else logging self._calculation_type", "ureg.hartree eigs_gw = get_data('E_GW') if eigs_gw[0] is None: return nspin", "optimization step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity( 'final', r'Force convergence target", "= sec_run.method[-1] return sec_scc # groundstate and hybrids calculation for", "if self._neigs_segment is None: data = np.transpose(self.data) self._neigs_segment = int(max(data[0]))", "sec_gw_eigenvalues.n_kpoints = len(eigs_gw) sec_gw_eigenvalues.kpoints = get_data('k_points') sec_gw_eigenvalues.energies = reshape(eigs_gw) sec_gw_eigenvalues.value_exchange", "= self.logger self.evalqp_parser.logger = self.logger self.dos_out_parser.logger = self.logger self.bandstructure_dat_parser.logger =", "0) sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlxas', [0, 0]) if self.input_xml_parser.get('xs/tddft') is", "'x_exciting_unit_cell_volume': ('Unit cell volume', ureg.bohr ** 3), 'x_exciting_brillouin_zone_volume': ('Brillouin zone", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= self.input_xml_parser.get('gw/ngridq', [1, 1, 1]) sec_gw.basis_set = 'mixed' sec_gw.qp_equation_treatment =", "None: self._nspin = 1 return self._nspin @property def number_of_k_points_per_segment(self): if", "'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get( 'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get(", "vi properties[v[0].strip()] = vi * unit properties['atom_resolved'] = atom_resolved return", "setattr(msection, name, val) # other metainfo for name in self.info_parser._miscellaneous_keys_mapping.keys():", "self._natoms = len(partial_dos) return self._natoms @property def number_of_dos(self): if self._ndos", "n_optimization_steps(self): return len(self.get('structure_optimization', {}).get('optimization_step', [])) def get_number_of_spin_channels(self): spin_treatment = self.get('initialization',", "'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage': ['core leakage'], 'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge':", "[{}])[0].get('force_convergence', [0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance = threshold_force def parse_method(self): sec_run =", "np.transpose(self.data) n_kpoints = np.where(data[0] == data[0][0])[0][1] bands = data[1:] bands", "val else: setattr(msection, name, val) # energy, moment, charge contributions", "band_energies = np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float) for i in", "self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3)) species = self.input_xml_parser.get('structure/species/speciesfile') if positions is None", "mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = filename.rsplit('.', 1)", "for v in data]) res = res.reshape((len(res), len(data), len(res[0]) //", "is None: return positions = np.dot(positions, cell.magnitude) return positions *", "= np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end = np.array( self.vertices[i + 1].attrib.get(self._coord_key).split(),", "step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity( 'final', r'Force convergence target achieved([\\s\\S]+?Opt)',", "band structure from one of the files bs_files = ['bandstructure.xml',", "elif name.startswith('bandstructure') and name.endswith('dat'): parser = self.bandstructure_dat_parser parser_function = self._parse_bandstructure_dat", "# you may not use this file except in compliance", "for name in names: val = energy_contributions.get(name, None) if val", "energy', 'Hartree'], 'x_exciting_hartree_energy': ['Hartree energy', 'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy', 'electron-nuclear", "moment contributions moment_contributions = iteration.get('moment_contributions', {}) for key, names in", "*Time', repeats=False, str_operation=str_to_array, convert=False, unit=ureg.hartree / ureg.bohr), Quantity( 'step', r'Optimization", "'geometry_optimization' sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization) threshold_force = structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence', [0.,", "EnergyEntry(value=val)) else: setattr(msection, key, val) if key == 'x_exciting_fermi_energy': sec_energy.fermi", "self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return self._energy_unit @property def number_of_spin_channels(self): if self._nspin is", "self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf = self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list = [ 'TET'", "for f in gw_files: self.parse_file(f, sec_scc) frequency_data = self.info_gw_parser.get('frequency_data', None)", "'%s.%s' % (filepath, target[1]) filepath = os.path.join(self.info_parser.maindir, filepath) if os.path.isfile(filepath)", "_parse_dos_out(self, sec_scc): data = self.dos_out_parser.data if data is None: return", "self.get('hybrids', {})) return reference.get('scf_iteration', [{}])[-1].get( name, [None, None])[-1] def get_scf_quantity(self,", "if not info_volume: break sec_scc.calculations_path.append(info_volume[0]) def init_parser(self): self.info_parser.mainfile = self.filepath", "self._distances @property def number_of_spin_channels(self): if self._nspin is None: self._nspin =", "unit=ureg.hartree, repeats=False, dtype=float), Quantity( 'time', r'Time spent in this optimization", "lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file = self.get_exciting_files('input.xml')", "(target[0], suffix) if target[1:]: filename = '%s.%s' % (filename, target[1])", "# convergence values for name in self.info_parser._convergence_keys_mapping.keys(): val = iteration.get(name)", "r'\\n *(.+?,.+)', str_operation=lambda x: [v.strip() for v in x.split(':')]), Quantity(", "if len(quantity) < n_scf: quantity = [None] * (n_scf -", "not None else section.get('final') if final is None: # get", "lattice_vectors lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal if len(sec_run.system)", "and ext == 'FXC': sec_scc = sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0])", "section.get('positions') if positions is None: species = self.get_initialization_parameter('species', []) if", "sec_method) # parse properties input_file = self.get_exciting_files('input.xml') if not input_file:", "include other xcf xc_functional_map = { 2: ['LDA_C_PZ', 'LDA_X_PZ'], 3:", "Quantity( 'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False) ) self._quantities.append( Quantity( 'fermi_energy',", "to global metainfo. This is killing me! if metainfo_name ==", "energy', 'correlation'], 'energy_sum_eigenvalues': ['Sum of eigenvalues', 'sum of eigenvalues'], 'x_exciting_effective_potential_energy':", "+ energy_fermi def _parse_band_out(self, sec_scc): self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies =", "else: setattr(msection, key, val) if key == 'x_exciting_fermi_energy': sec_energy.fermi =", "= self._parse_dos_out elif name.startswith('bandstructure') and name.endswith('dat'): parser = self.bandstructure_dat_parser parser_function", "self.input_xml_parser.get( 'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get( 'xs/BSE/xasedge', 'K') sec_method.x_exciting_xs_bse_xasspecies =", "408: ['HYB_GGA_XC_HSE03']} xc_functional = self.get('initialization', {}).get('xc_functional', None) if xc_functional is", "for f in options if f.endswith(file_ext)] options.sort() filenames = [os.path.join(self.info_parser.maindir,", "= { 2: ['LDA_C_PZ', 'LDA_X_PZ'], 3: ['LDA_C_PW', 'LDA_X_PZ'], 4: ['LDA_C_XALPHA'],", "[Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False, dtype=str, flatten=False)] initialization_quantities = [", "sec_run = self.archive.run[-1] # two versions of gw info files", "partialdos = partialdos.to('1/joule').magnitude lm_values = np.column_stack((np.arange(len(partialdos)), np.zeros(len(partialdos), dtype=np.int32))) for lm", "msection.m_create(Charges) sec_charges.value = [ val[n][1].magnitude for n in range(len(val))] *", "* ureg.hartree return res sec_eigenvalues = sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints = self.eigval_parser.get('k_points')", "as this is done in parser, however nspin is #", "Quantity('radial_points', rf'radial points in muffin-tin *: *({re_float})', dtype=np.int32), Quantity('positions_format', r'atomic", "= self.band_out_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints", "= positions sec_atoms.labels = atom_labels sec_atoms.periodic = [True] * 3", "sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_dat_parser.band_k_points nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment for", "None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1]", "self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization module stopped', sub_parser=TextParser(quantities=[ Quantity( 'optimization_step',", "None self._nspin = None self._nlm = None self._energies = None", "return # volume optimizations volume_index = 1 while True: info_volume", "return energy return np.array([d[1].get(key) for d in data]) * ureg.hartree", "('Total number of valence states', None), 'x_exciting_hamiltonian_size': ('Maximum Hamiltonian size',", "val = val_in.strip().split('\\n') properties = dict() atom_resolved = [] species", "if input_GW.xml does not exist self._quantities.append( Quantity( 'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)',", "None: bands = self.root.findall('./%s' % self._band_key) self._bands = [] if", "versions, input_gw.xml and input-gw.xml for f in ['input_gw.xml', 'input-gw.xml', 'input.xml']:", "= self.input_xml_parser.get( 'gw/scrcoul/scrtype', 'rpa') def parse_gw(self): sec_run = self.archive.run[-1] #", "= int(max(data[0])) return self._neigs_segment class BandOutParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs)", "energy_fermi def _parse_band_out(self, sec_scc): self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.band_out_parser.band_energies", "'positions', rf'\\d+ : *({re_float}) *({re_float}) *({re_float})', repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing',", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "('Number of empty states', None), 'x_exciting_valence_states': ('Total number of valence", "sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius') positions_format = specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format = positions_format positions", "TODO add support for info.xml, wannier.out if name.startswith('dos') and name.endswith('xml'):", "for d in data]) elif key == 'Znk': return np.array([d[1].get(key,", "0 l_list = set([int(e.attrib.get(self._l_key)) for e in self.partial_dos]) for li", "init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True))", "sec_dos.energies = data[0][0] * ureg.hartree + energy_fermi volume = self.info_parser.get_unit_cell_volume()", "= dist[:n_k_points] return self._distances @property def number_of_spin_channels(self): if self._nspin is", "else: spin = int(spin) - 1 val_l = self.partial_dos[i].attrib.get(self._l_key, None)", "achieved\\. Performing final SCF iteration|Reached self-consistent loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities),", "(n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape( data[4], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im =", "self._quantities.append( Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True)) class BandstructureDatParser(DataTextParser):", "count += 1 self._nkpts_segment.append(count) return self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if", "val_in[:val_in.rfind('\\n \\n')].strip() val = np.array([v.split() for v in val.split('\\n')], dtype=float)", "spent in this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False, dtype=float) ] self._quantities.append(Quantity(", "self.archive.run[-1] # TODO read from xml file def get_files(name): bse_types", "'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic energy', 'core electron kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion", "[] def str_to_frequency(val_in): val = [v.split() for v in val_in.split('\\n')]", "np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end = np.array( self.vertices[i + 1].attrib.get(self._coord_key).split(), dtype=float)", "/ self.energy_unit) elif 'partial' in key: if not self.partial_dos: return", "= np.transpose(self.data) n_kpoints = int(max(data[1])) bands = data[6:] bands =", "= self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax = rgkmax sec_method.x_exciting_xs_scissor = self.input_xml_parser.get('xs/scissor', 0.0)", "file_ext = default.split('.')[-1] mainfile_base = mainfile.rsplit('.', 1)[0].replace('INFO', '') options =", "name, key_unit in self._system_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0],", "[None])[0] if fermi_surface is None: return sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters", "case when there is a mismatch between files self.logger.warn( 'Mismatch", "r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'imized atomic positions\\s*\\(([a-z]+)\\)'), Quantity(", "n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im = np.reshape( data[2], (n_components, n_sigma)) def parse_loss(data, sec_scc):", "sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n + 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value =", "self._diagram_key)) return self._total_dos @property def partial_dos(self): if self._partial_dos is None:", "atom_resolved = [] species = None for v in val:", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_' in name: sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB' in name:", "species = self.get_initialization_parameter('species', []) for specie in species: positions_format =", "None @property def energy_unit(self): if self._energy_unit is None: axis =", "['Sum of eigenvalues', 'sum of eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective potential energy'],", "str_to_frequency(val_in): val = [v.split() for v in val_in.split('\\n')] val =", "data = np.transpose(self.data) n_kpoints = int(max(data[1])) bands = data[6:] bands", "'DFT' smearing_kind_map = { 'Gaussian': 'gaussian', 'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac': 'fermi',", "(nspin, len(occs) // nspin)) data['eigenvalues'] = np.reshape(eigs, (nspin, len(eigs) //", "'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron", "self.bandstructure_dat_parser.band_energies if band_energies is None: return # Get fermi energy:", "None), 'x_exciting_kpoint_offset': (r'k\\-point offset', None), 'x_exciting_number_kpoints': (r'Total number of k\\-points',", "# TODO I am not sure about format for spin-polarized", "= [ f for f in os.listdir( self.info_parser.maindir) if target[0]", "*: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic mass *: *({re_float})', dtype=np.float64,", "Apache License, Version 2.0 (the \"License\"); # you may not", "eigs] self._quantities.append( Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True)) class", "logger): self.filepath = filepath self.archive = archive self.logger = logger", "n_epsilon = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies =", "return self._distances @property def number_of_spin_channels(self): if self._nspin is None: self._nspin", "This is the case when there is a mismatch between", "get_initialization_parameter(self, key, default=None): return self.get('initialization', {}).get(key, default) class ExcitingParser: def", "data[4], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape( data[5], (n_components, n_excitons)) def", "for v in val: v = v.split(':') if len(v) <", "structure_optimization = self.info_parser.get('structure_optimization') if structure_optimization is not None: sec_worfklow.type =", "self.distances[i] == self.distances[i - 1]: self._nkpts_segment .append(count) count = 1", "= dict(hartree=ureg.hartree) def init_parameters(self): self._ndos = None self._natoms = None", "point in self.bands[0][0]] self._distances = np.array(self._distances, dtype=float) return self._distances @property", "None: sec_scc.energy = Energy(fermi=fermi_energy) gw_files = ['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT'] #", "np.array([v.split() for v in val.split('\\n')], dtype=float) val = np.transpose(val) occs", "labels += [specie.get('symbol')] * len(specie.get('positions')) return labels def get_positions_format(self, section):", "smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind is not None: if not", "start = self.vertices[i].attrib.get(self._coord_key).split() end = self.vertices[i + 1].attrib.get(self._coord_key).split() res.append([start, end])", "len(data) // nspin, 2)) data = np.transpose(data, axes=(2, 0, 1))", "info_volume = self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2, '0')) if not info_volume: break", "Energy, EnergyEntry, Charges, Forces, ForcesEntry, ScfIteration, BandGap ) from nomad.datamodel.metainfo.workflow", "= self.root.findall('./%s' % self._partialdos_key) self._natoms = len(partial_dos) return self._natoms @property", "self.fermisurf_parser.get('fermi_energy', None) if fermi_energy is not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface = fermi_energy", "0]) if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get( 'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge =", "r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization module stopped', sub_parser=TextParser(quantities=[ Quantity( 'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n", "'xs/tddft/drude', [0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel", "unit = ureg.elementary_charge elif 'moment' in val_in: unit = ureg.elementary_charge", "'spin-unpolarised' else 2 return n_spin def get_unit_cell_volume(self): return self.get('initialization', {}).get('x_exciting_unit_cell_volume',", "repeats=False, dtype=int), Quantity( 'force_convergence', r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree", "sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str),", "(n_components, n_loss)) # TODO check if format of files are", "None self._distances = None self._species = None @property def distances(self):", "*[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False)] self._miscellaneous_keys_mapping = { 'x_exciting_gap': (r'Estimated fundamental", "return if key == 'band_energies': # TODO I am not", "start = end res.append(res_n) elif key == 'band_k_points': res =", "key_unit in self._system_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1],", "str_operation=str_to_band_parameters, repeats=False)) self._quantities.append( Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree, repeats=True)) class", "None: continue metainfo_name = 'x_exciting_scf_threshold_%s_change' % name.split('_')[-2] setattr(sec_method, metainfo_name, threshold)", "Forces, ForcesEntry, ScfIteration, BandGap ) from nomad.datamodel.metainfo.workflow import Workflow, GeometryOptimization", "def get_atom_labels(self, section): labels = section.get('symbols') if labels is None:", "of gw info files gw_info_files = ['GW_INFO.OUT', 'GWINFO.OUT'] for f", "sec_scc is None: # This is the case when there", "also other energies are reported. energy_fermi = 0.0 * ureg.hartree", "continue if '_X_' in name: sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_' in name:", "sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get( 'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get( 'xs/tddft/kerndiag', False)", "x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi is not None: setattr(msection, 'x_exciting_dos_fermi',", "clathrate info clathrate_file = self.get_exciting_files('str.out') if clathrate_file: sec_system.x_exciting_clathrates = True", "= potential_mixing return sec_system def parse_configurations(self): sec_run = self.archive.run[-1] def", "{}).get('optimization_step', [])) def get_number_of_spin_channels(self): spin_treatment = self.get('initialization', {}).get( 'x_exciting_spin_treatment', 'spin-unpolarised')", "vii in v[1].split()] vi = vi[0] if len(vi) == 1", "'m' self._energy_key = 'e' self._dos_key = 'dos' self._unit_key = 'unit'", "sec_energy.fermi = val # charge contributions charge_contributions = iteration.get('charge_contributions', {})", "r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree, repeats=True)) class ExcitingEigenvalueParser(TextParser): def __init__(self): super().__init__(None) def", "if self._nspin is None: self._nspin = np.shape(np.transpose(self.data))[0] - 6 return", "self.root.find('./%s/%s' % (self._totaldos_key, self._diagram_key)) self._ndos = len(total_dos) return self._ndos @property", "elif name.startswith('input') and name.endswith('xml'): parser = self.input_xml_parser if self._calculation_type ==", "if val is None: continue if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_',", "self._calculation_type == 'xs': parser_function = self._parse_input_xs else: # TODO implement", "rf'nuclear charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic charge *:", "res * (1 / self.energy_unit) elif key == 'energies': return", "structure to # the original scale in which also other", "positions = np.vstack([s.get('positions') for s in species]) if positions is", "in range(len(val)): sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n + 1", "the files: bs_files = ['bandstructure-qp.dat', 'BAND-QP.OUT'] for fname in bs_files:", "['GW_INFO.OUT', 'GWINFO.OUT'] for f in gw_info_files: if self.get_exciting_files(f): self._calculation_type =", "= self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf = self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list = [", "self._partial_dos = self.root.findall('./%s/%s' % (self._partialdos_key, self._diagram_key)) return self._partial_dos @property def", "= dict() data['occupancies'] = np.reshape(occs, (nspin, len(occs) // nspin)) data['eigenvalues']", "elif xstype.lower() == 'tddft': self._parse_xs_tddft() def _parse_input_gw(self, sec_method): sec_gw =", "forces forces = section.get('forces') if forces is not None: sec_forces", "sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] # parse input xml", "self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is None: self._nkpts_segment =", "Quantity( 'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity(", "bs_files: if self.file_exists(fname): exciting_files.append(fname) break # Parse DFT band structure", "d in data]) else: energy = np.array([d[1].get(key, None) for d", "if self._band_energies is None: if self.data is None: return data", "== 'EXCITON': sec_scc = sec_run.m_create(Calculation) sccs.append(sec_scc) else: sec_scc = sccs[i]", "BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser = GWInfoParser() self.input_xml_parser = XMLParser() self.data_xs_parser = DataTextParser()", "= sec_worfklow.m_create(GeometryOptimization) threshold_force = structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence', [0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance", "= self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get( 'xs/nempty', 5) sec_method.x_exciting_xs_ngridq =", "bandstructure are added as separate section_k_band res = [] for", "return self._neigs_segment def parse(self, key): if self._results is None: self._results", "self.data_clathrate_parser.logger = self.logger def reuse_parser(self, parser): self.info_parser.quantities = parser.info_parser.quantities self.eigval_parser.quantities", "sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation type +: +(\\S+)'), Quantity( 'name_reference', r'\\n *(.+?,.+)',", "0.])[-1] sec_geometry_opt.input_force_maximum_tolerance = threshold_force def parse_method(self): sec_run = self.archive.run[-1] sec_method", "= np.hstack([np.reshape(v[key], (nspin, np.size(v[key]) // nspin)) for v in data])", "val if len(v) == 3], float)) return dict( number=np.array(val[0], dtype=int),", "'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols',", "this is overwritten when setting mainfile self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies", "'totaldos' self._partialdos_key = 'partialdos' self._diagram_key = 'diagram' self._l_key = 'l'", "and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3] def parse_xs(self): sec_run", "f in files if f.endswith('QMT%s.OUT' % str(i + 1).rjust(3, '0'))]", "= files[n] parser_function(section) # free up memory parser.mainfile = None", "self.partial_dos: return res = np.zeros(( self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos)) for", "if sec_scc is None: return # volume optimizations volume_index =", "self.get_initialization_parameter('lattice_vectors') if cell is None: return positions = np.dot(positions, cell.magnitude)", "\"\"\" mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = filename.rsplit('.',", "ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape( data[3], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape(", "in compliance with the License. # You may obtain a", "gw_files = ['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT'] # Parse GW band structure", "the files bs_files = ['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat'] for fname in", "for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break # Parse", "n_scf = len(self.get('energy_total_scf_iteration', [])) quantity = self.get('%s_scf_iteration' % name) if", "= iteration.get('energy_contributions', {}) for key, names in self._energy_keys_mapping.items(): val =", "is None: data = np.transpose(self.data)[0] self._neigs_segment = len(np.where(data == data[0])[0])", "all files related to quantity at all qpoints files =", "not None else logging self._calculation_type = None self.init_parser() sec_run =", "self._vertices @property def number_of_spin_channels(self): if self._nspin is None: self._nspin =", "steps are the # ones with the missing quantity if", "['Coulomb energy', 'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb energy', 'Coulomb'], 'energy_exchange': ['Exchange energy',", "= ExcitingEigenvalueParser() self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser() self.evalqp_parser = ExcitingEvalqpParser() self.dos_out_parser =", "self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get( 'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel =", "= self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance", "sec_system for name in self.info_parser._system_keys_mapping.keys(): val = self.info_parser.get_initialization_parameter(name) if val", "Quantity( 'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False)) def str_to_band_parameters(val_in): val =", "n in range(len(self.bands)): res_n = [] start = 0 band_energies", "it by concatenating species symbols species = self.get('initialization', {}).get('species', [])", "lm_values[lm] sec_dos_values.spin = spin sec_dos_values.atom_index = atom sec_dos_values.value = partialdos[lm][spin][atom]", "correct, i.e. columns are supposed # to be what they", "= len(self.bands[0]) // self.number_of_spin_channels return self._neigs_segment def parse(self, key): if", "{ 'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage': ['core leakage'], 'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge': ['interstitial'],", "self.get_exciting_files('%s_%s%s%s.OUT' % (quantity, file_ext, ext, fxctype)) data = [[], [],", "sec_method.x_exciting_volume_optimization = True def parse_scc(self, section): sec_run = self.archive.run[-1] final", "vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1 / ureg.bohr, repeats=False, convert=False), ] self._system_keys_mapping =", "@property def band_energies(self): if self._band_energies is None: data = np.transpose(self.data)", "'Coulomb potential'], 'energy_xc_potential': ['xc potential energy', 'xc potential'], 'energy_electrostatic': ['Hartree", "+ 1 return self._nlm @property def total_dos(self): if self._total_dos is", "or name.endswith('TXT')): parser = self.evalqp_parser parser_function = self._parse_evalqp elif name.startswith('TDOS')", "iteration.get(name) if val is None: continue if name == 'time':", "None) sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap is not None: sec_gap.value_fundamental", "str_operation=str_to_eigenvalues, repeats=True)) class ExcitingGWOutParser(TextParser): def __init__(self, mainfile, logger): super().__init__(mainfile, logger=logger)", "sec_gw_eigenvalues.kpoints = get_data('k_points') sec_gw_eigenvalues.energies = reshape(eigs_gw) sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx')) eigs_gw_C", "(n_components, n_sigma)) def parse_loss(data, sec_scc): n_components = len(data) data =", "self._diagram_key)) return self._partial_dos @property def energies(self): if self._energies is None:", "charge contributions charge_contributions = iteration.get('charge_contributions', {}) for key, names in", "= [ point.attrib.get(self._distance_key) for point in self.bands[0][0]] self._distances = np.array(self._distances,", "self.root.findall('./*/%s' % self._atom_key) for band in bands_atom: self._bands.append(band.findall('./%s' % self._band_key))", "return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic)", "sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value = dos[spin]", "sec_scc is None: return # volume optimizations volume_index = 1", "nspin = self.info_parser.get_number_of_spin_channels() sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = len(data)", "None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax", "bs_files: if self.file_exists(fname): exciting_files.append(fname) break for f in exciting_files: self.parse_file(f,", "1, 1]) sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk', [1, 1, 1]) rgkmax =", "is None: species = self.get_initialization_parameter('species', []) if species: positions =", "= [] for n in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] * len(atoms[n])) if", "sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap is not None: sec_gap.value_fundamental =", "* self.number_of_lm)) // self.number_of_lm else: spin = int(spin) - 1", "= optical_band_gap def parse_miscellaneous(self): sec_worfklow = self.archive.m_create(Workflow) sec_worfklow.type = 'single_point'", "for nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb]", "self._distances = dist[:n_k_points] return self._distances @property def number_of_spin_channels(self): if self._nspin", "def parse(self, key): if self._results is None: self._results = dict()", "with the License. # You may obtain a copy of", "Copyright The NOMAD Authors. # # This file is part", "name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' % key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False)) module_quantities =", "(r' APW functions', None), 'x_exciting_nuclear_charge': ('Total nuclear charge', ureg.elementary_charge), 'x_exciting_electronic_charge':", "= fermi_surface def _parse_evalqp(self, sec_scc): data = self.evalqp_parser.get('kpoints_eigenvalues') if data", "== 1. else 1 data = dict() data['occupancies'] = np.reshape(occs,", "% (name, bse_type, scr_type)) bse_files.append(files) return bse_files def get_data(files): data", "= [sec_scc_ref] # parse properties gw_info_files = self.get_exciting_files(gw_info_file) if len(gw_info_files)", "[]) for specie in species: sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels =", "kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): self._nspin =", "mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = default.rsplit('.', 1)", "am not sure about format for spin-polarized case! I assume", "'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get(", "= GWInfoParser() self.input_xml_parser = XMLParser() self.data_xs_parser = DataTextParser() self.data_clathrate_parser =", "else: continue try: parse_function(data, sec_scc) except Exception: self.logger.error('Error setting xs", "is stored. \"\"\" mainfile = os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target", "ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total core charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total valence charge',", "['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT'] # Parse GW band structure from one", "in bands]) if self._energy_unit: band_energy = band_energy * self._energy_unit self._band_energies.append(band_energy)", "if self.file_exists(fname): exciting_files.append(fname) break # Parse DFT band structure from", "@property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data = np.transpose(self.data)", "from nomad.datamodel.metainfo.workflow import Workflow, GeometryOptimization from .metainfo.exciting import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\", "except in compliance with the License. # You may obtain", "or atom_labels is None: return sec_system = sec_run.m_create(System) sec_atoms =", "sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface", "(n_components, n_epsilon)) def parse_sigma(data, sec_scc): n_components = len(data) data =", "*(.+?,.+)', str_operation=lambda x: [v.strip() for v in x.split(':')]), Quantity( 'parameters',", "self.logger.error('Error setting xs data', data=dict(file=quantity)) def _parse_xs_tddft(self): sec_run = self.archive.run[-1]", "self._band_energies.append(band_energy) start = end return self._band_energies @property def distances(self): if", "ureg.bohr ** 3), 'x_exciting_brillouin_zone_volume': ('Brillouin zone volume', 1 / ureg.bohr", "'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge': ['total charge in muffin-tins', 'total", "data[1:3] def parse_xs(self): sec_run = self.archive.run[-1] xs_info_files = self.get_exciting_files('INFOXS.OUT') if", "final = section if section.get('energy_total') is not None else section.get('final')", "is None: return sec_system = self.parse_system(section) if sec_system is not", "sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get( 'xs/BSE/xas', False)", "'coord' self._energy_key = 'eval' self._vertex_key = 'vertex' self._band_key = 'band'", "'volume_optimization': sec_method.x_exciting_volume_optimization = True def parse_scc(self, section): sec_run = self.archive.run[-1]", "'full') if self.input_xml_parser.get('xs/BSE') is not None: sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get( 'xs/BSE/aresbse',", "CONDITIONS OF ANY KIND, either express or implied. # See", "return else: return files = self.get_exciting_files(name) if len(files) > 1:", "in data]) else: energy = np.array([d[1].get(key, None) for d in", "val = [v.split() for v in val_in.split('\\n')] val = np.transpose(np.array([v", "'band_segm_labels': res = [] for i in range(len(self.vertices) - 1):", "* ureg.joule).to('hartree') sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = self.dos_parser.number_of_dos sec_dos.energies", "in x.split(':')]), Quantity( 'parameters', r'\\n *(.+?:.+)', repeats=True, str_operation=lambda x: [v.strip()", "= True self.data_clathrate_parser.mainfile = clathrate_file[0] if self.data_clathrate_parser.data: data = np.transpose(self.data_clathrate_parser.data)", "if name == 'time': msection.time_calculation = val else: setattr(msection, name,", "the files bs_files = ['dos.xml', 'TDOS.OUT'] for fname in bs_files:", "+ nkpts_segment band_energy = np.array([ np.transpose(energy)[start:end] for energy in band_energies])", "atom_resolved return properties def str_to_quantity_tolerances(val_in): return val_in.strip().replace('(', '').replace(')', '').split() def", "None: self._nkpts_segment = [] count = 1 for i in", "species species = self.info_parser.get_initialization_parameter('species', []) for specie in species: sec_atoms_group", "bands = data[6:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints))", "if self.dos_parser.get('totaldos', None) is None: return # Get fermi energy:", "all qpoints files = self.get_exciting_files('%s_%s%s%s.OUT' % (quantity, file_ext, ext, fxctype))", "in epsilon which is not parsed? sccs = [] for", "self._convergence_keys_mapping = { 'x_exciting_effective_potential_convergence': ( r'RMS change in effective potential", "is not None: sec_system.x_exciting_potential_mixing = potential_mixing return sec_system def parse_configurations(self):", "is not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface = band_parameters[0] sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface", "range(len(self.total_dos)): spin = self.total_dos[i].attrib.get(self._nspin_key, i) res[i] = self._get_dos(self._total_dos[i]) if self.energy_unit", "np.reshape( data[2], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape( data[3],", "if self.input_xml_parser.get('xs/tddft') is not None: sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get( 'xs/tddft/acont', False)", "* ureg.hartree if sec_scc.energy is not None: energy_fermi = sec_scc.energy.fermi", "= self.fermisurf_parser.get('band_parameters', None) if band_parameters is not None: sec_fermisurface.x_exciting_number_of_bands_fermi_surface =", "in names: val = charge_contributions.get(name, None) if val is not", "I am not certain about the format for the spin", "= [] def str_to_frequency(val_in): val = [v.split() for v in", "charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved'] } self._moment_keys_mapping = { 'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment':", "sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape( data[0], (n_components, n_sigma)) * ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re =", "// n_components sec_scc.x_exciting_xs_bse_loss_energies = np.reshape( data[0], (n_components, n_loss)) * ureg.hartree", "reshape(get_data('Sc')) if eigs_gw_C is None: eigs_gw_C = reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation =", "self._energy_unit = kwargs.get('energy_unit', None) self._units_mapping = dict(hartree=ureg.hartree) def init_parameters(self): self._ndos", "gw_info_files: if self.get_exciting_files(f): self._calculation_type = 'gw' gw_info_file = f break", "first!') self.info_gw_parser.mainfile = gw_info_files[0] fermi_energy = self.info_gw_parser.get('fermi_energy', None) if fermi_energy", "ureg.bohr atoms = self.input_xml_parser.get('structure/species/atom') atom_labels = [] for n in", "repeats=False, convert=False)] self._miscellaneous_keys_mapping = { 'x_exciting_gap': (r'Estimated fundamental gap', ureg.hartree),", "1. else 1 data = dict() data['occupancies'] = np.reshape(occs, (nspin,", "= rgkmax sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get( 'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get(", "name @property def n_optimization_steps(self): return len(self.get('structure_optimization', {}).get('optimization_step', [])) def get_number_of_spin_channels(self):", "# This file is part of NOMAD. # See https://nomad-lab.eu", "'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get(", "xml file sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref =", "energies(self): if self._energies is None: if self.total_dos is None: return", "np.shape(np.transpose(self.data)[1:])[0] return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is None:", "[] files_q = [f for f in files if f.endswith('QMT%s.OUT'", "if val is None: continue if name == 'x_exciting_spin_treatment': sub_sec", "make a parent class for dos and bandstructure super().__init__(None) self._distance_key", "positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True,", "BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) )", "self.get('%s_scf_iteration' % name) if quantity is None: return # this", "# method goes first since reference needed for sec_scc self.parse_method()", "get_number_of_spin_channels(self): spin_treatment = self.get('initialization', {}).get( 'x_exciting_spin_treatment', 'spin-unpolarised') n_spin = 1", "sec_xc_functional.reference = xc_functional.get('name_reference', [None, None])[1] sec_electronic.n_spin_channels = self.info_parser.get_number_of_spin_channels() if self._calculation_type", "name.endswith('xml'): parser = self.dos_parser parser_function = self._parse_dos elif name.startswith('bandstructure') and", "self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file = self.get_exciting_files('input.xml') if positions is None: #", "if sec_run.system: sec_scc.system_ref = sec_run.system[-1] sec_scc_ref = sec_run.calculation[0] sec_scc.starting_calculation_ref =", "data_q = np.transpose(data_q, axes=(2, 0, 1)) for j in range(len(data)):", "sub_sec = sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment = val elif name == 'x_exciting_species_rtmin':", "init_quantities(self): self._quantities = [] def str_to_frequency(val_in): val = [v.split() for", "charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False), Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict,", "val is None: continue if key == 'x_exciting_section_MT_moment_atom': for n", "self.archive.m_create(Workflow) sec_worfklow.type = 'single_point' structure_optimization = self.info_parser.get('structure_optimization') if structure_optimization is", "data[0][0])[0][1] bands = data[1:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues,", "GWInfoParser() self.input_xml_parser = XMLParser() self.data_xs_parser = DataTextParser() self.data_clathrate_parser = DataTextParser(dtype=str)", "for key, names in self._moment_keys_mapping.items(): val = None for name", "v.strip().split(':') if len(v) < 2: continue elif v[0].startswith('species'): species =", "self.input_xml_parser.get('xs/xstype', None) if xstype is not None: sec_method.x_exciting_xs_xstype = xstype", "# TODO implement reading of parameters from input.xml for normal", "self.dos_parser.number_of_dos sec_dos.energies = self.dos_parser.energies + energy_fermi volume = self.info_parser.get_unit_cell_volume() totaldos", "files. Will read all!', data=dict(file=name)) for n in range(len(files)): parser.mainfile", "NOMAD. # See https://nomad-lab.eu for further info. # # Licensed", "np.vstack([s.get('positions') for s in species]) if positions is None: return", "# TODO smearing with should have units of energy sec_smearing.width", "= 'e' self._dos_key = 'dos' self._unit_key = 'unit' self._energy_unit =", "'K') sec_method.x_exciting_xs_bse_xasspecies = self.input_xml_parser.get( 'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlxas',", "optical_band_gap = self.info_gw_parser.get('optical_band_gap', None) if optical_band_gap is not None: sec_gap.value_optical", "volume.to('m**3').magnitude for spin in range(len(dos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin", "dtype=int), values=val[1] * ureg.hartree, weights=val[2]) # TODO Read also input", "== 3], float)) return dict( number=np.array(val[0], dtype=int), values=val[1] * ureg.hartree,", "= self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] self.parse_file('input.xml', sec_method)", "if final is None else final if final is None:", "valence states', None), 'x_exciting_hamiltonian_size': ('Maximum Hamiltonian size', None), 'x_exciting_pw': (r'Maximum", "name.endswith('bxsf'): parser = self.fermisurf_parser parser_function = self._parse_fermisurface elif name.startswith('EVALQP') and", "= np.reshape( data[3], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape( data[4], (n_components,", "sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format',", "self._results = dict() if not self.bands: return if key ==", "nspin, len(data[0]))) sec_gw_eigenvalues = sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands =", "= iteration.get('moment_contributions', {}) for key, names in self._moment_keys_mapping.items(): val =", "sec_run.program = Program( name='exciting', version=self.info_parser.get('program_version', '').strip()) # method goes first", "def get_scf_threshold(self, name): reference = self.get('groundstate', self.get('hybrids', {})) return reference.get('scf_iteration',", "have the quantity # the only thing that we can", "# simply write parameters xc_functional = self.info_parser.get('initialization', {}).get('xc_functional') if xc_functional", "10) sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get( 'xs/nempty', 5) sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq', [1,", "= [f for f in files if f.endswith('QMT%s.OUT' % str(i", "module stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities = [ Quantity( 'atomic_positions', r'(Atomic", "{ 'x_exciting_gap': (r'Estimated fundamental gap', ureg.hartree), 'time': (r'Wall time \\(seconds\\)',", "number_of_spin_channels(self): if self._nspin is None: if not self.total_dos: return self._nspin", "species: sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number'))", "+= 1 self._nkpts_segment.append(count) return self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if self._neigs_segment", "if xstype.lower() == 'bse': self._parse_xs_bse() elif xstype.lower() == 'tddft': self._parse_xs_tddft()", "bandstructure file # atom-resolved bandstructure are added as separate section_k_band", "for further info. # # Licensed under the Apache License,", "is not None: sec_forces = sec_scc.m_create(Forces) sec_forces.total = ForcesEntry(value=forces) #", "iterations scf_iterations = section.get('scf_iteration', []) for scf_iteration in scf_iterations: sec_scf_iteration", "str_operation=str_to_atom_properties_dict, repeats=False, convert=False)] self._miscellaneous_keys_mapping = { 'x_exciting_gap': (r'Estimated fundamental gap',", "= ureg.elementary_charge * ureg.bohr val = val_in.strip().split('\\n') properties = dict()", "return # this is really problematic if some scf steps", "20: ['GGA_C_PBE', 'GGA_X_PBE'], 21: ['GGA_C_PBE', 'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26:", "scr_types = ['full', 'diag', 'noinvdiag', 'longrange'] bse_files = [] for", "sec_scc) # forces forces = section.get('forces') if forces is not", "xc_functional = self.get('initialization', {}).get('xc_functional', None) if xc_functional is None: return", "rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax = rgkmax", "self._band_k_points is None: data = np.transpose(self.data) self._band_k_points = [] start", "self._ndos = None self._natoms = None self._nspin = None self._nlm", "except Exception: self.logger.warn('Error setting metainfo.') # species species = self.info_parser.get_initialization_parameter('species',", "return self.get('initialization', {}).get('x_exciting_unit_cell_volume', 1.0 * ureg.bohr ** 3) def get_initialization_parameter(self,", "in l_list: self._nlm += 2 * li + 1 return", "'bse': self._parse_xs_bse() elif xstype.lower() == 'tddft': self._parse_xs_tddft() def _parse_input_gw(self, sec_method):", "= partialdos[lm][spin][atom] def _parse_bandstructure(self, sec_scc): # we need to set", "dict() data['occupancies'] = np.reshape(occs, (nspin, len(occs) // nspin)) data['eigenvalues'] =", "energy_fermi volume = self.info_parser.get_unit_cell_volume() totaldos = self.dos_parser.get('totaldos') * volume.to('m**3').magnitude for", "calculation for module in ['groundstate', 'hybrids']: sec_scc = parse_configuration(self.info_parser.get(module)) if", "occupancies which is problematic sometimes res = np.hstack([np.reshape(v[key], (nspin, np.size(v[key])", "be what they are. What is the fourth column in", "'pade') sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance = self.input_xml_parser.get( 'gw/mixbasis/epsmb',", "None: sec_system.x_exciting_potential_mixing = potential_mixing return sec_system def parse_configurations(self): sec_run =", "fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break # Parse DFT", "parse_function = parse_exciton elif quantity == 'EPSILON': parse_function = parse_epsilon", "maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity(", "first since reference needed for sec_scc self.parse_method() self.parse_configurations() self.parse_gw() self.parse_xs()", "self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' % (name, bse_type, scr_type)) bse_files.append(files) return bse_files def", "('Brillouin zone volume', 1 / ureg.bohr ** 3), 'x_exciting_number_of_atoms': ('Total", "self.input_xml_parser.get('xs/tddft') is not None: sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get( 'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity", "= ExcitingInfoParser() self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser =", "is None: return # Get fermi energy: it is used", "archive self.logger = logger if logger is not None else", "unit=key_unit[1], repeats=False)) module_quantities = [ Quantity( 'scf_iteration', r'(?:I| i)teration number", "gmb * gmaxvr sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average =", "by applicable law or agreed to in writing, software #", "n_excitons sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape( data[1], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies", "sec_scc = parse_configuration(optimization_step) if optimization_step.get('method') is not None: sec_scc.x_exciting_geometry_optimization_method =", "elif name.startswith('bandstructure') and name.endswith('xml'): parser = self.bandstructure_parser parser_function = self._parse_bandstructure", "= np.array(val[2].split(), dtype=float) vector = np.array([v.split() for v in val[3:6]],", "sec_scc_ref = sec_run.calculation[0] sec_scc.starting_calculation_ref = sec_scc_ref sec_scc.calculations_ref = [sec_scc_ref] #", "mesh = np.array(val[1].split(), dtype=int) origin = np.array(val[2].split(), dtype=float) vector =", "def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None) self._energy_unit =", "energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=1 / ureg.hartree), Quantity( 'charge_contributions', r'(?:Charges|Electron", "]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree / ureg.bohr, repeats=False, dtype=float), Quantity( 'energy_total', r'Total", "['Nuclear-nuclear energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy': ['Madelung energy', 'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic", "i in range(len(files)): data = get_data(files[i]) if not data: sccs.append(None)", "reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands = len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints = len(eigs_gw) sec_gw_eigenvalues.kpoints = get_data('k_points')", "sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands = len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints = len(eigs_gw) sec_gw_eigenvalues.kpoints", "specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius') positions_format = specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format = positions_format", "= charge_contributions.get('total charge') elif key == 'charge_total': pass else: setattr(msection,", "return self._bands @property def vertices(self): if self._vertices is None: self._vertices", "x: [v.strip() for v in x.split(':')])])) ) self._quantities.append(Quantity( 'initialization', r'(?:All", "xcf xc_functional_map = { 2: ['LDA_C_PZ', 'LDA_X_PZ'], 3: ['LDA_C_PW', 'LDA_X_PZ'],", "self.partial_dos]) for li in l_list: self._nlm += 2 * li", "sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft = sec_method.m_create(DFT) sec_electronic = sec_method.m_create(Electronic) sec_electronic.method = 'DFT'", "sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade')", "Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_dat_parser.band_k_points nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment", "return [nbands, mesh, origin, vector] self._quantities.append( Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters,", "sub_parser=TextParser(quantities=module_quantities) )) def get_atom_labels(self, section): labels = section.get('symbols') if labels", "= [] files_q = [f for f in files if", "def _parse_dos_out(self, sec_scc): data = self.dos_out_parser.data if data is None:", "= self.input_xml_parser.get('xs/tddft/aresdf', True) file_ext_list = [ 'TET' if tetradf else", "= [ Quantity( 'atomic_positions', r'(Atomic positions at this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[", "not None: sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get( 'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get(", "= self.input_xml_parser.get( 'xs/BSE/xasspecies', 0) sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlxas', [0, 0])", "= mainfile.strip('INFO.OUT') target = filename.rsplit('.', 1) filepath = '%s%s' %", "'mpd') sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb',", "TODO I am not certain if screening/BSE are children of", "key_unit in self._method_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1],", "None: sec_worfklow.type = 'geometry_optimization' sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization) threshold_force = structure_optimization.get(", "ureg.hartree return res sec_eigenvalues = sec_scc.m_create(BandEnergies) sec_eigenvalues.kpoints = self.eigval_parser.get('k_points') sec_eigenvalues.occupations", "applicable law or agreed to in writing, software # distributed", "Quantity( 'positions_format', r'Atomic positions at this step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)',", "unit=1 / ureg.hartree), Quantity( 'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False,", "if len(v) == 3], float)) return dict( number=np.array(val[0], dtype=int), values=val[1]", "+ 1].attrib.get(self._coord_key).split() res.append([start, end]) else: res = None self._results[key] =", "target = filename.rsplit('.', 1) filepath = '%s%s' % (target[0], suffix)", "n_kpoints = int(max(data[1])) bands = data[6:] bands = np.reshape(bands, (", "volume = self.info_parser.get_unit_cell_volume() dos = data[1] * (1 / ureg.hartree)", "See https://nomad-lab.eu for further info. # # Licensed under the", "Quantity( 'positions_format', r'imized atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str),", "positions * ureg.bohr def get_scf_threshold(self, name): reference = self.get('groundstate', self.get('hybrids',", "= parse_epsilon elif quantity == 'SIGMA': parse_function = parse_sigma elif", "= self.archive.run[-1] sec_method = sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft = sec_method.m_create(DFT) sec_electronic", "does not exist self._quantities.append( Quantity( 'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False)", "self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2, '0')) if not info_volume: break sec_scc.calculations_path.append(info_volume[0]) def", "elif quantity == 'EPSILON': parse_function = parse_epsilon elif quantity ==", "lattice symmetries', None), 'x_exciting_number_of_crystal_symmetries': ('Number of crystal symmetries', None), 'x_exciting_kpoint_grid':", "= self.filepath self.info_parser.logger = self.logger self.dos_parser.logger = self.logger self.bandstructure_parser.logger =", "1]) sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk', [1, 1, 1]) rgkmax = self.input_xml_parser.get('xs/rgkmax',", "sec_eigenvalues.kpoints = self.eigval_parser.get('k_points') sec_eigenvalues.occupations = get_data('occupancies') sec_eigenvalues.energies = get_data('eigenvalues') def", "None or species is None: continue lattice_vectors = np.array(lattice_vectors, dtype=float)", "ureg.hartree), 'x_exciting_energy_convergence': ( r'Absolute change in total energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence':", "xs_info_files: return self._calculation_type = 'xs' # inconsistency in the naming", "data = np.transpose(self.data) self._distances = data[5][:int(max(data[1]))] return self._distances @property def", "def energies(self): if self._energies is None: if self.total_dos is None:", "type +: +(\\S+)'), Quantity( 'name_reference', r'\\n *(.+?,.+)', str_operation=lambda x: [v.strip()", "= threshold_force def parse_method(self): sec_run = self.archive.run[-1] sec_method = sec_run.m_create(Method)", "clathrate_file[0] if self.data_clathrate_parser.data: data = np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates = np.transpose( np.array(data[:3],", "def band_k_points(self): if self._band_k_points is None: data = np.transpose(self.data) self._band_k_points", "symmetries', None), 'x_exciting_kpoint_grid': (r'k\\-point grid', None), 'x_exciting_kpoint_offset': (r'k\\-point offset', None),", "'x_exciting_number_of_bravais_lattice_symmetries': ('Number of Bravais lattice symmetries', None), 'x_exciting_number_of_crystal_symmetries': ('Number of", "= 'gw' gw_info_file = f break if not self._calculation_type ==", "positions is None or atom_labels is None: return sec_system =", "dict( number=np.array(val[0], dtype=int), values=val[1] * ureg.hartree, weights=val[2]) # TODO Read", "val = val_in.strip().split('\\n') energies = dict() for v in val:", "spin = int(spin) - 1 val_l = self.partial_dos[i].attrib.get(self._l_key, None) val_m", "nb in range(len(band_energies[n])): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints", "'time', r'Time spent in this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False, dtype=float)", "filenames = [filename] filenames = [f for f in filenames", "self.bandstructure_dat_parser parser_function = self._parse_bandstructure_dat elif name.startswith('BAND') and name.endswith('OUT'): parser =", "int(max(data[0])) return self._neigs_segment class BandOutParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin", "atom_resolved.append(((species, v[1] * unit))) else: vi = [float(vii) for vii", "(name.startswith('FERMISURF') or name.startswith('FS')) and name.endswith('bxsf'): parser = self.fermisurf_parser parser_function =", "n in range(len(val))] * val[0][1].units sec_charges.total = charge_contributions.get('total charge') elif", "np.array( self.vertices[i + 1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i])) elif key", "key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False)) module_quantities = [ Quantity( 'scf_iteration', r'(?:I|", "data_q: continue data_q = np.transpose(data_q, axes=(2, 0, 1)) for j", "numpy as np import os import re import logging from", "atom = i // (self.number_of_lm * self.number_of_spin_channels) res[lm][spin][atom] = self._get_dos(self.partial_dos[i])", "SCF iteration|Reached self-consistent loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions',", "sec_method_ref sec_method.methods_ref = [sec_method_ref] self.parse_file('input.xml', sec_method) # parse properties input_file", "int(val_m) + int(val_l) atom = i // (self.number_of_lm * self.number_of_spin_channels)", "[]) for n in range(len(band_energies)): # Get fermi energy: it", "self.eigval_parser = ExcitingEigenvalueParser() self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser() self.evalqp_parser = ExcitingEvalqpParser() self.dos_out_parser", "self.partial_dos is None: return self._nlm = 0 l_list = set([int(e.attrib.get(self._l_key))", "Quantity( 'step', r'Optimization step\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'method', r'method\\s*=\\s*(\\w+)', repeats=False,", "return self.input_xml_parser.mainfile = input_file[0] xstype = self.input_xml_parser.get('xs/xstype', '') if xstype.lower()", "sec_run = self.archive.run[-1] positions = self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors')", "filename) if os.path.isfile(filename): return [filename] filename = os.path.join(self.info_parser.maindir, default) if", "self.input_xml_parser.get( 'xs/tddft/drude', [0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001, 'hartree')", "range(len(dos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin sec_dos_values.value =", "= os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = filename.rsplit('.', 1) filepath", "self._quantities.append( Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*', unit=ureg.hartree, repeats=True)) class ExcitingEigenvalueParser(TextParser): def", "energy_fermi = energy_fermi.to(\"hartree\") sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi", "ureg.hartree) * volume.to('m**3').magnitude for spin in range(len(dos)): sec_dos_values = sec_dos.m_create(DosValues,", "APW functions', None), 'x_exciting_nuclear_charge': ('Total nuclear charge', ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total", "r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)',", "and is accessible in the same folder where the mainfile", "# TODO confirm no cell optimization in exciting sec_atoms.lattice_vectors =", "0]) rgkmax = self.input_xml_parser.get('xs/screening/rgkmax', None) if rgkmax is None: rgkmax", "options] else: filenames = [filename] filenames = [f for f", "(smearing_width * ureg.hartree).to('joule') # TODO smearing with should have units", "self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors = self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3)) species = self.input_xml_parser.get('structure/species/speciesfile') if", "\"License\"); # you may not use this file except in", "TODO Read also input parameters here if input_GW.xml does not", "energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence': ( r'Charge distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence': ( r'Abs\\.", "% key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1], repeats=False)) module_quantities = [ Quantity( 'scf_iteration',", "Exception: self.logger.warn('Error setting metainfo.') # species species = self.info_parser.get_initialization_parameter('species', [])", "[ Quantity( 'scf_iteration', r'(?:I| i)teration number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True),", "is not None: break if val is None: continue if", "def number_of_dos(self): if self._ndos is None: total_dos = self.root.find('./%s/%s' %", "= reshape(eigs_gw) sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx')) eigs_gw_C = reshape(get_data('Sc')) if eigs_gw_C", "e]) # read q points qpoints = self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity,", "point in diagram], dtype=float) return dos def parse(self, key): if", "if f.endswith(file_ext)] options.sort() filenames = [os.path.join(self.info_parser.maindir, f) for f in", "= np.transpose(np.array([v.split() for v in val[2:]], dtype=float)) eigs = {keys[i]:", "* gmaxvr sec_gw.bare_coulomb_cutofftype = self.input_xml_parser.get( 'gw/barecoul/cutofftype', 'none') sec_gw.screened_coulomb_volume_average = self.input_xml_parser.get(", "continue if quantity == 'EXCITON': sec_scc = sec_run.m_create(Calculation) sccs.append(sec_scc) else:", "val_in.strip().split('\\n')] val = val[0] if len(val) == 1 else val", "'triplet', 'RPA'] scr_types = ['full', 'diag', 'noinvdiag', 'longrange'] bse_files =", "= np.reshape(eigs, (nspin, len(eigs) // nspin)) return data self._quantities.append( Quantity(", "False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get( 'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get( 'xs/tddft/aresdf',", "s in species]) if positions is None: return positions =", "os.access(filepath, os.F_OK): return True return False def _parse_dos(self, sec_scc): if", "self.eigval_parser.quantities = parser.eigval_parser.quantities self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities self.evalqp_parser.quantities = parser.evalqp_parser.quantities self.info_gw_parser.quantities", "None: data = np.transpose(self.data) self._distances = data[5][:int(max(data[1]))] return self._distances @property", "scr_type in scr_types: files = self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' % (name, bse_type,", "sec_method if sec_run.system: sec_scc.system_ref = sec_run.system[-1] sec_scc_ref = sec_run.calculation[0] sec_scc.starting_calculation_ref", "return data = np.transpose(self.data) n_kpoints = int(max(data[1])) bands = data[6:]", "self._method_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) )", "i // (self.number_of_lm * self.number_of_spin_channels) res[lm][spin][atom] = self._get_dos(self.partial_dos[i]) if self.energy_unit", "= sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref =", "= parser.eigval_parser.quantities self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities self.evalqp_parser.quantities = parser.evalqp_parser.quantities self.info_gw_parser.quantities =", "self.number_of_spin_channels][i] = np.array( [e.attrib.get(self._energy_key) for e in self.bands[n][i]]) for nkpts_segment", "get_data(quantity, ext) if not data[0]: continue if quantity == 'EPSILON'", "None self._energies = None self._total_dos = None self._partial_dos = None", "* ureg.hartree, weights=val[2]) # TODO Read also input parameters here", "BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser = BandOutParser(energy_unit=ureg.hartree) self.info_gw_parser = GWInfoParser() self.input_xml_parser = XMLParser()", "sec_gw.basis_set = 'mixed' sec_gw.qp_equation_treatment = 'linearization' sec_gw.max_frequency = self.input_xml_parser.get( 'gw/freqgrid/freqmax',", "positions_format positions = specie.get('positions') positions = self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions", "@property def number_of_spin_channels(self): if self._nspin is None: self._nspin = np.shape(np.transpose(self.data)[1:])[0]", "== 'band_energies': # TODO I am not certain about the", "in val: v = v.strip().split(':') if len(v) < 2: continue", "xml file, there seems to be two versions, input_gw.xml and", "None: spin = (i % (self.number_of_spin_channels * self.number_of_lm)) // self.number_of_lm", "in range(len(self.total_dos)): spin = self.total_dos[i].attrib.get(self._nspin_key, i) res[i] = self._get_dos(self._total_dos[i]) if", "* val[0][1].units sec_charges.total = charge_contributions.get('total charge') elif key == 'charge_total':", "stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities = [ Quantity( 'atomic_positions', r'(Atomic positions", "it is # energy dos_up dos_down nspin = self.info_parser.get_number_of_spin_channels() sec_dos", "break # Parse DFT band structure from one of the", "self.input_xml_parser.get( 'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlbse', [0, 0, 0,", "further info. # # Licensed under the Apache License, Version", "v[0][2] atom_resolved.append(((species, v[1] * unit))) else: vi = [float(vii) for", "= totaldos[spin] partialdos = self.dos_parser.get('partialdos') if partialdos is None: return", "= self.info_gw_parser.get('frequency_data', None) if frequency_data is not None: number =", "repeats=False, dtype=float, unit=1 / ureg.hartree), Quantity( 'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]',", "Quantity( 'scf_iteration', r'(?:I| i)teration number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity(", "* ureg.bohr lattice_vectors = lattice_vectors * ureg.bohr atoms = self.input_xml_parser.get('structure/species/atom')", "= self.input_xml_parser.get('structure/species/speciesfile') if positions is None or lattice_vectors is None", "val = None for name in names: val = charge_contributions.get(name,", "1 / ureg.bohr ** 3), 'x_exciting_number_of_atoms': ('Total number of atoms", "= self.info_parser.get_unit_cell_volume() totaldos = self.dos_parser.get('totaldos') * volume.to('m**3').magnitude for spin in", "in options] else: filenames = [filename] filenames = [f for", "'step', r'Optimization step\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'method', r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str),", "self.evalqp_parser parser_function = self._parse_evalqp elif name.startswith('TDOS') and name.endswith('OUT'): parser =", "= DataTextParser() self.data_clathrate_parser = DataTextParser(dtype=str) # different names for different", "ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points =", "def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] def str_to_frequency(val_in):", "self.file_exists(fname): exciting_files.append(fname) break # Parse DFT band structure from one", "xs if self.input_xml_parser.get('xs/screening') is not None: sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get( 'xs/screening/nempty',", "options = [f for f in options if f.endswith(file_ext)] options.sort()", "'x_exciting_IBS_force_convergence': ( r'Abs\\. change in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree / ureg.bohr)} for", "str_to_eigenvalues(val_in): val = val_in[:val_in.rfind('\\n \\n')].strip() val = np.array([v.split() for v", "get_data('E_GW') if eigs_gw[0] is None: return nspin = self.info_parser.get_number_of_spin_channels() def", "v in val])) else: try: setattr(sec_system, name, val) except Exception:", "fname in bs_files: if self.file_exists(fname): gw_files.append(fname) break for f in", "sec_geometry_opt.input_force_maximum_tolerance = threshold_force def parse_method(self): sec_run = self.archive.run[-1] sec_method =", "data]) res = res.reshape((len(res), len(data), len(res[0]) // len(data))) if key", "section.get('positions_format') if positions_format is None: species = self.get_initialization_parameter('species', []) for", "= 1 for i in range(1, len(self.distances)): if self.distances[i] ==", "in bse_types: for scr_type in scr_types: files = self.get_exciting_files( '%s_BSE%s_SCR%s.OUT'", "self.input_xml_parser.get('xs/BSE/rgkmax', None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0)", "= int(spin) - 1 val_l = self.partial_dos[i].attrib.get(self._l_key, None) val_m =", "TextParser, Quantity, XMLParser, DataTextParser from nomad.datamodel.metainfo.simulation.run import Run, Program from", "are really correct, i.e. columns are supposed # to be", "elif key == 'charge_total': pass else: setattr(msection, key, val) #", "@property def n_optimization_steps(self): return len(self.get('structure_optimization', {}).get('optimization_step', [])) def get_number_of_spin_channels(self): spin_treatment", "= len(data) data = np.transpose(np.vstack(data)) n_sigma = len(data[0]) // n_components", "spin in range(len(totaldos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin = spin", "energy', 'core electron kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion correction'] } self._electron_charge_keys_mapping", "== 'band_k_points': res = [] for i in range(len(self.number_of_k_points_per_segment)): start", "not None: band_energy = band_energy * self._energy_unit res_n.append(band_energy) start =", "name == 'x_exciting_spin_treatment': sub_sec = sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment = val elif", "None) if positions_format is not None: break return positions_format def", "volume', ureg.bohr ** 3), 'x_exciting_brillouin_zone_volume': ('Brillouin zone volume', 1 /", "self._energy_unit self._band_energies.append(band_energy) start = end return self._band_energies @property def distances(self):", "None) if rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax", "[0, 0]) if self.input_xml_parser.get('xs/tddft') is not None: sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get(", "functions', 1 / ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum \\|G\\| for potential and", "is None: return [] name = xc_functional_map.get(xc_functional.type, []) return name", "axis = self.root.find('./axis') if axis is None: return self._energy_unit =", "= sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_parser.get('band_k_points') nkpts_segment", "reuse_parser(self, parser): self.info_parser.quantities = parser.info_parser.quantities self.eigval_parser.quantities = parser.eigval_parser.quantities self.fermisurf_parser.quantities =", "eigs = np.transpose(np.array([v.split() for v in val[2:]], dtype=float)) eigs =", "self._get_dos(self.partial_dos[i]) if self.energy_unit is not None: res = res *", "= 'm' self._energy_key = 'e' self._dos_key = 'dos' self._unit_key =", "len(self.distances)), dtype=float) for i in range(len(self.bands[n])): band_energies[i % self.number_of_spin_channels][i] =", "None or lattice_vectors is None or species is None: continue", "== 'SIGMA' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3] elif", "= end return self._band_energies @property def distances(self): if self._distances is", "self.input_xml_parser.get('structure/species/speciesfile') if positions is None or lattice_vectors is None or", "eigs = val[-2] nspin = 2 if occs[0] == 1.", "= 'atom' self._nspin = kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit', None)", "self._unit_key = 'unit' self._energy_unit = kwargs.get('energy_unit', None) self._units_mapping = dict(hartree=ureg.hartree)", "range(len(self.bands[n])): band_energies[i % self.number_of_spin_channels][i] = np.array( [e.attrib.get(self._energy_key) for e in", "Dos, DosValues, BandStructure, BandEnergies, Energy, EnergyEntry, Charges, Forces, ForcesEntry, ScfIteration,", "xc_functional.get('name_reference', [None, None])[0] sec_xc_functional.reference = xc_functional.get('name_reference', [None, None])[1] sec_electronic.n_spin_channels =", "unit=ureg.hartree, repeats=False) ) self._quantities.append( Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) )", "not aresdf else None] file_ext = '_'.join([e for e in", "None for name in names: val = moment_contributions.get(name, None) if", "band_seg_labels = self.bandstructure_parser.get('band_segm_labels') for nb in range(len(band_energies[n])): sec_k_band_segment = sec_k_band.m_create(BandEnergies)", "sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal if len(sec_run.system) > 1: return sec_system for", "parse_loss else: continue try: parse_function(data, sec_scc) except Exception: self.logger.error('Error setting", "info_volume: break sec_scc.calculations_path.append(info_volume[0]) def init_parser(self): self.info_parser.mainfile = self.filepath self.info_parser.logger =", "frequency_data = self.info_gw_parser.get('frequency_data', None) if frequency_data is not None: number", "= None self._band_energies = None self._neigs_segment = None self._nkpts_segment =", "sec_run = self.archive.run[-1] # TODO read from xml file def", "self.dos_parser.energies + energy_fermi volume = self.info_parser.get_unit_cell_volume() totaldos = self.dos_parser.get('totaldos') *", "self.bandstructure_parser.logger = self.logger self.eigval_parser.logger = self.logger self.fermisurf_parser.logger = self.logger self.evalqp_parser.logger", "sec_electronic.m_create(Smearing) smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind is not None: if", "= sec_method.m_create(Electronic) sec_electronic.method = 'DFT' smearing_kind_map = { 'Gaussian': 'gaussian',", "= [] if bands: self._bands.append(bands) # add atom-resolved bands_atom =", "self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] self.parse_file('input.xml', sec_method) #", "you may not use this file except in compliance with", "is None or lattice_vectors is None or species is None:", "is None: axis = self.root.find('./axis') if axis is None: return", "'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent in this optimization step\\s*:\\s*[\\d\\.]+ seconds))',", "val = val_in.strip().split('\\n') nbands = int(val[0]) mesh = np.array(val[1].split(), dtype=int)", "origin = np.array(val[2].split(), dtype=float) vector = np.array([v.split() for v in", "*: *(.+)'), Quantity('nuclear_charge', rf'nuclear charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge',", "Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False) ) self._quantities.append( Quantity( 'direct_band_gap',", "bands_atom = self.root.findall('./*/%s' % self._atom_key) for band in bands_atom: self._bands.append(band.findall('./%s'", "xc_functional_names.append(correlation) exchange = self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange) sec_xc_functional = sec_dft.m_create(XCFunctional) for", "'x_exciting_spin_treatment': ('Spin treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number of Bravais lattice symmetries',", "init_parameters(self): # TODO make a parent clas for bandstructure dat", "res.reshape((len(res), len(data), len(res[0]) // len(data))) if key == 'eigenvalues': res", "for fname in bs_files: if self.file_exists(fname): gw_files.append(fname) break for f", "self._distances = [ point.attrib.get(self._distance_key) for point in self.bands[0][0]] self._distances =", "module stopped', sub_parser=TextParser(quantities=module_quantities) )) def get_atom_labels(self, section): labels = section.get('symbols')", "sec_gap.value_optical = optical_band_gap def parse_miscellaneous(self): sec_worfklow = self.archive.m_create(Workflow) sec_worfklow.type =", "files if f.endswith('QMT%s.OUT' % str(i + 1).rjust(3, '0'))] for f", "module started([\\s\\S]+?)Structure\\-optimization module stopped', sub_parser=TextParser(quantities=[ Quantity( 'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time", "for n in range(len(band_energies)): # Get fermi energy: it is", "if positions is None: # get it from input.xml for", "None self._vertices = None self._distances = None self._species = None", "@property def partial_dos(self): if self._partial_dos is None: self._partial_dos = self.root.findall('./%s/%s'", "range(len(partialdos)): for spin in range(len(partialdos[lm])): for atom in range(len(partialdos[lm][spin])): sec_dos_values", "data]) * ureg.hartree eigs_gw = get_data('E_GW') if eigs_gw[0] is None:", "1) filename = '%s%s' % (target[0], suffix) if target[1:]: filename", "True) sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get( 'xs/tddft/drude', [0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter = self.input_xml_parser.get(", "if occs[0] == 1. else 1 data = dict() data['occupancies']", "= None self._species = None @property def distances(self): if self._distances", "self._nkpts_segment .append(count) count = 1 else: count += 1 self._nkpts_segment.append(count)", "None: dist = np.transpose(self.data)[0] n_k_points = np.where(dist == dist[0])[0][1] self._distances", "sec_gw.number_of_frequencies = int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0))", "_get_dos(self, diagram): dos = np.array( [point.attrib.get(self._dos_key) for point in diagram],", "xstype.lower() == 'tddft': self._parse_xs_tddft() def _parse_input_gw(self, sec_method): sec_gw = sec_method.m_create(GWMethod)", "v in val_in.strip().split('\\n')] val = val[0] if len(val) == 1", "input_file: self.input_xml_parser.mainfile = f correlation = self.input_xml_parser.get('libxc/correlation', None) xc_functional_names.append(correlation) exchange", "files = self.get_exciting_files('%s_%s%s%s.OUT' % (quantity, file_ext, ext, fxctype)) data =", "if self._nspin is None: self._nspin = np.shape(np.transpose(self.data)[1:])[0] return self._nspin @property", "def partial_dos(self): if self._partial_dos is None: self._partial_dos = self.root.findall('./%s/%s' %", "certain if screening/BSE are children of xs if self.input_xml_parser.get('xs/screening') is", "in scr_types: files = self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' % (name, bse_type, scr_type))", "= self.logger self.fermisurf_parser.logger = self.logger self.evalqp_parser.logger = self.logger self.dos_out_parser.logger =", "np.array([d[1].get(key) for d in data]) * ureg.hartree eigs_gw = get_data('E_GW')", "str_operation=lambda x: [v.strip() for v in x.split(':')])])) ) self._quantities.append(Quantity( 'initialization',", "local\\-orbitals', None)} self._method_keys_mapping = { 'smearing_kind': ('Smearing scheme', None), 'smearing_width':", "if self._bands is None: bands = self.root.findall('./%s' % self._band_key) self._bands", "in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.value =", "filename = os.path.join(self.info_parser.maindir, default) if not os.path.isfile(filename): file_ext = default.split('.')[-1]", "r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False), Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]',", "if not self.bands: return self._distances = [ point.attrib.get(self._distance_key) for point", "unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('atomic_mass', rf'atomic", "== 'gw': parser_function = self._parse_input_gw elif self._calculation_type == 'xs': parser_function", "eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective potential energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb potential energy', 'Coulomb", "= self.get_exciting_files('str.out') if clathrate_file: sec_system.x_exciting_clathrates = True self.data_clathrate_parser.mainfile = clathrate_file[0]", "self._partialdos_key = 'partialdos' self._diagram_key = 'diagram' self._l_key = 'l' self._m_key", "0) sec_method.x_exciting_xs_bse_rgkmax = rgkmax sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get( 'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd", "= int(max(data[1])) bands = data[6:] bands = np.reshape(bands, ( self.number_of_spin_channels,", "+ quantity return quantity def get_xc_functional_name(self): # TODO expand list", "and ext == 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3] elif quantity ==", "len(self.bands[0]) // self.number_of_spin_channels return self._neigs_segment def parse(self, key): if self._results", "is None: return positions = np.array(positions) positions_format = positions_format if", "self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.band_out_parser.band_energies if band_energies is None:", "None: sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method') if optimization_step.get('step') is not None: sec_scc.x_exciting_geometry_optimization_step", "] self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization module started([\\s\\S]+?)Structure\\-optimization module stopped', sub_parser=TextParser(quantities=[ Quantity(", "= self.input_xml_parser.get('xs/ngridq', [1, 1, 1]) sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk', [1, 1,", "i in range(len(self.number_of_k_points_per_segment)): start = np.array( self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end =", "sec_scc): self.band_out_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.band_out_parser.band_energies if band_energies is", "not None: smearing_width = (smearing_width * ureg.hartree).to('joule') # TODO smearing", "in ['input_gw.xml', 'input-gw.xml', 'input.xml']: self.parse_file(f, sec_method) xc_functional_name = ' '.join(self.info_parser.get_xc_functional_name())", "key == 'band_segm_start_end': res = [] for i in range(len(self.number_of_k_points_per_segment)):", "len(data) data = np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components = n_components n_excitons = len(data[0])", "= clathrate_file[0] if self.data_clathrate_parser.data: data = np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates = np.transpose(", "== 'spin-unpolarised' else 2 return n_spin def get_unit_cell_volume(self): return self.get('initialization',", "'positions_format', r'Atomic positions\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions',", "elif name == 'x_exciting_species_rtmin': setattr(sec_system, name, ' '.join([str(v) for v", "original scale in which also other energies are reported. energy_fermi", "in self._convergence_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\(\\)\\d\\.\\-\\+Ee ]+)' % key_unit[0], str_operation=str_to_quantity_tolerances, unit=key_unit[1],", "Quantity( 'positions', rf'\\d+ : *({re_float}) *({re_float}) *({re_float})', repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity(", "r'Absolute change in total energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence': ( r'Charge distance\\s*\\(target\\)',", "not None: sec_scc.energy = Energy(fermi=fermi_energy) gw_files = ['EVALQP.DAT', 'EVALQP.TXT', 'TDOS-QP.OUT']", "atom_labels is None: return sec_system = sec_run.m_create(System) sec_atoms = sec_system.m_create(Atoms)", "is not None: energy_fermi = sec_scc.energy.fermi energy_fermi = (energy_fermi.magnitude *", "\\((.+?)\\)', flatten=False), Quantity( 'positions', rf'\\d+ : *({re_float}) *({re_float}) *({re_float})', repeats=True,", "= band_energy * self._energy_unit res_n.append(band_energy) start = end res.append(res_n) elif", "repeats=True)) class ExcitingGWOutParser(TextParser): def __init__(self, mainfile, logger): super().__init__(mainfile, logger=logger) def", "file except in compliance with the License. # You may", "None self._neigs_segment = None self._vertices = None self._distances = None", "self._total_dos is None: self._total_dos = self.root.findall('./%s/%s' % (self._totaldos_key, self._diagram_key)) return", "break for f in gw_files: self.parse_file(f, sec_scc) frequency_data = self.info_gw_parser.get('frequency_data',", "self._nlm = None self._energies = None self._total_dos = None self._partial_dos", "[1, 1, 1]) sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk', [1, 1, 1]) rgkmax", "* ureg.hartree sec_scc.x_exciting_xs_bse_loss = np.reshape( data[1], (n_components, n_loss)) # TODO", "not isinstance(smearing_kind, str): smearing_kind = smearing_kind[0] smearing_kind = smearing_kind_map[smearing_kind] sec_smearing.kind", "names in self._energy_keys_mapping.items(): val = None for name in names:", "if data is None: return # Get fermi energy: it", "= specie.get('symbol') sec_atoms_group.x_exciting_geometry_atom_number = str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius =", "\\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False, str_operation=str_to_array, convert=False, unit=ureg.hartree / ureg.bohr), Quantity( 'step',", "data[0][0][0] * ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:] elif quantity == 'EPSILON'", "self.logger self.dos_out_parser.logger = self.logger self.bandstructure_dat_parser.logger = self.logger self.band_out_parser.logger = self.logger", "[]) for scf_iteration in scf_iterations: sec_scf_iteration = sec_scc.m_create(ScfIteration) parse_scf(scf_iteration, sec_scf_iteration)", "self._electron_charge_keys_mapping.items(): val = None for name in names: val =", "range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.value = band_energies[nb]", "v = v.strip().split(':') if len(v) < 2: continue elif v[0].startswith('species'):", "self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq = self.input_xml_parser.get('gw/ngridq', [1, 1, 1]) sec_gw.basis_set =", "{ 'Gaussian': 'gaussian', 'Methfessel-Paxton': 'methfessel-paxton', 'Fermi-Dirac': 'fermi', 'Extended': 'tetrahedra'} sec_smearing", "None: return return np.reshape(data, (nspin, len(data) // nspin, len(data[0]))) sec_gw_eigenvalues", "keys = val[1].split() eigs = np.transpose(np.array([v.split() for v in val[2:]],", "confirm no cell optimization in exciting sec_atoms.lattice_vectors = lattice_vectors lattice_vectors_reciprocal", "sec_method.x_exciting_xs_tetra = self.input_xml_parser.get( 'xs/tetra/tetradf', False) def _parse_xs_bse(self): sec_run = self.archive.run[-1]", "'xs/tddft/aresdf', False) sec_method.x_exciting_xs_tddft_anti_resonant_xc_kernel = self.input_xml_parser.get( 'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get(", "None in energy: return energy return np.array([d[1].get(key) for d in", "sec_k_band.energy_fermi = energy_fermi nkpts_segment = self.band_out_parser.number_of_k_points_per_segment for nb in range(len(band_energies)):", "self._neigs_segment def parse(self, key): if self._results is None: self._results =", "sec_xc_functional.name = xc_functional.get('name_reference', [None, None])[0] sec_xc_functional.reference = xc_functional.get('name_reference', [None, None])[1]", "we need to set nspin again as this is overwritten", "return self._band_k_points @property def distances(self): if self._distances is None: data", "file sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref", "to include other xcf xc_functional_map = { 2: ['LDA_C_PZ', 'LDA_X_PZ'],", "data', data=dict(file=quantity)) def _parse_xs_tddft(self): sec_run = self.archive.run[-1] fxctype = self.input_xml_parser.get('xs/tddft/fxctype',", "if positions_format == 'lattice': cell = self.get_initialization_parameter('lattice_vectors') if cell is", "if self._energy_unit is None: axis = self.root.find('./axis') if axis is", "= self.fermisurf_parser.get('fermi_energy', None) if fermi_energy is not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface =", "* ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape( data[2], (n_components, n_excitons)) * ureg.hartree", "None) is None: return nspin = self.info_parser.get_number_of_spin_channels() def get_data(key): data", "self.number_of_spin_channels return self._neigs_segment def parse(self, key): if self._results is None:", "sec_fermisurface.x_exciting_number_of_mesh_points_fermi_surface = np.product(band_parameters[1]) sec_fermisurface.x_exciting_grid_fermi_surface = band_parameters[1] sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface", "i in range(len(self.vertices) - 1): start = self.vertices[i].attrib.get('label') end =", "sometimes res = np.hstack([np.reshape(v[key], (nspin, np.size(v[key]) // nspin)) for v", "if not self.partial_dos: return res = np.zeros(( self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms,", "None: sec_xc_functional.name = xc_functional.get('name_reference', [None, None])[0] sec_xc_functional.reference = xc_functional.get('name_reference', [None,", "ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective Wigner radius, r\\_s', ureg.bohr), 'x_exciting_empty_states': ('Number of", "self.dos_parser.get('totaldos') * volume.to('m**3').magnitude for spin in range(len(totaldos)): sec_dos_values = sec_dos.m_create(DosValues,", "is None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') # TODO", "sub_parser=TextParser(quantities=[ Quantity('number', r'Species : *(\\d+)', dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file', r'parameters", "for v in x.split(':')])])) ) self._quantities.append(Quantity( 'initialization', r'(?:All units are", "= None @property def energy_unit(self): if self._energy_unit is None: axis", "self._energy_key = 'e' self._dos_key = 'dos' self._unit_key = 'unit' self._energy_unit", "# TODO read from xml file def get_files(name): bse_types =", "n_spin = 1 if spin_treatment.lower() == 'spin-unpolarised' else 2 return", "= self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions', {}))", "1)) for j in range(len(data)): data[j].append(data_q[j]) return data for quantity", "= 'vertex' self._band_key = 'band' self._atom_key = 'atom' self._nspin =", "is None else final if final is None: return sec_scc", "for n in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] * len(atoms[n])) if positions is", "val) except Exception: self.logger.warn('Error setting metainfo.') # species species =", "parse_function = parse_epsilon elif quantity == 'SIGMA': parse_function = parse_sigma", "ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total valence charge', ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective Wigner radius,", "str_to_band_parameters(val_in): val = val_in.strip().split('\\n') nbands = int(val[0]) mesh = np.array(val[1].split(),", "return self._energies = np.array( [float(point.attrib.get(self._energy_key)) for point in self.total_dos[0]]) if", "'x_exciting_interstitial_moment': ['interstitial'], 'x_exciting_total_MT_moment': ['total moment in muffin-tins'], 'x_exciting_total_moment': ['total moment'],", "dtype=float, unit=1 / ureg.hartree), Quantity( 'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict,", "is None: continue if key == 'x_exciting_section_MT_charge_atom': for n in", "names: val = energy_contributions.get(name, None) if val is not None:", "metainfo. This is killing me! if metainfo_name == 'x_exciting_scf_threshold_energy_change': sec_method.scf", "range(len(partialdos[lm][spin])): sec_dos_values = sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind = 'spherical' sec_dos_values.lm =", "= data[1] * (1 / ureg.hartree) * volume.to('m**3').magnitude for spin", "positions if positions is not None else section.get('positions') if positions", "if final is None: # get it from last scf_iteration", "str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr) ] self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent loop", "it is used to un-shift the band structure to #", "= self.band_out_parser parser_function = self._parse_band_out elif name.startswith('input') and name.endswith('xml'): parser", "# TODO check if format of files are really correct,", "sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get( 'gw/selfenergy/nempty', 0)) sec_gw.self_energy_singularity_treatment = self.input_xml_parser.get( 'gw/selfenergy/singularity', 'mpd')", "for i in range(len(self.number_of_k_points_per_segment)): start = self.vertices[i].attrib.get(self._coord_key).split() end = self.vertices[i", "def number_of_k_points_per_segment(self): if self._nkpts_segment is None: self._nkpts_segment = [] count", "get_data(files[i]) if not data: sccs.append(None) continue if quantity == 'EXCITON':", "self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser = ExcitingEigenvalueParser() self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser() self.evalqp_parser", "continue data_q = np.transpose(data_q, axes=(2, 0, 1)) for j in", "not section: return sec_scc = self.parse_scc(section) if sec_scc is None:", "sec_dos_values.value = totaldos[spin] partialdos = self.dos_parser.get('partialdos') if partialdos is None:", "= i % self.number_of_lm else: lm = int(val_l) ** 2", "return self._nlm @property def total_dos(self): if self._total_dos is None: self._total_dos", "is not None: res = res * (1 / self.energy_unit)", "xc_functional = self.info_parser.get('initialization', {}).get('xc_functional') if xc_functional is not None: sec_xc_functional.name", "This file is part of NOMAD. # See https://nomad-lab.eu for", "( r'Absolute change in total energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence': ( r'Charge", "parse_system(self, section): sec_run = self.archive.run[-1] positions = self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors", "def str_to_energy_dict(val_in): val = val_in.strip().split('\\n') energies = dict() for v", "if sec_method.x_exciting_xs_bse_xas: sec_method.x_exciting_xs_bse_xasatom = self.input_xml_parser.get( 'xs/BSE/xasatom', 0) sec_method.x_exciting_xs_bse_xasedge = self.input_xml_parser.get(", "filepath = os.path.join(self.info_parser.maindir, filepath) if os.path.isfile(filepath) and os.access(filepath, os.F_OK): return", "True) sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get( 'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get( 'xs/BSE/sciavqhd',", "return sec_scc = sec_run.m_create(Calculation) def parse_scf(iteration, msection): energy_total = iteration.get('energy_total')", "None: continue if '_X_' in name: sec_xc_functional.exchange.append(Functional(name=name)) elif '_C_' in", "} self._electron_charge_keys_mapping = { 'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage': ['core leakage'], 'x_exciting_valence_charge':", "= res class ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities", "cell volume', ureg.bohr ** 3), 'x_exciting_brillouin_zone_volume': ('Brillouin zone volume', 1", "% (filepath, target[1]) filepath = os.path.join(self.info_parser.maindir, filepath) if os.path.isfile(filepath) and", "Quantity( 'final', r'(?:Convergence targets achieved\\. Performing final SCF iteration|Reached self-consistent", "if energy_total is not None: sec_energy.total = EnergyEntry(value=energy_total) x_exciting_dos_fermi =", "(self._totaldos_key, self._diagram_key)) self._ndos = len(total_dos) return self._ndos @property def number_of_lm(self):", "( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies = [] start = 0", "return [kpts, eigs] self._quantities.append( Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue,", "sec_system = self.parse_system(section) if sec_system is not None: sec_scc.system_ref =", "self.info_gw_parser.get('fundamental_band_gap', None) sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap) if fundamental_band_gap is not None:", "= self.vertices[i].attrib.get('label') end = self.vertices[i + 1].attrib.get('label') res.append([ '\\u0393' if", "from nomad.datamodel.metainfo.simulation.run import Run, Program from nomad.datamodel.metainfo.simulation.method import ( Method,", "self.fermisurf_parser.get('fermi_surface', [None])[0] if fermi_surface is None: return sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface)", "self._nkpts_segment = None @property def band_energies(self): if self._band_energies is None:", "True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14) rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax', None)", "\\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)', str_operation=str_to_eigenvalue, repeats=True)) class BandstructureDatParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs)", "in self.info_parser._system_keys_mapping.keys(): val = self.info_parser.get_initialization_parameter(name) if val is None: continue", "sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape( data[2], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength =", "[ point.attrib.get(self._distance_key) for point in self.bands[0][0]] self._distances = np.array(self._distances, dtype=float)", "/ ureg.bohr, repeats=False, convert=False), ] self._system_keys_mapping = { 'x_exciting_unit_cell_volume': ('Unit", "'fermi', 'Extended': 'tetrahedra'} sec_smearing = sec_electronic.m_create(Smearing) smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind') if", "EXCITON and file type', data=dict(file=quantity)) sec_scc = sec_run.m_create(Calculation) if quantity", "get_atom_labels(self, section): labels = section.get('symbols') if labels is None: #", "= self.root.findall('./%s/%s' % (self._partialdos_key, self._diagram_key)) return self._partial_dos @property def energies(self):", "mainfile.strip('INFO.OUT') target = filename.rsplit('.', 1) filepath = '%s%s' % (target[0],", "self.bandstructure_parser.get('band_segm_labels') for nb in range(len(band_energies[n])): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints =", "data = np.transpose(np.vstack(data)) n_sigma = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_sigma_energies =", "or species is None: continue lattice_vectors = np.array(lattice_vectors, dtype=float) lattice_vectors", "for specie in species: sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels = specie.get('symbol')", "self.get_initialization_parameter('species', []) if species: positions = np.vstack([s.get('positions') for s in", "cell optimization in exciting sec_atoms.lattice_vectors = lattice_vectors lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter(", "parse_configuration(section): if not section: return sec_scc = self.parse_scc(section) if sec_scc", "repeats=True)) def str_to_eigenvalues(val_in): val = val_in[:val_in.rfind('\\n \\n')].strip() val = np.array([v.split()", "unit=ureg.hartree / ureg.bohr), ]), repeats=False)) self._quantities.append(Quantity( 'hybrids', r'Hybrids module started([\\s\\S]+?)Hybrids", "spent in this optimization step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity( 'final',", "* (n_scf - len(quantity)) + quantity return quantity def get_xc_functional_name(self):", "self._diagram_key = 'diagram' self._l_key = 'l' self._m_key = 'm' self._energy_key", "* (1 / self.energy_unit) elif 'partial' in key: if not", "= np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates = np.transpose( np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels = list(data[3])", "start + nkpts_segment band_energy = np.array([np.transpose(band)[start:end] for band in bands])", "gmb * gmaxvr pwm = self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax = pwm", "[0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance = threshold_force def parse_method(self): sec_run = self.archive.run[-1]", "not necessary as this is done in parser, however nspin", "sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get( 'xs/nempty', 5) sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq', [1, 1,", "'x_exciting_hartree_energy': ['Hartree energy', 'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy', 'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy':", "i.e. columns are supposed # to be what they are.", "'x_exciting_coulomb_energy': ['Coulomb energy', 'Coulomb'], 'energy_exchange': ['Exchange energy', 'exchange'], 'x_exciting_exchange_energy': ['Exchange", "sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3] elif quantity == 'LOSS' and ext ==", "filename = '%s%s' % (target[0], suffix) if target[1:]: filename =", "species = self.get('initialization', {}).get('species', []) labels = [] for specie", "in gw_info_files: if self.get_exciting_files(f): self._calculation_type = 'gw' gw_info_file = f", "dtype=float)])), Quantity( 'forces', r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time',", "self._nspin = None self._nkpts_segment = None self._neigs_segment = None self._vertices", "if optical_band_gap is not None: sec_gap.value_optical = optical_band_gap def parse_miscellaneous(self):", "( Calculation, Dos, DosValues, BandStructure, BandEnergies, Energy, EnergyEntry, Charges, Forces,", "= vi[0] if len(vi) == 1 else vi properties[v[0].strip()] =", "atom_labels sec_atoms.periodic = [True] * 3 # TODO confirm no", "= DataTextParser(dtype=str) # different names for different versions of exciting", "len(quantity) < n_scf: quantity = [None] * (n_scf - len(quantity))", "1 / ureg.bohr), 'x_exciting_gmaxvr': (r'Maximum \\|G\\| for potential and density',", "None: return sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters = self.fermisurf_parser.get('band_parameters', None) if", "break if not self._calculation_type == 'gw': return sec_method = sec_run.m_create(Method)", "end = start + nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end]) start = end", "not None: self._energies = self._energies * self.energy_unit return self._energies def", "ureg from nomad.parsing.file_parser import TextParser, Quantity, XMLParser, DataTextParser from nomad.datamodel.metainfo.simulation.run", "def number_of_spin_channels(self): if self._nspin is None: self._nspin = np.shape(np.transpose(self.data)[1:])[0] return", "'x_exciting_total_MT_charge': ['total charge in muffin-tins', 'total in muffin-tins'], 'charge_total': ['total", "not parsed? sccs = [] for quantity in ['EXCITON', 'EPSILON',", "= ['GW_INFO.OUT', 'GWINFO.OUT'] for f in gw_info_files: if self.get_exciting_files(f): self._calculation_type", "parser, however nspin is # determined from occupancies which is", "data is None: return # Get fermi energy: it is", ")) def get_atom_labels(self, section): labels = section.get('symbols') if labels is", "3)) sec_gw.mixed_basis_tolerance = self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001) gmb = self.input_xml_parser.get('gw/mixbasis/gmb', 1.0)", "this step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)',", "self._bands is None: bands = self.root.findall('./%s' % self._band_key) self._bands =", "what they are. What is the fourth column in epsilon", "= val_in[:val_in.rfind('\\n \\n')].strip() val = np.array([v.split() for v in val.split('\\n')],", "= (energy_fermi.magnitude * ureg.joule).to('hartree') # TODO I am not sure", "# inconsistency in the naming convention for xs input xml", "convergence target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n',", "sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = len(data) // nspin data = np.reshape(data,", "sec_atoms.lattice_vectors = lattice_vectors lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal", "= moment_contributions.get(name, None) if val is not None: break if", "read only first!') self.info_gw_parser.mainfile = gw_info_files[0] fermi_energy = self.info_gw_parser.get('fermi_energy', None)", "# energy, moment, charge contributions parse_scf(final, sec_scc) # forces forces", "smearing_width.magnitude for name in self.info_parser._convergence_keys_mapping.keys(): threshold = self.info_parser.get_scf_threshold(name) if threshold", "Quantity('muffin_tin_radius', rf'muffin-tin radius *: *({re_float})', dtype=np.float64, unit=ureg.bohr), Quantity('radial_points', rf'radial points", "partialdos = self.dos_parser.get('partialdos') if partialdos is None: return partialdos =", "potential_mixing return sec_system def parse_configurations(self): sec_run = self.archive.run[-1] def parse_configuration(section):", "= 'eval' self._vertex_key = 'vertex' self._band_key = 'band' self._atom_key =", "* volume.to('m**3').magnitude for spin in range(len(dos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total)", "= sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = len(data) // nspin data =", "quantity == 'LOSS': parse_function = parse_loss else: continue try: parse_function(data,", "3: ['LDA_C_PW', 'LDA_X_PZ'], 4: ['LDA_C_XALPHA'], 5: ['LDA_C_VBH'], 20: ['GGA_C_PBE', 'GGA_X_PBE'],", "energies self._quantities = [Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False, dtype=str, flatten=False)]", "= None self._nkpts_segment = None self._neigs_segment = None self._bands =", "return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is None: self._nkpts_segment", "* ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points", "continue if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_', '')), EnergyEntry(value=val)) else: setattr(msection,", "xs_info_files = self.get_exciting_files('INFOXS.OUT') if not xs_info_files: return self._calculation_type = 'xs'", "in bs_files: if self.file_exists(fname): exciting_files.append(fname) break for f in exciting_files:", "parse_epsilon(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_epsilon =", "= self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file = self.get_exciting_files('input.xml') if positions is None:", "data = dict() data['occupancies'] = np.reshape(occs, (nspin, len(occs) // nspin))", "val) if key == 'x_exciting_fermi_energy': sec_energy.fermi = val # charge", "sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] self.parse_file('input.xml', sec_method) # parse", "= np.array([v.split() for v in val.split('\\n')], dtype=float) val = np.transpose(val)", "= data[1:3] elif quantity == 'SIGMA' and ext == 'NLF_FXC':", "= np.transpose(self.data) n_kpoints = np.where(data[0] == data[0][0])[0][1] bands = data[1:]", "'frequency_data', r'frequency list:\\s*\\<\\s*#\\s*freqs\\s*weight\\s*>\\s*([\\d\\.Ee\\s\\-]+)', str_operation=str_to_frequency, repeats=False) ) self._quantities.append( Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi", "'FS.bxsf'] # Parse DFT DOS from one of the files", "specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format = positions_format positions = specie.get('positions') positions = self.info_parser.get_atom_positions(", "unit = ureg.elementary_charge * ureg.bohr val = val_in.strip().split('\\n') properties =", "in val if len(v) == 3], float)) return dict( number=np.array(val[0],", "in range(len(self.vertices) - 1): start = self.vertices[i].attrib.get('label') end = self.vertices[i", "return data def parse_exciton(data, sec_scc): n_components = len(data) data =", "'xc potential'], 'energy_electrostatic': ['Hartree energy', 'Hartree'], 'x_exciting_hartree_energy': ['Hartree energy', 'Hartree'],", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "def init_parameters(self): self._nspin = None self._distances = None self._band_energies =", "filename = '%s.%s' % (filename, target[1]) filename = os.path.join(self.info_parser.maindir, filename)", "optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False, dtype=float) ] self._quantities.append(Quantity( 'structure_optimization', r'Structure\\-optimization module", "self._band_energies = [] start = 0 for nkpts_segment in self.number_of_k_points_per_segment:", "= v[1][0] if len(v[1]) == 1 else v[1] if species", "for i in range(len(self.bands[n])): band_energies[i % self.number_of_spin_channels][i] = np.array( [e.attrib.get(self._energy_key)", "key == 'x_exciting_section_MT_moment_atom': for n in range(len(val)): sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom)", "sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape( data[0], (n_components, n_epsilon)) *", "if fundamental_band_gap is not None: sec_gap.value_fundamental = fundamental_band_gap optical_band_gap =", "section): sec_run = self.archive.run[-1] final = section if section.get('energy_total') is", "Quantity( 'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=ureg.hartree), Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n", "self.logger.warn('Found multiple files. Will read all!', data=dict(file=name)) for n in", "EnergyEntry(value=energy_total) x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi') if x_exciting_dos_fermi is not None: setattr(msection,", "XMLParser, DataTextParser from nomad.datamodel.metainfo.simulation.run import Run, Program from nomad.datamodel.metainfo.simulation.method import", "0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw', 10) sec_method.x_exciting_xs_number_of_empty_states = self.input_xml_parser.get( 'xs/nempty',", "self._distances is None: if not self.bands: return self._distances = [", "def number_of_lm(self): if self._nlm is None: if self.partial_dos is None:", "return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') # TODO I am", "Dos.total) sec_dos_values.spin = spin sec_dos_values.value = dos[spin] # TODO add", "in ['groundstate', 'hybrids']: sec_scc = parse_configuration(self.info_parser.get(module)) if sec_scc is None:", "v in val[2:]], dtype=float)) eigs = {keys[i]: eigs[i] for i", "self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent loop started|Groundstate module started)([\\s\\S]+?)Groundstate module stopped', sub_parser=TextParser(quantities=module_quantities),", "in name: sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name)) if not xc_functional_names: # simply", ") self._quantities.append( Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity(", "'LOSS']: files = get_files(quantity) for i in range(len(files)): data =", "= self.archive.run[-1] fxctype = self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf = self.input_xml_parser.get('xs/tetra/tetradf', None)", "change in total energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence': ( r'Charge distance\\s*\\(target\\)', ureg.elementary_charge),", "self._quantities = [Quantity( 'program_version', r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False, dtype=str, flatten=False)] initialization_quantities", "if self.data_xs_parser.data is None: continue data.append(self.data_xs_parser.data) return data def parse_exciton(data,", "1: self.logger.warn('Found multiple GW info files, will read only first!')", "for vi in v[1].split()] v[1] = v[1][0] if len(v[1]) ==", "*\\n\\-{10}|Time spent in this optimization step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity(", "1]) rgkmax = self.input_xml_parser.get('xs/rgkmax', None) if rgkmax is None: rgkmax", "def get_initialization_parameter(self, key, default=None): return self.get('initialization', {}).get(key, default) class ExcitingParser:", "def number_of_spin_channels(self): if self._nspin is None: self._nspin = 1 return", "elif '_C_' in name: sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB' in name: sec_xc_functional.hybrid.append(Functional(name=name))", "['EPSILON', 'LOSS', 'SIGMA']: for ext in ['FXC', 'NLF_FXC']: data =", "fundamental gap', ureg.hartree), 'time': (r'Wall time \\(seconds\\)', ureg.s)} for name,", "targets achieved\\. Performing final SCF iteration|Reached self-consistent loops maximum)([\\s\\S]+?)(\\n *\\n\\+{10})',", "sec_system = sec_run.m_create(System) sec_atoms = sec_system.m_create(Atoms) sec_atoms.positions = positions sec_atoms.labels", "energy', 'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb energy', 'Coulomb'], 'energy_exchange': ['Exchange energy', 'exchange'],", "False) sec_method.x_exciting_xs_tddft_lmax_alda = self.input_xml_parser.get( 'xs/tddft/lmaxalda', 3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get( 'xs/tddft/mdfqtype',", "dos = data[1] * (1 / ureg.hartree) * volume.to('m**3').magnitude for", "None def _parse_input_xs(self, sec_method): xstype = self.input_xml_parser.get('xs/xstype', None) if xstype", "break if val is None: continue if key == 'x_exciting_section_MT_moment_atom':", "'TDOS.OUT'] for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break #", "is not None: sec_xc_functional.name = xc_functional.get('name_reference', [None, None])[0] sec_xc_functional.reference =", "in parser, however nspin is # determined from occupancies which", "Quantity( 'charge_contributions', r'(?:Charges|Electron charges\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False), Quantity( 'moment_contributions',", "None: eigs_gw_C = reshape(get_data('Re(Sc)')) sec_gw_eigenvalues.value_correlation = eigs_gw_C sec_gw_eigenvalues.value_xc_potential = reshape(get_data('Vxc'))", "= None @property def distances(self): if self._distances is None: if", "scf_quantities = [ Quantity( 'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=ureg.hartree),", "self.number_of_k_points_per_segment: end = start + nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end]) start =", "*: *({re_float})', dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin radius *: *({re_float})', dtype=np.float64,", "Quantity('positions_format', r'atomic positions \\((.+?)\\)', flatten=False), Quantity( 'positions', rf'\\d+ : *({re_float})", "rgkmax = self.input_xml_parser.get('xs/screening/rgkmax', None) if rgkmax is None: rgkmax =", "self.logger self.data_xs_parser.logger = self.logger self.data_clathrate_parser.logger = self.logger def reuse_parser(self, parser):", "val[0][1].units sec_charges.total = charge_contributions.get('total charge') elif key == 'charge_total': pass", "= self.dos_parser.energies + energy_fermi volume = self.info_parser.get_unit_cell_volume() totaldos = self.dos_parser.get('totaldos')", "['valence'], 'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge': ['total charge in muffin-tins', 'total in", "energy_total is not None: sec_energy.total = EnergyEntry(value=energy_total) x_exciting_dos_fermi = iteration.get('x_exciting_dos_fermi')", "None: continue setattr(msection, name, val) # other metainfo for name", "parser = self.bandstructure_dat_parser parser_function = self._parse_bandstructure_dat elif name.startswith('BAND') and name.endswith('OUT'):", "if self.distances[i] == self.distances[i - 1]: self._nkpts_segment.append(count) count = 1", "is None: return # this is really problematic if some", "= self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get( 'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel", "is a mismatch between files self.logger.warn( 'Mismatch in EXCITON and", "v[0].startswith('species'): species = re.search(re_symbol, v[-1]).group(1) elif v[0].startswith('atom'): v[0] = v[0].split()", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "len(eigs) // nspin)) return data self._quantities.append( Quantity( 'eigenvalues_occupancies', r'\\(state\\, eigenvalue", "= int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance = self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001) gmb", "'energy_kinetic_electronic': ['Kinetic energy', 'electronic kinetic'], 'energy_coulomb': ['Coulomb energy', 'Coulomb'], 'x_exciting_coulomb_energy':", "sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind = 'spherical' sec_dos_values.lm = lm_values[lm] sec_dos_values.spin =", "not info_volume: break sec_scc.calculations_path.append(info_volume[0]) def init_parser(self): self.info_parser.mainfile = self.filepath self.info_parser.logger", "self.input_xml_parser if self._calculation_type == 'gw': parser_function = self._parse_input_gw elif self._calculation_type", "correction'] } self._electron_charge_keys_mapping = { 'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage': ['core leakage'],", "= None @property def band_energies(self): if self._band_energies is None: data", "None] file_ext = '_'.join([e for e in file_ext_list if e])", "is None: fundamental_band_gap = self.info_gw_parser.get('fundamental_band_gap', None) sec_gap = sec_scc.eigenvalues[-1].m_create(BandGap) if", "= np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies = [] start", "will read only first!') self.info_gw_parser.mainfile = gw_info_files[0] fermi_energy = self.info_gw_parser.get('fermi_energy',", "required by applicable law or agreed to in writing, software", "nspin = 2 if occs[0] == 1. else 1 data", "not None: setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi) # energy contributions energy_contributions =", "of local\\-orbitals', None)} self._method_keys_mapping = { 'smearing_kind': ('Smearing scheme', None),", "energy_fermi is None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') #", "data[0][0] * ureg.hartree + energy_fermi volume = self.info_parser.get_unit_cell_volume() dos =", "diagram], dtype=float) return dos def parse(self, key): if self._results is", "break if val is None: continue if key == 'x_exciting_section_MT_charge_atom':", "sub_parser=TextParser(quantities=[ Quantity( 'optimization_step', r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent in this optimization", "section_k_band res = [] for n in range(len(self.bands)): res_n =", "'total' in key: if not self.total_dos: return res = np.zeros((self.number_of_spin_channels,", "is problematic sometimes res = np.hstack([np.reshape(v[key], (nspin, np.size(v[key]) // nspin))", "agreed to in writing, software # distributed under the License", "gw_info_files = ['GW_INFO.OUT', 'GWINFO.OUT'] for f in gw_info_files: if self.get_exciting_files(f):", "for f in input_file: self.input_xml_parser.mainfile = f positions = self.input_xml_parser.get('structure/species/atom/coord')", "self._nspin is None: self._nspin = 1 return self._nspin @property def", "is None: self._total_dos = self.root.findall('./%s/%s' % (self._totaldos_key, self._diagram_key)) return self._total_dos", "sec_fermisurface = sec_scc.m_create(x_exciting_section_fermi_surface) band_parameters = self.fermisurf_parser.get('band_parameters', None) if band_parameters is", "certain about the format for the spin polarized case #", "same folder where the mainfile is stored. \"\"\" mainfile =", "sec_fermisurface.x_exciting_origin_fermi_surface = band_parameters[2] sec_fermisurface.x_exciting_vectors_fermi_surface = band_parameters[3] fermi_energy = self.fermisurf_parser.get('fermi_energy', None)", "for point in diagram], dtype=float) return dos def parse(self, key):", "'xs/tddft/fxcbsesplit', 0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution =", "None self.init_parser() sec_run = self.archive.m_create(Run) sec_run.program = Program( name='exciting', version=self.info_parser.get('program_version',", "= sec_system.m_create(Atoms) sec_atoms.positions = positions sec_atoms.labels = atom_labels sec_atoms.periodic =", "self._nlm @property def total_dos(self): if self._total_dos is None: self._total_dos =", "f in input_file: self.input_xml_parser.mainfile = f correlation = self.input_xml_parser.get('libxc/correlation', None)", "atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file = self.get_exciting_files('input.xml') if positions is", "total_dos(self): if self._total_dos is None: self._total_dos = self.root.findall('./%s/%s' % (self._totaldos_key,", "for i in range(len(files)): data = get_data(files[i]) if not data:", "scr_types: files = self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' % (name, bse_type, scr_type)) bse_files.append(files)", "energy', 'correlation'], 'x_exciting_correlation_energy': ['Correlation energy', 'correlation'], 'energy_sum_eigenvalues': ['Sum of eigenvalues',", "from nomad.datamodel.metainfo.simulation.method import ( Method, DFT, Electronic, Smearing, XCFunctional, Functional,", "for j in range(len(data)): data[j].append(data_q[j]) return data for quantity in", "not None: sec_forces = sec_scc.m_create(Forces) sec_forces.total = ForcesEntry(value=forces) # scf", "self._nspin @property def number_of_atoms(self): if self._natoms is None: partial_dos =", "repeats=True, str_operation=lambda x: [v.strip() for v in x.split(':')])])) ) self._quantities.append(Quantity(", "sec_gw.frequency_grid_type = self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies = int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16))", "[ Quantity( 'atomic_positions', r'(Atomic positions at this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity(", "gw_info_files[0] fermi_energy = self.info_gw_parser.get('fermi_energy', None) if fermi_energy is not None:", "self.info_parser.logger = self.logger self.dos_parser.logger = self.logger self.bandstructure_parser.logger = self.logger self.eigval_parser.logger", "setattr(msection, name, val) # energy, moment, charge contributions parse_scf(final, sec_scc)", "ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape( data[2], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength", "Quantity( 'parameters', r'\\n *(.+?:.+)', repeats=True, str_operation=lambda x: [v.strip() for v", "def reuse_parser(self, parser): self.info_parser.quantities = parser.info_parser.quantities self.eigval_parser.quantities = parser.eigval_parser.quantities self.fermisurf_parser.quantities", "self.vertices[i].attrib.get(self._coord_key).split(), dtype=float) end = np.array( self.vertices[i + 1].attrib.get(self._coord_key).split(), dtype=float) res.append(np.linspace(start,", "['GGA_C_PBE', 'GGA_X_WC'], 30: ['GGA_C_AM05', 'GGA_C_AM05'], 300: ['GGA_C_BGCP', 'GGA_X_PBE'], 406: ['HYB_GGA_XC_PBEH'],", "sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components = n_components", "= f if self.data_xs_parser.data is None: continue data.append(self.data_xs_parser.data) return data", "return self._distances = [ point.attrib.get(self._distance_key) for point in self.bands[0][0]] self._distances", "filenames def file_exists(self, filename): \"\"\"Checks if a the given filename", "ureg.hartree).to('joule') # TODO smearing with should have units of energy", "= val_in.strip().split('\\n') nbands = int(val[0]) mesh = np.array(val[1].split(), dtype=int) origin", "ExcitingInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): re_symbol = re.compile(r'([A-Z][a-z]?)') def", "def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: data = np.transpose(self.data)[0] self._neigs_segment", "(n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_binding_energies = np.reshape( data[2], (n_components, n_excitons))", "1 / ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector grid sizes', None), 'x_exciting_gvector_total': (r'Total", "in exciting_files: self.parse_file(f, sec_scc) # structure optimization structure_optimization = self.info_parser.get('structure_optimization',", "OR CONDITIONS OF ANY KIND, either express or implied. #", "= None self._band_k_points = None @property def band_energies(self): if self._band_energies", "that we can do is to assume that the first", "= self.info_parser.get_number_of_spin_channels() band_energies = self.band_out_parser.band_energies if band_energies is None: return", "energy return np.array([d[1].get(key) for d in data]) * ureg.hartree eigs_gw", "Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) initialization_quantities.append(Quantity( 'species',", "if data[0] is None: return return np.reshape(data, (nspin, len(data) //", "sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius') positions_format = specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format", "1]) sec_gw.basis_set = 'mixed' sec_gw.qp_equation_treatment = 'linearization' sec_gw.max_frequency = self.input_xml_parser.get(", "('Total electronic charge', ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total core charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial':", "('Number of crystal symmetries', None), 'x_exciting_kpoint_grid': (r'k\\-point grid', None), 'x_exciting_kpoint_offset':", "= np.transpose(np.vstack(data)) n_sigma = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape(", "= [] class ExcitingInfoParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): re_symbol", "self.input_xml_parser.get( 'xs/nempty', 5) sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq', [1, 1, 1]) sec_method.x_exciting_xs_ngridk", "'methfessel-paxton', 'Fermi-Dirac': 'fermi', 'Extended': 'tetrahedra'} sec_smearing = sec_electronic.m_create(Smearing) smearing_kind =", "is # determined from occupancies which is problematic sometimes res", "if sec_scc.energy is not None: energy_fermi = sec_scc.energy.fermi energy_fermi =", "res = [] for i in range(len(self.vertices) - 1): start", "energy_fermi is None: return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_dos", "= np.reshape( data[2], (n_components, n_sigma)) def parse_loss(data, sec_scc): n_components =", "= self.input_xml_parser.get( 'xs/tddft/fxcbsesplit', 0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA')", "pwm = self.input_xml_parser.get('gw/barecoul/pwm', 2.0) sec_gw.bare_coulomb_gmax = pwm * gmb *", "break return positions_format def get_atom_positions(self, section={}, positions=None, positions_format=None): positions =", "governing permissions and # limitations under the License. # import", "data[1:] bands = np.reshape(bands, ( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, n_kpoints)) self._band_energies =", "{ 'smearing_kind': ('Smearing scheme', None), 'smearing_width': ('Smearing width', None)} for", "@property def energy_unit(self): if self._energy_unit is None: axis = self.root.find('./axis')", "n in range(len(val)): sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n +", "(1 / self.energy_unit) elif key == 'energies': return self.energies else:", "['core'], 'x_exciting_core_leakage': ['core leakage'], 'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge': ['total", "[sec_scc_ref] # parse properties gw_info_files = self.get_exciting_files(gw_info_file) if len(gw_info_files) >", "'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*', unit=ureg.hartree, repeats=False)) def str_to_band_parameters(val_in): val = val_in.strip().split('\\n')", "frequency_data is not None: number = frequency_data.get('number') sec_method.gw.number_of_frequencies = len(number)", "is None: bands = self.root.findall('./%s' % self._band_key) self._bands = []", "['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat'] for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname)", "self._band_energies @property def band_k_points(self): if self._band_k_points is None: data =", "n_kpoints = np.where(data[0] == data[0][0])[0][1] bands = data[1:] bands =", "Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental", "positions_format = section.get('positions_format') if positions_format is None: species = self.get_initialization_parameter('species',", "n_k_points = np.where(dist == dist[0])[0][1] self._distances = dist[:n_k_points] return self._distances", "== dist[0])[0][1] self._distances = dist[:n_k_points] return self._distances @property def number_of_spin_channels(self):", "'spin-unpolarised') n_spin = 1 if spin_treatment.lower() == 'spin-unpolarised' else 2", "rgkmax sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get( 'xs/screening/screentype', 'full') if self.input_xml_parser.get('xs/BSE') is not", "cell.magnitude) return positions * ureg.bohr def get_scf_threshold(self, name): reference =", "r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree / ureg.bohr, repeats=False, dtype=float),", "may not use this file except in compliance with the", "sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get( 'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get( 'xs/BSE/sciavqhd', False)", "case # I cannot find an example bandstructure file #", "str(specie.get('number')) sec_atoms_group.x_exciting_muffin_tin_points = specie.get('radial_points') sec_atoms_group.x_exciting_muffin_tin_radius = specie.get('muffin_tin_radius') positions_format = specie.get('positions_format')", "sec_atoms_group.x_exciting_atom_position_format = positions_format positions = specie.get('positions') positions = self.info_parser.get_atom_positions( positions=positions,", "logger): super().__init__(mainfile, logger=logger) def init_quantities(self): self._quantities = [] class ExcitingInfoParser(TextParser):", "add PDOS def _parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies =", "sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance = self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001)", "= self.archive.run[-1] # TODO read from xml file def get_files(name):", "val elif name == 'x_exciting_species_rtmin': setattr(sec_system, name, ' '.join([str(v) for", ") from nomad.datamodel.metainfo.simulation.system import ( System, Atoms ) from nomad.datamodel.metainfo.simulation.calculation", "is not None: sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get( 'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff =", "'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion correction'] } self._electron_charge_keys_mapping = { 'x_exciting_core_charge': ['core'],", "# # Licensed under the Apache License, Version 2.0 (the", "positions_format = specie.get('positions_format') sec_atoms_group.x_exciting_atom_position_format = positions_format positions = specie.get('positions') positions", "sec_gw_eigenvalues = sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor = reshape(get_data('Znk')) sec_gw_eigenvalues.n_bands = len(eigs_gw[0]) sec_gw_eigenvalues.n_kpoints", "init_parameters(self): self._nspin = None self._nkpts_segment = None self._neigs_segment = None", "start = end return self._band_energies @property def band_k_points(self): if self._band_k_points", "= np.transpose(self.data) self._band_k_points = [] start = 0 for nkpts_segment", "files and properties exciting_files = ['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf'] # Parse", "DOS from one of the files bs_files = ['dos.xml', 'TDOS.OUT']", "None: self._vertices = self.root.findall('./%s' % self._vertex_key) return self._vertices @property def", "= self.input_xml_parser.get('xs/xstype', '') if xstype.lower() == 'bse': self._parse_xs_bse() elif xstype.lower()", "contributions parse_scf(final, sec_scc) # forces forces = section.get('forces') if forces", "TODO read from xml file def get_files(name): bse_types = ['IP',", "msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n + 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value", "we can do is to assume that the first steps", "None: res = res * (1 / self.energy_unit) elif key", "separate section_k_band res = [] for n in range(len(self.bands)): res_n", "'hartree') sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get( 'xs/tddft/intraband',", "qpoints = self.input_xml_parser.get('xs/qpointset/qpoint') def get_data(quantity, ext): # all files related", "init_quantities(self): re_symbol = re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in): val = [v.split(':')[-1].split() for", "parser_function = self._parse_input_gw elif self._calculation_type == 'xs': parser_function = self._parse_input_xs", "= None self._nlm = None self._energies = None self._total_dos =", "np.transpose(np.array([v.split() for v in val[2:]], dtype=float)) eigs = {keys[i]: eigs[i]", "name.startswith('bandstructure') and name.endswith('xml'): parser = self.bandstructure_parser parser_function = self._parse_bandstructure elif", "1]: self._nkpts_segment.append(count) count = 1 else: count += 1 self._nkpts_segment.append(count)", "self._nlm += 2 * li + 1 return self._nlm @property", "self.input_xml_parser.get('xs/tddft/fxctype', 'RPA') tetradf = self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont = self.input_xml_parser.get('xs/tddft/nwacont', None)", "(nspin, len(data) // nspin, 2)) data = np.transpose(data, axes=(2, 0,", "name): reference = self.get('groundstate', self.get('hybrids', {})) return reference.get('scf_iteration', [{}])[-1].get( name,", "if self.data_xs_parser.data is None: continue data_q.append(self.data_xs_parser.data) if not data_q: continue", "Get fermi energy: it is used to un-shift the DOS", "n_scf: quantity = [None] * (n_scf - len(quantity)) + quantity", "or val_m is None: lm = i % self.number_of_lm else:", "None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_rgkmax = rgkmax sec_method.x_exciting_xs_scissor =", "self.info_parser.get('initialization', {}).get('xc_functional') if xc_functional is not None: sec_xc_functional.name = xc_functional.get('name_reference',", "@property def number_of_lm(self): if self._nlm is None: if self.partial_dos is", "[] start = 0 for nkpts_segment in self.number_of_k_points_per_segment: end =", "sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlbse', [0, 0, 0, 0]) if sec_method.x_exciting_xs_bse_xas:", "get_data(key): data = self.eigval_parser.get('eigenvalues_occupancies') # reshaping is not necessary as", "'x_exciting_gvector_total': (r'Total number of G\\-vectors', None), 'x_exciting_lmaxapw': (r' APW functions',", "sec_worfklow.type = 'single_point' structure_optimization = self.info_parser.get('structure_optimization') if structure_optimization is not", "= ForcesEntry(value=forces) # scf iterations scf_iterations = section.get('scf_iteration', []) for", "= self.dos_parser parser_function = self._parse_dos elif name.startswith('bandstructure') and name.endswith('xml'): parser", "scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0], repeats=False, unit=key_unit[1])) self._convergence_keys_mapping = {", "= band_energies[n][nb] + energy_fermi def _parse_eigenvalues(self, sec_scc): if self.eigval_parser.get('eigenvalues_occupancies', None)", "[None, None])[-1] def get_scf_quantity(self, name): n_scf = len(self.get('energy_total_scf_iteration', [])) quantity", "positions = self.info_parser.get_atom_positions(section.get('atomic_positions', {})) lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions',", "def str_to_eigenvalues(val_in): val = val_in[:val_in.rfind('\\n \\n')].strip() val = np.array([v.split() for", "1 else: count += 1 self._nkpts_segment.append(count) return self._nkpts_segment @property def", "= section.get('scf_iteration', []) for scf_iteration in scf_iterations: sec_scf_iteration = sec_scc.m_create(ScfIteration)", "= self.input_xml_parser.get( 'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra = self.input_xml_parser.get( 'xs/tetra/tetradf', False) def", "= self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels = self.bandstructure_parser.get('band_segm_labels') for nb in range(len(band_energies[n])): sec_k_band_segment", "= msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n + 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0]", "reading of parameters from input.xml for normal calculations # in", "of parameters from input.xml for normal calculations # in addition", "sec_scc.x_exciting_xs_bse_sigma_re = np.reshape( data[1], (n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im = np.reshape( data[2],", "TODO smearing with should have units of energy sec_smearing.width =", "sec_k_band_segment.energies = band_energies[nb] + energy_fermi def _parse_band_out(self, sec_scc): self.band_out_parser._nspin =", "np.transpose(energy)[start:end] for energy in band_energies]) if self._energy_unit is not None:", "energy', 'total energy'], 'x_exciting_fermi_energy': ['Fermi energy', 'Fermi'], 'energy_kinetic_electronic': ['Kinetic energy',", "rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax = rgkmax sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get(", "key_unit[0], repeats=False, unit=key_unit[1])) self._convergence_keys_mapping = { 'x_exciting_effective_potential_convergence': ( r'RMS change", "xc_functional_name sec_scc = sec_run.m_create(Calculation) sec_scc.method_ref = sec_method if sec_run.system: sec_scc.system_ref", "sec_scc = sec_run.m_create(Calculation) if quantity == 'EXCITON': parse_function = parse_exciton", "# # This file is part of NOMAD. # See", "and name.endswith('xml'): parser = self.bandstructure_parser parser_function = self._parse_bandstructure elif name.startswith('EIGVAL')", "(n_components, n_excitons)) def parse_epsilon(data, sec_scc): n_components = len(data) data =", "exciting_files = ['EIGVAL.OUT', 'FERMISURF.bxsf', 'FS.bxsf'] # Parse DFT DOS from", "ScfIteration, BandGap ) from nomad.datamodel.metainfo.workflow import Workflow, GeometryOptimization from .metainfo.exciting", "potential and density', 1 / ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector grid sizes',", "dtype=float) lattice_vectors *= self.input_xml_parser.get('structure/crystal/scale', 1.0) positions = np.dot(positions, lattice_vectors) *", "return np.array([d[1].get(key, None) for d in data]) else: energy =", "in range(1, len(self.distances)): if self.distances[i] == self.distances[i - 1]: self._nkpts_segment", "self._band_energies is None: data = np.transpose(self.data) n_kpoints = np.where(data[0] ==", "= self.archive.m_create(Workflow) sec_worfklow.type = 'single_point' structure_optimization = self.info_parser.get('structure_optimization') if structure_optimization", "parse input xml file, there seems to be two versions,", "= self.input_xml_parser.get( 'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states = int( self.input_xml_parser.get('gw/nempty', 0)) sec_gw.ngridq", "None)} for name, key_unit in self._system_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n'", "// nspin)) for v in data]) res = res.reshape((len(res), len(data),", "= self._energies * self.energy_unit return self._energies def _get_dos(self, diagram): dos", "self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_parser.get('band_energies', []) for n in", "sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0] * ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:] elif quantity", "= 'x_exciting_scf_threshold_%s_change' % name.split('_')[-2] setattr(sec_method, metainfo_name, threshold) # additionally, set", "rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax', None) if rgkmax is None: rgkmax =", "to un-shift the DOS to # the original scale in", "len(self.total_dos) return self._nspin @property def number_of_atoms(self): if self._natoms is None:", "target[1:]: filepath = '%s.%s' % (filepath, target[1]) filepath = os.path.join(self.info_parser.maindir,", "ureg.bohr), Quantity( 'step', r'Optimization step\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'method', r'method\\s*=\\s*(\\w+)',", "= np.reshape( data[5], (n_components, n_excitons)) def parse_epsilon(data, sec_scc): n_components =", "atom in range(len(partialdos[lm][spin])): sec_dos_values = sec_dos.m_create(DosValues, Dos.atom_projected) sec_dos_values.m_kind = 'spherical'", "% (self._partialdos_key, self._diagram_key)) return self._partial_dos @property def energies(self): if self._energies", "= mainfile.rsplit('.', 1)[0].replace('INFO', '') options = [ f for f", "if name is None: continue if '_X_' in name: sec_xc_functional.exchange.append(Functional(name=name))", "for f in ['input_gw.xml', 'input-gw.xml', 'input.xml']: self.parse_file(f, sec_method) xc_functional_name =", "key): if self._results is None: self._results = dict() if not", "This is killing me! if metainfo_name == 'x_exciting_scf_threshold_energy_change': sec_method.scf =", "key == 'x_exciting_section_MT_charge_atom': for n in range(len(val)): sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom)", "= 'unit' self._energy_unit = kwargs.get('energy_unit', None) self._units_mapping = dict(hartree=ureg.hartree) def", "== 'SIGMA' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3] def", "have units of energy sec_smearing.width = smearing_width.magnitude for name in", "self.logger self.dos_parser.logger = self.logger self.bandstructure_parser.logger = self.logger self.eigval_parser.logger = self.logger", "i % self.number_of_lm else: lm = int(val_l) ** 2 +", "= dos[spin] # TODO add PDOS def _parse_bandstructure_dat(self, sec_scc): self.bandstructure_dat_parser._nspin", "'smearing_kind': ('Smearing scheme', None), 'smearing_width': ('Smearing width', None)} for name,", "bse_type, scr_type)) bse_files.append(files) return bse_files def get_data(files): data = []", "self.info_parser.get_scf_threshold(name) if threshold is None: continue metainfo_name = 'x_exciting_scf_threshold_%s_change' %", "> 1: self.logger.warn('Found multiple GW info files, will read only", "21: ['GGA_C_PBE', 'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE', 'GGA_X_WC'], 30:", "v in val.split('\\n')], dtype=float) val = np.transpose(val) occs = val[-1]", "all!', data=dict(file=name)) for n in range(len(files)): parser.mainfile = files[n] parser_function(section)", "i in range(len(qpoints)): data_q = [] files_q = [f for", "['Correlation energy', 'correlation'], 'energy_sum_eigenvalues': ['Sum of eigenvalues', 'sum of eigenvalues'],", "== 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3] elif quantity == 'LOSS' and", ": *({re_float}) *({re_float}) *({re_float})', repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing', r'Using ([\\w", "parse_scf(scf_iteration, sec_scf_iteration) return sec_scc def parse_system(self, section): sec_run = self.archive.run[-1]", "np.reshape( data[1], (n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape( data[2], (n_components, n_epsilon))", "sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization) threshold_force = structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence', [0., 0.])[-1]", "= mainfile.strip('INFO.OUT') target = default.rsplit('.', 1) filename = '%s%s' %", "= parser.fermisurf_parser.quantities self.evalqp_parser.quantities = parser.evalqp_parser.quantities self.info_gw_parser.quantities = parser.info_gw_parser.quantities def parse(self,", "in data]) * ureg.hartree eigs_gw = get_data('E_GW') if eigs_gw[0] is", "in writing, software # distributed under the License is distributed", "only first!') self.info_gw_parser.mainfile = gw_info_files[0] fermi_energy = self.info_gw_parser.get('fermi_energy', None) if", "= [f for f in options if f.endswith(file_ext)] options.sort() filenames", "np.array(val[2].split(), dtype=float) vector = np.array([v.split() for v in val[3:6]], dtype=float)", "= kwargs.get('energy_unit', None) def init_parameters(self): # TODO make a parent", "TODO add support for more output files and properties exciting_files", "{})) return reference.get('scf_iteration', [{}])[-1].get( name, [None, None])[-1] def get_scf_quantity(self, name):", "*(.+)'), Quantity('nuclear_charge', rf'nuclear charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic", "setattr(msection, key, val) # convergence values for name in self.info_parser._convergence_keys_mapping.keys():", "parse_function = parse_sigma elif quantity == 'LOSS': parse_function = parse_loss", "Quantity( 'atomic_positions', r'(Atomic positions at this step\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format',", "band_energies[nb] + energy_fermi def parse_file(self, name, section): # TODO add", "self.bands[0][0]] self._distances = np.array(self._distances, dtype=float) return self._distances @property def bands(self):", "'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb energy', 'Coulomb'], 'energy_exchange': ['Exchange energy', 'exchange'], 'x_exciting_exchange_energy':", "fourth column in epsilon which is not parsed? sccs =", "= np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components = n_components n_excitons = len(data[0]) // n_components", "species = v[0][2] atom_resolved.append(((species, v[1] * unit))) else: vi =", "= self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind is not None: if not isinstance(smearing_kind,", "charge', ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total electronic charge', ureg.elementary_charge), 'x_exciting_core_charge_initial': ('Total core", "self.logger self.bandstructure_dat_parser.logger = self.logger self.band_out_parser.logger = self.logger self.info_gw_parser.logger = self.logger", "bandstructure dat and xml self._nspin = None self._nkpts_segment = None", "atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree", "self.info_parser = ExcitingInfoParser() self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser", "self._neigs_segment = None self._bands = None self._vertices = None self._distances", "= structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence', [0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance = threshold_force def", "- 1]: self._nkpts_segment .append(count) count = 1 else: count +=", "ExcitingEigenvalueParser() self.fermisurf_parser = ExcitingFermiSurfaceBxsfParser() self.evalqp_parser = ExcitingEvalqpParser() self.dos_out_parser = DataTextParser()", "== 'x_exciting_fermi_energy': sec_energy.fermi = val # charge contributions charge_contributions =", "self.info_parser.get_initialization_parameter(name) if val is None: continue if name == 'x_exciting_spin_treatment':", "should have units of energy sec_smearing.width = smearing_width.magnitude for name", "= None for name in names: val = energy_contributions.get(name, None)", "volume optimizations volume_index = 1 while True: info_volume = self.get_exciting_files('run_dir%s/INFO.OUT'", "self.info_parser.quantities = parser.info_parser.quantities self.eigval_parser.quantities = parser.eigval_parser.quantities self.fermisurf_parser.quantities = parser.fermisurf_parser.quantities self.evalqp_parser.quantities", "'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles = int(self.input_xml_parser.get( 'gw/selfenergy/npol', 0)) sec_gw.self_energy_c_number_of_empty_states = int(self.input_xml_parser.get(", "ureg.hartree, weights=val[2]) # TODO Read also input parameters here if", "in this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False, dtype=float) ] self._quantities.append(Quantity( 'structure_optimization',", "r'\\s*EXCITING\\s*([\\w\\-\\(\\)\\. ]+)\\s*started', repeats=False, dtype=str, flatten=False)] initialization_quantities = [ Quantity( 'lattice_vectors',", "achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(imized atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity(", "def parse_loss(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_loss", "sec_method.gw.frequency_weights = frequency_data.get('weights') fundamental_band_gap = self.info_gw_parser.get('direct_band_gap', None) if fundamental_band_gap is", "val_in.strip().replace('(', '').replace(')', '').split() def str_to_energy_dict(val_in): val = val_in.strip().split('\\n') energies =", "start + nkpts_segment band_energy = np.array([ np.transpose(energy)[start:end] for energy in", "str_to_eigenvalue(val_in): val = val_in.strip().split('\\n') kpts = np.array(val[0].split(), dtype=float) keys =", "is None: species = self.get_initialization_parameter('species', []) for specie in species:", "lattice_vectors) * ureg.bohr lattice_vectors = lattice_vectors * ureg.bohr atoms =", "name in self.info_parser._system_keys_mapping.keys(): val = self.info_parser.get_initialization_parameter(name) if val is None:", "np.transpose(self.data_clathrate_parser.data) sec_system.x_exciting_clathrates_atom_coordinates = np.transpose( np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels = list(data[3]) else:", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "functions', None), 'x_exciting_nuclear_charge': ('Total nuclear charge', ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total electronic", "sec_method.x_exciting_xs_broadening = self.input_xml_parser.get( 'xs/broad', 0.01, 'hartree') sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get( 'xs/gqmax',", "of Bravais lattice symmetries', None), 'x_exciting_number_of_crystal_symmetries': ('Number of crystal symmetries',", "= self.input_xml_parser.get('xs/ngridk', [1, 1, 1]) rgkmax = self.input_xml_parser.get('xs/rgkmax', None) if", "dtype=float), Quantity( 'energy_total', r'Total energy at this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree,", "positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude # clathrate info clathrate_file =", "1 return self._nspin @property def number_of_k_points_per_segment(self): if self._nkpts_segment is None:", "1.0) sec_gw.mixed_basis_gmax = gmb * gmaxvr pwm = self.input_xml_parser.get('gw/barecoul/pwm', 2.0)", "return data for quantity in ['EPSILON', 'LOSS', 'SIGMA']: for ext", "= f break if not self._calculation_type == 'gw': return sec_method", "self._atom_key = 'atom' self._nspin = kwargs.get('nspin', None) self._energy_unit = kwargs.get('energy_unit',", "= np.transpose(data_q, axes=(2, 0, 1)) for j in range(len(data)): data[j].append(data_q[j])", "sec_scc = sec_run.m_create(Calculation) def parse_scf(iteration, msection): energy_total = iteration.get('energy_total') sec_energy", "= [float(vi) for vi in v[1].split()] v[1] = v[1][0] if", "self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): self._nspin = None self._nkpts_segment", "['HYB_GGA_XC_HSE03']} xc_functional = self.get('initialization', {}).get('xc_functional', None) if xc_functional is None:", "self.fermisurf_parser parser_function = self._parse_fermisurface elif name.startswith('EVALQP') and (name.endswith('DAT') or name.endswith('TXT')):", "= np.reshape( data[2], (n_components, n_epsilon)) def parse_sigma(data, sec_scc): n_components =", "properties[v[0].strip()] = vi * unit properties['atom_resolved'] = atom_resolved return properties", "self.dos_out_parser.logger = self.logger self.bandstructure_dat_parser.logger = self.logger self.band_out_parser.logger = self.logger self.info_gw_parser.logger", "self.input_xml_parser.get('xs/BSE') is not None: sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get( 'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff", "repeats=False, convert=False), Quantity( 'x_exciting_dos_fermi', r'DOS at Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False,", "fermi_energy = self.fermisurf_parser.get('fermi_energy', None) if fermi_energy is not None: sec_fermisurface.x_exciting_fermi_energy_fermi_surface", "structure_optimization = self.info_parser.get('structure_optimization', {}) for optimization_step in structure_optimization.get('optimization_step', []): sec_scc", "(self.number_of_spin_channels * self.number_of_lm)) // self.number_of_lm else: spin = int(spin) -", "= np.array([d[1].get(key, None) for d in data]) if None in", "structure optimization structure_optimization = self.info_parser.get('structure_optimization', {}) for optimization_step in structure_optimization.get('optimization_step',", "= res * (1 / self.energy_unit) elif 'partial' in key:", "= self.info_parser.get('initialization', {}).get('xc_functional') if xc_functional is not None: sec_xc_functional.name =", "np.reshape( data[0], (n_components, n_epsilon)) * ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape( data[1],", "License. # import numpy as np import os import re", "'xs/BSE/sciavqbd', False) sec_method.x_exciting_xs_bse_sciavqhd = self.input_xml_parser.get( 'xs/BSE/sciavqhd', False) sec_method.x_exciting_xs_bse_sciavqwg = self.input_xml_parser.get(", "= n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape( data[0], (n_components, n_epsilon)) * ureg.hartree", "get_positions_format(self, section): positions_format = section.get('positions_format') if positions_format is None: species", "ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] self._quantities.append(", "# Unless required by applicable law or agreed to in", "None self._neigs_segment = None self._bands = None self._vertices = None", "'xs/BSE/nstlxas', [0, 0]) if self.input_xml_parser.get('xs/tddft') is not None: sec_method.x_exciting_xs_tddft_analytic_continuation =", "else logging self._calculation_type = None self.init_parser() sec_run = self.archive.m_create(Run) sec_run.program", "return sec_system def parse_configurations(self): sec_run = self.archive.run[-1] def parse_configuration(section): if", "self._energy_unit is None: axis = self.root.find('./axis') if axis is None:", "if None in energy: return energy return np.array([d[1].get(key) for d", "Quantity( 'force_convergence', r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee ]+)', str_operation=str_to_quantity_tolerances, unit=ureg.hartree / ureg.bohr,", "(n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im = np.reshape( data[2], (n_components, n_sigma)) def parse_loss(data,", "['Hartree energy', 'Hartree'], 'x_exciting_hartree_energy': ['Hartree energy', 'Hartree'], 'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy',", "if xstype is not None: sec_method.x_exciting_xs_xstype = xstype sec_method.x_exciting_electronic_structure_method =", "self.partial_dos[i].attrib.get(self._l_key, None) val_m = self.partial_dos[i].attrib.get(self._m_key, None) if val_l is None", "= 'geometry_optimization' sec_geometry_opt = sec_worfklow.m_create(GeometryOptimization) threshold_force = structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence',", "time \\(seconds\\)', ureg.s)} for name, key_unit in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name,", "{}).get('x_exciting_unit_cell_volume', 1.0 * ureg.bohr ** 3) def get_initialization_parameter(self, key, default=None):", "the Apache License, Version 2.0 (the \"License\"); # you may", "== 'x_exciting_species_rtmin': setattr(sec_system, name, ' '.join([str(v) for v in val]))", "range(len(qpoints)): data_q = [] files_q = [f for f in", "sec_method_ref sec_method.methods_ref = [sec_method_ref] # parse input xml file, there", "'x_exciting_lo': (r'Total number of local\\-orbitals', None)} self._method_keys_mapping = { 'smearing_kind':", "= self.input_xml_parser.get( 'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get( 'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric", "/ self.energy_unit) elif key == 'energies': return self.energies else: res", "sec_scc def parse_system(self, section): sec_run = self.archive.run[-1] positions = self.info_parser.get_atom_positions(section.get('atomic_positions',", "get it by concatenating species symbols species = self.get('initialization', {}).get('species',", "this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False, dtype=float), Quantity( 'time', r'Time spent", "r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False)", "= np.reshape( data[0], (n_components, n_epsilon)) * ureg.hartree sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape(", "self._results[key] = res class ExcitingFermiSurfaceBxsfParser(TextParser): def __init__(self): super().__init__(None) def init_quantities(self):", "'groundstate', r'(?:Self\\-consistent loop started|Groundstate module started)([\\s\\S]+?)Groundstate module stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False))", "def number_of_band_segment_eigenvalues(self): if self._neigs_segment is None: self._neigs_segment = len(self.bands[0]) //", "final if final is None: return sec_scc = sec_run.m_create(Calculation) def", "fxctype)) data = [[], [], []] for i in range(len(qpoints)):", "= (energy_fermi.magnitude * ureg.joule).to('hartree') sec_dos = sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies =", "key_unit[0], unit=key_unit[1], repeats=False) ) initialization_quantities.append(Quantity( 'species', rf'(Species : *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float}", "for f in files: self.data_xs_parser.mainfile = f if self.data_xs_parser.data is", "if self.energy_unit is not None: res = res * (1", "1.0) sec_gw.frequency_grid_type = self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies = int(self.input_xml_parser.get( 'gw/freqgrid/nomeg',", "self.info_gw_parser.logger = self.logger self.input_xml_parser.logger = self.logger self.data_xs_parser.logger = self.logger self.data_clathrate_parser.logger", "= filepath self.archive = archive self.logger = logger if logger", "repeats=True), Quantity( 'final', r'Force convergence target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity(", "= [os.path.join(self.info_parser.maindir, f) for f in options] else: filenames =", "_parse_eigenvalues(self, sec_scc): if self.eigval_parser.get('eigenvalues_occupancies', None) is None: return nspin =", "for f in filenames if os.access(f, os.F_OK)] return filenames def", "positions is None: # get it from input.xml for f", "= ureg.elementary_charge elif 'moment' in val_in: unit = ureg.elementary_charge *", "r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) class ExcitingEvalqpParser(TextParser): def __init__(self): super().__init__(None) def", "x_exciting_dos_fermi) # energy contributions energy_contributions = iteration.get('energy_contributions', {}) for key,", "def __init__(self, mainfile, logger): super().__init__(mainfile, logger=logger) def init_quantities(self): self._quantities =", "rgkmax is None: rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0) sec_method.x_exciting_xs_bse_rgkmax = rgkmax", "dict(hartree=ureg.hartree) def init_parameters(self): self._ndos = None self._natoms = None self._nspin", "forces = section.get('forces') if forces is not None: sec_forces =", "= np.array( [float(point.attrib.get(self._energy_key)) for point in self.total_dos[0]]) if self.energy_unit is", "= [ Quantity( 'scf_iteration', r'(?:I| i)teration number :([\\s\\S]+?)(?:\\n *\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities),", "'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get( 'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get(", "set threshold to global metainfo. This is killing me! if", "DFT DOS from one of the files bs_files = ['dos.xml',", "Exception: self.logger.error('Error setting xs data', data=dict(file=quantity)) def _parse_xs_tddft(self): sec_run =", "sec_scc.x_exciting_xs_tddft_loss_function_local_field = data[1] elif quantity == 'LOSS' and ext ==", "*({re_float})', dtype=np.int32), Quantity('positions_format', r'atomic positions \\((.+?)\\)', flatten=False), Quantity( 'positions', rf'\\d+", "not None: sec_scc.x_exciting_maximum_force_magnitude = force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1] sec_scc =", "None: break if val is None: continue if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr(", "grid', None), 'x_exciting_kpoint_offset': (r'k\\-point offset', None), 'x_exciting_number_kpoints': (r'Total number of", "in energy: return energy return np.array([d[1].get(key) for d in data])", "iteration.get('energy_total') sec_energy = msection.m_create(Energy) if energy_total is not None: sec_energy.total", "sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n + 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol =", "filename.rsplit('.', 1) filepath = '%s%s' % (target[0], suffix) if target[1:]:", "it is used to un-shift the DOS to # the", "Scf, BasisSet ) from nomad.datamodel.metainfo.simulation.system import ( System, Atoms )", "( Method, DFT, Electronic, Smearing, XCFunctional, Functional, GW as GWMethod,", "'BAND.OUT', 'bandstructure.dat'] for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break", "= np.array([v.split() for v in val[3:6]], dtype=float) return [nbands, mesh,", "nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels = self.bandstructure_parser.get('band_segm_labels') for nb in range(len(band_energies[n])):", "self.logger self.eigval_parser.logger = self.logger self.fermisurf_parser.logger = self.logger self.evalqp_parser.logger = self.logger", "cell is None: return positions = np.dot(positions, cell.magnitude) return positions", "f in exciting_files: self.parse_file(f, sec_scc) # structure optimization structure_optimization =", "energy, moment, charge contributions parse_scf(final, sec_scc) # forces forces =", "= len(self.get('energy_total_scf_iteration', [])) quantity = self.get('%s_scf_iteration' % name) if quantity", "in os.listdir( self.info_parser.maindir) if target[0] in f and mainfile_base in", "naming convention for xs input xml file sec_method = sec_run.m_create(Method)", "def get_xc_functional_name(self): # TODO expand list to include other xcf", "Quantity( 'x_exciting_dos_fermi', r'DOS at Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float, unit=1", "self._energy_keys_mapping = { 'energy_total': ['Total energy', 'total energy'], 'x_exciting_fermi_energy': ['Fermi", "in self.number_of_k_points_per_segment: end = start + nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end]) start", "def energy_unit(self): if self._energy_unit is None: axis = self.root.find('./axis') if", "self.total_dos: return res = np.zeros((self.number_of_spin_channels, self.number_of_dos)) for i in range(len(self.total_dos)):", "step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True,", "None @property def distances(self): if self._distances is None: if not", "'SIGMA' and ext == 'FXC': sec_scc.x_exciting_xs_tddft_sigma_local_field = data[1:3] elif quantity", "not None: sec_method.x_exciting_xs_xstype = xstype sec_method.x_exciting_electronic_structure_method = xstype sec_method.x_exciting_xs_broadening =", "nomad.parsing.file_parser import TextParser, Quantity, XMLParser, DataTextParser from nomad.datamodel.metainfo.simulation.run import Run,", "and name.endswith('OUT'): parser = self.band_out_parser parser_function = self._parse_band_out elif name.startswith('input')", "break if val is None: continue if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy,", "else section.get('positions') if positions is None: species = self.get_initialization_parameter('species', [])", "name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) initialization_quantities.append(Quantity( 'species', rf'(Species", "end.lower() == 'gamma' else end]) elif key == 'band_segm_start_end': res", "sec_run.m_create(Calculation) sec_scc.x_exciting_xs_tddft_number_of_epsilon_values = len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0] * ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field", "sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment = val elif name == 'x_exciting_species_rtmin': setattr(sec_system, name,", "= self.evalqp_parser.get('kpoints_eigenvalues') if data is None: return def get_data(key): if", "['dos.xml', 'TDOS.OUT'] for fname in bs_files: if self.file_exists(fname): exciting_files.append(fname) break", "in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0], repeats=False, unit=key_unit[1])) self._convergence_keys_mapping", "None) def init_parameters(self): # TODO make a parent clas for", "repeats=False)) optimization_quantities = [ Quantity( 'atomic_positions', r'(Atomic positions at this", "if val is None: continue if key == 'x_exciting_section_MT_moment_atom': for", "for spin in range(len(totaldos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin =", "*({re_float})', repeats=True, dtype=np.dtype(np.float64))]))) initialization_quantities.append(Quantity( 'potential_mixing', r'Using ([\\w ]+) potential mixing',", "(1 / self.energy_unit) elif 'partial' in key: if not self.partial_dos:", "= [] self._quantities.append( Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True)) def str_to_eigenvalues(val_in):", "data = np.transpose(data, axes=(2, 0, 1)) sec_dos.energies = data[0][0] *", "radius, r\\_s', ureg.bohr), 'x_exciting_empty_states': ('Number of empty states', None), 'x_exciting_valence_states':", "/ ureg.hartree) * volume.to('m**3').magnitude for spin in range(len(dos)): sec_dos_values =", "data = np.transpose(self.data)[0] self._neigs_segment = len(np.where(data == data[0])[0]) return self._neigs_segment", "r'\\n *(.+?:.+)', repeats=True, str_operation=lambda x: [v.strip() for v in x.split(':')])]))", "Quantity( 'band_parameters', r'BANDGRID_3D_BANDS\\s*([\\d\\.\\-Ee\\s]+)', str_operation=str_to_band_parameters, repeats=False)) self._quantities.append( Quantity( 'fermi_surface', r'BAND:\\s*\\d+\\s*([\\d\\-\\+\\.Ee\\s]+)\\n *E*',", "band_k_points(self): if self._band_k_points is None: data = np.transpose(self.data) self._band_k_points =", "sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity = self.input_xml_parser.get( 'xs/tddft/ahc', False) sec_method.x_exciting_xs_tddft_anti_resonant_dielectric = self.input_xml_parser.get( 'xs/tddft/aresdf', False)", "= self.input_xml_parser.get('structure/species/atom/coord') lattice_vectors = self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3)) species = self.input_xml_parser.get('structure/species/speciesfile')", "BandStructure, BandEnergies, Energy, EnergyEntry, Charges, Forces, ForcesEntry, ScfIteration, BandGap )", "and hybrids calculation for module in ['groundstate', 'hybrids']: sec_scc =", "band_energies is None: return # Get fermi energy: it is", "r'\\(state\\, eigenvalue and occupancy below\\)\\s*([\\d\\.Ee\\-\\s]+?(?:\\n *\\n))', str_operation=str_to_eigenvalues, repeats=True)) class ExcitingGWOutParser(TextParser):", "[1, 1, 1]) rgkmax = self.input_xml_parser.get('xs/rgkmax', None) if rgkmax is", "species: positions_format = specie.get('positions_format', None) if positions_format is not None:", "sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.energies = band_energies[nb]", "= np.transpose(np.vstack(data)) n_loss = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_loss_energies = np.reshape(", "parser_function = self._parse_fermisurface elif name.startswith('EVALQP') and (name.endswith('DAT') or name.endswith('TXT')): parser", "ExcitingGWOutParser(TextParser): def __init__(self, mainfile, logger): super().__init__(mainfile, logger=logger) def init_quantities(self): self._quantities", "= end return self._band_k_points @property def distances(self): if self._distances is", "if not xs_info_files: return self._calculation_type = 'xs' # inconsistency in", "__init__(self, **kwargs): # TODO make a parent class for dos", "dtype=float)) sec_system.x_exciting_clathrates_atom_labels = list(data[3]) else: sec_system.x_exciting_clathrates = False potential_mixing =", "continue # add data to scc # TODO add support", "energy', 'electronic kinetic'], 'energy_coulomb': ['Coulomb energy', 'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb energy',", "= lattice_vectors * ureg.bohr atoms = self.input_xml_parser.get('structure/species/atom') atom_labels = []", "Quantity( 'forces', r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False,", "self._band_k_points = None @property def band_energies(self): if self._band_energies is None:", "None) self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): # TODO make", "% (filename, target[1]) filename = os.path.join(self.info_parser.maindir, filename) if os.path.isfile(filename): return", "= xstype sec_method.x_exciting_electronic_structure_method = xstype sec_method.x_exciting_xs_broadening = self.input_xml_parser.get( 'xs/broad', 0.01,", "= 'band' self._atom_key = 'atom' self._nspin = kwargs.get('nspin', None) self._energy_unit", "final = section.get('optimization_step', [None])[-1] if final is None else final", "target[1:]: filename = '%s.%s' % (filename, target[1]) filename = os.path.join(self.info_parser.maindir,", "*\\n\\+{10}|\\+\\-{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=True), Quantity( 'final', r'(?:Convergence targets achieved\\. Performing final", "'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlbse', [0, 0, 0, 0])", "Parse GW band structure from one of the files: bs_files", "parse_exciton(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components =", "Quantity('nuclear_charge', rf'nuclear charge *: *({re_float})', dtype=np.float64, unit=ureg.elementary_charge), Quantity('electronic_charge', rf'electronic charge", "v[0] = v[0].split() v[1] = [float(vi) for vi in v[1].split()]", "again as this is overwritten when setting mainfile self.bandstructure_parser._nspin =", "data['eigenvalues'] = np.reshape(eigs, (nspin, len(eigs) // nspin)) return data self._quantities.append(", "None), 'x_exciting_nuclear_charge': ('Total nuclear charge', ureg.elementary_charge), 'x_exciting_electronic_charge': ('Total electronic charge',", "are. What is the fourth column in epsilon which is", "from one of the files bs_files = ['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat']", "re.search(re_symbol, v[-1]).group(1) elif v[0].startswith('atom'): v[0] = v[0].split() v[1] = [float(vi)", "spin = self.partial_dos[i].attrib.get(self._nspin_key, None) if spin is None: spin =", "0.00001, 'hartree') sec_method.x_exciting_xs_tddft_xc_kernel = self.input_xml_parser.get( 'xs/tddft/fxctype', 'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get(", ") from nomad.datamodel.metainfo.workflow import Workflow, GeometryOptimization from .metainfo.exciting import x_exciting_section_MT_charge_atom,", "val = None for name in names: val = energy_contributions.get(name,", "r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1 / ureg.bohr, repeats=False, convert=False), ]", "self._results is None: self._results = dict() if not self.bands: return", "Quantity( 'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False, convert=False), Quantity( 'x_exciting_dos_fermi', r'DOS", "species = re.search(re_symbol, v[-1]).group(1) elif v[0].startswith('atom'): v[0] = v[0].split() v[1]", "self.input_xml_parser.mainfile = input_file[0] xstype = self.input_xml_parser.get('xs/xstype', '') if xstype.lower() ==", "os.path.basename(self.info_parser.mainfile) suffix = mainfile.strip('INFO.OUT') target = default.rsplit('.', 1) filename =", "here if input_GW.xml does not exist self._quantities.append( Quantity( 'frequency_data', r'frequency", "is None: return sec_system = sec_run.m_create(System) sec_atoms = sec_system.m_create(Atoms) sec_atoms.positions", "self.vertices[i + 1].attrib.get(self._coord_key).split() res.append([start, end]) else: res = None self._results[key]", "= len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape(", "\\|G\\+k\\|\\_max \\(rgkmax\\)', None), 'x_exciting_species_rtmin': (r'Species with R\\^MT\\_min', None), 'x_exciting_gkmax': (r'Maximum", "f and mainfile_base in f] options = [f for f", "self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file = self.get_exciting_files('input.xml') if positions", "number_of_lm(self): if self._nlm is None: if self.partial_dos is None: return", "def parse_gw(self): sec_run = self.archive.run[-1] # two versions of gw", "for quantity in ['EPSILON', 'LOSS', 'SIGMA']: for ext in ['FXC',", "rgkmax = self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax = rgkmax sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get(", "positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude # clathrate info clathrate_file = self.get_exciting_files('str.out')", "self.number_of_lm)) // self.number_of_lm else: spin = int(spin) - 1 val_l", "= { 'x_exciting_unit_cell_volume': ('Unit cell volume', ureg.bohr ** 3), 'x_exciting_brillouin_zone_volume':", "# free up memory parser.mainfile = None def _parse_input_xs(self, sec_method):", "convention for xs input xml file sec_method = sec_run.m_create(Method) sec_method_ref", "r'(Optimization step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent in this optimization step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities),", "partialdos[lm][spin][atom] def _parse_bandstructure(self, sec_scc): # we need to set nspin", "range(len(val))] * val[0][1].units sec_charges.total = charge_contributions.get('total charge') elif key ==", "% (self._totaldos_key, self._diagram_key)) return self._total_dos @property def partial_dos(self): if self._partial_dos", "@property def band_energies(self): if self._band_energies is None: if self.data is", "at this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)', unit=ureg.hartree, repeats=False, dtype=float), Quantity( 'time', r'Time", "data[0], (n_components, n_sigma)) * ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re = np.reshape( data[1], (n_components,", "= np.transpose(data, axes=(2, 0, 1)) sec_dos.energies = data[0][0] * ureg.hartree", "(energy_fermi.magnitude * ureg.joule).to('hartree') # TODO I am not sure about", "= { 'x_exciting_gap': (r'Estimated fundamental gap', ureg.hartree), 'time': (r'Wall time", "len(gw_info_files) > 1: self.logger.warn('Found multiple GW info files, will read", "ureg.bohr) ] self._quantities.append(Quantity( 'groundstate', r'(?:Self\\-consistent loop started|Groundstate module started)([\\s\\S]+?)Groundstate module", "if spin_treatment.lower() == 'spin-unpolarised' else 2 return n_spin def get_unit_cell_volume(self):", "sec_gw.qp_equation_treatment = 'linearization' sec_gw.max_frequency = self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type =", "- 1 val_l = self.partial_dos[i].attrib.get(self._l_key, None) val_m = self.partial_dos[i].attrib.get(self._m_key, None)", ") scf_quantities = [ Quantity( 'energy_total', r'[Tt]*otal energy\\s*:\\s*([\\-\\d\\.Ee]+)', repeats=False, dtype=float,", "parser_function = self._parse_bandstructure_dat elif name.startswith('BAND') and name.endswith('OUT'): parser = self.band_out_parser", "self.dos_parser parser_function = self._parse_dos elif name.startswith('bandstructure') and name.endswith('xml'): parser =", "sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_dat_parser.band_k_points", "'initialization', r'(?:All units are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) )", "of eigenvalues', 'sum of eigenvalues'], 'x_exciting_effective_potential_energy': ['Effective potential energy'], 'x_exciting_coulomb_potential_energy':", "not self.total_dos: return self._nspin = len(self.total_dos) return self._nspin @property def", "{ 'energy_total': ['Total energy', 'total energy'], 'x_exciting_fermi_energy': ['Fermi energy', 'Fermi'],", "columns are supposed # to be what they are. What", "'EPSILON' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3] elif quantity", "= self.info_parser.get('structure_optimization', {}) for optimization_step in structure_optimization.get('optimization_step', []): sec_scc =", "self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_parser.get('band_energies', []) for n in range(len(band_energies)): #", "method goes first since reference needed for sec_scc self.parse_method() self.parse_configurations()", "None: data = np.transpose(self.data) n_kpoints = np.where(data[0] == data[0][0])[0][1] bands", "return energy_fermi = (energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic)", "parse_miscellaneous(self): sec_worfklow = self.archive.m_create(Workflow) sec_worfklow.type = 'single_point' structure_optimization = self.info_parser.get('structure_optimization')", "len(v) == 3], float)) return dict( number=np.array(val[0], dtype=int), values=val[1] *", "type', data=dict(file=quantity)) sec_scc = sec_run.m_create(Calculation) if quantity == 'EXCITON': parse_function", "self._quantities.append( Quantity( 'optical_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Optical BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) class ExcitingEvalqpParser(TextParser): def", "val = iteration.get(name) if val is None: continue if name", "self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get( 'gw/mixbasis/lmaxmb', 3)) sec_gw.mixed_basis_tolerance =", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "ureg.s)} for name, key_unit in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' %", "'energy_contributions', r'(?:Energies|_)([\\+\\-\\s\\w\\.\\:]+?)\\n *(?:DOS|Density)', str_operation=str_to_energy_dict, repeats=False, convert=False), Quantity( 'x_exciting_dos_fermi', r'DOS at", "except Exception: self.logger.error('Error setting xs data', data=dict(file=quantity)) def _parse_xs_tddft(self): sec_run", "name.startswith('EVALQP') and (name.endswith('DAT') or name.endswith('TXT')): parser = self.evalqp_parser parser_function =", "ones with the missing quantity if len(quantity) < n_scf: quantity", "key == 'k_points': return np.array([d[0][:3] for d in data]) elif", "super().__init__(mainfile, logger=logger) def init_quantities(self): self._quantities = [] class ExcitingInfoParser(TextParser): def", "* ureg.bohr ** 3) def get_initialization_parameter(self, key, default=None): return self.get('initialization',", "files related to quantity at all qpoints files = self.get_exciting_files('%s_%s%s%s.OUT'", "np.transpose(np.vstack(data)) sec_scc.x_exciting_xs_bse_number_of_components = n_components n_excitons = len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_excitons", "'electronic kinetic'], 'energy_coulomb': ['Coulomb energy', 'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb energy', 'Coulomb'],", "{}).get('xc_functional', None) if xc_functional is None: return [] name =", "= self.input_xml_parser.get( 'gw/freqgrid/freqmax', 1.0) sec_gw.frequency_grid_type = self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies", "self.input_xml_parser.get( 'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get( 'xs/tddft/kerndiag', False) sec_method.x_exciting_xs_tddft_lmax_alda =", "species = self.get_initialization_parameter('species', []) if species: positions = np.vstack([s.get('positions') for", "'gamma' else start, '\\u0393' if end.lower() == 'gamma' else end])", "elif quantity == 'EPSILON' and ext == 'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field =", "if key == 'k_points': return np.array([d[0][:3] for d in data])", "Program from nomad.datamodel.metainfo.simulation.method import ( Method, DFT, Electronic, Smearing, XCFunctional,", "repeats=True)) class BandstructureDatParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin',", "self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies = int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles =", "a parent clas for bandstructure dat and xml self._nspin =", "return self._ndos @property def number_of_lm(self): if self._nlm is None: if", "len(vi) == 1 else vi properties[v[0].strip()] = vi * unit", "rgkmax sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get( 'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get( 'xs/BSE/sciavqbd',", "energy sec_smearing.width = smearing_width.magnitude for name in self.info_parser._convergence_keys_mapping.keys(): threshold =", "# atom-resolved bandstructure are added as separate section_k_band res =", "'HYB' in name: sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name)) if not xc_functional_names: #", "permissions and # limitations under the License. # import numpy", "val = self.info_parser.get_initialization_parameter(name) if val is None: continue if name", "names for different versions of exciting self._energy_keys_mapping = { 'energy_total':", "is killing me! if metainfo_name == 'x_exciting_scf_threshold_energy_change': sec_method.scf = Scf(threshold_energy_change=threshold)", "read all!', data=dict(file=name)) for n in range(len(files)): parser.mainfile = files[n]", "exciting sec_atoms.lattice_vectors = lattice_vectors lattice_vectors_reciprocal = self.info_parser.get_initialization_parameter( 'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal =", "sec_scc.x_exciting_xs_tddft_sigma_no_local_field = data[1:3] def parse_xs(self): sec_run = self.archive.run[-1] xs_info_files =", "self.band_out_parser.band_energies if band_energies is None: return # Get fermi energy:", "{ 2: ['LDA_C_PZ', 'LDA_X_PZ'], 3: ['LDA_C_PW', 'LDA_X_PZ'], 4: ['LDA_C_XALPHA'], 5:", "= data[0][0] * ureg.hartree + energy_fermi volume = self.info_parser.get_unit_cell_volume() dos", "xstype is not None: sec_method.x_exciting_xs_xstype = xstype sec_method.x_exciting_electronic_structure_method = xstype", "if len(v) < 2: continue energies[v[0].strip()] = float(v[1]) * ureg.hartree", "self._vertices is None: self._vertices = self.root.findall('./%s' % self._vertex_key) return self._vertices", "two versions, input_gw.xml and input-gw.xml for f in ['input_gw.xml', 'input-gw.xml',", "]+):\\s*k\\-point', repeats=True)) def str_to_eigenvalues(val_in): val = val_in[:val_in.rfind('\\n \\n')].strip() val =", "dtype=np.int32), Quantity('positions_format', r'atomic positions \\((.+?)\\)', flatten=False), Quantity( 'positions', rf'\\d+ :", "'lattice_vectors_reciprocal') sec_atoms.lattice_vectors_reciprocal = lattice_vectors_reciprocal if len(sec_run.system) > 1: return sec_system", "ureg.hartree), 'x_exciting_charge_convergence': ( r'Charge distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence': ( r'Abs\\. change", "Quantity( 'k_points', r'\\s*\\d+\\s*([\\d\\.Ee\\- ]+):\\s*k\\-point', repeats=True)) def str_to_eigenvalues(val_in): val = val_in[:val_in.rfind('\\n", ".metainfo.exciting import x_exciting_section_MT_charge_atom, x_exciting_section_MT_moment_atom,\\ x_exciting_section_spin, x_exciting_section_fermi_surface,\\ x_exciting_section_atoms_group re_float = r'[-+]?\\d+\\.\\d*(?:[Ee][-+]\\d+)?'", "self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels = self.bandstructure_parser.get('band_segm_labels') for nb in range(len(band_energies[n])): sec_k_band_segment =", "if not isinstance(smearing_kind, str): smearing_kind = smearing_kind[0] smearing_kind = smearing_kind_map[smearing_kind]", "'dos' self._unit_key = 'unit' self._energy_unit = kwargs.get('energy_unit', None) self._units_mapping =", "['LDA_C_VBH'], 20: ['GGA_C_PBE', 'GGA_X_PBE'], 21: ['GGA_C_PBE', 'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'],", "super().__init__(None) def init_quantities(self): self._quantities = [] def str_to_frequency(val_in): val =", "np.size(v[key]) // nspin)) for v in data]) res = res.reshape((len(res),", "0.0 * ureg.hartree if sec_scc.energy is not None: energy_fermi =", "dist[:n_k_points] return self._distances @property def number_of_spin_channels(self): if self._nspin is None:", "self._calculation_type == 'gw': return sec_method = sec_run.m_create(Method) sec_method_ref = self.archive.run[-1].method[0]", "None: axis = self.root.find('./axis') if axis is None: return self._energy_unit", "def str_to_array(val_in): val = [v.split(':')[-1].split() for v in val_in.strip().split('\\n')] val", "= self.input_xml_parser.get( 'xs/broad', 0.01, 'hartree') sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get( 'xs/gqmax', 0.0,", "some scf steps dont have the quantity # the only", "Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_parser.get('band_k_points') nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment", "= len(eigs_gw) sec_gw_eigenvalues.kpoints = get_data('k_points') sec_gw_eigenvalues.energies = reshape(eigs_gw) sec_gw_eigenvalues.value_exchange =", "self._neigs_segment = None self._vertices = None self._distances = None self._band_energies", "None: if not isinstance(smearing_kind, str): smearing_kind = smearing_kind[0] smearing_kind =", "if self._neigs_segment is None: self._neigs_segment = len(self.bands[0]) // self.number_of_spin_channels return", "bse_files.append(files) return bse_files def get_data(files): data = [] for f", "+ 1).rjust(3, '0'))] for f in files_q: self.data_xs_parser.mainfile = f", "else: try: setattr(sec_system, name, val) except Exception: self.logger.warn('Error setting metainfo.')", ") for name, key_unit in self._method_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n'", "energy_fermi band_k_points = self.bandstructure_dat_parser.band_k_points nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment for nb in", "band_energies[i % self.number_of_spin_channels][i] = np.array( [e.attrib.get(self._energy_key) for e in self.bands[n][i]])", "for n in range(len(val)): sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n", "is not None: sec_method.x_exciting_xs_tddft_analytic_continuation = self.input_xml_parser.get( 'xs/tddft/acont', False) sec_method.x_exciting_xs_tddft_anomalous_Hall_conductivity =", "@property def number_of_k_points_per_segment(self): if self._nkpts_segment is None: self._nkpts_segment = []", "IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False, str_operation=str_to_array, convert=False, unit=ureg.hartree / ureg.bohr), Quantity(", "None self._band_energies = None self._band_k_points = None @property def band_energies(self):", "[0., 0., 0.]) # TODO I am not certain if", "for f in exciting_files: self.parse_file(f, sec_scc) # structure optimization structure_optimization", "['LDA_C_PW', 'LDA_X_PZ'], 4: ['LDA_C_XALPHA'], 5: ['LDA_C_VBH'], 20: ['GGA_C_PBE', 'GGA_X_PBE'], 21:", "1).rjust(3, '0'))] for f in files_q: self.data_xs_parser.mainfile = f if", "specie.get('positions_format', None) if positions_format is not None: break return positions_format", "= self.input_xml_parser.get( 'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get( 'xs/tddft/drude', [0., 0.])", "np.reshape( data[2], (n_components, n_sigma)) def parse_loss(data, sec_scc): n_components = len(data)", "*\\n\\+{10})', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format',", "'band_k_points': res = [] for i in range(len(self.number_of_k_points_per_segment)): start =", "* ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:] elif quantity == 'EPSILON' and", "start = 0 band_energies = np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues, len(self.distances)), dtype=float)", "val = val[0] if len(val) == 1 else val return", "** 3), 'x_exciting_number_of_atoms': ('Total number of atoms per unit cell',", "= None self._nspin = None self._nlm = None self._energies =", "def str_to_quantity_tolerances(val_in): return val_in.strip().replace('(', '').replace(')', '').split() def str_to_energy_dict(val_in): val =", "__init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'k_points',", "'').strip()) # method goes first since reference needed for sec_scc", "np.array([v.split() for v in val[3:6]], dtype=float) return [nbands, mesh, origin,", "self._energy_keys_mapping.items(): val = None for name in names: val =", "self._natoms = None self._nspin = None self._nlm = None self._energies", "self.input_xml_parser.get('libxc/exchange', None) xc_functional_names.append(exchange) sec_xc_functional = sec_dft.m_create(XCFunctional) for name in xc_functional_names:", "dtype=float) vector = np.array([v.split() for v in val[3:6]], dtype=float) return", "= self.logger self.dos_out_parser.logger = self.logger self.bandstructure_dat_parser.logger = self.logger self.band_out_parser.logger =", "threshold_force def parse_method(self): sec_run = self.archive.run[-1] sec_method = sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo'))", "len(data[0][0][0]) sec_scc.x_exciting_xs_tddft_epsilon_energies = data[0][0][0] * ureg.hartree sec_scc.x_exciting_xs_tddft_dielectric_function_local_field = data[1:] elif", "not None: sec_xc_functional.name = xc_functional.get('name_reference', [None, None])[0] sec_xc_functional.reference = xc_functional.get('name_reference',", "None) if spin is None: spin = (i % (self.number_of_spin_channels", "elif quantity == 'SIGMA': parse_function = parse_sigma elif quantity ==", "key == 'charge_total': pass else: setattr(msection, key, val) # moment", "*\\n))', str_operation=str_to_eigenvalues, repeats=True)) class ExcitingGWOutParser(TextParser): def __init__(self, mainfile, logger): super().__init__(mainfile,", "n_components = len(data) data = np.transpose(np.vstack(data)) n_loss = len(data[0]) //", "the given filename exists and is accessible in the same", "sec_eigenvalues.energies = get_data('eigenvalues') def _parse_fermisurface(self, sec_scc): fermi_surface = self.fermisurf_parser.get('fermi_surface', [None])[0]", "it from last scf_iteration or optimization_step final = section.get('scf_iteration', [None])[-1]", "3) sec_method.x_exciting_xs_tddft_macroscopic_dielectric_function_q_treatment = self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get( 'xs/tddft/nwacont',", "r'(?:Self\\-consistent loop started|Groundstate module started)([\\s\\S]+?)Groundstate module stopped', sub_parser=TextParser(quantities=module_quantities), repeats=False)) optimization_quantities", "= XMLParser() self.data_xs_parser = DataTextParser() self.data_clathrate_parser = DataTextParser(dtype=str) # different", "(nspin, len(data) // nspin, len(data[0]))) sec_gw_eigenvalues = sec_scc.m_create(BandEnergies) sec_gw_eigenvalues.qp_linearization_prefactor =", "self.info_parser.mainfile = self.filepath self.info_parser.logger = self.logger self.dos_parser.logger = self.logger self.bandstructure_parser.logger", "init_parameters(self): self._ndos = None self._natoms = None self._nspin = None", "and # limitations under the License. # import numpy as", "of the files: bs_files = ['bandstructure-qp.dat', 'BAND-QP.OUT'] for fname in", "= parser.evalqp_parser.quantities self.info_gw_parser.quantities = parser.info_gw_parser.quantities def parse(self, filepath, archive, logger):", "hybrids calculation for module in ['groundstate', 'hybrids']: sec_scc = parse_configuration(self.info_parser.get(module))", "f in gw_files: self.parse_file(f, sec_scc) frequency_data = self.info_gw_parser.get('frequency_data', None) if", "= ExcitingEvalqpParser() self.dos_out_parser = DataTextParser() self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser =", "'hybrids']: sec_scc = parse_configuration(self.info_parser.get(module)) if sec_scc is None: continue #", "== 'gamma' else start, '\\u0393' if end.lower() == 'gamma' else", "None else final if final is None: return sec_scc =", "0) sec_method.x_exciting_xs_screening_ngridk = self.input_xml_parser.get( 'xs/screening/ngridk', [0, 0, 0]) rgkmax =", "sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints = band_k_points[nb] sec_k_band_segment.energies = band_energies[nb] +", "file # atom-resolved bandstructure are added as separate section_k_band res", "= [ val[n][1].magnitude for n in range(len(val))] * val[0][1].units sec_charges.total", "nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.kpoints", "sec_method.gw.number_of_frequencies = len(number) sec_method.gw.frequency_number = number sec_method.gw.frequency_values = frequency_data.get('values') sec_method.gw.frequency_weights", "filename = os.path.join(self.info_parser.maindir, filename) if os.path.isfile(filename): return [filename] filename =", "'xc_functional', r'(Exchange-correlation type[\\s\\S]+?\\n *\\n)', sub_parser=TextParser(quantities=[ Quantity('type', r'Exchange-correlation type +: +(\\S+)'),", "for n in range(len(self.bands)): res_n = [] start = 0", "Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])),", "files gw_info_files = ['GW_INFO.OUT', 'GWINFO.OUT'] for f in gw_info_files: if", "== self.distances[i - 1]: self._nkpts_segment .append(count) count = 1 else:", "force_convergence[0] sec_scc.x_exciting_geometry_optimization_threshold_force = force_convergence[1] sec_scc = parse_configuration(structure_optimization) if sec_scc is", "if axis is None: return self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return", "repeats=False) ) initialization_quantities.append(Quantity( 'species', rf'(Species : *\\d+ *\\(\\w+\\)[\\s\\S]+?{re_float} *{re_float} *{re_float}\\n\\s*\\n)',", "val is None: continue setattr(msection, name, val) # other metainfo", "not self.partial_dos: return res = np.zeros(( self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos))", "['FXC', 'NLF_FXC']: data = get_data(quantity, ext) if not data[0]: continue", "not None: res = res * (1 / self.energy_unit) elif", "sec_gw.core_treatment = self.input_xml_parser.get( 'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states = int( self.input_xml_parser.get('gw/nempty', 0))", "self._total_dos = self.root.findall('./%s/%s' % (self._totaldos_key, self._diagram_key)) return self._total_dos @property def", "default.rsplit('.', 1) filename = '%s%s' % (target[0], suffix) if target[1:]:", "of xs if self.input_xml_parser.get('xs/screening') is not None: sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get(", "is None: lm = i % self.number_of_lm else: lm =", "if len(gw_info_files) > 1: self.logger.warn('Found multiple GW info files, will", "'x_exciting_scf_threshold_%s_change' % name.split('_')[-2] setattr(sec_method, metainfo_name, threshold) # additionally, set threshold", "unit=ureg.hartree, repeats=False)) def str_to_band_parameters(val_in): val = val_in.strip().split('\\n') nbands = int(val[0])", "ureg.bohr), ]), repeats=False)) self._quantities.append(Quantity( 'hybrids', r'Hybrids module started([\\s\\S]+?)Hybrids module stopped',", "else self.get_positions_format(section) if positions_format == 'lattice': cell = self.get_initialization_parameter('lattice_vectors') if", "key_unit in self._miscellaneous_keys_mapping.items(): scf_quantities.append(Quantity( name, r'%s\\s*\\:*\\s*([\\-\\d\\.Ee]+)' % key_unit[0], repeats=False, unit=key_unit[1]))", "= self.input_xml_parser.get( 'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get( 'xs/BSE/lmaxdielt', 14) rgkmax", "= [True] * 3 # TODO confirm no cell optimization", "versions of exciting self._energy_keys_mapping = { 'energy_total': ['Total energy', 'total", "self.get('initialization', {}).get(key, default) class ExcitingParser: def __init__(self): self.info_parser = ExcitingInfoParser()", "(name.endswith('DAT') or name.endswith('TXT')): parser = self.evalqp_parser parser_function = self._parse_evalqp elif", "threshold_force = structure_optimization.get( 'optimization_step', [{}])[0].get('force_convergence', [0., 0.])[-1] sec_geometry_opt.input_force_maximum_tolerance = threshold_force", "get_xc_functional_name(self): # TODO expand list to include other xcf xc_functional_map", "atoms = self.input_xml_parser.get('structure/species/atom') atom_labels = [] for n in range(len(atoms)):", "True) file_ext_list = [ 'TET' if tetradf else None, 'AC'", "val = val_in.strip().split('\\n') kpts = np.array(val[0].split(), dtype=float) keys = val[1].split()", "1 self._nkpts_segment.append(count) return self._nkpts_segment @property def number_of_band_segment_eigenvalues(self): if self._neigs_segment is", "= self.eigval_parser parser_function = self._parse_eigenvalues elif (name.startswith('FERMISURF') or name.startswith('FS')) and", "count = 1 else: count += 1 self._nkpts_segment.append(count) return self._nkpts_segment", "smearing_kind is not None: if not isinstance(smearing_kind, str): smearing_kind =", "sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(Atomic positions\\s*\\([\\s\\S]+?)\\n\\n', sub_parser=TextParser(quantities=[ Quantity( 'positions_format', r'Atomic", "if nwacont else None, 'NAR' if not aresdf else None]", "('Total core charge', ureg.elementary_charge), 'x_exciting_valence_charge_initial': ('Total valence charge', ureg.elementary_charge), 'x_exciting_wigner_radius':", "'gamma' else end]) elif key == 'band_segm_start_end': res = []", "for s in species]) if positions is None: return positions", "r'Time spent in this optimization step\\s*\\:\\s*([\\-\\d\\.Ee]+)\\s*seconds', unit=ureg.s, repeats=False, dtype=float) ]", "'x_exciting_fermi_energy': ['Fermi energy', 'Fermi'], 'energy_kinetic_electronic': ['Kinetic energy', 'electronic kinetic'], 'energy_coulomb':", "for bandstructure dat and xml self._nspin = None self._nkpts_segment =", "and name.endswith('bxsf'): parser = self.fermisurf_parser parser_function = self._parse_fermisurface elif name.startswith('EVALQP')", "r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False) ) self._quantities.append( Quantity( 'fundamental_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Fundamental BandGap\\s*\\((?P<__unit>\\w+)\\)\\s*\\:(\\s*[\\d\\.]+)\\s', repeats=False)", "reference.get('scf_iteration', [{}])[-1].get( name, [None, None])[-1] def get_scf_quantity(self, name): n_scf =", "self.evalqp_parser.logger = self.logger self.dos_out_parser.logger = self.logger self.bandstructure_dat_parser.logger = self.logger self.band_out_parser.logger", "None: lm = i % self.number_of_lm else: lm = int(val_l)", "= sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_dat_parser.band_k_points nkpts_segment", "if quantity == 'EXCITON': parse_function = parse_exciton elif quantity ==", "= end return self._band_energies @property def band_k_points(self): if self._band_k_points is", "'x_exciting_electron_nuclear_energy': ['Electron-nuclear energy', 'electron-nuclear '], 'x_exciting_nuclear_nuclear_energy': ['Nuclear-nuclear energy', 'nuclear-nuclear'], 'x_exciting_madelung_energy':", "xstype sec_method.x_exciting_electronic_structure_method = xstype sec_method.x_exciting_xs_broadening = self.input_xml_parser.get( 'xs/broad', 0.01, 'hartree')", "[] count = 1 for i in range(1, len(self.distances)): if", "that the first steps are the # ones with the", "# scf iterations scf_iterations = section.get('scf_iteration', []) for scf_iteration in", "self.input_xml_parser.get('xs/screening') is not None: sec_method.x_exciting_xs_screening_number_of_empty_states = self.input_xml_parser.get( 'xs/screening/nempty', 0) sec_method.x_exciting_xs_screening_ngridk", "suffix) if target[1:]: filename = '%s.%s' % (filename, target[1]) filename", "i in range(len(self.number_of_k_points_per_segment)): start = self.vertices[i].attrib.get(self._coord_key).split() end = self.vertices[i +", "sec_scc): # we need to set nspin again as this", "val is None: continue if key.startswith('energy_'): sec_energy.m_add_sub_section(getattr( Energy, key.replace('energy_', '')),", "parser_function = self._parse_evalqp elif name.startswith('TDOS') and name.endswith('OUT'): parser = self.dos_out_parser", "[]] for i in range(len(qpoints)): data_q = [] files_q =", "= self.input_xml_parser.get( 'xs/tddft/mdfqtype', 0) sec_method.x_exciting_xs_tddft_analytic_continuation_number_of_intervals = self.input_xml_parser.get( 'xs/tddft/nwacont', 0) sec_method.x_exciting_xs_tetra", "{})) lattice_vectors = self.info_parser.get_initialization_parameter('lattice_vectors') atom_labels = self.info_parser.get_atom_labels(section.get('atomic_positions', {})) input_file =", "'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False) ) self._quantities.append( Quantity( 'direct_band_gap', r'\\-\\s*G0W0\\s*\\-\\s*\\-+\\s*[\\s\\S]*?Direct", "'energy_coulomb': ['Coulomb energy', 'Coulomb'], 'x_exciting_coulomb_energy': ['Coulomb energy', 'Coulomb'], 'energy_exchange': ['Exchange", "return [] name = xc_functional_map.get(xc_functional.type, []) return name @property def", "assume it is # energy dos_up dos_down nspin = self.info_parser.get_number_of_spin_channels()", "bse_types = ['IP', 'singlet', 'triplet', 'RPA'] scr_types = ['full', 'diag',", "in self._system_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False)", "'LDA_X_PZ'], 3: ['LDA_C_PW', 'LDA_X_PZ'], 4: ['LDA_C_XALPHA'], 5: ['LDA_C_VBH'], 20: ['GGA_C_PBE',", "np.transpose(data[2:5])[start:end]) start = end return self._band_k_points @property def distances(self): if", "= np.transpose(self.data)[0] self._neigs_segment = len(np.where(data == data[0])[0]) return self._neigs_segment class", "other energies are reported. energy_fermi = 0.0 * ureg.hartree if", "None) self._units_mapping = dict(hartree=ureg.hartree) def init_parameters(self): self._ndos = None self._natoms", "= None for name in names: val = moment_contributions.get(name, None)", "= sec_system.m_create(x_exciting_section_spin) sub_sec.x_exciting_spin_treatment = val elif name == 'x_exciting_species_rtmin': setattr(sec_system,", "[None])[-1] if final is None else final if final is", "self.info_parser.get_initialization_parameter('x_exciting_rgkmax', 0.) sec_method.x_exciting_xs_screening_rgkmax = rgkmax sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get( 'xs/screening/screentype', 'full')", "def _parse_eigenvalues(self, sec_scc): if self.eigval_parser.get('eigenvalues_occupancies', None) is None: return nspin", "= self.fermisurf_parser parser_function = self._parse_fermisurface elif name.startswith('EVALQP') and (name.endswith('DAT') or", "= self.input_xml_parser.get('xs/vkloff', [0., 0., 0.]) # TODO I am not", "== 'EPSILON': parse_function = parse_epsilon elif quantity == 'SIGMA': parse_function", "sec_scc): self.bandstructure_dat_parser._nspin = self.info_parser.get_number_of_spin_channels() band_energies = self.bandstructure_dat_parser.band_energies if band_energies is", "nspin again as this is overwritten when setting mainfile self.bandstructure_parser._nspin", "*{re_float} *{re_float}\\n\\s*\\n)', repeats=True, sub_parser=TextParser(quantities=[ Quantity('number', r'Species : *(\\d+)', dtype=np.int32), Quantity('symbol',", "sec_run.method[-1] return sec_scc # groundstate and hybrids calculation for module", "= fundamental_band_gap optical_band_gap = self.info_gw_parser.get('optical_band_gap', None) if optical_band_gap is not", "is not None: self._energies = self._energies * self.energy_unit return self._energies", "sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk', [1, 1, 1]) rgkmax = self.input_xml_parser.get('xs/rgkmax', None)", "def init_quantities(self): self._quantities = [] self._quantities.append( Quantity( 'fermi_energy', r'Fermi Energy:\\s*([\\d\\.]+)\\s*',", "are reported. energy_fermi = sec_scc.energy.fermi if energy_fermi is None: continue", "self._energy_unit: band_energy = band_energy * self._energy_unit self._band_energies.append(band_energy) start = end", "sec_scc.m_create(Dos, Calculation.dos_electronic) sec_dos.n_energies = self.dos_parser.number_of_dos sec_dos.energies = self.dos_parser.energies + energy_fermi", "self._total_dos = None self._partial_dos = None @property def energy_unit(self): if", "'RPA') sec_method.x_exciting_xs_tddft_finite_q_intraband_contribution = self.input_xml_parser.get( 'xs/tddft/intraband', False) sec_method.x_exciting_xs_tddft_diagonal_xc_kernel = self.input_xml_parser.get( 'xs/tddft/kerndiag',", "elif name.startswith('BAND') and name.endswith('OUT'): parser = self.band_out_parser parser_function = self._parse_band_out", "# all files related to quantity at all qpoints files", "energies are reported. energy_fermi = sec_scc.energy.fermi if energy_fermi is None:", "None) self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): self._nspin = None", "seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity( 'final', r'Force convergence target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities),", "symmetries', None), 'x_exciting_number_of_crystal_symmetries': ('Number of crystal symmetries', None), 'x_exciting_kpoint_grid': (r'k\\-point", "= res.reshape((len(res), len(data), len(res[0]) // len(data))) if key == 'eigenvalues':", "= xc_functional_map.get(xc_functional.type, []) return name @property def n_optimization_steps(self): return len(self.get('structure_optimization',", "None) if xc_functional is None: return [] name = xc_functional_map.get(xc_functional.type,", "None) def init_parameters(self): self._nspin = None self._nkpts_segment = None self._neigs_segment", "{}).get( 'x_exciting_spin_treatment', 'spin-unpolarised') n_spin = 1 if spin_treatment.lower() == 'spin-unpolarised'", "if self.file_exists(fname): gw_files.append(fname) break for f in gw_files: self.parse_file(f, sec_scc)", "r'Total atomic forces including IBS \\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Time', repeats=False, str_operation=str_to_array, convert=False,", "= None self._distances = None self._band_energies = None self._band_k_points =", "return self._total_dos @property def partial_dos(self): if self._partial_dos is None: self._partial_dos", "for energy in band_energies]) if self._energy_unit is not None: band_energy", "BandOutParser(DataTextParser): def __init__(self, **kwargs): super().__init__(**kwargs) self._nspin = kwargs.get('nspin', None) self._energy_unit", "self._band_energies = None self._neigs_segment = None self._nkpts_segment = None @property", "r'Hybrids module started([\\s\\S]+?)Hybrids module stopped', sub_parser=TextParser(quantities=module_quantities) )) def get_atom_labels(self, section):", "in self._method_keys_mapping.items(): initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False)", "= energy_fermi band_k_points = self.bandstructure_parser.get('band_k_points') nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels =", "contributions moment_contributions = iteration.get('moment_contributions', {}) for key, names in self._moment_keys_mapping.items():", "r'RMS change in effective potential \\(target\\)', ureg.hartree), 'x_exciting_energy_convergence': ( r'Absolute", "v[1] * unit))) else: vi = [float(vii) for vii in", "leakage'], 'x_exciting_valence_charge': ['valence'], 'x_exciting_interstitial_charge': ['interstitial'], 'x_exciting_total_MT_charge': ['total charge in muffin-tins',", "ExcitingEvalqpParser() self.dos_out_parser = DataTextParser() self.bandstructure_dat_parser = BandstructureDatParser(energy_unit=ureg.hartree) self.band_out_parser = BandOutParser(energy_unit=ureg.hartree)", "self.info_gw_parser = GWInfoParser() self.input_xml_parser = XMLParser() self.data_xs_parser = DataTextParser() self.data_clathrate_parser", "sec_method.x_exciting_xs_bse_xas_number_of_bands = self.input_xml_parser.get( 'xs/BSE/nstlxas', [0, 0]) if self.input_xml_parser.get('xs/tddft') is not", "this is really problematic if some scf steps dont have", "simply write parameters xc_functional = self.info_parser.get('initialization', {}).get('xc_functional') if xc_functional is", "bs_files = ['bandstructure.xml', 'BAND.OUT', 'bandstructure.dat'] for fname in bs_files: if", "is not None: sec_scc.system_ref = sec_system sec_scc.method_ref = sec_run.method[-1] return", "sec_scc.method_ref = sec_run.method[-1] return sec_scc # groundstate and hybrids calculation", "def n_optimization_steps(self): return len(self.get('structure_optimization', {}).get('optimization_step', [])) def get_number_of_spin_channels(self): spin_treatment =", "in species: labels += [specie.get('symbol')] * len(specie.get('positions')) return labels def", "= [] species = None for v in val: v", "elif 'HYB' in name: sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name)) if not xc_functional_names:", "parsed? sccs = [] for quantity in ['EXCITON', 'EPSILON', 'SIGMA',", "self._energy_unit @property def number_of_spin_channels(self): if self._nspin is None: if not", "1, 1]) sec_gw.basis_set = 'mixed' sec_gw.qp_equation_treatment = 'linearization' sec_gw.max_frequency =", "str_operation=str_to_energy_dict, repeats=False, convert=False), Quantity( 'x_exciting_dos_fermi', r'DOS at Fermi energy \\(states\\/Ha\\/cell\\)\\s*:\\s*([\\-\\d\\.Ee]+)',", "sec_method.x_exciting_xs_bse_sciavbd = self.input_xml_parser.get( 'xs/BSE/sciavbd', True) sec_method.x_exciting_xs_bse_sciavqbd = self.input_xml_parser.get( 'xs/BSE/sciavqbd', False)", "if key == 'band_energies': # TODO I am not certain", "sec_method_ref = self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] self.parse_file('input.xml',", "= archive self.logger = logger if logger is not None", "\\(\\w+\\)\\s*\\:(\\s*atom[\\-\\s\\w\\.\\:]*?)\\n *Atomic', repeats=False, str_operation=str_to_array, dtype=float, unit=ureg.hartree / ureg.bohr) ] self._quantities.append(Quantity(", "iteration.get('energy_contributions', {}) for key, names in self._energy_keys_mapping.items(): val = None", "related to quantity at all qpoints files = self.get_exciting_files('%s_%s%s%s.OUT' %", "range(len(val)): sec_mt_moment_atom = msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n + 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol", "setattr(msection, 'x_exciting_dos_fermi', x_exciting_dos_fermi) # energy contributions energy_contributions = iteration.get('energy_contributions', {})", "2.0) sec_gw.bare_coulomb_gmax = pwm * gmb * gmaxvr sec_gw.bare_coulomb_cutofftype =", "scc # TODO add support for more output files and", "= None self._natoms = None self._nspin = None self._nlm =", "quantity in ['EPSILON', 'LOSS', 'SIGMA']: for ext in ['FXC', 'NLF_FXC']:", "for spin in range(len(dos)): sec_dos_values = sec_dos.m_create(DosValues, Dos.total) sec_dos_values.spin =", "= self.bandstructure_parser.get('band_segm_labels') for nb in range(len(band_energies[n])): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints", "sec_method.x_exciting_xs_gqmax = self.input_xml_parser.get( 'xs/gqmax', 0.0, '1/bohr') sec_method.x_exciting_xs_lmaxapw = self.input_xml_parser.get('xs/lmaxapw', 10)", "else None] file_ext = '_'.join([e for e in file_ext_list if", "+ nkpts_segment self._band_k_points.append( np.transpose(data[2:5])[start:end]) start = end return self._band_k_points @property", "None: self._partial_dos = self.root.findall('./%s/%s' % (self._partialdos_key, self._diagram_key)) return self._partial_dos @property", "data def parse_exciton(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data))", "= section.get('optimization_step', [None])[-1] if final is None else final if", "if val is not None: break if val is None:", "= get_data('k_points') sec_gw_eigenvalues.energies = reshape(eigs_gw) sec_gw_eigenvalues.value_exchange = reshape(get_data('Sx')) eigs_gw_C =", "= kwargs.get('energy_unit', None) def init_parameters(self): self._nspin = None self._distances =", "smearing with should have units of energy sec_smearing.width = smearing_width.magnitude", "get_scf_quantity(self, name): n_scf = len(self.get('energy_total_scf_iteration', [])) quantity = self.get('%s_scf_iteration' %", "express or implied. # See the License for the specific", "Energy, key.replace('energy_', '')), EnergyEntry(value=val)) else: setattr(msection, key, val) if key", "sec_scc.x_exciting_xs_tddft_loss_function_no_local_field = data[1] elif quantity == 'SIGMA' and ext ==", "for different versions of exciting self._energy_keys_mapping = { 'energy_total': ['Total", "lm = int(val_l) ** 2 + int(val_m) + int(val_l) atom", "val[2:]], dtype=float)) eigs = {keys[i]: eigs[i] for i in range(len(keys))}", "tetradf else None, 'AC' if nwacont else None, 'NAR' if", "DataTextParser(dtype=str) # different names for different versions of exciting self._energy_keys_mapping", "= np.transpose( np.array(data[:3], dtype=float)) sec_system.x_exciting_clathrates_atom_labels = list(data[3]) else: sec_system.x_exciting_clathrates =", "elif 'partial' in key: if not self.partial_dos: return res =", "is done in parser, however nspin is # determined from", "if not self._calculation_type == 'gw': return sec_method = sec_run.m_create(Method) sec_method_ref", "val.split('\\n')], dtype=float) val = np.transpose(val) occs = val[-1] eigs =", "if self.partial_dos is None: return self._nlm = 0 l_list =", "density', 1 / ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector grid sizes', None), 'x_exciting_gvector_total':", "'tetrahedra'} sec_smearing = sec_electronic.m_create(Smearing) smearing_kind = self.info_parser.get_initialization_parameter('smearing_kind') if smearing_kind is", "cell = self.get_initialization_parameter('lattice_vectors') if cell is None: return positions =", "class ExcitingGWOutParser(TextParser): def __init__(self, mainfile, logger): super().__init__(mainfile, logger=logger) def init_quantities(self):", "['GGA_C_PBE', 'GGA_X_PBE_R'], 22: ['GGA_C_PBE_SOL', 'GGA_X_PBE_SOL'], 26: ['GGA_C_PBE', 'GGA_X_WC'], 30: ['GGA_C_AM05',", "*(\\d+)', dtype=np.int32), Quantity('symbol', r'\\((\\w+)\\)'), Quantity('file', r'parameters loaded from *: *(.+)'),", "if self.energy_unit is not None: self._energies = self._energies * self.energy_unit", "def init_parameters(self): # TODO make a parent clas for bandstructure", "None), 'x_exciting_lmaxapw': (r' APW functions', None), 'x_exciting_nuclear_charge': ('Total nuclear charge',", "None) if val_l is None or val_m is None: lm", "self._energies = np.array( [float(point.attrib.get(self._energy_key)) for point in self.total_dos[0]]) if self.energy_unit", "self.evalqp_parser.quantities = parser.evalqp_parser.quantities self.info_gw_parser.quantities = parser.info_gw_parser.quantities def parse(self, filepath, archive,", "= np.transpose(self.data) self._neigs_segment = int(max(data[0])) return self._neigs_segment class BandOutParser(DataTextParser): def", "is None: return return np.reshape(data, (nspin, len(data) // nspin, len(data[0])))", "= fermi_energy sec_fermisurface.x_exciting_values_fermi_surface = fermi_surface def _parse_evalqp(self, sec_scc): data =", "problematic sometimes res = np.hstack([np.reshape(v[key], (nspin, np.size(v[key]) // nspin)) for", "*(.+?:.+)', repeats=True, str_operation=lambda x: [v.strip() for v in x.split(':')])])) )", "'gw/selfenergy/singularity', 'mpd') sec_gw.self_energy_c_analytical_continuation = self.input_xml_parser.get( 'gw/selfenergy/actype', 'pade') sec_gw.mixed_basis_lmax = int(self.input_xml_parser.get(", "rf'atomic mass *: *({re_float})', dtype=np.float64, unit=ureg.electron_mass), Quantity('muffin_tin_radius', rf'muffin-tin radius *:", "sec_scc is None: continue # add data to scc #", "self._l_key = 'l' self._m_key = 'm' self._energy_key = 'e' self._dos_key", "= np.transpose(np.array([v for v in val if len(v) == 3],", "self._neigs_segment = int(max(data[0])) return self._neigs_segment class BandOutParser(DataTextParser): def __init__(self, **kwargs):", "return np.reshape(data, (nspin, len(data) // nspin, len(data[0]))) sec_gw_eigenvalues = sec_scc.m_create(BandEnergies)", "sec_dos.n_energies = self.dos_parser.number_of_dos sec_dos.energies = self.dos_parser.energies + energy_fermi volume =", "return sec_scc = self.parse_scc(section) if sec_scc is None: return sec_system", "files = self.get_exciting_files( '%s_BSE%s_SCR%s.OUT' % (name, bse_type, scr_type)) bse_files.append(files) return", "is None: return self._energy_unit = self._units_mapping.get(axis.attrib.get(self._unit_key).lower(), 1) return self._energy_unit @property", "self.dos_parser = DOSXMLParser(energy_unit=ureg.hartree) self.bandstructure_parser = BandstructureXMLParser(energy_unit=ureg.hartree) self.eigval_parser = ExcitingEigenvalueParser() self.fermisurf_parser", "= self.input_xml_parser.get( 'gw/freqgrid/fgrid', 'gaule2') sec_gw.number_of_frequencies = int(self.input_xml_parser.get( 'gw/freqgrid/nomeg', 16)) sec_gw.self_energy_c_number_of_poles", "= res * (1 / self.energy_unit) elif key == 'energies':", "None for v in val: v = v.strip().split(':') if len(v)", "_parse_xs_bse(self): sec_run = self.archive.run[-1] # TODO read from xml file", "'method', r'method\\s*=\\s*(\\w+)', repeats=False, dtype=str), Quantity( 'n_scf_iterations', r'Number of (?:total)* scf", "'Madelung'], 'x_exciting_core_electron_kinetic_energy': ['Core-electron kinetic energy', 'core electron kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2", "of crystal symmetries', None), 'x_exciting_kpoint_grid': (r'k\\-point grid', None), 'x_exciting_kpoint_offset': (r'k\\-point", "dtype=float) def str_to_atom_properties_dict(val_in): unit = None if 'charge' in val_in:", "'charge_total': ['total charge'], 'x_exciting_section_MT_charge_atom': ['atom_resolved'] } self._moment_keys_mapping = { 'x_exciting_interstitial_moment':", "xs data', data=dict(file=quantity)) def _parse_xs_tddft(self): sec_run = self.archive.run[-1] fxctype =", "if metainfo_name == 'x_exciting_scf_threshold_energy_change': sec_method.scf = Scf(threshold_energy_change=threshold) xc_functional_names = self.info_parser.get_xc_functional_name()", "np.transpose(self.data) self._neigs_segment = int(max(data[0])) return self._neigs_segment class BandOutParser(DataTextParser): def __init__(self,", "ForcesEntry, ScfIteration, BandGap ) from nomad.datamodel.metainfo.workflow import Workflow, GeometryOptimization from", "in val.split('\\n')], dtype=float) val = np.transpose(val) occs = val[-1] eigs", "other xcf xc_functional_map = { 2: ['LDA_C_PZ', 'LDA_X_PZ'], 3: ['LDA_C_PW',", "1): start = self.vertices[i].attrib.get('label') end = self.vertices[i + 1].attrib.get('label') res.append([", "// nspin)) data['eigenvalues'] = np.reshape(eigs, (nspin, len(eigs) // nspin)) return", "it from input.xml for f in input_file: self.input_xml_parser.mainfile = f", "*= self.input_xml_parser.get('structure/crystal/scale', 1.0) positions = np.dot(positions, lattice_vectors) * ureg.bohr lattice_vectors", "= len(data[0]) // n_components sec_scc.x_exciting_xs_bse_sigma_energies = np.reshape( data[0], (n_components, n_sigma))", "at this step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity( 'positions',", "'xs/BSE/lmaxdielt', 14) rgkmax = self.input_xml_parser.get('xs/BSE/rgkmax', None) if rgkmax is None:", "None or val_m is None: lm = i % self.number_of_lm", "= int(val[0]) mesh = np.array(val[1].split(), dtype=int) origin = np.array(val[2].split(), dtype=float)", "self._ndos is None: total_dos = self.root.find('./%s/%s' % (self._totaldos_key, self._diagram_key)) self._ndos", "muffin-tins'], 'x_exciting_total_moment': ['total moment'], 'x_exciting_section_MT_moment_atom': ['atom_resolved'] } def get_exciting_files(self, default):", "in self.info_parser._miscellaneous_keys_mapping.keys(): val = iteration.get(name) if val is None: continue", "= np.transpose(val) occs = val[-1] eigs = val[-2] nspin =", "in total energy\\s*\\(target\\)', ureg.hartree), 'x_exciting_charge_convergence': ( r'Charge distance\\s*\\(target\\)', ureg.elementary_charge), 'x_exciting_IBS_force_convergence':", "['LDA_C_XALPHA'], 5: ['LDA_C_VBH'], 20: ['GGA_C_PBE', 'GGA_X_PBE'], 21: ['GGA_C_PBE', 'GGA_X_PBE_R'], 22:", "= self.info_parser.get_initialization_parameter('x_exciting_gmaxvr', 0) sec_gw.core_treatment = self.input_xml_parser.get( 'gw/coreflag', 'all') sec_gw.polarizability_number_of_empty_states =", "cell', None), 'x_exciting_spin_treatment': ('Spin treatment', None), 'x_exciting_number_of_bravais_lattice_symmetries': ('Number of Bravais", "ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re = np.reshape( data[1], (n_components, n_sigma)) sec_scc.x_exciting_xs_bse_sigma_im = np.reshape(", "= self.dos_parser.get('partialdos') if partialdos is None: return partialdos = partialdos.to('1/joule').magnitude", "return bse_files def get_data(files): data = [] for f in", "None: data = np.transpose(self.data) self._neigs_segment = int(max(data[0])) return self._neigs_segment class", "* unit))) else: vi = [float(vii) for vii in v[1].split()]", "if key == 'x_exciting_section_MT_moment_atom': for n in range(len(val)): sec_mt_moment_atom =", "= self.info_gw_parser.get('optical_band_gap', None) if optical_band_gap is not None: sec_gap.value_optical =", "'positions_format', r'Atomic positions at this step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True,", "'lattice_vectors_reciprocal', r'Reciprocal lattice vectors\\s*[\\(cartesian\\)]*\\s*:\\s*([\\-0-9\\.\\s]+)\\n', str_operation=str_to_array, unit=1 / ureg.bohr, repeats=False, convert=False),", "res.append(np.linspace(start, end, self.number_of_k_points_per_segment[i])) elif key == 'band_segm_labels': res = []", "= start + nkpts_segment band_energy = np.array([ np.transpose(energy)[start:end] for energy", "'FERMISURF.bxsf', 'FS.bxsf'] # Parse DFT DOS from one of the", "files bs_files = ['dos.xml', 'TDOS.OUT'] for fname in bs_files: if", "self.filepath self.info_parser.logger = self.logger self.dos_parser.logger = self.logger self.bandstructure_parser.logger = self.logger", "* self._energy_unit self._band_energies.append(band_energy) start = end return self._band_energies @property def", "len(occs) // nspin)) data['eigenvalues'] = np.reshape(eigs, (nspin, len(eigs) // nspin))", "as this is overwritten when setting mainfile self.bandstructure_parser._nspin = self.info_parser.get_number_of_spin_channels()", "r'Using ([\\w ]+) potential mixing', repeats=False, flatten=False) ) initialization_quantities.append(Quantity( 'xc_functional',", "self.input_xml_parser.get( 'gw/mixbasis/epsmb', 0.0001) gmb = self.input_xml_parser.get('gw/mixbasis/gmb', 1.0) sec_gw.mixed_basis_gmax = gmb", "sec_k_band.energy_fermi = energy_fermi band_k_points = self.bandstructure_parser.get('band_k_points') nkpts_segment = self.bandstructure_parser.number_of_k_points_per_segment band_seg_labels", "determined from occupancies which is problematic sometimes res = np.hstack([np.reshape(v[key],", "specie in species: labels += [specie.get('symbol')] * len(specie.get('positions')) return labels", "['DFT-D2 dispersion correction'] } self._electron_charge_keys_mapping = { 'x_exciting_core_charge': ['core'], 'x_exciting_core_leakage':", "range(len(keys))} return [kpts, eigs] self._quantities.append( Quantity( 'kpoints_eigenvalues', r'\\s*k\\-point \\#\\s*\\d+:\\s*([\\d\\s\\.\\-]+)([ \\w\\(\\)]+\\n)([\\s\\d\\.\\-Ee]+)',", "atom sec_dos_values.value = partialdos[lm][spin][atom] def _parse_bandstructure(self, sec_scc): # we need", "me! if metainfo_name == 'x_exciting_scf_threshold_energy_change': sec_method.scf = Scf(threshold_energy_change=threshold) xc_functional_names =", "self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas = self.input_xml_parser.get( 'xs/BSE/xas', False) sec_method.x_exciting_xs_bse_number_of_bands =", "range(len(self.bands)): res_n = [] start = 0 band_energies = np.zeros((", "'x_exciting_correlation_energy': ['Correlation energy', 'correlation'], 'energy_sum_eigenvalues': ['Sum of eigenvalues', 'sum of", "'EPSILON': parse_function = parse_epsilon elif quantity == 'SIGMA': parse_function =", "sec_scc is None: return sec_system = self.parse_system(section) if sec_system is", "make a parent clas for bandstructure dat and xml self._nspin", "= self.input_xml_parser.get( 'xs/BSE/sciavqwg', False) sec_method.x_exciting_xs_bse_sciavtype = self.input_xml_parser.get( 'xs/BSE/sciavtype', 'spherical') sec_method.x_exciting_xs_bse_xas", "sec_scc.x_exciting_xs_bse_exciton_amplitude_re = np.reshape( data[4], (n_components, n_excitons)) sec_scc.x_exciting_xs_bse_exciton_amplitude_im = np.reshape( data[5],", "'%s_BSE%s_SCR%s.OUT' % (name, bse_type, scr_type)) bse_files.append(files) return bse_files def get_data(files):", "+ 1].attrib.get('label') res.append([ '\\u0393' if start.lower() == 'gamma' else start,", "'partial' in key: if not self.partial_dos: return res = np.zeros((", "'')), EnergyEntry(value=val)) else: setattr(msection, key, val) if key == 'x_exciting_fermi_energy':", "r'Force convergence target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False), Quantity( 'atomic_positions', r'(imized atomic", "if val is None: continue if key == 'x_exciting_section_MT_charge_atom': for", "for key, names in self._electron_charge_keys_mapping.items(): val = None for name", "'NLF_FXC': sec_scc.x_exciting_xs_tddft_dielectric_function_no_local_field = data[1:3] elif quantity == 'LOSS' and ext", "** 2 + int(val_m) + int(val_l) atom = i //", "sec_xc_functional.correlation.append(Functional(name=name)) elif 'HYB' in name: sec_xc_functional.hybrid.append(Functional(name=name)) else: sec_xc_functional.contributions.append(Functional(name=name)) if not", "np.array([np.transpose(band)[start:end] for band in bands]) if self._energy_unit: band_energy = band_energy", "= np.reshape( data[1], (n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape( data[2], (n_components,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "empty states', None), 'x_exciting_valence_states': ('Total number of valence states', None),", "is really problematic if some scf steps dont have the", "val[3:6]], dtype=float) return [nbands, mesh, origin, vector] self._quantities.append( Quantity( 'band_parameters',", "self._energies = None self._total_dos = None self._partial_dos = None @property", "3), 'x_exciting_brillouin_zone_volume': ('Brillouin zone volume', 1 / ureg.bohr ** 3),", "= self.info_parser.get_unit_cell_volume() dos = data[1] * (1 / ureg.hartree) *", "len(data[0]) // n_components sec_scc.x_exciting_xs_bse_number_of_energy_points = n_epsilon sec_scc.x_exciting_xs_bse_epsilon_energies = np.reshape( data[0],", "None: smearing_width = (smearing_width * ureg.hartree).to('joule') # TODO smearing with", "'partialdos' self._diagram_key = 'diagram' self._l_key = 'l' self._m_key = 'm'", "1: self.logger.warn('Found multiple files. Will read all!', data=dict(file=name)) for n", "Electronic, Smearing, XCFunctional, Functional, GW as GWMethod, Scf, BasisSet )", "* self.number_of_spin_channels) res[lm][spin][atom] = self._get_dos(self.partial_dos[i]) if self.energy_unit is not None:", "list to include other xcf xc_functional_map = { 2: ['LDA_C_PZ',", "self.get_exciting_files(name) if len(files) > 1: self.logger.warn('Found multiple files. Will read", "= [] for f in files: self.data_xs_parser.mainfile = f if", "name) if quantity is None: return # this is really", "self.info_parser.get('structure_optimization') if structure_optimization is not None: sec_worfklow.type = 'geometry_optimization' sec_geometry_opt", "self.bandstructure_dat_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints =", "]), repeats=False)) self._quantities.append(Quantity( 'hybrids', r'Hybrids module started([\\s\\S]+?)Hybrids module stopped', sub_parser=TextParser(quantities=module_quantities)", "name.endswith('OUT'): parser = self.dos_out_parser parser_function = self._parse_dos_out elif name.startswith('bandstructure') and", "__init__(self): super().__init__(None) def init_quantities(self): self._quantities = [] def str_to_frequency(val_in): val", "in range(len(files)): data = get_data(files[i]) if not data: sccs.append(None) continue", "data[2], (n_components, n_sigma)) def parse_loss(data, sec_scc): n_components = len(data) data", "= self.bandstructure_parser.get('band_energies', []) for n in range(len(band_energies)): # Get fermi", "logging from nomad.units import ureg from nomad.parsing.file_parser import TextParser, Quantity,", "'gw': parser_function = self._parse_input_gw elif self._calculation_type == 'xs': parser_function =", "and density', 1 / ureg.bohr), 'x_exciting_gvector_size': (r'G\\-vector grid sizes', None),", "start = 0 for nkpts_segment in self.number_of_k_points_per_segment: end = start", "Version 2.0 (the \"License\"); # you may not use this", "= self.get('initialization', {}).get( 'x_exciting_spin_treatment', 'spin-unpolarised') n_spin = 1 if spin_treatment.lower()", "* len(atoms[n])) if positions is None or atom_labels is None:", "self.eigval_parser.logger = self.logger self.fermisurf_parser.logger = self.logger self.evalqp_parser.logger = self.logger self.dos_out_parser.logger", "return self._distances @property def bands(self): if self._bands is None: bands", "return np.array([d[1].get(key) for d in data]) * ureg.hartree eigs_gw =", "= np.reshape( data[0], (n_components, n_sigma)) * ureg.hartree sec_scc.x_exciting_xs_bse_sigma_re = np.reshape(", "* ureg.bohr atoms = self.input_xml_parser.get('structure/species/atom') atom_labels = [] for n", "is the fourth column in epsilon which is not parsed?", "'x_exciting_effective_potential_energy': ['Effective potential energy'], 'x_exciting_coulomb_potential_energy': ['Coulomb potential energy', 'Coulomb potential'],", "= section.get('symbols') if labels is None: # we get it", "# Parse GW band structure from one of the files:", "if xc_functional is not None: sec_xc_functional.name = xc_functional.get('name_reference', [None, None])[0]", "np.reshape(eigs, (nspin, len(eigs) // nspin)) return data self._quantities.append( Quantity( 'eigenvalues_occupancies',", "v in val_in.split('\\n')] val = np.transpose(np.array([v for v in val", "sec_method.x_exciting_xs_screening_rgkmax = rgkmax sec_method.x_exciting_xs_screening_type = self.input_xml_parser.get( 'xs/screening/screentype', 'full') if self.input_xml_parser.get('xs/BSE')", "'x_exciting_kpoint_offset': (r'k\\-point offset', None), 'x_exciting_number_kpoints': (r'Total number of k\\-points', None),", "None self._band_energies = None self._neigs_segment = None self._nkpts_segment = None", "the first steps are the # ones with the missing", "self.dos_parser.logger = self.logger self.bandstructure_parser.logger = self.logger self.eigval_parser.logger = self.logger self.fermisurf_parser.logger", "= np.reshape( data[2], (n_components, n_excitons)) * ureg.hartree sec_scc.x_exciting_xs_bse_exciton_oscillator_strength = np.reshape(", "return labels def get_positions_format(self, section): positions_format = section.get('positions_format') if positions_format", "'x_exciting_effective_potential_convergence': ( r'RMS change in effective potential \\(target\\)', ureg.hartree), 'x_exciting_energy_convergence':", "archive, logger): self.filepath = filepath self.archive = archive self.logger =", "metainfo_name = 'x_exciting_scf_threshold_%s_change' % name.split('_')[-2] setattr(sec_method, metainfo_name, threshold) # additionally,", "(nspin, len(eigs) // nspin)) return data self._quantities.append( Quantity( 'eigenvalues_occupancies', r'\\(state\\,", "in max\\-nonIBS\\-force\\s*\\(target\\)', ureg.hartree / ureg.bohr)} for name, key_unit in self._convergence_keys_mapping.items():", "(energy_fermi.magnitude * ureg.joule).to('hartree') sec_k_band = sec_scc.m_create(BandStructure, Calculation.band_structure_electronic) sec_k_band.energy_fermi = energy_fermi", "quantity in ['EXCITON', 'EPSILON', 'SIGMA', 'LOSS']: files = get_files(quantity) for", "is None: self._results = dict() if not self.bands: return if", "self.archive.run[-1] sec_method = sec_run.m_create(Method) sec_method.basis_set.append(BasisSet(type='(L)APW+lo')) sec_dft = sec_method.m_create(DFT) sec_electronic =", "self.archive = archive self.logger = logger if logger is not", "val) # moment contributions moment_contributions = iteration.get('moment_contributions', {}) for key,", "energy = np.array([d[1].get(key, None) for d in data]) if None", "self.parse_system(section) if sec_system is not None: sec_scc.system_ref = sec_system sec_scc.method_ref", "self.archive.run[-1].method[0] sec_method.starting_method_ref = sec_method_ref sec_method.methods_ref = [sec_method_ref] # parse input", "% self._atom_key) for band in bands_atom: self._bands.append(band.findall('./%s' % self._band_key)) return", "res = res * (1 / self.energy_unit) elif key ==", "missing quantity if len(quantity) < n_scf: quantity = [None] *", "is None: return self._energies = np.array( [float(point.attrib.get(self._energy_key)) for point in", "= self.input_xml_parser.get( 'structure/crystal/basevect', np.eye(3)) species = self.input_xml_parser.get('structure/species/speciesfile') if positions is", "dtype=float) return self._distances @property def bands(self): if self._bands is None:", "not self.total_dos: return res = np.zeros((self.number_of_spin_channels, self.number_of_dos)) for i in", "input parameters here if input_GW.xml does not exist self._quantities.append( Quantity(", "str(volume_index).rjust(2, '0')) if not info_volume: break sec_scc.calculations_path.append(info_volume[0]) def init_parser(self): self.info_parser.mainfile", "None), 'x_exciting_valence_states': ('Total number of valence states', None), 'x_exciting_hamiltonian_size': ('Maximum", "= msection.m_create(x_exciting_section_MT_moment_atom) sec_mt_moment_atom.x_exciting_MT_moment_atom_index = n + 1 sec_mt_moment_atom.x_exciting_MT_moment_atom_symbol = val[n][0]", "'AC' if nwacont else None, 'NAR' if not aresdf else", "Program( name='exciting', version=self.info_parser.get('program_version', '').strip()) # method goes first since reference", "n in range(len(files)): parser.mainfile = files[n] parser_function(section) # free up", "'charge_total': pass else: setattr(msection, key, val) # moment contributions moment_contributions", "= False potential_mixing = self.info_parser.get_initialization_parameter('potential_mixing') if potential_mixing is not None:", "self.info_parser.get_initialization_parameter('species', []) for specie in species: sec_atoms_group = sec_system.m_create(x_exciting_section_atoms_group) sec_atoms_group.x_exciting_geometry_atom_labels", "quantity at all qpoints files = self.get_exciting_files('%s_%s%s%s.OUT' % (quantity, file_ext,", "repeats=False) ) self._quantities.append( Quantity( 'fermi_energy', r'\\-\\s*G0W0.+\\-\\s*\\-+\\s*[\\s\\S]*?Fermi [Ee]nergy\\s*[:=](\\s*-?[\\d\\.]+)\\s', unit=ureg.hartree, repeats=False) )", "(self._partialdos_key, self._diagram_key)) return self._partial_dos @property def energies(self): if self._energies is", "sub_parser=TextParser(quantities=optimization_quantities), repeats=True), Quantity( 'final', r'Force convergence target achieved([\\s\\S]+?Opt)', sub_parser=TextParser(quantities=scf_quantities), repeats=False),", "r'(?:All units are atomic|Starting initialization)([\\s\\S]+?)(?:Using|Ending initialization)', repeats=False, sub_parser=TextParser(quantities=initialization_quantities)) ) scf_quantities", "{})) input_file = self.get_exciting_files('input.xml') if positions is None: # get", "super().__init__(None) def init_quantities(self): re_symbol = re.compile(r'([A-Z][a-z]?)') def str_to_array(val_in): val =", "sec_method.x_exciting_xs_ngridq = self.input_xml_parser.get('xs/ngridq', [1, 1, 1]) sec_method.x_exciting_xs_ngridk = self.input_xml_parser.get('xs/ngridk', [1,", "concatenating species symbols species = self.get('initialization', {}).get('species', []) labels =", "['groundstate', 'hybrids']: sec_scc = parse_configuration(self.info_parser.get(module)) if sec_scc is None: continue", "n + 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol = val[n][0] sec_mt_charge_atom.x_exciting_MT_charge_atom_value = val[n][1] sec_charges", "return False def _parse_dos(self, sec_scc): if self.dos_parser.get('totaldos', None) is None:", "= val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1] else: setattr(msection, key, val) #", "None: sec_method.x_exciting_xs_bse_antiresonant = self.input_xml_parser.get( 'xs/BSE/aresbse', True) sec_method.x_exciting_xs_bse_angular_momentum_cutoff = self.input_xml_parser.get( 'xs/BSE/lmaxdielt',", "1 while True: info_volume = self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2, '0')) if", "scf iterations scf_iterations = section.get('scf_iteration', []) for scf_iteration in scf_iterations:", "range(len(val)): sec_mt_charge_atom = msection.m_create(x_exciting_section_MT_charge_atom) sec_mt_charge_atom.x_exciting_MT_charge_atom_index = n + 1 sec_mt_charge_atom.x_exciting_MT_charge_atom_symbol", "is not None: sec_scc.energy = Energy(fermi=fermi_energy) gw_files = ['EVALQP.DAT', 'EVALQP.TXT',", "= self.get_initialization_parameter('lattice_vectors') if cell is None: return positions = np.dot(positions,", "'noinvdiag', 'longrange'] bse_files = [] for bse_type in bse_types: for", "[ f for f in os.listdir( self.info_parser.maindir) if target[0] in", "valence charge', ureg.elementary_charge), 'x_exciting_wigner_radius': (r'Effective Wigner radius, r\\_s', ureg.bohr), 'x_exciting_empty_states':", "def parse_xs(self): sec_run = self.archive.run[-1] xs_info_files = self.get_exciting_files('INFOXS.OUT') if not", "self._energy_unit = kwargs.get('energy_unit', None) def init_parameters(self): self._nspin = None self._distances", "% key_unit[0], repeats=False, unit=key_unit[1])) self._convergence_keys_mapping = { 'x_exciting_effective_potential_convergence': ( r'RMS", "v[0].split() v[1] = [float(vi) for vi in v[1].split()] v[1] =", "n_components = len(data) data = np.transpose(np.vstack(data)) n_sigma = len(data[0]) //", "= self.logger self.band_out_parser.logger = self.logger self.info_gw_parser.logger = self.logger self.input_xml_parser.logger =", "(?:total)* scf iterations\\s*\\:\\s*(\\d+)', repeats=False, dtype=int), Quantity( 'force_convergence', r'Maximum force magnitude\\s*\\(target\\)\\s*\\:(\\s*[\\(\\)\\d\\.\\-\\+Ee", "parser = self.fermisurf_parser parser_function = self._parse_fermisurface elif name.startswith('EVALQP') and (name.endswith('DAT')", "initialization_quantities.append( Quantity( name, r'%s\\s*:\\s*([\\s\\S]*?)\\n' % key_unit[0], unit=key_unit[1], repeats=False) ) initialization_quantities.append(Quantity(", "self.info_parser.get_unit_cell_volume() totaldos = self.dos_parser.get('totaldos') * volume.to('m**3').magnitude for spin in range(len(totaldos)):", "return # Get fermi energy: it is used to un-shift", "def number_of_spin_channels(self): if self._nspin is None: self._nspin = np.shape(np.transpose(self.data))[0] -", "= nkpts_segment[nb] sec_k_band_segment.value = band_energies[nb] + energy_fermi def parse_file(self, name,", "end return self._band_energies @property def distances(self): if self._distances is None:", "nkpts_segment band_energy = np.array([ np.transpose(energy)[start:end] for energy in band_energies]) if", "def distances(self): if self._distances is None: dist = np.transpose(self.data)[0] n_k_points", "= [[], [], []] for i in range(len(qpoints)): data_q =", "= lm_values[lm] sec_dos_values.spin = spin sec_dos_values.atom_index = atom sec_dos_values.value =", "= 1 if spin_treatment.lower() == 'spin-unpolarised' else 2 return n_spin", "res = np.zeros(( self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos)) for i in", "continue metainfo_name = 'x_exciting_scf_threshold_%s_change' % name.split('_')[-2] setattr(sec_method, metainfo_name, threshold) #", "Quantity( 'moment_contributions', r'(?:Moments\\s*\\:*\\s*)([\\-\\s\\w\\.\\:\\(\\)]+?)\\n *[A-Z\\+]', str_operation=str_to_atom_properties_dict, repeats=False, convert=False)] self._miscellaneous_keys_mapping = {", "for normal calculations # in addition to INFO.OUT return else:", "= np.zeros(( self.number_of_lm, self.number_of_spin_channels, self.number_of_atoms, self.number_of_dos)) for i in range(len(self.partial_dos)):", "self.get_exciting_files('input.xml') if positions is None: # get it from input.xml", "setattr(msection, key, val) # moment contributions moment_contributions = iteration.get('moment_contributions', {})", "Quantity( 'positions', r'\\s*:\\s*([\\d\\.\\-]+\\s*[\\d\\.\\-]+\\s*[\\d\\.\\-]+)', repeats=True, dtype=float)])), Quantity( 'forces', r'Total atomic forces", "def parse_epsilon(data, sec_scc): n_components = len(data) data = np.transpose(np.vstack(data)) n_epsilon", "nb in range(len(band_energies)): sec_k_band_segment = sec_k_band.m_create(BandEnergies) sec_k_band_segment.n_kpoints = nkpts_segment[nb] sec_k_band_segment.value", "unit=key_unit[1])) self._convergence_keys_mapping = { 'x_exciting_effective_potential_convergence': ( r'RMS change in effective", "name, section): # TODO add support for info.xml, wannier.out if", "= self.bandstructure_dat_parser.band_k_points nkpts_segment = self.bandstructure_dat_parser.number_of_k_points_per_segment for nb in range(len(band_energies)): sec_k_band_segment", "get_data('occupancies') sec_eigenvalues.energies = get_data('eigenvalues') def _parse_fermisurface(self, sec_scc): fermi_surface = self.fermisurf_parser.get('fermi_surface',", "= [] start = 0 band_energies = np.zeros(( self.number_of_spin_channels, self.number_of_band_segment_eigenvalues,", "// n_components sec_scc.x_exciting_xs_bse_number_of_excitons = n_excitons sec_scc.x_exciting_xs_bse_exciton_energies = np.reshape( data[1], (n_components,", "= None self._results[key] = res class DOSXMLParser(XMLParser): def __init__(self, **kwargs):", "for e in self.bands[n][i]]) for nkpts_segment in self.number_of_k_points_per_segment: end =", "elif self._calculation_type == 'xs': parser_function = self._parse_input_xs else: # TODO", "def file_exists(self, filename): \"\"\"Checks if a the given filename exists", "electron kinetic'], 'x_exciting_dft_d2_dispersion_correction': ['DFT-D2 dispersion correction'] } self._electron_charge_keys_mapping = {", "* self._energy_unit res_n.append(band_energy) start = end res.append(res_n) elif key ==", "self.info_gw_parser.get('fermi_energy', None) if fermi_energy is not None: sec_scc.energy = Energy(fermi=fermi_energy)", "= 1 while True: info_volume = self.get_exciting_files('run_dir%s/INFO.OUT' % str(volume_index).rjust(2, '0'))", "= self.input_xml_parser.get('xs/tetra/tetradf', None) nwacont = self.input_xml_parser.get('xs/tddft/nwacont', None) aresdf = self.input_xml_parser.get('xs/tddft/aresdf',", "key == 'eigenvalues': res = res * ureg.hartree return res", "sec_scc.x_exciting_geometry_optimization_method = optimization_step.get('method') if optimization_step.get('step') is not None: sec_scc.x_exciting_geometry_optimization_step =", "positions at this step\\s*\\(([a-z]+)\\)'), Quantity( 'symbols', r'atom\\s*\\d+\\s*(\\w+)', repeats=True, dtype=str), Quantity(", "val[n][0] sec_mt_moment_atom.x_exciting_MT_moment_atom_value = val[n][1] else: setattr(msection, key, val) # convergence", "self.input_xml_parser.get( 'xs/tddft/aresfxc', True) sec_method.x_exciting_xs_tddft_drude = self.input_xml_parser.get( 'xs/tddft/drude', [0., 0.]) sec_method.x_exciting_xs_tddft_split_parameter", "res = res * ureg.hartree return res sec_eigenvalues = sec_scc.m_create(BandEnergies)", "is None: data = np.transpose(self.data) self._neigs_segment = int(max(data[0])) return self._neigs_segment", "sec_scc.x_exciting_xs_bse_epsilon_re = np.reshape( data[1], (n_components, n_epsilon)) sec_scc.x_exciting_xs_bse_epsilon_im = np.reshape( data[2],", "data to scc # TODO add support for more output", "else end]) elif key == 'band_segm_start_end': res = [] for", "n in range(len(atoms)): atom_labels.extend([species[n].split('.')[0]] * len(atoms[n])) if positions is None", "\\(rgkmax\\)', None), 'x_exciting_species_rtmin': (r'Species with R\\^MT\\_min', None), 'x_exciting_gkmax': (r'Maximum \\|G\\+k\\|", "= specie.get('positions') positions = self.info_parser.get_atom_positions( positions=positions, positions_format=positions_format).to('m') sec_atoms_group.x_exciting_geometry_atom_positions = positions.magnitude", "step\\s*\\d+[\\s\\S]+?(?:\\n *\\n\\-{10}|Time spent in this optimization step\\s*:\\s*[\\d\\.]+ seconds))', sub_parser=TextParser(quantities=optimization_quantities), repeats=True),", "unit))) else: vi = [float(vii) for vii in v[1].split()] vi", "= len(data[0]) // n_components sec_scc.x_exciting_xs_bse_loss_energies = np.reshape( data[0], (n_components, n_loss))", "if self._ndos is None: total_dos = self.root.find('./%s/%s' % (self._totaldos_key, self._diagram_key))", "= get_data(files[i]) if not data: sccs.append(None) continue if quantity ==", "% self._vertex_key) return self._vertices @property def number_of_spin_channels(self): if self._nspin is" ]
[ "# noqa: E501 \"\"\"Test checkpoint to ask server to fail", ":return: FileMetaDataArrayEnveloped If the method is called asynchronously, returns the", "return self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data)", "API definition for simcore-service-storage service # noqa: E501 OpenAPI spec", "header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 #", "(data) = self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return", "noqa: E501 return data def check_action_post_with_http_info(self, action, **kwargs): # noqa:", ":param async_req bool :param str action: (required) :param str data:", "E501 \"\"\"Get available storage locations # noqa: E501 This method", "the required parameter `user_id` when calling `get_storage_locations`\") # noqa: E501", "asynchronous HTTP request, please pass async_req=True >>> thread = api.update_file_meta_data(file_id,", "E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings =", "\"Got an unexpected keyword argument '%s'\" \" to method get_file_metadata\"", "# noqa: E501 \"\"\"Get available storage locations # noqa: E501", "thread = api.delete_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", "'action' in local_var_params: path_params['action'] = local_var_params['action'] # noqa: E501 query_params", "= ['file_id', 'location_id', 'user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content')", "True if kwargs.get('async_req'): return self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "keyword argument '%s'\" \" to method get_file_metadata\" % key )", "noqa: E501 collection_formats = {} path_params = {} if 'location_id'", "async_req=True >>> thread = api.delete_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result", "request, please pass async_req=True >>> thread = api.get_file_metadata_with_http_info(file_id, location_id, user_id,", "collection_formats=collection_formats) def upload_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "= [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for", ":param str user_id: (required) :param str uuid_filter: :return: FileMetaDataArrayEnveloped If", "request, please pass async_req=True >>> thread = api.get_files_metadata_with_http_info(location_id, user_id, async_req=True)", "E501 return self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params,", "files=local_var_files, response_type='FileMetaDataArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa:", "% key ) local_var_params[key] = val del local_var_params['kwargs'] # verify", "request, please pass async_req=True >>> thread = api.delete_file_with_http_info(file_id, location_id, user_id,", "is None): raise ValueError(\"Missing the required parameter `location_id` when calling", "= [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params,", "'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa:", "= [] # noqa: E501 return self.api_client.call_api( '/locations', 'GET', path_params,", "required parameter 'user_id' is set if ('user_id' not in local_var_params", "if kwargs.get('async_req'): return self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "pass async_req=True >>> thread = api.health_check_with_http_info(async_req=True) >>> result = thread.get()", "`update_file_meta_data`\") # noqa: E501 collection_formats = {} path_params = {}", ">>> thread = api.check_action_post(action, async_req=True) >>> result = thread.get() :param", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self, file_id, location_id, user_id, **kwargs): #", "if 'fake_type' in local_var_params: body_params = local_var_params['fake_type'] # HTTP header", "# noqa: E501 OpenAPI spec version: 0.1.0 Contact: <EMAIL> Generated", ">>> thread = api.delete_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result =", "response_type='HealthCheckEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501", "response_type='FakeEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501", "update_file_meta_data(self, file_id, location_id, **kwargs): # noqa: E501 \"\"\"Update File Metadata", ">>> thread = api.check_action_post_with_http_info(action, async_req=True) >>> result = thread.get() :param", "'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FakeEnveloped', # noqa:", "str user_id: (required) :param str extra_location: :param str extra_source: :return:", "ValueError(\"Missing the required parameter `user_id` when calling `download_file`\") # noqa:", "request, please pass async_req=True >>> thread = api.get_storage_locations(user_id, async_req=True) >>>", "pass async_req=True >>> thread = api.check_action_post_with_http_info(action, async_req=True) >>> result =", "not in all_params: raise TypeError( \"Got an unexpected keyword argument", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_file_metadata(self,", "'file_meta_data_type' in local_var_params: body_params = local_var_params['file_meta_data_type'] # HTTP header `Accept`", "in local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter'])) # noqa: E501 header_params = {}", "Do not edit the class manually. \"\"\" def __init__(self, api_client=None):", "local_var_params['location_id'] # noqa: E501 query_params = [] header_params = {}", "'extra_location', 'extra_source'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_files_metadata(self, location_id, user_id,", "(data) = self.health_check_with_http_info(**kwargs) # noqa: E501 return data def health_check_with_http_info(self,", "def get_file_metadata_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get", "= {} path_params = {} query_params = [] header_params =", "noqa: E501 return data def delete_file_with_http_info(self, file_id, location_id, user_id, **kwargs):", "header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'),", "'/check/{action}', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FakeEnveloped', #", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_storage_locations(self, user_id, **kwargs): # noqa:", "when calling `delete_file`\") # noqa: E501 # verify the required", "request thread. \"\"\" local_var_params = locals() all_params = ['location_id', 'user_id',", "E501 \"\"\"Deletes File # noqa: E501 This method makes a", "`get_files_metadata`\") # noqa: E501 # verify the required parameter 'user_id'", "local_var_params or local_var_params['file_id'] is None): raise ValueError(\"Missing the required parameter", "all_params = ['file_id', 'location_id', 'user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only')", "'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id'] # noqa: E501 query_params", "= [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET', path_params,", "all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key, val in six.iteritems(local_var_params['kwargs']): if", "is called asynchronously, returns the request thread. \"\"\" local_var_params =", "to method get_files_metadata\" % key ) local_var_params[key] = val del", "default. To make an asynchronous HTTP request, please pass async_req=True", "requested file # noqa: E501 This method makes a synchronous", "str location_id: (required) :param FileMetaDataType file_meta_data_type: :return: FileMetaDataEnveloped If the", "get_files_metadata_with_http_info(self, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get Files Metadata", "body_params = local_var_params['fake_type'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(", "location_id, user_id, **kwargs): # noqa: E501 \"\"\"Deletes File # noqa:", "else: (data) = self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 return data", "argument '%s'\" \" to method get_file_metadata\" % key ) local_var_params[key]", "async_req bool :param str user_id: (required) :return: FileLocationArrayEnveloped If the", "'action' is set if ('action' not in local_var_params or local_var_params['action']", "or local_var_params['location_id'] is None): raise ValueError(\"Missing the required parameter `location_id`", "**kwargs) # noqa: E501 return data def download_file_with_http_info(self, file_id, location_id,", "thread = api.check_action_post_with_http_info(action, async_req=True) >>> result = thread.get() :param async_req", "= [] local_var_files = {} body_params = None if 'file_meta_data_type'", "= True if kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501", "# noqa: E501 if 'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id']", "the required parameter `location_id` when calling `get_files_metadata`\") # noqa: E501", "FileMetaDataEnveloped If the method is called asynchronously, returns the request", "\"Got an unexpected keyword argument '%s'\" \" to method get_files_metadata\"", "is None): raise ValueError(\"Missing the required parameter `action` when calling", "'uuid_filter' in local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter'])) # noqa: E501 header_params =", "local_var_params['kwargs'] # verify the required parameter 'action' is set if", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id,", "**kwargs): # noqa: E501 \"\"\"Service health-check endpoint # noqa: E501", "= api_client def check_action_post(self, action, **kwargs): # noqa: E501 \"\"\"Test", "path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FakeEnveloped', # noqa: E501", "not in local_var_params or local_var_params['file_id'] is None): raise ValueError(\"Missing the", "path_params['fileId'] = local_var_params['file_id'] # noqa: E501 if 'location_id' in local_var_params:", ">>> result = thread.get() :param async_req bool :param str user_id:", "set if ('location_id' not in local_var_params or local_var_params['location_id'] is None):", "path_params['location_id'] = local_var_params['location_id'] # noqa: E501 query_params = [] if", "api.check_action_post(action, async_req=True) >>> result = thread.get() :param async_req bool :param", "user_id, **kwargs) # noqa: E501 return data def delete_file_with_http_info(self, file_id,", "all_params = ['user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout')", "local_var_params or local_var_params['user_id'] is None): raise ValueError(\"Missing the required parameter", "path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa: E501", ") local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params", "def download_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns", "self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 return data def get_storage_locations_with_http_info(self, user_id,", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_files_metadata(self, location_id, user_id, **kwargs):", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.upload_file_with_http_info(file_id, location_id, user_id,", "asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_file_with_http_info(file_id,", "kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 else: (data)", "file_id: (required) :param str location_id: (required) :param FileMetaDataType file_meta_data_type: :return:", "return data def delete_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa:", ":param str file_id: (required) :param str location_id: (required) :param str", "# noqa: E501 This method makes a synchronous HTTP request", ">>> thread = api.get_storage_locations_with_http_info(user_id, async_req=True) >>> result = thread.get() :param", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs) # noqa: E501", "parameter `location_id` when calling `download_file`\") # noqa: E501 # verify", "api.health_check(async_req=True) >>> result = thread.get() :param async_req bool :return: HealthCheckEnveloped", "**kwargs) # noqa: E501 return data def update_file_meta_data_with_http_info(self, file_id, location_id,", "header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'),", "val del local_var_params['kwargs'] # verify the required parameter 'action' is", "API and state of the service behind # noqa: E501", "<EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import", "**kwargs) # noqa: E501 else: (data) = self.upload_file_with_http_info(file_id, location_id, user_id,", "# noqa: E501 collection_formats = {} path_params = {} query_params", "E501 return data def health_check_with_http_info(self, **kwargs): # noqa: E501 \"\"\"Service", "request, please pass async_req=True >>> thread = api.check_action_post_with_http_info(action, async_req=True) >>>", "def get_file_metadata(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.check_action_post_with_http_info(action, **kwargs) #", "query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped', # noqa: E501 auth_settings=auth_settings,", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.upload_file_with_http_info(file_id, location_id,", "= [] header_params = {} form_params = [] local_var_files =", "if kwargs.get('async_req'): return self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "[] local_var_files = {} body_params = None if 'file_meta_data_type' in", "= [] # noqa: E501 return self.api_client.call_api( '/check/{action}', 'POST', path_params,", "check_action_post\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "E501 header_params = {} form_params = [] local_var_files = {}", "async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def", "if ('action' not in local_var_params or local_var_params['action'] is None): raise", "user_id: (required) :return: PresignedLinkEnveloped If the method is called asynchronously,", "This method makes a synchronous HTTP request by default. To", "please pass async_req=True >>> thread = api.get_file_metadata_with_http_info(file_id, location_id, user_id, async_req=True)", "\"\"\"NOTE: This class is auto generated by OpenAPI Generator Ref:", "'fake_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key,", "# noqa: E501 if 'extra_location' in local_var_params: query_params.append(('extra_location', local_var_params['extra_location'])) #", "noqa: E501 \"\"\"Returns upload link or performs copy operation to", "location_id, **kwargs): # noqa: E501 \"\"\"Update File Metadata # noqa:", "local_var_params or local_var_params['location_id'] is None): raise ValueError(\"Missing the required parameter", "# noqa: E501 else: (data) = self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) #", "('action' not in local_var_params or local_var_params['action'] is None): raise ValueError(\"Missing", "# noqa: E501 # verify the required parameter 'location_id' is", "when calling `get_files_metadata`\") # noqa: E501 collection_formats = {} path_params", "thread.get() :param async_req bool :return: HealthCheckEnveloped If the method is", "= self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 return data def", "if api_client is None: api_client = ApiClient() self.api_client = api_client", "\" to method download_file\" % key ) local_var_params[key] = val", "= api.get_file_metadata(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "collection_formats=collection_formats) def delete_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "= [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET', path_params,", "noqa: E501 \"\"\"Update File Metadata # noqa: E501 This method", "'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped', # noqa:", "six from simcore_service_storage_sdk.api_client import ApiClient class UsersApi(object): \"\"\"NOTE: This class", "**kwargs) # noqa: E501 else: (data) = self.get_file_metadata_with_http_info(file_id, location_id, user_id,", "the required parameter `user_id` when calling `get_file_metadata`\") # noqa: E501", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_file_metadata(self, file_id,", "E501 \"\"\"Get File Metadata # noqa: E501 This method makes", "= {} if 'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id'] #", "{} body_params = None if 'file_meta_data_type' in local_var_params: body_params =", "# verify the required parameter 'file_id' is set if ('file_id'", "E501 if 'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id'] # noqa:", "return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", "all_params = ['file_id', 'location_id', 'file_meta_data_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only')", "query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'uuid_filter' in local_var_params: query_params.append(('uuid_filter',", "\"\"\" def __init__(self, api_client=None): if api_client is None: api_client =", "parameter `location_id` when calling `get_files_metadata`\") # noqa: E501 # verify", "# noqa: E501 return data def get_files_metadata_with_http_info(self, location_id, user_id, **kwargs):", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id,", "= self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 return data def", "str user_id: (required) :return: FileMetaDataEnveloped If the method is called", "('file_id' not in local_var_params or local_var_params['file_id'] is None): raise ValueError(\"Missing", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def health_check(self, **kwargs):", ":param async_req bool :return: HealthCheckEnveloped If the method is called", "definition for simcore-service-storage service # noqa: E501 OpenAPI spec version:", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_storage_locations(self, user_id, **kwargs): #", ">>> thread = api.get_storage_locations(user_id, async_req=True) >>> result = thread.get() :param", "def delete_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Deletes", "required parameter `file_id` when calling `download_file`\") # noqa: E501 #", "argument '%s'\" \" to method check_action_post\" % key ) local_var_params[key]", "= thread.get() :param async_req bool :param str user_id: (required) :return:", "self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data) =", "parameter `file_id` when calling `download_file`\") # noqa: E501 # verify", "local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params =", "ValueError(\"Missing the required parameter `user_id` when calling `get_files_metadata`\") # noqa:", "noqa: E501 else: (data) = self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa:", "async_req=True >>> thread = api.get_storage_locations(user_id, async_req=True) >>> result = thread.get()", "`location_id` when calling `get_files_metadata`\") # noqa: E501 # verify the", "required parameter `file_id` when calling `get_file_metadata`\") # noqa: E501 #", "E501 \"\"\"Get Files Metadata # noqa: E501 This method makes", "= api.delete_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 header_params = {} form_params", "location_id: (required) :param str user_id: (required) :return: FileMetaDataEnveloped If the", "# noqa: E501 return data def check_action_post_with_http_info(self, action, **kwargs): #", "HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501", "api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True) >>> result = thread.get() :param async_req bool", "**kwargs) # noqa: E501 return data def get_files_metadata_with_http_info(self, location_id, user_id,", "FileLocationArrayEnveloped If the method is called asynchronously, returns the request", "**kwargs) # noqa: E501 return data def get_storage_locations_with_http_info(self, user_id, **kwargs):", "thread. \"\"\" local_var_params = locals() all_params = ['user_id'] # noqa:", "unexpected keyword argument '%s'\" \" to method check_action_post\" % key", "api.update_file_meta_data(file_id, location_id, async_req=True) >>> result = thread.get() :param async_req bool", "if 'data' in local_var_params: query_params.append(('data', local_var_params['data'])) # noqa: E501 header_params", "noqa: E501 return data def get_file_metadata_with_http_info(self, file_id, location_id, user_id, **kwargs):", "E501 else: (data) = self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 return", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_storage_locations(self, user_id,", "None): raise ValueError(\"Missing the required parameter `file_id` when calling `upload_file`\")", "None): raise ValueError(\"Missing the required parameter `location_id` when calling `update_file_meta_data`\")", "asynchronous HTTP request, please pass async_req=True >>> thread = api.get_storage_locations(user_id,", "get_file_metadata(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get File", "# noqa: E501 Some general information on the API and", "parameter `location_id` when calling `update_file_meta_data`\") # noqa: E501 collection_formats =", "{} path_params = {} query_params = [] header_params = {}", "the request thread. \"\"\" local_var_params = locals() all_params = ['action',", "request, please pass async_req=True >>> thread = api.upload_file_with_http_info(file_id, location_id, user_id,", "calling `update_file_meta_data`\") # noqa: E501 collection_formats = {} path_params =", "user_id: (required) :param str extra_location: :param str extra_source: :return: PresignedLinkEnveloped", ":param str file_id: (required) :param str location_id: (required) :param FileMetaDataType", "noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params, query_params, header_params, body=body_params,", "body=body_params, post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'),", "is None: api_client = ApiClient() self.api_client = api_client def check_action_post(self,", "action, **kwargs): # noqa: E501 \"\"\"Test checkpoint to ask server", "absolute_import import re # noqa: F401 # python 2 and", "\"\"\"Get Files Metadata # noqa: E501 This method makes a", "HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json'])", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id, **kwargs) #", "# noqa: E501 return data def update_file_meta_data_with_http_info(self, file_id, location_id, **kwargs):", "or echo back the transmitted data # noqa: E501 This", "E501 else: (data) = self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def update_file_meta_data(self, file_id,", "all_params = ['action', 'data', 'fake_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only')", "is None): raise ValueError(\"Missing the required parameter `file_id` when calling", "self.health_check_with_http_info(**kwargs) # noqa: E501 else: (data) = self.health_check_with_http_info(**kwargs) # noqa:", "method get_files_metadata\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "please pass async_req=True >>> thread = api.delete_file_with_http_info(file_id, location_id, user_id, async_req=True)", "in local_var_params: path_params['location_id'] = local_var_params['location_id'] # noqa: E501 query_params =", "request thread. \"\"\" local_var_params = locals() all_params = ['action', 'data',", "in local_var_params: body_params = local_var_params['file_meta_data_type'] # HTTP header `Accept` header_params['Accept']", "= thread.get() :param async_req bool :param str action: (required) :param", "is set if ('file_id' not in local_var_params or local_var_params['file_id'] is", "# python 2 and python 3 compatibility library import six", "# noqa: E501 return self.api_client.call_api( '/check/{action}', 'POST', path_params, query_params, header_params,", "operation to datcore # noqa: E501 This method makes a", "`user_id` when calling `upload_file`\") # noqa: E501 collection_formats = {}", "request, please pass async_req=True >>> thread = api.update_file_meta_data(file_id, location_id, async_req=True)", "thread = api.get_files_metadata_with_http_info(location_id, user_id, async_req=True) >>> result = thread.get() :param", "collection_formats = {} path_params = {} if 'location_id' in local_var_params:", "link or performs copy operation to datcore # noqa: E501", "= ['file_id', 'location_id', 'file_meta_data_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content')", "raise ValueError(\"Missing the required parameter `file_id` when calling `upload_file`\") #", "required parameter `location_id` when calling `update_file_meta_data`\") # noqa: E501 collection_formats", "(required) :param str extra_location: :param str extra_source: :return: PresignedLinkEnveloped If", "E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params,", "unexpected keyword argument '%s'\" \" to method get_files_metadata\" % key", "location_id: (required) :param str user_id: (required) :return: None If the", "`delete_file`\") # noqa: E501 # verify the required parameter 'location_id'", "please pass async_req=True >>> thread = api.update_file_meta_data(file_id, location_id, async_req=True) >>>", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self, file_id, location_id, user_id,", "when calling `upload_file`\") # noqa: E501 collection_formats = {} path_params", "= {} body_params = None if 'fake_type' in local_var_params: body_params", "locals() all_params = ['file_id', 'location_id', 'file_meta_data_type'] # noqa: E501 all_params.append('async_req')", "local_var_params['kwargs'] # verify the required parameter 'user_id' is set if", "None): raise ValueError(\"Missing the required parameter `file_id` when calling `delete_file`\")", "post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), #", "method delete_file\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "health_check\" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_files_metadata(self, location_id,", "E501 else: (data) = self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501", "noqa: E501 return data def get_files_metadata_with_http_info(self, location_id, user_id, **kwargs): #", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs)", "= self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 return data def get_storage_locations_with_http_info(self,", "if 'extra_location' in local_var_params: query_params.append(('extra_location', local_var_params['extra_location'])) # noqa: E501 if", "six.iteritems(local_var_params['kwargs']): if key not in all_params: raise TypeError( \"Got an", "parameter `user_id` when calling `upload_file`\") # noqa: E501 collection_formats =", "= {} if 'file_id' in local_var_params: path_params['fileId'] = local_var_params['file_id'] #", "the required parameter `location_id` when calling `get_file_metadata`\") # noqa: E501", "**kwargs) # noqa: E501 return data def upload_file_with_http_info(self, file_id, location_id,", "argument '%s'\" \" to method get_files_metadata\" % key ) local_var_params[key]", ":return: FileMetaDataEnveloped If the method is called asynchronously, returns the", "E501 \"\"\"Update File Metadata # noqa: E501 This method makes", "**kwargs): # noqa: E501 \"\"\"Update File Metadata # noqa: E501", "Ref: https://openapi-generator.tech Do not edit the class manually. \"\"\" def", "E501 return data def delete_file_with_http_info(self, file_id, location_id, user_id, **kwargs): #", "return self.api_client.call_api( '/check/{action}', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", ">>> thread = api.get_files_metadata_with_http_info(location_id, user_id, async_req=True) >>> result = thread.get()", "query_params.append(('uuid_filter', local_var_params['uuid_filter'])) # noqa: E501 header_params = {} form_params =", "location_id: (required) :param FileMetaDataType file_meta_data_type: :return: FileMetaDataEnveloped If the method", "async_req bool :param str file_id: (required) :param str location_id: (required)", "header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting", "request thread. \"\"\" local_var_params = locals() all_params = [] #", "result = thread.get() :param async_req bool :param str action: (required)", ":param async_req bool :param str user_id: (required) :return: FileLocationArrayEnveloped If", "return self.health_check_with_http_info(**kwargs) # noqa: E501 else: (data) = self.health_check_with_http_info(**kwargs) #", "an unexpected keyword argument '%s'\" \" to method update_file_meta_data\" %", "information on the API and state of the service behind", "result = thread.get() :param async_req bool :return: HealthCheckEnveloped If the", "local_var_params['extra_source'])) # noqa: E501 header_params = {} form_params = []", "= locals() all_params = ['location_id', 'user_id', 'uuid_filter'] # noqa: E501", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def update_file_meta_data(self, file_id, location_id,", ":param FakeType fake_type: :return: FakeEnveloped If the method is called", "returns the request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'):", "an unexpected keyword argument '%s'\" \" to method delete_file\" %", "get_storage_locations_with_http_info(self, user_id, **kwargs): # noqa: E501 \"\"\"Get available storage locations", "collection_formats = {} path_params = {} if 'action' in local_var_params:", "noqa: E501 else: (data) = self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501", "noqa: E501 else: (data) = self.health_check_with_http_info(**kwargs) # noqa: E501 return", "please pass async_req=True >>> thread = api.check_action_post_with_http_info(action, async_req=True) >>> result", "thread = api.health_check(async_req=True) >>> result = thread.get() :param async_req bool", "OpenAPI spec version: 0.1.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\"", "behind # noqa: E501 This method makes a synchronous HTTP", "local_var_params: body_params = local_var_params['file_meta_data_type'] # HTTP header `Accept` header_params['Accept'] =", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_file_metadata(self, file_id, location_id, user_id, **kwargs): #", "# noqa: E501 else: (data) = self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) #", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_files_metadata(self, location_id, user_id, **kwargs): # noqa:", "local_var_params: path_params['location_id'] = local_var_params['location_id'] # noqa: E501 query_params = []", "**kwargs) # noqa: E501 return data def delete_file_with_http_info(self, file_id, location_id,", "# noqa: E501 collection_formats = {} path_params = {} if", "Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import re", "data: :param FakeType fake_type: :return: FakeEnveloped If the method is", "verify the required parameter 'action' is set if ('action' not", "noqa: E501 return self.api_client.call_api( '/', 'GET', path_params, query_params, header_params, body=body_params,", "Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import", "noqa: E501 \"\"\"Returns download link for requested file # noqa:", "delete_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Deletes File", "# noqa: E501 ['application/json']) # noqa: E501 # Authentication setting", "[] local_var_files = {} body_params = None if 'fake_type' in", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id, user_id, **kwargs)", "server to fail or echo back the transmitted data #", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_file_metadata(self, file_id, location_id, user_id,", "if 'file_meta_data_type' in local_var_params: body_params = local_var_params['file_meta_data_type'] # HTTP header", "user_id, **kwargs) # noqa: E501 else: (data) = self.delete_file_with_http_info(file_id, location_id,", "data def get_storage_locations_with_http_info(self, user_id, **kwargs): # noqa: E501 \"\"\"Get available", "transmitted data # noqa: E501 This method makes a synchronous", "= {} query_params = [] if 'user_id' in local_var_params: query_params.append(('user_id',", "async_req=True >>> thread = api.get_storage_locations_with_http_info(user_id, async_req=True) >>> result = thread.get()", "# noqa: E501 else: (data) = self.health_check_with_http_info(**kwargs) # noqa: E501", "{} query_params = [] header_params = {} form_params = []", "noqa: E501 else: (data) = self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) #", ") local_var_params[key] = val del local_var_params['kwargs'] # verify the required", "in local_var_params: query_params.append(('extra_location', local_var_params['extra_location'])) # noqa: E501 if 'extra_source' in", "the required parameter `action` when calling `check_action_post`\") # noqa: E501", "async_req=True >>> thread = api.check_action_post(action, async_req=True) >>> result = thread.get()", "= [] if 'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa:", ":param str action: (required) :param str data: :param FakeType fake_type:", "file_meta_data_type: :return: FileMetaDataEnveloped If the method is called asynchronously, returns", "# noqa: F401 # python 2 and python 3 compatibility", "noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key, val in", "in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 header_params = {}", "True if kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501", "if ('location_id' not in local_var_params or local_var_params['location_id'] is None): raise", "request thread. \"\"\" local_var_params = locals() all_params = ['user_id'] #", "local_var_params['action'] # noqa: E501 query_params = [] if 'data' in", "response_type='FileMetaDataEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501", "(required) :return: FileMetaDataEnveloped If the method is called asynchronously, returns", "\"Got an unexpected keyword argument '%s'\" \" to method update_file_meta_data\"", "self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 else: (data) = self.check_action_post_with_http_info(action, **kwargs)", "local_var_params['user_id'])) # noqa: E501 if 'uuid_filter' in local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter']))", "ValueError(\"Missing the required parameter `file_id` when calling `update_file_meta_data`\") # noqa:", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def download_file(self, file_id, location_id, user_id, **kwargs): # noqa:", ":param str user_id: (required) :return: FileMetaDataEnveloped If the method is", "import absolute_import import re # noqa: F401 # python 2", "api_client = ApiClient() self.api_client = api_client def check_action_post(self, action, **kwargs):", "return data def update_file_meta_data_with_http_info(self, file_id, location_id, **kwargs): # noqa: E501", "ValueError(\"Missing the required parameter `location_id` when calling `get_file_metadata`\") # noqa:", "def __init__(self, api_client=None): if api_client is None: api_client = ApiClient()", "local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter'])) # noqa: E501 header_params = {} form_params", "body=body_params, post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'),", "asynchronous HTTP request, please pass async_req=True >>> thread = api.check_action_post_with_http_info(action,", "[] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT', path_params, query_params,", "the request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return", "header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'),", "= None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json'])", "# noqa: E501 \"\"\"Deletes File # noqa: E501 This method", "= locals() all_params = ['file_id', 'location_id', 'user_id', 'extra_location', 'extra_source'] #", "required parameter `location_id` when calling `delete_file`\") # noqa: E501 #", "{} body_params = None if 'fake_type' in local_var_params: body_params =", "FileMetaDataArrayEnveloped If the method is called asynchronously, returns the request", "noqa: E501 return self.api_client.call_api( '/check/{action}', 'POST', path_params, query_params, header_params, body=body_params,", "{} if 'file_id' in local_var_params: path_params['fileId'] = local_var_params['file_id'] # noqa:", "(data) = self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 return data", "files=local_var_files, response_type='FileLocationArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa:", "return self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data)", "= val del local_var_params['kwargs'] collection_formats = {} path_params = {}", "None if 'fake_type' in local_var_params: body_params = local_var_params['fake_type'] # HTTP", "= {} path_params = {} if 'action' in local_var_params: path_params['action']", "# HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa:", "keyword argument '%s'\" \" to method check_action_post\" % key )", "the required parameter 'user_id' is set if ('user_id' not in", "api.delete_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "request, please pass async_req=True >>> thread = api.upload_file(file_id, location_id, user_id,", "required parameter `user_id` when calling `upload_file`\") # noqa: E501 collection_formats", "local_var_params = locals() all_params = ['file_id', 'location_id', 'user_id'] # noqa:", "api.delete_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "user_id, **kwargs) # noqa: E501 else: (data) = self.download_file_with_http_info(file_id, location_id,", ":param str user_id: (required) :param str extra_location: :param str extra_source:", "self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 return data def get_files_metadata_with_http_info(self,", "= self.health_check_with_http_info(**kwargs) # noqa: E501 return data def health_check_with_http_info(self, **kwargs):", "by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import re #", "method is called asynchronously, returns the request thread. \"\"\" kwargs['_return_http_data_only']", "= [] local_var_files = {} body_params = None if 'fake_type'", "(required) :param str user_id: (required) :return: None If the method", "asynchronous HTTP request, please pass async_req=True >>> thread = api.update_file_meta_data_with_http_info(file_id,", "noqa: E501 else: (data) = self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) #", "in local_var_params: query_params.append(('data', local_var_params['data'])) # noqa: E501 header_params = {}", "# noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content',", "\"\"\" local_var_params = locals() all_params = ['location_id', 'user_id', 'uuid_filter'] #", "# noqa: E501 else: (data) = self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs)", "async_req=True >>> thread = api.get_file_metadata_with_http_info(file_id, location_id, user_id, async_req=True) >>> result", "HTTP request, please pass async_req=True >>> thread = api.update_file_meta_data_with_http_info(file_id, location_id,", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def download_file(self, file_id,", "local_var_params = locals() all_params = ['location_id', 'user_id', 'uuid_filter'] # noqa:", "bool :return: HealthCheckEnveloped If the method is called asynchronously, returns", "str extra_source: :return: PresignedLinkEnveloped If the method is called asynchronously,", "\"Got an unexpected keyword argument '%s'\" \" to method upload_file\"", "files=local_var_files, response_type='FakeEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa:", "noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET', path_params, query_params, header_params, body=body_params,", "or local_var_params['user_id'] is None): raise ValueError(\"Missing the required parameter `user_id`", "query_params.append(('extra_source', local_var_params['extra_source'])) # noqa: E501 header_params = {} form_params =", "# noqa: E501 query_params = [] if 'data' in local_var_params:", "= True if kwargs.get('async_req'): return self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) #", "\"\"\"Returns download link for requested file # noqa: E501 This", "None If the method is called asynchronously, returns the request", "\"Got an unexpected keyword argument '%s'\" \" to method get_storage_locations\"", "the service behind # noqa: E501 This method makes a", "= True if kwargs.get('async_req'): return self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) #", "api.get_storage_locations_with_http_info(user_id, async_req=True) >>> result = thread.get() :param async_req bool :param", "required parameter `file_id` when calling `update_file_meta_data`\") # noqa: E501 #", "calling `delete_file`\") # noqa: E501 collection_formats = {} path_params =", "path_params = {} if 'file_id' in local_var_params: path_params['fileId'] = local_var_params['file_id']", "{} path_params = {} query_params = [] if 'user_id' in", ":param str uuid_filter: :return: FileMetaDataArrayEnveloped If the method is called", "asynchronous HTTP request, please pass async_req=True >>> thread = api.health_check(async_req=True)", "parameter `file_id` when calling `delete_file`\") # noqa: E501 # verify", "locals() all_params = ['file_id', 'location_id', 'user_id', 'extra_location', 'extra_source'] # noqa:", "# noqa: E501 if 'uuid_filter' in local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter'])) #", "= True if kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa:", "HTTP request, please pass async_req=True >>> thread = api.get_files_metadata(location_id, user_id,", "= ['user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for", "form_params = [] local_var_files = {} body_params = None if", "File # noqa: E501 This method makes a synchronous HTTP", "def get_storage_locations(self, user_id, **kwargs): # noqa: E501 \"\"\"Get available storage", "response_type='FileMetaDataArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501", "get_files_metadata(self, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get Files Metadata", "E501 # Authentication setting auth_settings = [] # noqa: E501", "local_var_params['location_id'] # noqa: E501 query_params = [] if 'user_id' in", "setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/',", "if 'extra_source' in local_var_params: query_params.append(('extra_source', local_var_params['extra_source'])) # noqa: E501 header_params", "'user_id', 'extra_location', 'extra_source'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout')", "\"\"\" local_var_params = locals() all_params = ['file_id', 'location_id', 'user_id', 'extra_location',", "make an asynchronous HTTP request, please pass async_req=True >>> thread", "asynchronous HTTP request, please pass async_req=True >>> thread = api.get_files_metadata(location_id,", "None): raise ValueError(\"Missing the required parameter `user_id` when calling `delete_file`\")", "required parameter 'location_id' is set if ('location_id' not in local_var_params", "local_var_params: query_params.append(('extra_source', local_var_params['extra_source'])) # noqa: E501 header_params = {} form_params", "is None): raise ValueError(\"Missing the required parameter `user_id` when calling", ":return: None If the method is called asynchronously, returns the", "data def upload_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "raise ValueError(\"Missing the required parameter `user_id` when calling `download_file`\") #", "user_id: (required) :return: None If the method is called asynchronously,", ":param str user_id: (required) :return: PresignedLinkEnveloped If the method is", "path_params['location_id'] = local_var_params['location_id'] # noqa: E501 query_params = [] header_params", "header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header", "header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) #", "when calling `upload_file`\") # noqa: E501 # verify the required", "return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", "ValueError(\"Missing the required parameter `user_id` when calling `get_storage_locations`\") # noqa:", "by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class", "# noqa: E501 return self.api_client.call_api( '/', 'GET', path_params, query_params, header_params,", "del local_var_params['kwargs'] # verify the required parameter 'user_id' is set", "str user_id: (required) :return: PresignedLinkEnveloped If the method is called", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_file(self, file_id, location_id,", "`download_file`\") # noqa: E501 # verify the required parameter 'location_id'", "HTTP request by default. To make an asynchronous HTTP request,", "query_params = [] header_params = {} form_params = [] local_var_files", ">>> result = thread.get() :param async_req bool :param str action:", "True if kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs) # noqa: E501 else: (data)", "self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 return data def check_action_post_with_http_info(self, action,", "local_var_params['file_id'] is None): raise ValueError(\"Missing the required parameter `file_id` when", "# noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(", "UsersApi(object): \"\"\"NOTE: This class is auto generated by OpenAPI Generator", "is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not", "pass async_req=True >>> thread = api.download_file_with_http_info(file_id, location_id, user_id, async_req=True) >>>", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations', 'GET',", "return self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data)", "[] # noqa: E501 return self.api_client.call_api( '/locations', 'GET', path_params, query_params,", "files=local_var_files, response_type='PresignedLinkEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa:", "location_id, user_id, **kwargs) # noqa: E501 else: (data) = self.get_file_metadata_with_http_info(file_id,", "E501 \"\"\"Service health-check endpoint # noqa: E501 Some general information", "noqa: E501 else: (data) = self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) #", "pass async_req=True >>> thread = api.get_file_metadata_with_http_info(file_id, location_id, user_id, async_req=True) >>>", "header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'),", "= local_var_params['location_id'] # noqa: E501 query_params = [] if 'user_id'", "[] if 'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501", "upload_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns upload", "asynchronous HTTP request, please pass async_req=True >>> thread = api.health_check_with_http_info(async_req=True)", "download_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns download", "HTTP request, please pass async_req=True >>> thread = api.get_file_metadata_with_http_info(file_id, location_id,", "Generator Ref: https://openapi-generator.tech Do not edit the class manually. \"\"\"", "\" to method health_check\" % key ) local_var_params[key] = val", "noqa: E501 \"\"\"Deletes File # noqa: E501 This method makes", "path_params = {} query_params = [] header_params = {} form_params", "all_params.append('_preload_content') all_params.append('_request_timeout') for key, val in six.iteritems(local_var_params['kwargs']): if key not", "self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None,", "required parameter 'action' is set if ('action' not in local_var_params", "location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns upload link or", "thread. \"\"\" local_var_params = locals() all_params = ['file_id', 'location_id', 'user_id',", "parameter `location_id` when calling `delete_file`\") # noqa: E501 # verify", "in all_params: raise TypeError( \"Got an unexpected keyword argument '%s'\"", "parameter 'file_id' is set if ('file_id' not in local_var_params or", "(required) :return: PresignedLinkEnveloped If the method is called asynchronously, returns", "def download_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns", "self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 else: (data) = self.update_file_meta_data_with_http_info(file_id,", "return self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data)", "\"\"\" local_var_params = locals() all_params = ['file_id', 'location_id', 'user_id'] #", "is set if ('action' not in local_var_params or local_var_params['action'] is", "in local_var_params: path_params['fileId'] = local_var_params['file_id'] # noqa: E501 if 'location_id'", "setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/check/{action}',", "when calling `download_file`\") # noqa: E501 # verify the required", "available storage locations # noqa: E501 This method makes a", "# noqa: E501 else: (data) = self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs)", "= {} query_params = [] header_params = {} form_params =", "key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the", "unexpected keyword argument '%s'\" \" to method delete_file\" % key", "`get_storage_locations`\") # noqa: E501 collection_formats = {} path_params = {}", "makes a synchronous HTTP request by default. To make an", "[] # noqa: E501 return self.api_client.call_api( '/check/{action}', 'POST', path_params, query_params,", "header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'),", "utf-8 \"\"\" simcore-service-storage API API definition for simcore-service-storage service #", "or performs copy operation to datcore # noqa: E501 This", "asynchronous HTTP request, please pass async_req=True >>> thread = api.get_file_metadata_with_http_info(file_id,", "del local_var_params['kwargs'] # verify the required parameter 'file_id' is set", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def download_file(self, file_id, location_id,", "noqa: E501 return data def update_file_meta_data_with_http_info(self, file_id, location_id, **kwargs): #", "api_client def check_action_post(self, action, **kwargs): # noqa: E501 \"\"\"Test checkpoint", "'location_id', 'user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for", "update_file_meta_data\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "# noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key, val", "in local_var_params: path_params['action'] = local_var_params['action'] # noqa: E501 query_params =", "{} body_params = None # HTTP header `Accept` header_params['Accept'] =", "noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params, query_params, header_params, body=body_params,", "**kwargs) # noqa: E501 return data def get_file_metadata_with_http_info(self, file_id, location_id,", "local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'uuid_filter' in local_var_params:", "if 'file_id' in local_var_params: path_params['fileId'] = local_var_params['file_id'] # noqa: E501", "`location_id` when calling `upload_file`\") # noqa: E501 # verify the", "= {} path_params = {} if 'file_id' in local_var_params: path_params['fileId']", "# noqa: E501 header_params = {} form_params = [] local_var_files", "# HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501", "['user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key,", "noqa: E501 return self.api_client.call_api( '/locations', 'GET', path_params, query_params, header_params, body=body_params,", "user_id, **kwargs): # noqa: E501 \"\"\"Returns upload link or performs", "argument '%s'\" \" to method upload_file\" % key ) local_var_params[key]", "user_id, **kwargs): # noqa: E501 \"\"\"Deletes File # noqa: E501", "argument '%s'\" \" to method download_file\" % key ) local_var_params[key]", "\"\"\"Service health-check endpoint # noqa: E501 Some general information on", "keyword argument '%s'\" \" to method upload_file\" % key )", "# noqa: E501 else: (data) = self.check_action_post_with_http_info(action, **kwargs) # noqa:", "the request thread. \"\"\" local_var_params = locals() all_params = ['location_id',", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self, file_id, location_id, user_id, **kwargs):", "__future__ import absolute_import import re # noqa: F401 # python", "result = thread.get() :param async_req bool :param str location_id: (required)", "# verify the required parameter 'action' is set if ('action'", "calling `delete_file`\") # noqa: E501 # verify the required parameter", "local_var_params = locals() all_params = ['user_id'] # noqa: E501 all_params.append('async_req')", "return data def health_check_with_http_info(self, **kwargs): # noqa: E501 \"\"\"Service health-check", "get_storage_locations\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "the required parameter `file_id` when calling `update_file_meta_data`\") # noqa: E501", "for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params:", "ApiClient class UsersApi(object): \"\"\"NOTE: This class is auto generated by", "E501 \"\"\"Returns upload link or performs copy operation to datcore", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs) # noqa:", "raise ValueError(\"Missing the required parameter `file_id` when calling `update_file_meta_data`\") #", "\"\"\"Deletes File # noqa: E501 This method makes a synchronous", "**kwargs): # noqa: E501 \"\"\"Returns download link for requested file", "pass async_req=True >>> thread = api.get_files_metadata(location_id, user_id, async_req=True) >>> result", "\" to method upload_file\" % key ) local_var_params[key] = val", "\" to method check_action_post\" % key ) local_var_params[key] = val", "local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter", "thread = api.delete_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", "all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key, val in six.iteritems(local_var_params['kwargs']): if key", "argument '%s'\" \" to method get_storage_locations\" % key ) local_var_params[key]", "of the service behind # noqa: E501 This method makes", "'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', # noqa:", "None): raise ValueError(\"Missing the required parameter `location_id` when calling `get_files_metadata`\")", "'/locations/{location_id}/files/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped', #", "result = thread.get() :param async_req bool :param str file_id: (required)", "please pass async_req=True >>> thread = api.upload_file_with_http_info(file_id, location_id, user_id, async_req=True)", "`Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication", "`delete_file`\") # noqa: E501 # verify the required parameter 'user_id'", "pass async_req=True >>> thread = api.health_check(async_req=True) >>> result = thread.get()", "location_id, user_id, **kwargs) # noqa: E501 else: (data) = self.delete_file_with_http_info(file_id,", "None): raise ValueError(\"Missing the required parameter `file_id` when calling `update_file_meta_data`\")", "an unexpected keyword argument '%s'\" \" to method check_action_post\" %", "noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True),", ":param async_req bool :param str location_id: (required) :param str user_id:", "= api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True) >>> result = thread.get() :param async_req", "upload_file\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "thread.get() :param async_req bool :param str user_id: (required) :return: FileLocationArrayEnveloped", "# noqa: E501 query_params = [] if 'user_id' in local_var_params:", "link for requested file # noqa: E501 This method makes", "[] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET', path_params, query_params,", "Files Metadata # noqa: E501 This method makes a synchronous", "location_id, user_id, **kwargs) # noqa: E501 else: (data) = self.download_file_with_http_info(file_id,", "= True if kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) #", "collection_formats=collection_formats) def get_storage_locations(self, user_id, **kwargs): # noqa: E501 \"\"\"Get available", "= locals() all_params = ['action', 'data', 'fake_type'] # noqa: E501", ">>> result = thread.get() :param async_req bool :return: HealthCheckEnveloped If", "spec version: 0.1.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from", "method download_file\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "E501 \"\"\"Test checkpoint to ask server to fail or echo", "= api.get_storage_locations(user_id, async_req=True) >>> result = thread.get() :param async_req bool", "bool :param str action: (required) :param str data: :param FakeType", "if kwargs.get('async_req'): return self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 else: (data)", "thread = api.check_action_post(action, async_req=True) >>> result = thread.get() :param async_req", "local_var_params['location_id'] is None): raise ValueError(\"Missing the required parameter `location_id` when", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs)", "`location_id` when calling `update_file_meta_data`\") # noqa: E501 collection_formats = {}", "files=local_var_files, response_type='HealthCheckEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa:", "all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout')", "HealthCheckEnveloped If the method is called asynchronously, returns the request", "asynchronously, returns the request thread. \"\"\" kwargs['_return_http_data_only'] = True if", "# noqa: E501 else: (data) = self.download_file_with_http_info(file_id, location_id, user_id, **kwargs)", "raise ValueError(\"Missing the required parameter `location_id` when calling `get_files_metadata`\") #", "noqa: E501 if 'extra_location' in local_var_params: query_params.append(('extra_location', local_var_params['extra_location'])) # noqa:", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id, location_id,", "post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), #", "api.upload_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/metadata',", "\"\"\" local_var_params = locals() all_params = ['action', 'data', 'fake_type'] #", "self.api_client = api_client def check_action_post(self, action, **kwargs): # noqa: E501", "noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE', path_params, query_params, header_params, body=body_params,", "please pass async_req=True >>> thread = api.health_check(async_req=True) >>> result =", "'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', # noqa:", "user_id, **kwargs): # noqa: E501 \"\"\"Returns download link for requested", "`user_id` when calling `get_file_metadata`\") # noqa: E501 collection_formats = {}", "return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", "back the transmitted data # noqa: E501 This method makes", "parameter 'action' is set if ('action' not in local_var_params or", "[] header_params = {} form_params = [] local_var_files = {}", "keyword argument '%s'\" \" to method health_check\" % key )", "`get_files_metadata`\") # noqa: E501 collection_formats = {} path_params = {}", "E501 Some general information on the API and state of", "in local_var_params or local_var_params['location_id'] is None): raise ValueError(\"Missing the required", "str location_id: (required) :param str user_id: (required) :return: PresignedLinkEnveloped If", "def update_file_meta_data_with_http_info(self, file_id, location_id, **kwargs): # noqa: E501 \"\"\"Update File", "else: (data) = self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "E501 # verify the required parameter 'location_id' is set if", "str data: :param FakeType fake_type: :return: FakeEnveloped If the method", "noqa: E501 collection_formats = {} path_params = {} query_params =", "parameter `user_id` when calling `get_storage_locations`\") # noqa: E501 collection_formats =", "'%s'\" \" to method delete_file\" % key ) local_var_params[key] =", "kwargs.get('async_req'): return self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else:", "% key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats =", "location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns download link for", "https://openapi-generator.tech \"\"\" from __future__ import absolute_import import re # noqa:", "if kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs) # noqa: E501 else: (data) =", "raise ValueError(\"Missing the required parameter `user_id` when calling `get_file_metadata`\") #", "'location_id' is set if ('location_id' not in local_var_params or local_var_params['location_id']", "to method get_file_metadata\" % key ) local_var_params[key] = val del", "raise ValueError(\"Missing the required parameter `user_id` when calling `upload_file`\") #", "str action: (required) :param str data: :param FakeType fake_type: :return:", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_file_metadata(self, file_id, location_id,", "method makes a synchronous HTTP request by default. To make", "E501 else: (data) = self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self,", "('user_id' not in local_var_params or local_var_params['user_id'] is None): raise ValueError(\"Missing", "= local_var_params['location_id'] # noqa: E501 query_params = [] header_params =", "{} path_params = {} if 'action' in local_var_params: path_params['action'] =", "data def health_check_with_http_info(self, **kwargs): # noqa: E501 \"\"\"Service health-check endpoint", "noqa: E501 else: (data) = self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) #", "thread = api.get_file_metadata(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", "parameter `user_id` when calling `get_file_metadata`\") # noqa: E501 collection_formats =", "= None if 'fake_type' in local_var_params: body_params = local_var_params['fake_type'] #", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id,", "pass async_req=True >>> thread = api.upload_file(file_id, location_id, user_id, async_req=True) >>>", "method is called asynchronously, returns the request thread. \"\"\" local_var_params", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def update_file_meta_data(self, file_id, location_id, **kwargs): # noqa: E501", "**kwargs) # noqa: E501 else: (data) = self.delete_file_with_http_info(file_id, location_id, user_id,", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def update_file_meta_data(self, file_id, location_id, **kwargs):", "api.get_file_metadata(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "please pass async_req=True >>> thread = api.check_action_post(action, async_req=True) >>> result", "# noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET', path_params, query_params, header_params,", "# noqa: E501 return self.api_client.call_api( '/locations', 'GET', path_params, query_params, header_params,", "user_id, **kwargs) # noqa: E501 return data def download_file_with_http_info(self, file_id,", "E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params,", "(required) :param FileMetaDataType file_meta_data_type: :return: FileMetaDataEnveloped If the method is", "return self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 else: (data) =", ">>> result = thread.get() :param async_req bool :param str file_id:", "str location_id: (required) :param str user_id: (required) :return: None If", "def update_file_meta_data(self, file_id, location_id, **kwargs): # noqa: E501 \"\"\"Update File", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.check_action_post_with_http_info(action, **kwargs)", "please pass async_req=True >>> thread = api.delete_file(file_id, location_id, user_id, async_req=True)", "import ApiClient class UsersApi(object): \"\"\"NOTE: This class is auto generated", "pass async_req=True >>> thread = api.delete_file(file_id, location_id, user_id, async_req=True) >>>", "= local_var_params['file_id'] # noqa: E501 if 'location_id' in local_var_params: path_params['location_id']", "post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), #", "(data) = self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return", "all_params = ['location_id', 'user_id', 'uuid_filter'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only')", "all_params = ['file_id', 'location_id', 'user_id', 'extra_location', 'extra_source'] # noqa: E501", "raise ValueError(\"Missing the required parameter `location_id` when calling `download_file`\") #", "noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET', path_params, query_params, header_params, body=body_params,", "async_req bool :param str action: (required) :param str data: :param", "body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'),", "\"\"\"Get File Metadata # noqa: E501 This method makes a", "in local_var_params: query_params.append(('extra_source', local_var_params['extra_source'])) # noqa: E501 header_params = {}", "file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get File Metadata", "required parameter `action` when calling `check_action_post`\") # noqa: E501 collection_formats", "unexpected keyword argument '%s'\" \" to method upload_file\" % key", "noqa: E501 # verify the required parameter 'user_id' is set", "E501 else: (data) = self.health_check_with_http_info(**kwargs) # noqa: E501 return data", "# noqa: E501 \"\"\"Get File Metadata # noqa: E501 This", "raise ValueError(\"Missing the required parameter `location_id` when calling `delete_file`\") #", "the API and state of the service behind # noqa:", "argument '%s'\" \" to method health_check\" % key ) local_var_params[key]", "self.health_check_with_http_info(**kwargs) # noqa: E501 return data def health_check_with_http_info(self, **kwargs): #", "noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( #", "{} if 'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id'] # noqa:", "self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 return data def update_file_meta_data_with_http_info(self,", "async_req=True) >>> result = thread.get() :param async_req bool :param str", "required parameter `location_id` when calling `upload_file`\") # noqa: E501 #", "ask server to fail or echo back the transmitted data", "data def get_files_metadata_with_http_info(self, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get", "'%s'\" \" to method get_files_metadata\" % key ) local_var_params[key] =", "True if kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501", "async_req=True >>> thread = api.delete_file(file_id, location_id, user_id, async_req=True) >>> result", "noqa: E501 if 'uuid_filter' in local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter'])) # noqa:", "please pass async_req=True >>> thread = api.get_files_metadata_with_http_info(location_id, user_id, async_req=True) >>>", "user_id: (required) :return: FileMetaDataEnveloped If the method is called asynchronously,", "noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT', path_params, query_params, header_params, body=body_params,", ":return: PresignedLinkEnveloped If the method is called asynchronously, returns the", "the request thread. \"\"\" local_var_params = locals() all_params = ['file_id',", "else: (data) = self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 return", "# noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params, query_params, header_params,", "return self.api_client.call_api( '/locations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", "# noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE', path_params, query_params, header_params,", "del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params =", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_file(self, file_id, location_id, user_id,", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_storage_locations(self, user_id, **kwargs): # noqa: E501", "locals() all_params = ['file_id', 'location_id', 'user_id'] # noqa: E501 all_params.append('async_req')", "async_req=True >>> thread = api.get_file_metadata(file_id, location_id, user_id, async_req=True) >>> result", "**kwargs): # noqa: E501 \"\"\"Get Files Metadata # noqa: E501", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.download_file_with_http_info(file_id, location_id,", "local_var_params = locals() all_params = ['action', 'data', 'fake_type'] # noqa:", "E501 \"\"\"Returns download link for requested file # noqa: E501", "the required parameter 'action' is set if ('action' not in", "update_file_meta_data_with_http_info(self, file_id, location_id, **kwargs): # noqa: E501 \"\"\"Update File Metadata", "`file_id` when calling `get_file_metadata`\") # noqa: E501 # verify the", "local_var_params['uuid_filter'])) # noqa: E501 header_params = {} form_params = []", "general information on the API and state of the service", "pass async_req=True >>> thread = api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True) >>> result", "request, please pass async_req=True >>> thread = api.download_file(file_id, location_id, user_id,", "if kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 else:", "api.upload_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "ApiClient() self.api_client = api_client def check_action_post(self, action, **kwargs): # noqa:", "if 'uuid_filter' in local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter'])) # noqa: E501 header_params", "# noqa: E501 query_params = [] header_params = {} form_params", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def download_file(self, file_id, location_id, user_id, **kwargs):", "local_var_params['kwargs'] # verify the required parameter 'location_id' is set if", "str location_id: (required) :param str user_id: (required) :param str extra_location:", "user_id, **kwargs) # noqa: E501 else: (data) = self.get_file_metadata_with_http_info(file_id, location_id,", "check_action_post_with_http_info(self, action, **kwargs): # noqa: E501 \"\"\"Test checkpoint to ask", "3 compatibility library import six from simcore_service_storage_sdk.api_client import ApiClient class", "'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'uuid_filter'", "# noqa: E501 return data def health_check_with_http_info(self, **kwargs): # noqa:", "copy operation to datcore # noqa: E501 This method makes", "**kwargs) # noqa: E501 return data def check_action_post_with_http_info(self, action, **kwargs):", "if kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 else: (data)", "= ['location_id', 'user_id', 'uuid_filter'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content')", "`user_id` when calling `get_files_metadata`\") # noqa: E501 collection_formats = {}", "local_var_params = locals() all_params = [] # noqa: E501 all_params.append('async_req')", "raise ValueError(\"Missing the required parameter `user_id` when calling `delete_file`\") #", "else: (data) = self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "FakeType fake_type: :return: FakeEnveloped If the method is called asynchronously,", "async_req=True >>> thread = api.get_files_metadata_with_http_info(location_id, user_id, async_req=True) >>> result =", "set if ('user_id' not in local_var_params or local_var_params['user_id'] is None):", "(required) :param str user_id: (required) :param str uuid_filter: :return: FileMetaDataArrayEnveloped", "response_type='FileLocationArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501", "auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)", "del local_var_params['kwargs'] # verify the required parameter 'location_id' is set", "class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do", "asynchronous HTTP request, please pass async_req=True >>> thread = api.upload_file_with_http_info(file_id,", "file_id: (required) :param str location_id: (required) :param str user_id: (required)", "None): raise ValueError(\"Missing the required parameter `action` when calling `check_action_post`\")", "\"\"\" local_var_params = locals() all_params = [] # noqa: E501", "to method upload_file\" % key ) local_var_params[key] = val del", "please pass async_req=True >>> thread = api.get_storage_locations(user_id, async_req=True) >>> result", "data def delete_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "= {} path_params = {} query_params = [] if 'user_id'", "str uuid_filter: :return: FileMetaDataArrayEnveloped If the method is called asynchronously,", "required parameter `file_id` when calling `delete_file`\") # noqa: E501 #", "when calling `update_file_meta_data`\") # noqa: E501 # verify the required", "= [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT', path_params,", "to method download_file\" % key ) local_var_params[key] = val del", "the required parameter 'file_id' is set if ('file_id' not in", "location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get Files Metadata #", "None): raise ValueError(\"Missing the required parameter `file_id` when calling `get_file_metadata`\")", "str extra_location: :param str extra_source: :return: PresignedLinkEnveloped If the method", "self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped',", "\" to method get_file_metadata\" % key ) local_var_params[key] = val", "'user_id', 'uuid_filter'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for", "return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", "bool :param str file_id: (required) :param str location_id: (required) :param", "# coding: utf-8 \"\"\" simcore-service-storage API API definition for simcore-service-storage", "delete_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Deletes File", "the required parameter `file_id` when calling `get_file_metadata`\") # noqa: E501", "= ApiClient() self.api_client = api_client def check_action_post(self, action, **kwargs): #", "self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings =", "(required) :param str location_id: (required) :param str user_id: (required) :return:", "download link for requested file # noqa: E501 This method", "HTTP request, please pass async_req=True >>> thread = api.health_check(async_req=True) >>>", "'%s'\" \" to method check_action_post\" % key ) local_var_params[key] =", "unexpected keyword argument '%s'\" \" to method update_file_meta_data\" % key", "HTTP request, please pass async_req=True >>> thread = api.health_check_with_http_info(async_req=True) >>>", "async_req=True >>> thread = api.upload_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result", "calling `get_files_metadata`\") # noqa: E501 collection_formats = {} path_params =", "noqa: E501 OpenAPI spec version: 0.1.0 Contact: <EMAIL> Generated by:", "HTTP request, please pass async_req=True >>> thread = api.delete_file_with_http_info(file_id, location_id,", "raise ValueError(\"Missing the required parameter `user_id` when calling `get_files_metadata`\") #", "raise ValueError(\"Missing the required parameter `file_id` when calling `download_file`\") #", "'/locations/{location_id}/files/{fileId}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, #", "required parameter `user_id` when calling `delete_file`\") # noqa: E501 collection_formats", "parameter `file_id` when calling `upload_file`\") # noqa: E501 # verify", "calling `download_file`\") # noqa: E501 collection_formats = {} path_params =", "parameter 'location_id' is set if ('location_id' not in local_var_params or", "post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), #", "# verify the required parameter 'location_id' is set if ('location_id'", "E501 else: (data) = self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501", "= True if kwargs.get('async_req'): return self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) #", "**kwargs): # noqa: E501 \"\"\"Test checkpoint to ask server to", "return self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 else: (data) = self.get_storage_locations_with_http_info(user_id,", "async_req=True >>> thread = api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True) >>> result =", "E501 return self.api_client.call_api( '/locations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params,", "'extra_source'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key,", "echo back the transmitted data # noqa: E501 This method", "header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501", "(required) :param str location_id: (required) :param str user_id: (required) :param", "\"\"\" simcore-service-storage API API definition for simcore-service-storage service # noqa:", "\"Got an unexpected keyword argument '%s'\" \" to method download_file\"", "user_id: (required) :param str uuid_filter: :return: FileMetaDataArrayEnveloped If the method", "import six from simcore_service_storage_sdk.api_client import ApiClient class UsersApi(object): \"\"\"NOTE: This", "= self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings", "api.get_storage_locations(user_id, async_req=True) >>> result = thread.get() :param async_req bool :param", "keyword argument '%s'\" \" to method update_file_meta_data\" % key )", "the required parameter `file_id` when calling `delete_file`\") # noqa: E501", ">>> thread = api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True) >>> result = thread.get()", "(data) = self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 return data", "keyword argument '%s'\" \" to method get_files_metadata\" % key )", "noqa: E501 if 'extra_source' in local_var_params: query_params.append(('extra_source', local_var_params['extra_source'])) # noqa:", "request, please pass async_req=True >>> thread = api.check_action_post(action, async_req=True) >>>", "local_var_params['fake_type'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) #", "request, please pass async_req=True >>> thread = api.get_file_metadata(file_id, location_id, user_id,", "E501 # verify the required parameter 'user_id' is set if", "for simcore-service-storage service # noqa: E501 OpenAPI spec version: 0.1.0", "request thread. \"\"\" local_var_params = locals() all_params = ['file_id', 'location_id',", "ValueError(\"Missing the required parameter `location_id` when calling `get_files_metadata`\") # noqa:", "local_var_params['user_id'] is None): raise ValueError(\"Missing the required parameter `user_id` when", "self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data) =", "else: (data) = self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "`Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_file(self, file_id, location_id, user_id, **kwargs):", "HTTP request, please pass async_req=True >>> thread = api.upload_file(file_id, location_id,", "files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa:", "= locals() all_params = ['user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only')", "data def download_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "thread = api.get_files_metadata(location_id, user_id, async_req=True) >>> result = thread.get() :param", "in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'uuid_filter' in", "body_params = None if 'fake_type' in local_var_params: body_params = local_var_params['fake_type']", "E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params,", "['file_id', 'location_id', 'user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout')", "# noqa: E501 return data def upload_file_with_http_info(self, file_id, location_id, user_id,", "HTTP request, please pass async_req=True >>> thread = api.delete_file(file_id, location_id,", "thread = api.upload_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def update_file_meta_data(self, file_id, location_id, **kwargs): #", "pass async_req=True >>> thread = api.get_file_metadata(file_id, location_id, user_id, async_req=True) >>>", ":param str location_id: (required) :param str user_id: (required) :param str", "check_action_post(self, action, **kwargs): # noqa: E501 \"\"\"Test checkpoint to ask", "calling `upload_file`\") # noqa: E501 collection_formats = {} path_params =", "Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api(", "None): raise ValueError(\"Missing the required parameter `location_id` when calling `download_file`\")", "required parameter `user_id` when calling `get_storage_locations`\") # noqa: E501 collection_formats", "all_params: raise TypeError( \"Got an unexpected keyword argument '%s'\" \"", "['file_id', 'location_id', 'user_id', 'extra_location', 'extra_source'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only')", "ValueError(\"Missing the required parameter `user_id` when calling `upload_file`\") # noqa:", "the required parameter `user_id` when calling `upload_file`\") # noqa: E501", "ValueError(\"Missing the required parameter `file_id` when calling `upload_file`\") # noqa:", "api.get_files_metadata(location_id, user_id, async_req=True) >>> result = thread.get() :param async_req bool", "FileMetaDataType file_meta_data_type: :return: FileMetaDataEnveloped If the method is called asynchronously,", "'file_id' is set if ('file_id' not in local_var_params or local_var_params['file_id']", "['action', 'data', 'fake_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout')", "E501 if 'extra_location' in local_var_params: query_params.append(('extra_location', local_var_params['extra_location'])) # noqa: E501", "async_req=True >>> thread = api.update_file_meta_data(file_id, location_id, async_req=True) >>> result =", "= api.download_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 else: (data) = self.get_storage_locations_with_http_info(user_id, **kwargs)", "noqa: E501 This method makes a synchronous HTTP request by", "response_type='PresignedLinkEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501", "HTTP request, please pass async_req=True >>> thread = api.get_file_metadata(file_id, location_id,", "called asynchronously, returns the request thread. \"\"\" kwargs['_return_http_data_only'] = True", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.download_file_with_http_info(file_id, location_id, user_id,", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def health_check(self, **kwargs): # noqa:", "pass async_req=True >>> thread = api.delete_file_with_http_info(file_id, location_id, user_id, async_req=True) >>>", "endpoint # noqa: E501 Some general information on the API", "= {} body_params = None # HTTP header `Accept` header_params['Accept']", "E501 OpenAPI spec version: 0.1.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech", "\"\"\" local_var_params = locals() all_params = ['user_id'] # noqa: E501", "**kwargs): # noqa: E501 \"\"\"Deletes File # noqa: E501 This", "# noqa: E501 else: (data) = self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs)", "(data) = self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return", "val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise TypeError(", "'user_id' is set if ('user_id' not in local_var_params or local_var_params['user_id']", "[] if 'data' in local_var_params: query_params.append(('data', local_var_params['data'])) # noqa: E501", "`location_id` when calling `download_file`\") # noqa: E501 # verify the", "locals() all_params = ['location_id', 'user_id', 'uuid_filter'] # noqa: E501 all_params.append('async_req')", "`upload_file`\") # noqa: E501 # verify the required parameter 'user_id'", "(required) :param str location_id: (required) :param FileMetaDataType file_meta_data_type: :return: FileMetaDataEnveloped", "def delete_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Deletes", "to method delete_file\" % key ) local_var_params[key] = val del", "data def update_file_meta_data_with_http_info(self, file_id, location_id, **kwargs): # noqa: E501 \"\"\"Update", "location_id, user_id, async_req=True) >>> result = thread.get() :param async_req bool", "download_file\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "**kwargs): # noqa: E501 \"\"\"Get File Metadata # noqa: E501", "# verify the required parameter 'user_id' is set if ('user_id'", "def get_files_metadata(self, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get Files", "if key not in all_params: raise TypeError( \"Got an unexpected", "E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'),", "to method check_action_post\" % key ) local_var_params[key] = val del", "PresignedLinkEnveloped If the method is called asynchronously, returns the request", "None): raise ValueError(\"Missing the required parameter `file_id` when calling `download_file`\")", "query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings,", "`download_file`\") # noqa: E501 # verify the required parameter 'user_id'", "if 'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if", "= api.get_file_metadata_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "collection_formats=collection_formats) def download_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "collection_formats=collection_formats) def get_files_metadata(self, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get", "request, please pass async_req=True >>> thread = api.get_files_metadata(location_id, user_id, async_req=True)", "raise ValueError(\"Missing the required parameter `location_id` when calling `update_file_meta_data`\") #", "__init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client", "`get_file_metadata`\") # noqa: E501 collection_formats = {} path_params = {}", "an unexpected keyword argument '%s'\" \" to method get_storage_locations\" %", ":return: FileLocationArrayEnveloped If the method is called asynchronously, returns the", "by default. To make an asynchronous HTTP request, please pass", "noqa: E501 return data def health_check_with_http_info(self, **kwargs): # noqa: E501", "= [] if 'data' in local_var_params: query_params.append(('data', local_var_params['data'])) # noqa:", "noqa: E501 # verify the required parameter 'location_id' is set", "raise ValueError(\"Missing the required parameter `user_id` when calling `get_storage_locations`\") #", "required parameter `location_id` when calling `get_file_metadata`\") # noqa: E501 #", "E501 else: (data) = self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "val del local_var_params['kwargs'] # verify the required parameter 'location_id' is", "collection_formats = {} path_params = {} query_params = [] if", "def health_check_with_http_info(self, **kwargs): # noqa: E501 \"\"\"Service health-check endpoint #", "**kwargs) # noqa: E501 else: (data) = self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs)", "raise ValueError(\"Missing the required parameter `file_id` when calling `delete_file`\") #", "# noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET', path_params, query_params, header_params,", "class UsersApi(object): \"\"\"NOTE: This class is auto generated by OpenAPI", "location_id, user_id, **kwargs) # noqa: E501 return data def get_file_metadata_with_http_info(self,", "synchronous HTTP request by default. To make an asynchronous HTTP", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_file_with_http_info(file_id,", "{} query_params = [] if 'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id']))", "locals() all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content')", "path_params = {} if 'action' in local_var_params: path_params['action'] = local_var_params['action']", "result = thread.get() :param async_req bool :param str user_id: (required)", "required parameter `location_id` when calling `download_file`\") # noqa: E501 #", "when calling `get_file_metadata`\") # noqa: E501 collection_formats = {} path_params", "(data) = self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 return data def", "'%s'\" \" to method update_file_meta_data\" % key ) local_var_params[key] =", "local_var_files = {} body_params = None if 'fake_type' in local_var_params:", "# noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params, query_params, header_params,", "when calling `update_file_meta_data`\") # noqa: E501 collection_formats = {} path_params", "is set if ('user_id' not in local_var_params or local_var_params['user_id'] is", "a synchronous HTTP request by default. To make an asynchronous", "local_var_params = locals() all_params = ['file_id', 'location_id', 'user_id', 'extra_location', 'extra_source']", "E501 return data def update_file_meta_data_with_http_info(self, file_id, location_id, **kwargs): # noqa:", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def download_file(self, file_id, location_id, user_id, **kwargs): #", "`user_id` when calling `download_file`\") # noqa: E501 collection_formats = {}", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET',", "from simcore_service_storage_sdk.api_client import ApiClient class UsersApi(object): \"\"\"NOTE: This class is", "[] local_var_files = {} body_params = None # HTTP header", "raise TypeError( \"Got an unexpected keyword argument '%s'\" \" to", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_file(self, file_id, location_id, user_id, **kwargs): # noqa:", "query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FakeEnveloped', # noqa: E501 auth_settings=auth_settings,", "header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'),", "fail or echo back the transmitted data # noqa: E501", ":param str data: :param FakeType fake_type: :return: FakeEnveloped If the", "thread = api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True) >>> result = thread.get() :param", "E501 return self.api_client.call_api( '/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params,", "OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.", "calling `check_action_post`\") # noqa: E501 collection_formats = {} path_params =", "thread = api.health_check_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool", "str file_id: (required) :param str location_id: (required) :param FileMetaDataType file_meta_data_type:", "noqa: E501 \"\"\"Get available storage locations # noqa: E501 This", "return data def download_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa:", "method check_action_post\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "files=local_var_files, response_type='FileMetaDataEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa:", "E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params,", "= thread.get() :param async_req bool :return: HealthCheckEnveloped If the method", "location_id, user_id, **kwargs) # noqa: E501 return data def delete_file_with_http_info(self,", "required parameter `user_id` when calling `get_files_metadata`\") # noqa: E501 collection_formats", "async_req bool :param str location_id: (required) :param str user_id: (required)", "File Metadata # noqa: E501 This method makes a synchronous", "'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'extra_location'", "method health_check\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "required parameter `file_id` when calling `upload_file`\") # noqa: E501 #", "kwargs.get('async_req'): return self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 else: (data) =", "collection_formats=collection_formats) def health_check(self, **kwargs): # noqa: E501 \"\"\"Service health-check endpoint", "api.download_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "local_var_params: path_params['action'] = local_var_params['action'] # noqa: E501 query_params = []", "the required parameter 'location_id' is set if ('location_id' not in", "`upload_file`\") # noqa: E501 # verify the required parameter 'location_id'", "else: (data) = self.health_check_with_http_info(**kwargs) # noqa: E501 return data def", "noqa: E501 if 'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id'] #", "class manually. \"\"\" def __init__(self, api_client=None): if api_client is None:", "parameter `user_id` when calling `delete_file`\") # noqa: E501 collection_formats =", "return data def get_storage_locations_with_http_info(self, user_id, **kwargs): # noqa: E501 \"\"\"Get", "\" to method delete_file\" % key ) local_var_params[key] = val", "to method update_file_meta_data\" % key ) local_var_params[key] = val del", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/check/{action}', 'POST',", "to datcore # noqa: E501 This method makes a synchronous", "Metadata # noqa: E501 This method makes a synchronous HTTP", "fake_type: :return: FakeEnveloped If the method is called asynchronously, returns", "**kwargs) # noqa: E501 else: (data) = self.get_files_metadata_with_http_info(location_id, user_id, **kwargs)", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def download_file(self,", "get_file_metadata_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get File", "E501 return self.api_client.call_api( '/check/{action}', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params,", ":param str extra_source: :return: PresignedLinkEnveloped If the method is called", "async_req=True >>> thread = api.check_action_post_with_http_info(action, async_req=True) >>> result = thread.get()", "coding: utf-8 \"\"\" simcore-service-storage API API definition for simcore-service-storage service", "performs copy operation to datcore # noqa: E501 This method", "if ('file_id' not in local_var_params or local_var_params['file_id'] is None): raise", "https://openapi-generator.tech Do not edit the class manually. \"\"\" def __init__(self,", "True if kwargs.get('async_req'): return self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "**kwargs): # noqa: E501 \"\"\"Get available storage locations # noqa:", "thread = api.get_storage_locations_with_http_info(user_id, async_req=True) >>> result = thread.get() :param async_req", "the request thread. \"\"\" local_var_params = locals() all_params = []", "ValueError(\"Missing the required parameter `file_id` when calling `download_file`\") # noqa:", "body=body_params, post_params=form_params, files=local_var_files, response_type='FakeEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'),", "raise ValueError(\"Missing the required parameter `location_id` when calling `upload_file`\") #", ":param str location_id: (required) :param str user_id: (required) :return: None", "simcore-service-storage API API definition for simcore-service-storage service # noqa: E501", "parameter 'user_id' is set if ('user_id' not in local_var_params or", "thread = api.download_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", ":param str user_id: (required) :return: FileLocationArrayEnveloped If the method is", "None: api_client = ApiClient() self.api_client = api_client def check_action_post(self, action,", "To make an asynchronous HTTP request, please pass async_req=True >>>", ":param str location_id: (required) :param str user_id: (required) :return: PresignedLinkEnveloped", "calling `upload_file`\") # noqa: E501 # verify the required parameter", "local_var_params['user_id'])) # noqa: E501 header_params = {} form_params = []", "= api.delete_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "None if 'file_meta_data_type' in local_var_params: body_params = local_var_params['file_meta_data_type'] # HTTP", "user_id, **kwargs): # noqa: E501 \"\"\"Get available storage locations #", "not in local_var_params or local_var_params['action'] is None): raise ValueError(\"Missing the", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id, **kwargs)", "download_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns download", "async_req=True >>> thread = api.health_check_with_http_info(async_req=True) >>> result = thread.get() :param", "= api.download_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "please pass async_req=True >>> thread = api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True) >>>", "kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 else: (data)", "required parameter 'file_id' is set if ('file_id' not in local_var_params", "setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations',", "please pass async_req=True >>> thread = api.health_check_with_http_info(async_req=True) >>> result =", ":param str user_id: (required) :return: None If the method is", "raise ValueError(\"Missing the required parameter `action` when calling `check_action_post`\") #", "unexpected keyword argument '%s'\" \" to method download_file\" % key", "path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped', # noqa: E501", "\" to method get_storage_locations\" % key ) local_var_params[key] = val", "calling `get_file_metadata`\") # noqa: E501 # verify the required parameter", "calling `get_storage_locations`\") # noqa: E501 collection_formats = {} path_params =", "`file_id` when calling `delete_file`\") # noqa: E501 # verify the", "local_var_params: query_params.append(('data', local_var_params['data'])) # noqa: E501 header_params = {} form_params", ">>> thread = api.get_files_metadata(location_id, user_id, async_req=True) >>> result = thread.get()", "noqa: E501 else: (data) = self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa:", ":return: FakeEnveloped If the method is called asynchronously, returns the", "edit the class manually. \"\"\" def __init__(self, api_client=None): if api_client", "E501 return data def upload_file_with_http_info(self, file_id, location_id, user_id, **kwargs): #", "async_req=True >>> thread = api.upload_file(file_id, location_id, user_id, async_req=True) >>> result", "`file_id` when calling `update_file_meta_data`\") # noqa: E501 # verify the", "query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', # noqa: E501 auth_settings=auth_settings,", "the required parameter `file_id` when calling `upload_file`\") # noqa: E501", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE',", "(required) :return: FileLocationArrayEnveloped If the method is called asynchronously, returns", "= [] # noqa: E501 return self.api_client.call_api( '/', 'GET', path_params,", "noqa: F401 # python 2 and python 3 compatibility library", "'location_id', 'user_id', 'extra_location', 'extra_source'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content')", "bool :param str user_id: (required) :return: FileLocationArrayEnveloped If the method", "# Authentication setting auth_settings = [] # noqa: E501 return", "keyword argument '%s'\" \" to method get_storage_locations\" % key )", "\"Got an unexpected keyword argument '%s'\" \" to method health_check\"", "'extra_source' in local_var_params: query_params.append(('extra_source', local_var_params['extra_source'])) # noqa: E501 header_params =", "HTTP request, please pass async_req=True >>> thread = api.get_files_metadata_with_http_info(location_id, user_id,", "'user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key,", "`user_id` when calling `delete_file`\") # noqa: E501 collection_formats = {}", "in local_var_params or local_var_params['user_id'] is None): raise ValueError(\"Missing the required", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def health_check(self,", ">>> thread = api.update_file_meta_data(file_id, location_id, async_req=True) >>> result = thread.get()", "'/locations/{location_id}/files/{fileId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', #", "E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def download_file(self, file_id, location_id, user_id,", "True if kwargs.get('async_req'): return self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "ValueError(\"Missing the required parameter `user_id` when calling `delete_file`\") # noqa:", "None): raise ValueError(\"Missing the required parameter `location_id` when calling `upload_file`\")", "thread. \"\"\" local_var_params = locals() all_params = [] # noqa:", "body_params = local_var_params['file_meta_data_type'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(", "ValueError(\"Missing the required parameter `location_id` when calling `update_file_meta_data`\") # noqa:", "pass async_req=True >>> thread = api.upload_file_with_http_info(file_id, location_id, user_id, async_req=True) >>>", "= api.health_check(async_req=True) >>> result = thread.get() :param async_req bool :return:", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_file(self,", "or local_var_params['action'] is None): raise ValueError(\"Missing the required parameter `action`", "`location_id` when calling `get_file_metadata`\") # noqa: E501 # verify the", "`get_file_metadata`\") # noqa: E501 # verify the required parameter 'user_id'", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH',", "local_var_params: path_params['fileId'] = local_var_params['file_id'] # noqa: E501 if 'location_id' in", "[] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key,", "'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped', # noqa:", "key not in all_params: raise TypeError( \"Got an unexpected keyword", "if kwargs.get('async_req'): return self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.check_action_post_with_http_info(action,", "collection_formats=collection_formats) def update_file_meta_data(self, file_id, location_id, **kwargs): # noqa: E501 \"\"\"Update", "'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 header_params =", "user_id, async_req=True) >>> result = thread.get() :param async_req bool :param", "path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', # noqa: E501", "`update_file_meta_data`\") # noqa: E501 # verify the required parameter 'location_id'", "noqa: E501 \"\"\"Service health-check endpoint # noqa: E501 Some general", "user_id, **kwargs) # noqa: E501 return data def upload_file_with_http_info(self, file_id,", "This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech", "True if kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 else:", "noqa: E501 \"\"\"Test checkpoint to ask server to fail or", "# noqa: E501 return data def download_file_with_http_info(self, file_id, location_id, user_id,", "thread. \"\"\" local_var_params = locals() all_params = ['file_id', 'location_id', 'user_id']", "def health_check(self, **kwargs): # noqa: E501 \"\"\"Service health-check endpoint #", "= [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params,", "= api.check_action_post(action, async_req=True) >>> result = thread.get() :param async_req bool", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_file_metadata(self, file_id, location_id, user_id, **kwargs):", "the request thread. \"\"\" local_var_params = locals() all_params = ['user_id']", "(required) :param str data: :param FakeType fake_type: :return: FakeEnveloped If", "= [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE', path_params,", "an unexpected keyword argument '%s'\" \" to method download_file\" %", "local_var_params['file_meta_data_type'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) #", "the required parameter `location_id` when calling `delete_file`\") # noqa: E501", "key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise", "noqa: E501 return data def get_storage_locations_with_http_info(self, user_id, **kwargs): # noqa:", "= api.upload_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "request, please pass async_req=True >>> thread = api.health_check(async_req=True) >>> result", "def get_storage_locations_with_http_info(self, user_id, **kwargs): # noqa: E501 \"\"\"Get available storage", "'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', # noqa:", "local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = []", "verify the required parameter 'user_id' is set if ('user_id' not", "E501 else: (data) = self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 return", "if 'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 header_params", ">>> result = thread.get() :param async_req bool :param str location_id:", "set if ('file_id' not in local_var_params or local_var_params['file_id'] is None):", "asynchronous HTTP request, please pass async_req=True >>> thread = api.upload_file(file_id,", "None): raise ValueError(\"Missing the required parameter `user_id` when calling `get_files_metadata`\")", "post_params=form_params, files=local_var_files, response_type='FakeEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), #", "= api.check_action_post_with_http_info(action, async_req=True) >>> result = thread.get() :param async_req bool", "bool :param str location_id: (required) :param str user_id: (required) :param", "{} path_params = {} if 'file_id' in local_var_params: path_params['fileId'] =", "**kwargs) # noqa: E501 else: (data) = self.check_action_post_with_http_info(action, **kwargs) #", "FakeEnveloped If the method is called asynchronously, returns the request", "the required parameter `user_id` when calling `download_file`\") # noqa: E501", "[] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params, query_params,", "when calling `download_file`\") # noqa: E501 collection_formats = {} path_params", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT',", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.download_file_with_http_info(file_id,", "api.get_files_metadata_with_http_info(location_id, user_id, async_req=True) >>> result = thread.get() :param async_req bool", "E501 query_params = [] if 'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id']))", "None): raise ValueError(\"Missing the required parameter `location_id` when calling `delete_file`\")", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs)", "'%s'\" \" to method download_file\" % key ) local_var_params[key] =", "extra_location: :param str extra_source: :return: PresignedLinkEnveloped If the method is", "keyword argument '%s'\" \" to method delete_file\" % key )", "verify the required parameter 'location_id' is set if ('location_id' not", "HTTP request, please pass async_req=True >>> thread = api.download_file_with_http_info(file_id, location_id,", "an asynchronous HTTP request, please pass async_req=True >>> thread =", "`file_id` when calling `download_file`\") # noqa: E501 # verify the", "= locals() all_params = ['file_id', 'location_id', 'user_id'] # noqa: E501", "ValueError(\"Missing the required parameter `file_id` when calling `get_file_metadata`\") # noqa:", "= ['action', 'data', 'fake_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content')", "local_var_params: query_params.append(('extra_location', local_var_params['extra_location'])) # noqa: E501 if 'extra_source' in local_var_params:", "uuid_filter: :return: FileMetaDataArrayEnveloped If the method is called asynchronously, returns", "method update_file_meta_data\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "calling `get_files_metadata`\") # noqa: E501 # verify the required parameter", "api.get_file_metadata_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "noqa: E501 \"\"\"Get File Metadata # noqa: E501 This method", "path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped', # noqa: E501", "parameter `action` when calling `check_action_post`\") # noqa: E501 collection_formats =", "TypeError( \"Got an unexpected keyword argument '%s'\" \" to method", "= {} form_params = [] local_var_files = {} body_params =", "local_var_params['kwargs'] # verify the required parameter 'file_id' is set if", "in local_var_params or local_var_params['action'] is None): raise ValueError(\"Missing the required", "**kwargs) # noqa: E501 else: (data) = self.download_file_with_http_info(file_id, location_id, user_id,", "thread. \"\"\" local_var_params = locals() all_params = ['action', 'data', 'fake_type']", "'%s'\" \" to method health_check\" % key ) local_var_params[key] =", "request, please pass async_req=True >>> thread = api.update_file_meta_data_with_http_info(file_id, location_id, async_req=True)", "if kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 else:", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def health_check(self, **kwargs): # noqa: E501 \"\"\"Service health-check", "user_id, **kwargs) # noqa: E501 else: (data) = self.get_files_metadata_with_http_info(location_id, user_id,", "= True if kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs) # noqa: E501 else:", "file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns upload link", "returns the request thread. \"\"\" local_var_params = locals() all_params =", "file_id, location_id, **kwargs): # noqa: E501 \"\"\"Update File Metadata #", "noqa: E501 collection_formats = {} path_params = {} if 'file_id'", "location_id, **kwargs) # noqa: E501 else: (data) = self.update_file_meta_data_with_http_info(file_id, location_id,", "return data def upload_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa:", "thread.get() :param async_req bool :param str location_id: (required) :param str", "self.api_client.call_api( '/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped',", "locals() all_params = ['user_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content')", "the method is called asynchronously, returns the request thread. \"\"\"", "'/locations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped', #", "E501 collection_formats = {} path_params = {} if 'file_id' in", "unexpected keyword argument '%s'\" \" to method get_file_metadata\" % key", "E501 return data def check_action_post_with_http_info(self, action, **kwargs): # noqa: E501", "= api.upload_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param", "keyword argument '%s'\" \" to method download_file\" % key )", "ValueError(\"Missing the required parameter `user_id` when calling `get_file_metadata`\") # noqa:", "request, please pass async_req=True >>> thread = api.health_check_with_http_info(async_req=True) >>> result", "def upload_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns", "local_var_params['file_id'] # noqa: E501 if 'location_id' in local_var_params: path_params['location_id'] =", "'%s'\" \" to method get_storage_locations\" % key ) local_var_params[key] =", "version: 0.1.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__", "None): raise ValueError(\"Missing the required parameter `user_id` when calling `get_storage_locations`\")", "when calling `get_storage_locations`\") # noqa: E501 collection_formats = {} path_params", ":param str extra_location: :param str extra_source: :return: PresignedLinkEnveloped If the", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET',", "method upload_file\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "= ['file_id', 'location_id', 'user_id', 'extra_location', 'extra_source'] # noqa: E501 all_params.append('async_req')", "\"\"\"Returns upload link or performs copy operation to datcore #", "thread = api.download_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", "please pass async_req=True >>> thread = api.upload_file(file_id, location_id, user_id, async_req=True)", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_file(self, file_id,", "pass async_req=True >>> thread = api.get_files_metadata_with_http_info(location_id, user_id, async_req=True) >>> result", "when calling `delete_file`\") # noqa: E501 collection_formats = {} path_params", "= val del local_var_params['kwargs'] # verify the required parameter 'file_id'", "2 and python 3 compatibility library import six from simcore_service_storage_sdk.api_client", "# noqa: E501 # verify the required parameter 'user_id' is", "if ('user_id' not in local_var_params or local_var_params['user_id'] is None): raise", "file # noqa: E501 This method makes a synchronous HTTP", "'location_id', 'file_meta_data_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for", "file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Deletes File #", "def get_files_metadata_with_http_info(self, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get Files", "key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {}", "self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data def", "self.api_client.call_api( '/locations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped',", "async_req=True >>> thread = api.health_check(async_req=True) >>> result = thread.get() :param", "to method get_storage_locations\" % key ) local_var_params[key] = val del", "calling `download_file`\") # noqa: E501 # verify the required parameter", "an unexpected keyword argument '%s'\" \" to method health_check\" %", "{} form_params = [] local_var_files = {} body_params = None", "please pass async_req=True >>> thread = api.download_file(file_id, location_id, user_id, async_req=True)", "an unexpected keyword argument '%s'\" \" to method get_file_metadata\" %", "HTTP request, please pass async_req=True >>> thread = api.check_action_post_with_http_info(action, async_req=True)", "= api.get_files_metadata_with_http_info(location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_file_metadata(self, file_id, location_id, user_id, **kwargs): # noqa:", "None): raise ValueError(\"Missing the required parameter `location_id` when calling `get_file_metadata`\")", "location_id, async_req=True) >>> result = thread.get() :param async_req bool :param", "noqa: E501 header_params = {} form_params = [] local_var_files =", "self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped',", "= self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data", "local_var_params: body_params = local_var_params['fake_type'] # HTTP header `Accept` header_params['Accept'] =", "collection_formats = {} path_params = {} if 'file_id' in local_var_params:", "E501 collection_formats = {} path_params = {} if 'action' in", "query_params.append(('data', local_var_params['data'])) # noqa: E501 header_params = {} form_params =", "the required parameter `user_id` when calling `delete_file`\") # noqa: E501", "thread. \"\"\" local_var_params = locals() all_params = ['file_id', 'location_id', 'file_meta_data_type']", "noqa: E501 query_params = [] if 'data' in local_var_params: query_params.append(('data',", "# noqa: E501 \"\"\"Returns download link for requested file #", "else: (data) = self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'),", "required parameter `location_id` when calling `get_files_metadata`\") # noqa: E501 #", "F401 # python 2 and python 3 compatibility library import", "request, please pass async_req=True >>> thread = api.download_file_with_http_info(file_id, location_id, user_id,", ">>> thread = api.delete_file(file_id, location_id, user_id, async_req=True) >>> result =", "an unexpected keyword argument '%s'\" \" to method get_files_metadata\" %", "ValueError(\"Missing the required parameter `action` when calling `check_action_post`\") # noqa:", "E501 if 'extra_source' in local_var_params: query_params.append(('extra_source', local_var_params['extra_source'])) # noqa: E501", "'file_meta_data_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key,", "# noqa: E501 else: (data) = self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa:", "[] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET', path_params, query_params,", "**kwargs) # noqa: E501 else: (data) = self.get_storage_locations_with_http_info(user_id, **kwargs) #", "None): raise ValueError(\"Missing the required parameter `user_id` when calling `download_file`\")", "None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) #", "action: (required) :param str data: :param FakeType fake_type: :return: FakeEnveloped", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def health_check(self, **kwargs): #", "noqa: E501 query_params = [] if 'user_id' in local_var_params: query_params.append(('user_id',", "parameter `file_id` when calling `update_file_meta_data`\") # noqa: E501 # verify", "asynchronous HTTP request, please pass async_req=True >>> thread = api.check_action_post(action,", "# noqa: E501 \"\"\"Returns upload link or performs copy operation", "get_storage_locations(self, user_id, **kwargs): # noqa: E501 \"\"\"Get available storage locations", "(data) = self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return", "is called asynchronously, returns the request thread. \"\"\" kwargs['_return_http_data_only'] =", "auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit", "kwargs.get('async_req'): return self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else:", "file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns download link", "\"Got an unexpected keyword argument '%s'\" \" to method check_action_post\"", "= val del local_var_params['kwargs'] # verify the required parameter 'action'", "state of the service behind # noqa: E501 This method", "parameter `user_id` when calling `download_file`\") # noqa: E501 collection_formats =", "'%s'\" \" to method upload_file\" % key ) local_var_params[key] =", "self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data) =", "service behind # noqa: E501 This method makes a synchronous", "None): raise ValueError(\"Missing the required parameter `user_id` when calling `get_file_metadata`\")", "local_var_files = {} body_params = None if 'file_meta_data_type' in local_var_params:", "asynchronously, returns the request thread. \"\"\" local_var_params = locals() all_params", "the required parameter `user_id` when calling `get_files_metadata`\") # noqa: E501", ":param async_req bool :param str file_id: (required) :param str location_id:", "E501 collection_formats = {} path_params = {} if 'location_id' in", "query_params = [] if 'data' in local_var_params: query_params.append(('data', local_var_params['data'])) #", "self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data def", "\"\"\"Get available storage locations # noqa: E501 This method makes", "return self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) # noqa: E501 else: (data) =", ">>> thread = api.health_check_with_http_info(async_req=True) >>> result = thread.get() :param async_req", "compatibility library import six from simcore_service_storage_sdk.api_client import ApiClient class UsersApi(object):", "self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication", "= True if kwargs.get('async_req'): return self.check_action_post_with_http_info(action, **kwargs) # noqa: E501", "E501 return data def get_storage_locations_with_http_info(self, user_id, **kwargs): # noqa: E501", "`check_action_post`\") # noqa: E501 collection_formats = {} path_params = {}", "(required) :return: None If the method is called asynchronously, returns", "api_client is None: api_client = ApiClient() self.api_client = api_client def", "= {} body_params = None if 'file_meta_data_type' in local_var_params: body_params", "location_id, **kwargs) # noqa: E501 return data def update_file_meta_data_with_http_info(self, file_id,", "header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FakeEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'),", "asynchronous HTTP request, please pass async_req=True >>> thread = api.download_file(file_id,", "argument '%s'\" \" to method update_file_meta_data\" % key ) local_var_params[key]", "kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else:", "raise ValueError(\"Missing the required parameter `location_id` when calling `get_file_metadata`\") #", "for requested file # noqa: E501 This method makes a", "query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 header_params = {} form_params =", "set if ('action' not in local_var_params or local_var_params['action'] is None):", "python 2 and python 3 compatibility library import six from", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_files_metadata(self,", "noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings", "local_var_params['user_id'])) # noqa: E501 if 'extra_location' in local_var_params: query_params.append(('extra_location', local_var_params['extra_location']))", "E501 collection_formats = {} path_params = {} query_params = []", "{} if 'action' in local_var_params: path_params['action'] = local_var_params['action'] # noqa:", "`delete_file`\") # noqa: E501 collection_formats = {} path_params = {}", "the transmitted data # noqa: E501 This method makes a", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def update_file_meta_data(self, file_id, location_id, **kwargs): # noqa:", "`file_id` when calling `upload_file`\") # noqa: E501 # verify the", "= self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data", ":param str location_id: (required) :param FileMetaDataType file_meta_data_type: :return: FileMetaDataEnveloped If", "= api.health_check_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return:", "'file_id' in local_var_params: path_params['fileId'] = local_var_params['file_id'] # noqa: E501 if", "user_id, **kwargs): # noqa: E501 \"\"\"Get Files Metadata # noqa:", "noqa: E501 return data def download_file_with_http_info(self, file_id, location_id, user_id, **kwargs):", "simcore-service-storage service # noqa: E501 OpenAPI spec version: 0.1.0 Contact:", "raise ValueError(\"Missing the required parameter `file_id` when calling `get_file_metadata`\") #", "E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa:", "path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', # noqa: E501", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id, location_id, user_id,", "def upload_file_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns", "`location_id` when calling `delete_file`\") # noqa: E501 # verify the", "please pass async_req=True >>> thread = api.get_file_metadata(file_id, location_id, user_id, async_req=True)", "unexpected keyword argument '%s'\" \" to method get_storage_locations\" % key", "api.health_check_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: HealthCheckEnveloped", "setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata',", "asynchronous HTTP request, please pass async_req=True >>> thread = api.get_files_metadata_with_http_info(location_id,", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs)", "form_params = [] local_var_files = {} body_params = None #", "asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_file(file_id,", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa:", "an unexpected keyword argument '%s'\" \" to method upload_file\" %", "health-check endpoint # noqa: E501 Some general information on the", ">>> thread = api.get_file_metadata_with_http_info(file_id, location_id, user_id, async_req=True) >>> result =", "pass async_req=True >>> thread = api.get_storage_locations_with_http_info(user_id, async_req=True) >>> result =", "return self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", "query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', # noqa: E501 auth_settings=auth_settings,", ">>> thread = api.download_file(file_id, location_id, user_id, async_req=True) >>> result =", "extra_source: :return: PresignedLinkEnveloped If the method is called asynchronously, returns", "method get_file_metadata\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "API API definition for simcore-service-storage service # noqa: E501 OpenAPI", "# noqa: E501 \"\"\"Get Files Metadata # noqa: E501 This", "pass async_req=True >>> thread = api.update_file_meta_data(file_id, location_id, async_req=True) >>> result", "local_var_params['extra_location'])) # noqa: E501 if 'extra_source' in local_var_params: query_params.append(('extra_source', local_var_params['extra_source']))", "unexpected keyword argument '%s'\" \" to method health_check\" % key", "E501 return data def get_files_metadata_with_http_info(self, location_id, user_id, **kwargs): # noqa:", "[] # noqa: E501 return self.api_client.call_api( '/', 'GET', path_params, query_params,", "= val del local_var_params['kwargs'] # verify the required parameter 'location_id'", "please pass async_req=True >>> thread = api.get_storage_locations_with_http_info(user_id, async_req=True) >>> result", "= {} if 'action' in local_var_params: path_params['action'] = local_var_params['action'] #", "data # noqa: E501 This method makes a synchronous HTTP", "when calling `get_files_metadata`\") # noqa: E501 # verify the required", "(required) :param str user_id: (required) :param str extra_location: :param str", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_storage_locations(self, user_id, **kwargs):", "get_file_metadata\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_storage_locations(self,", "query_params.append(('extra_location', local_var_params['extra_location'])) # noqa: E501 if 'extra_source' in local_var_params: query_params.append(('extra_source',", "python 3 compatibility library import six from simcore_service_storage_sdk.api_client import ApiClient", "E501 query_params = [] if 'data' in local_var_params: query_params.append(('data', local_var_params['data']))", "thread = api.update_file_meta_data(file_id, location_id, async_req=True) >>> result = thread.get() :param", "'%s'\" \" to method get_file_metadata\" % key ) local_var_params[key] =", "request by default. To make an asynchronous HTTP request, please", "user_id, **kwargs) # noqa: E501 else: (data) = self.upload_file_with_http_info(file_id, location_id,", "`get_file_metadata`\") # noqa: E501 # verify the required parameter 'location_id'", "asynchronous HTTP request, please pass async_req=True >>> thread = api.get_file_metadata(file_id,", "kwargs.get('async_req'): return self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 else: (data) =", "= {} path_params = {} if 'location_id' in local_var_params: path_params['location_id']", "body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'),", "# noqa: E501 # Authentication setting auth_settings = [] #", "Some general information on the API and state of the", "not edit the class manually. \"\"\" def __init__(self, api_client=None): if", "# noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self, file_id,", "local_var_params['action'] is None): raise ValueError(\"Missing the required parameter `action` when", "0.1.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import", "else: (data) = self.get_storage_locations_with_http_info(user_id, **kwargs) # noqa: E501 return data", "return data def check_action_post_with_http_info(self, action, **kwargs): # noqa: E501 \"\"\"Test", "`Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa:", "please pass async_req=True >>> thread = api.get_files_metadata(location_id, user_id, async_req=True) >>>", "return self.api_client.call_api( '/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", ">>> thread = api.get_file_metadata(file_id, location_id, user_id, async_req=True) >>> result =", "health_check_with_http_info(self, **kwargs): # noqa: E501 \"\"\"Service health-check endpoint # noqa:", "'/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped', #", "noqa: E501 collection_formats = {} path_params = {} if 'action'", "self.api_client.call_api( '/locations/{location_id}/files/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped',", "location_id, user_id, **kwargs): # noqa: E501 \"\"\"Get File Metadata #", "the required parameter `location_id` when calling `download_file`\") # noqa: E501", "E501 if 'uuid_filter' in local_var_params: query_params.append(('uuid_filter', local_var_params['uuid_filter'])) # noqa: E501", "the class manually. \"\"\" def __init__(self, api_client=None): if api_client is", "simcore_service_storage_sdk.api_client import ApiClient class UsersApi(object): \"\"\"NOTE: This class is auto", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self, file_id, location_id, user_id, **kwargs): # noqa:", "(data) = self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 return data def", "**kwargs): # noqa: E501 \"\"\"Returns upload link or performs copy", "return data def get_files_metadata_with_http_info(self, location_id, user_id, **kwargs): # noqa: E501", "= local_var_params['file_meta_data_type'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json'])", "str user_id: (required) :return: FileLocationArrayEnveloped If the method is called", "= True if kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa:", "else: (data) = self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 return", "E501 else: (data) = self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "parameter `location_id` when calling `upload_file`\") # noqa: E501 # verify", "from __future__ import absolute_import import re # noqa: F401 #", "val del local_var_params['kwargs'] # verify the required parameter 'file_id' is", "upload link or performs copy operation to datcore # noqa:", "noqa: E501 # Authentication setting auth_settings = [] # noqa:", ">>> thread = api.health_check(async_req=True) >>> result = thread.get() :param async_req", "noqa: E501 Some general information on the API and state", "local_var_files = {} body_params = None # HTTP header `Accept`", "'fake_type' in local_var_params: body_params = local_var_params['fake_type'] # HTTP header `Accept`", "local_var_params or local_var_params['action'] is None): raise ValueError(\"Missing the required parameter", "locals() all_params = ['action', 'data', 'fake_type'] # noqa: E501 all_params.append('async_req')", "= self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data", "HTTP request, please pass async_req=True >>> thread = api.download_file(file_id, location_id,", "# noqa: E501 return data def get_file_metadata_with_http_info(self, file_id, location_id, user_id,", "# noqa: E501 return data def delete_file_with_http_info(self, file_id, location_id, user_id,", "= self.download_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data", "('location_id' not in local_var_params or local_var_params['location_id'] is None): raise ValueError(\"Missing", "re # noqa: F401 # python 2 and python 3", "post_params=form_params, files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), #", "calling `update_file_meta_data`\") # noqa: E501 # verify the required parameter", ":param FileMetaDataType file_meta_data_type: :return: FileMetaDataEnveloped If the method is called", "async_req=True >>> thread = api.download_file(file_id, location_id, user_id, async_req=True) >>> result", "health_check(self, **kwargs): # noqa: E501 \"\"\"Service health-check endpoint # noqa:", "= locals() all_params = ['file_id', 'location_id', 'file_meta_data_type'] # noqa: E501", "ValueError(\"Missing the required parameter `file_id` when calling `delete_file`\") # noqa:", "query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'extra_location' in local_var_params: query_params.append(('extra_location',", "# noqa: E501 return data def get_storage_locations_with_http_info(self, user_id, **kwargs): #", ":param str location_id: (required) :param str user_id: (required) :return: FileMetaDataEnveloped", "location_id, user_id, **kwargs) # noqa: E501 return data def download_file_with_http_info(self,", "self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data def", "parameter `file_id` when calling `get_file_metadata`\") # noqa: E501 # verify", "val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params", "# noqa: E501 \"\"\"Update File Metadata # noqa: E501 This", "\" to method update_file_meta_data\" % key ) local_var_params[key] = val", "'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped', # noqa:", "user_id, **kwargs) # noqa: E501 return data def get_file_metadata_with_http_info(self, file_id,", "argument '%s'\" \" to method delete_file\" % key ) local_var_params[key]", "body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(", "local_var_params = locals() all_params = ['file_id', 'location_id', 'file_meta_data_type'] # noqa:", "= local_var_params['fake_type'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json'])", "query_params = [] if 'user_id' in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) #", "= locals() all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only')", "E501 return data def download_file_with_http_info(self, file_id, location_id, user_id, **kwargs): #", "parameter `user_id` when calling `get_files_metadata`\") # noqa: E501 collection_formats =", "query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HealthCheckEnveloped', # noqa: E501 auth_settings=auth_settings,", "\"\"\" from __future__ import absolute_import import re # noqa: F401", "HTTP request, please pass async_req=True >>> thread = api.get_storage_locations(user_id, async_req=True)", "`user_id` when calling `get_storage_locations`\") # noqa: E501 collection_formats = {}", "'/locations/{location_id}/files/{fileId}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', #", "'/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', #", "# noqa: E501 if 'extra_source' in local_var_params: query_params.append(('extra_source', local_var_params['extra_source'])) #", "storage locations # noqa: E501 This method makes a synchronous", "self.api_client.call_api( '/check/{action}', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FakeEnveloped',", "ValueError(\"Missing the required parameter `location_id` when calling `download_file`\") # noqa:", "path_params = {} query_params = [] if 'user_id' in local_var_params:", "'data' in local_var_params: query_params.append(('data', local_var_params['data'])) # noqa: E501 header_params =", "not in local_var_params or local_var_params['location_id'] is None): raise ValueError(\"Missing the", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id, location_id,", "= self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 #", "response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501", "= None if 'file_meta_data_type' in local_var_params: body_params = local_var_params['file_meta_data_type'] #", "(required) :param str user_id: (required) :return: PresignedLinkEnveloped If the method", "= val del local_var_params['kwargs'] # verify the required parameter 'user_id'", "parameter `location_id` when calling `get_file_metadata`\") # noqa: E501 # verify", "noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self, file_id, location_id,", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_file_with_http_info(file_id, location_id,", "'/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped', #", "self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataEnveloped',", "\"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_file_with_http_info(file_id, location_id, user_id,", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def health_check(self, **kwargs): # noqa: E501 \"\"\"Service", "self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped',", "pass async_req=True >>> thread = api.check_action_post(action, async_req=True) >>> result =", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs) #", "when calling `check_action_post`\") # noqa: E501 collection_formats = {} path_params", "not in local_var_params or local_var_params['user_id'] is None): raise ValueError(\"Missing the", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.download_file_with_http_info(file_id, location_id, user_id, **kwargs)", "E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key, val in six.iteritems(local_var_params['kwargs']):", "api.check_action_post_with_http_info(action, async_req=True) >>> result = thread.get() :param async_req bool :param", "ValueError(\"Missing the required parameter `location_id` when calling `delete_file`\") # noqa:", "body_params = None if 'file_meta_data_type' in local_var_params: body_params = local_var_params['file_meta_data_type']", "= local_var_params['action'] # noqa: E501 query_params = [] if 'data'", "(required) :param str user_id: (required) :return: FileMetaDataEnveloped If the method", ">>> thread = api.upload_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result =", "api.download_file(file_id, location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.check_action_post_with_http_info(action, **kwargs) # noqa:", "required parameter `user_id` when calling `get_file_metadata`\") # noqa: E501 collection_formats", "= self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type`", "['file_id', 'location_id', 'file_meta_data_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout')", "`action` when calling `check_action_post`\") # noqa: E501 collection_formats = {}", "asynchronous HTTP request, please pass async_req=True >>> thread = api.download_file_with_http_info(file_id,", "to method health_check\" % key ) local_var_params[key] = val del", "_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def update_file_meta_data(self,", "= self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 return data def check_action_post_with_http_info(self,", "location_id, user_id, **kwargs) # noqa: E501 else: (data) = self.upload_file_with_http_info(file_id,", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/', 'GET',", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id,", "async_req=True >>> thread = api.get_files_metadata(location_id, user_id, async_req=True) >>> result =", ">>> thread = api.upload_file(file_id, location_id, user_id, async_req=True) >>> result =", "'data', 'fake_type'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for", "service # noqa: E501 OpenAPI spec version: 0.1.0 Contact: <EMAIL>", "or local_var_params['file_id'] is None): raise ValueError(\"Missing the required parameter `file_id`", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_storage_locations(self, user_id, **kwargs): # noqa: E501 \"\"\"Get", "noqa: E501 \"\"\"Get Files Metadata # noqa: E501 This method", "in local_var_params: body_params = local_var_params['fake_type'] # HTTP header `Accept` header_params['Accept']", "str location_id: (required) :param str user_id: (required) :return: FileMetaDataEnveloped If", "str user_id: (required) :param str uuid_filter: :return: FileMetaDataArrayEnveloped If the", "HTTP request, please pass async_req=True >>> thread = api.update_file_meta_data(file_id, location_id,", "in local_var_params or local_var_params['file_id'] is None): raise ValueError(\"Missing the required", "(required) :param str uuid_filter: :return: FileMetaDataArrayEnveloped If the method is", "async_req bool :return: HealthCheckEnveloped If the method is called asynchronously,", "\"\"\" local_var_params = locals() all_params = ['file_id', 'location_id', 'file_meta_data_type'] #", "collection_formats=collection_formats) def get_file_metadata(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "location_id: (required) :param str user_id: (required) :param str extra_location: :param", "path_params['action'] = local_var_params['action'] # noqa: E501 query_params = [] if", "ValueError(\"Missing the required parameter `location_id` when calling `upload_file`\") # noqa:", "the required parameter `location_id` when calling `update_file_meta_data`\") # noqa: E501", "if 'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id'] # noqa: E501", "str file_id: (required) :param str location_id: (required) :param str user_id:", "None): raise ValueError(\"Missing the required parameter `user_id` when calling `upload_file`\")", "called asynchronously, returns the request thread. \"\"\" local_var_params = locals()", "E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params,", "thread = api.get_storage_locations(user_id, async_req=True) >>> result = thread.get() :param async_req", "path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileLocationArrayEnveloped', # noqa: E501", ">>> thread = api.download_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result =", "['location_id', 'user_id', 'uuid_filter'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout')", "True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_file(self, file_id, location_id, user_id, **kwargs): #", "user_id: (required) :return: FileLocationArrayEnveloped If the method is called asynchronously,", "str user_id: (required) :return: None If the method is called", "api_client=None): if api_client is None: api_client = ApiClient() self.api_client =", "when calling `get_file_metadata`\") # noqa: E501 # verify the required", "the required parameter `file_id` when calling `download_file`\") # noqa: E501", "location_id, user_id, **kwargs) # noqa: E501 return data def upload_file_with_http_info(self,", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_files_metadata(self, location_id, user_id, **kwargs): #", "['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] =", "locations # noqa: E501 This method makes a synchronous HTTP", "[] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'DELETE', path_params, query_params,", "generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the", "[] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'PATCH', path_params, query_params,", "asynchronous HTTP request, please pass async_req=True >>> thread = api.get_storage_locations_with_http_info(user_id,", "body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'),", "# noqa: E501 \"\"\"Service health-check endpoint # noqa: E501 Some", "and state of the service behind # noqa: E501 This", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs)", "and python 3 compatibility library import six from simcore_service_storage_sdk.api_client import", "\"\"\"Update File Metadata # noqa: E501 This method makes a", "True if kwargs.get('async_req'): return self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 else:", "is set if ('location_id' not in local_var_params or local_var_params['location_id'] is", "self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) # noqa: E501 else: (data) = self.get_files_metadata_with_http_info(location_id,", "= thread.get() :param async_req bool :param str location_id: (required) :param", "all_params.append('_request_timeout') for key, val in six.iteritems(local_var_params['kwargs']): if key not in", "HTTP request, please pass async_req=True >>> thread = api.get_storage_locations_with_http_info(user_id, async_req=True)", "return data def get_file_metadata_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa:", "If the method is called asynchronously, returns the request thread.", "on the API and state of the service behind #", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id, user_id, **kwargs) #", "kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_file_meta_data_with_http_info(file_id, location_id, **kwargs) #", "delete_file\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "= thread.get() :param async_req bool :param str file_id: (required) :param", "return self.api_client.call_api( '/locations/{location_id}/files/{fileId}/metadata', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files,", "= [] local_var_files = {} body_params = None # HTTP", "`upload_file`\") # noqa: E501 collection_formats = {} path_params = {}", "the required parameter `location_id` when calling `upload_file`\") # noqa: E501", "noqa: E501 else: (data) = self.check_action_post_with_http_info(action, **kwargs) # noqa: E501", "\"\"\"Test checkpoint to ask server to fail or echo back", "kwargs.get('async_req'): return self.health_check_with_http_info(**kwargs) # noqa: E501 else: (data) = self.health_check_with_http_info(**kwargs)", "request, please pass async_req=True >>> thread = api.delete_file(file_id, location_id, user_id,", "thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_files_metadata_with_http_info(location_id, user_id,", "thread.get() :param async_req bool :param str file_id: (required) :param str", "\" to method get_files_metadata\" % key ) local_var_params[key] = val", "calling `get_file_metadata`\") # noqa: E501 collection_formats = {} path_params =", "method get_storage_locations\" % key ) local_var_params[key] = val del local_var_params['kwargs']", "noqa: E501 return data def upload_file_with_http_info(self, file_id, location_id, user_id, **kwargs):", "data def get_file_metadata_with_http_info(self, file_id, location_id, user_id, **kwargs): # noqa: E501", "{} path_params = {} if 'location_id' in local_var_params: path_params['location_id'] =", "location_id: (required) :param str user_id: (required) :return: PresignedLinkEnveloped If the", "import re # noqa: F401 # python 2 and python", "thread.get() :param async_req bool :param str action: (required) :param str", "_request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_files_metadata(self, location_id, user_id, **kwargs): # noqa: E501", "data def check_action_post_with_http_info(self, action, **kwargs): # noqa: E501 \"\"\"Test checkpoint", "thread = api.get_file_metadata_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", "HTTP request, please pass async_req=True >>> thread = api.upload_file_with_http_info(file_id, location_id,", "'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PresignedLinkEnveloped', # noqa:", "True if kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa:", "E501 return data def get_file_metadata_with_http_info(self, file_id, location_id, user_id, **kwargs): #", "thread. \"\"\" local_var_params = locals() all_params = ['location_id', 'user_id', 'uuid_filter']", "query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped', # noqa: E501 auth_settings=auth_settings,", "if 'action' in local_var_params: path_params['action'] = local_var_params['action'] # noqa: E501", "manually. \"\"\" def __init__(self, api_client=None): if api_client is None: api_client", "location_id: (required) :param str user_id: (required) :param str uuid_filter: :return:", "E501 query_params = [] header_params = {} form_params = []", "async_req=True >>> thread = api.download_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result", "header_params = {} form_params = [] local_var_files = {} body_params", "self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 return data def", "thread = api.upload_file_with_http_info(file_id, location_id, user_id, async_req=True) >>> result = thread.get()", "setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}',", "in local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'extra_location' in", "HTTP request, please pass async_req=True >>> thread = api.check_action_post(action, async_req=True)", "noqa: E501 query_params = [] header_params = {} form_params =", "return self.check_action_post_with_http_info(action, **kwargs) # noqa: E501 else: (data) = self.check_action_post_with_http_info(action,", "user_id, **kwargs): # noqa: E501 \"\"\"Get File Metadata # noqa:", "to fail or echo back the transmitted data # noqa:", "collection_formats = {} path_params = {} query_params = [] header_params", "del local_var_params['kwargs'] # verify the required parameter 'action' is set", "local_var_params['data'])) # noqa: E501 header_params = {} form_params = []", "= api.update_file_meta_data(file_id, location_id, async_req=True) >>> result = thread.get() :param async_req", "pass async_req=True >>> thread = api.get_storage_locations(user_id, async_req=True) >>> result =", "request, please pass async_req=True >>> thread = api.get_storage_locations_with_http_info(user_id, async_req=True) >>>", "`download_file`\") # noqa: E501 collection_formats = {} path_params = {}", "please pass async_req=True >>> thread = api.download_file_with_http_info(file_id, location_id, user_id, async_req=True)", "_preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def health_check(self, **kwargs): # noqa: E501", "str location_id: (required) :param str user_id: (required) :param str uuid_filter:", "upload_file(self, file_id, location_id, user_id, **kwargs): # noqa: E501 \"\"\"Returns upload", "= api.get_files_metadata(location_id, user_id, async_req=True) >>> result = thread.get() :param async_req", "val del local_var_params['kwargs'] # verify the required parameter 'user_id' is", "path_params = {} if 'location_id' in local_var_params: path_params['location_id'] = local_var_params['location_id']", "required parameter `user_id` when calling `download_file`\") # noqa: E501 collection_formats", ":return: HealthCheckEnveloped If the method is called asynchronously, returns the", "\"Got an unexpected keyword argument '%s'\" \" to method delete_file\"", "library import six from simcore_service_storage_sdk.api_client import ApiClient class UsersApi(object): \"\"\"NOTE:", "datcore # noqa: E501 This method makes a synchronous HTTP", "local_var_params: query_params.append(('user_id', local_var_params['user_id'])) # noqa: E501 if 'extra_location' in local_var_params:", "post_params=form_params, files=local_var_files, response_type='FileMetaDataArrayEnveloped', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), #", "request thread. \"\"\" kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.upload_file_with_http_info(file_id,", "['application/json']) # noqa: E501 # Authentication setting auth_settings = []", "'extra_location' in local_var_params: query_params.append(('extra_location', local_var_params['extra_location'])) # noqa: E501 if 'extra_source'", "pass async_req=True >>> thread = api.download_file(file_id, location_id, user_id, async_req=True) >>>", "'uuid_filter'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key,", "checkpoint to ask server to fail or echo back the", "if kwargs.get('async_req'): return self.get_file_metadata_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501", "# noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'PUT', path_params, query_params, header_params,", "in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise TypeError( \"Got", "= api.get_storage_locations_with_http_info(user_id, async_req=True) >>> result = thread.get() :param async_req bool", "verify the required parameter 'file_id' is set if ('file_id' not", "kwargs.get('async_req'): return self.delete_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else:", "self.upload_file_with_http_info(file_id, location_id, user_id, **kwargs) # noqa: E501 else: (data) =", "auth_settings = [] # noqa: E501 return self.api_client.call_api( '/locations/{location_id}/files/{fileId}', 'GET',", "user_id, **kwargs) # noqa: E501 return data def get_files_metadata_with_http_info(self, location_id,", "to ask server to fail or echo back the transmitted", "def check_action_post(self, action, **kwargs): # noqa: E501 \"\"\"Test checkpoint to", "E501 This method makes a synchronous HTTP request by default.", "get_files_metadata\" % key ) local_var_params[key] = val del local_var_params['kwargs'] #", "def check_action_post_with_http_info(self, action, **kwargs): # noqa: E501 \"\"\"Test checkpoint to", "self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type']" ]
[ "2021-10-22 14:23 from django.db import migrations class Migration(migrations.Migration): dependencies =", "= [ ('reservation_management', '0020_greenpass'), ] operations = [ migrations.DeleteModel( name='GreenPass',", "import migrations class Migration(migrations.Migration): dependencies = [ ('reservation_management', '0020_greenpass'), ]", "<filename>reservation_management/migrations/0021_delete_greenpass.py # Generated by Django 3.2.7 on 2021-10-22 14:23 from", "[ ('reservation_management', '0020_greenpass'), ] operations = [ migrations.DeleteModel( name='GreenPass', ),", "3.2.7 on 2021-10-22 14:23 from django.db import migrations class Migration(migrations.Migration):", "# Generated by Django 3.2.7 on 2021-10-22 14:23 from django.db", "class Migration(migrations.Migration): dependencies = [ ('reservation_management', '0020_greenpass'), ] operations =", "('reservation_management', '0020_greenpass'), ] operations = [ migrations.DeleteModel( name='GreenPass', ), ]", "Generated by Django 3.2.7 on 2021-10-22 14:23 from django.db import", "Django 3.2.7 on 2021-10-22 14:23 from django.db import migrations class", "Migration(migrations.Migration): dependencies = [ ('reservation_management', '0020_greenpass'), ] operations = [", "by Django 3.2.7 on 2021-10-22 14:23 from django.db import migrations", "14:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [", "dependencies = [ ('reservation_management', '0020_greenpass'), ] operations = [ migrations.DeleteModel(", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reservation_management', '0020_greenpass'),", "on 2021-10-22 14:23 from django.db import migrations class Migration(migrations.Migration): dependencies", "migrations class Migration(migrations.Migration): dependencies = [ ('reservation_management', '0020_greenpass'), ] operations", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reservation_management'," ]
[ "Using Ideal IAF Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u],", "0 output_ext = '.png' # Define algorithm parameters and input", "Noise' % noise_power print fig_title u = func_timer(bl.gen_band_limited)(dur, dt, f,", "None: fig_title = 'IAF Input Signal with No Noise' else:", "d_list = [d1, d2] R_list = [R1, R2] C_list =", "func_timer import bionet.utils.band_limited as bl import bionet.utils.plotting as pl import", "\"\"\" # Copyright (c) 2009-2015, <NAME> # All rights reserved.", "# threshold R2 = 9.0 # resistance C2 = 0.01", "not satisfied'): sys.exit() b_list = np.array([b1, b2]) d_list = np.array([d1,", "Using Leaky IAF Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u],", "python \"\"\" Demos of encoding and decoding algorithms using populations", "C_list) pl.plot_compare(t, u, u_rec, fig_title, output_name + str(output_count) + output_ext)", "= 0.7 # threshold R1 = np.inf # resistance C1", "1 fig_title = 'Signal Decoded Using Ideal IAF Population Decoder'", "+= 1 pl.plot_encoded(t, u, s_list[1], fig_title + ' #2', output_name", "pl.plot_encoded(t, u, s_list[1], fig_title + ' #2', output_name + str(output_count)", "output_ext = '.png' # Define algorithm parameters and input signal:", "using populations of IAF neurons. \"\"\" # Copyright (c) 2009-2015,", "input signal: dur = 0.1 dt = 1e-6 f =", "= 2*np.pi*f t = np.arange(0, dur, dt) np.random.seed(0) noise_power =", "'Signal Encoded Using Leaky IAF Encoder' print fig_title s_list =", "+ output_ext) output_count += 1 pl.plot_encoded(t, u, s_list[1], fig_title +", "Population Decoder' print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur, dt, bw,", "# bias d2 = 0.8 # threshold R2 = np.inf", "output_ext) # Test ideal IAF algorithms: b1 = 3.5 #", "b2]) d_list = np.array([d1, d2]) R_list = np.array([R1, R2]) C_list", "Signal with No Noise' else: fig_title = 'IAF Input Signal", "ValueError('reconstruction condition not satisfied'): sys.exit() b_list = np.array([b1, b2]) d_list", "d1 = 0.7 # threshold R1 = np.inf # resistance", "dt, bw, b_list, d_list, R_list, C_list) pl.plot_compare(t, u, u_rec, fig_title,", "+= 1 fig_title = 'Signal Decoded Using Ideal IAF Population", "except ValueError('reconstruction condition not satisfied'): sys.exit() b2 = 3.4 #", "output_ext) output_count += 1 fig_title = 'Signal Decoded Using Leaky", "bionet.ted.iaf as iaf # For determining output plot file names:", "resistance C1 = 0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b1,", "C2 = 0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b2, d2,", "# Copyright (c) 2009-2015, <NAME> # All rights reserved. #", "resistance C2 = 0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b2,", "import numpy as np # Set matplotlib backend so that", "Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u], dt, b_list, d_list,", "as iaf # For determining output plot file names: output_name", "import bionet.ted.iaf as iaf # For determining output plot file", "fig_title = 'Signal Encoded Using Leaky IAF Encoder' print fig_title", "Using Leaky IAF Population Decoder' print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list,", "R_list, C_list) pl.plot_encoded(t, u, s_list[0], fig_title + ' #1', output_name", "bionet.utils.misc import func_timer import bionet.utils.band_limited as bl import bionet.utils.plotting as", "b1 = 3.5 # bias d1 = 0.7 # threshold", "# threshold R1 = 10.0 # resistance C1 = 0.01", "IAF Population Decoder' print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur, dt,", "# threshold R1 = np.inf # resistance C1 = 0.01", "output_name = 'iaf_pop_demo_' output_count = 0 output_ext = '.png' #", "not satisfied'): sys.exit() b_list = [b1, b2] d_list = [d1,", "= 0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b2, d2, R2,", "be generated without a # display: import matplotlib matplotlib.use('AGG') from", "noise_power) pl.plot_signal(t, u, fig_title, output_name + str(output_count) + output_ext) #", "Leaky IAF Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u], dt,", "= [b1, b2] d_list = [d1, d2] R_list = [R1,", "1 fig_title = 'Signal Encoded Using Leaky IAF Encoder' print", "1 fig_title = 'Signal Decoded Using Leaky IAF Population Decoder'", "b2, d2, R2, C2) except ValueError('reconstruction condition not satisfied'): sys.exit()", "license: # http://www.opensource.org/licenses/bsd-license import sys import numpy as np #", "1e-6 f = 32 bw = 2*np.pi*f t = np.arange(0,", "# capacitance try: iaf.iaf_recoverable(u, bw, b2, d2, R2, C2) except", "d2, R2, C2) except ValueError('reconstruction condition not satisfied'): sys.exit() b_list", "import sys import numpy as np # Set matplotlib backend", "output_count = 0 output_ext = '.png' # Define algorithm parameters", "Decoded Using Ideal IAF Population Decoder' print fig_title u_rec =", "b_list, d_list, R_list, C_list) pl.plot_encoded(t, u, s_list[0], fig_title + '", "= 'iaf_pop_demo_' output_count = 0 output_ext = '.png' # Define", "= 'Signal Encoded Using Ideal IAF Encoder' print fig_title s_list", "# resistance C1 = 0.01 # capacitance try: iaf.iaf_recoverable(u, bw,", "iaf.iaf_recoverable(u, bw, b1, d1, R1, C1) except ValueError('reconstruction condition not", "0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b2, d2, R2, C2)", "bw, b2, d2, R2, C2) except ValueError('reconstruction condition not satisfied'):", "of IAF neurons. \"\"\" # Copyright (c) 2009-2015, <NAME> #", "fig_title, output_name + str(output_count) + output_ext) # Test leaky IAF", "IAF neurons. \"\"\" # Copyright (c) 2009-2015, <NAME> # All", "fig_title u = func_timer(bl.gen_band_limited)(dur, dt, f, noise_power) pl.plot_signal(t, u, fig_title,", "= np.array([C1, C2]) output_count += 1 fig_title = 'Signal Encoded", "C1 = 0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b1, d1,", "= 1e-6 f = 32 bw = 2*np.pi*f t =", "# bias d2 = 0.8 # threshold R2 = 9.0", "+ str(output_count) + output_ext) # Test ideal IAF algorithms: b1", "algorithm parameters and input signal: dur = 0.1 dt =", "dt) np.random.seed(0) noise_power = None if noise_power == None: fig_title", "u_rec, fig_title, output_name + str(output_count) + output_ext) # Test ideal", "bias d2 = 0.8 # threshold R2 = np.inf #", "np.array([R1, R2]) C_list = np.array([C1, C2]) output_count += 1 fig_title", "'IAF Input Signal with No Noise' else: fig_title = 'IAF", "b2 = 3.4 # bias d2 = 0.8 # threshold", "terms of the BSD license: # http://www.opensource.org/licenses/bsd-license import sys import", "(c) 2009-2015, <NAME> # All rights reserved. # Distributed under", "= np.arange(0, dur, dt) np.random.seed(0) noise_power = None if noise_power", "fig_title = 'Signal Decoded Using Ideal IAF Population Decoder' print", "np.inf # resistance C2 = 0.01 # capacitance try: iaf.iaf_recoverable(u,", "bias d2 = 0.8 # threshold R2 = 9.0 #", "0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b1, d1, R1, C1)", "iaf # For determining output plot file names: output_name =", "10.0 # resistance C1 = 0.01 # capacitance try: iaf.iaf_recoverable(u,", "+ output_ext) # Test ideal IAF algorithms: b1 = 3.5", "b2] d_list = [d1, d2] R_list = [R1, R2] C_list", "= np.array([b1, b2]) d_list = np.array([d1, d2]) R_list = np.array([R1,", "output_count += 1 pl.plot_encoded(t, u, s_list[1], fig_title + ' #2',", "C2]) output_count += 1 fig_title = 'Signal Encoded Using Leaky", "encoding and decoding algorithms using populations of IAF neurons. \"\"\"", "output_name + str(output_count) + output_ext) # Test leaky IAF algorithms:", "R2 = 9.0 # resistance C2 = 0.01 # capacitance", "can be generated without a # display: import matplotlib matplotlib.use('AGG')", "bw, b1, d1, R1, C1) except ValueError('reconstruction condition not satisfied'):", "Using Ideal IAF Population Decoder' print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list,", "condition not satisfied'): sys.exit() b_list = np.array([b1, b2]) d_list =", "print fig_title u = func_timer(bl.gen_band_limited)(dur, dt, f, noise_power) pl.plot_signal(t, u,", "str(output_count) + output_ext) output_count += 1 pl.plot_encoded(t, u, s_list[1], fig_title", "fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u], dt, b_list, d_list, R_list, C_list)", "C2) except ValueError('reconstruction condition not satisfied'): sys.exit() b_list = np.array([b1,", "= func_timer(iaf.iaf_decode_pop)(s_list, dur, dt, bw, b_list, d_list, R_list, C_list) pl.plot_compare(t,", "u], dt, b_list, d_list, R_list, C_list) pl.plot_encoded(t, u, s_list[0], fig_title", "ideal IAF algorithms: b1 = 3.5 # bias d1 =", "output_name + str(output_count) + output_ext) output_count += 1 pl.plot_encoded(t, u,", "func_timer(bl.gen_band_limited)(dur, dt, f, noise_power) pl.plot_signal(t, u, fig_title, output_name + str(output_count)", "iaf.iaf_recoverable(u, bw, b2, d2, R2, C2) except ValueError('reconstruction condition not", "dur, dt, bw, b_list, d_list, R_list, C_list) pl.plot_compare(t, u, u_rec,", "func_timer(iaf.iaf_decode_pop)(s_list, dur, dt, bw, b_list, d_list, R_list, C_list) pl.plot_compare(t, u,", "dt, f, noise_power) pl.plot_signal(t, u, fig_title, output_name + str(output_count) +", "1 pl.plot_encoded(t, u, s_list[1], fig_title + ' #2', output_name +", "satisfied'): sys.exit() b_list = [b1, b2] d_list = [d1, d2]", "= 0 output_ext = '.png' # Define algorithm parameters and", "u, fig_title, output_name + str(output_count) + output_ext) # Test leaky", "Distributed under the terms of the BSD license: # http://www.opensource.org/licenses/bsd-license", "No Noise' else: fig_title = 'IAF Input Signal with %d", "Ideal IAF Population Decoder' print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur,", "2009-2015, <NAME> # All rights reserved. # Distributed under the", "threshold R1 = np.inf # resistance C1 = 0.01 #", "= 9.0 # resistance C2 = 0.01 # capacitance try:", "Decoded Using Leaky IAF Population Decoder' print fig_title u_rec =", "# Set matplotlib backend so that plots can be generated", "signal: dur = 0.1 dt = 1e-6 f = 32", "# Test ideal IAF algorithms: b1 = 3.5 # bias", "' #2', output_name + str(output_count) + output_ext) output_count += 1", "else: fig_title = 'IAF Input Signal with %d dB of", "with No Noise' else: fig_title = 'IAF Input Signal with", "print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u], dt, b_list, d_list, R_list,", "= 0.8 # threshold R2 = np.inf # resistance C2", "= np.inf # resistance C2 = 0.01 # capacitance try:", "IAF algorithms: b1 = 3.5 # bias d1 = 0.7", "Input Signal with %d dB of Noise' % noise_power print", "C2) except ValueError('reconstruction condition not satisfied'): sys.exit() b_list = [b1,", "d1 = 0.7 # threshold R1 = 10.0 # resistance", "as np # Set matplotlib backend so that plots can", "'.png' # Define algorithm parameters and input signal: dur =", "of the BSD license: # http://www.opensource.org/licenses/bsd-license import sys import numpy", "0.8 # threshold R2 = np.inf # resistance C2 =", "matplotlib matplotlib.use('AGG') from bionet.utils.misc import func_timer import bionet.utils.band_limited as bl", "Define algorithm parameters and input signal: dur = 0.1 dt", "R2] C_list = [C1, C2] output_count += 1 fig_title =", "3.4 # bias d2 = 0.8 # threshold R2 =", "Copyright (c) 2009-2015, <NAME> # All rights reserved. # Distributed", "import func_timer import bionet.utils.band_limited as bl import bionet.utils.plotting as pl", "u = func_timer(bl.gen_band_limited)(dur, dt, f, noise_power) pl.plot_signal(t, u, fig_title, output_name", "file names: output_name = 'iaf_pop_demo_' output_count = 0 output_ext =", "# display: import matplotlib matplotlib.use('AGG') from bionet.utils.misc import func_timer import", "fig_title = 'Signal Encoded Using Ideal IAF Encoder' print fig_title", "sys.exit() b2 = 3.4 # bias d2 = 0.8 #", "f, noise_power) pl.plot_signal(t, u, fig_title, output_name + str(output_count) + output_ext)", "Encoded Using Ideal IAF Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u,", "satisfied'): sys.exit() b2 = 3.4 # bias d2 = 0.8", "output_name + str(output_count) + output_ext) # Test ideal IAF algorithms:", "dt, b_list, d_list, R_list, C_list) pl.plot_encoded(t, u, s_list[0], fig_title +", "Signal with %d dB of Noise' % noise_power print fig_title", "fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur, dt, bw, b_list, d_list, R_list,", "fig_title + ' #2', output_name + str(output_count) + output_ext) output_count", "neurons. \"\"\" # Copyright (c) 2009-2015, <NAME> # All rights", "np # Set matplotlib backend so that plots can be", "Ideal IAF Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u], dt,", "# resistance C2 = 0.01 # capacitance try: iaf.iaf_recoverable(u, bw,", "Demos of encoding and decoding algorithms using populations of IAF", "d_list = np.array([d1, d2]) R_list = np.array([R1, R2]) C_list =", "output_name + str(output_count) + output_ext) output_count += 1 fig_title =", "rights reserved. # Distributed under the terms of the BSD", "bias d1 = 0.7 # threshold R1 = np.inf #", "b1, d1, R1, C1) except ValueError('reconstruction condition not satisfied'): sys.exit()", "pl.plot_compare(t, u, u_rec, fig_title, output_name + str(output_count) + output_ext) #", "Leaky IAF Population Decoder' print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur,", "+ output_ext) output_count += 1 fig_title = 'Signal Decoded Using", "0.7 # threshold R1 = 10.0 # resistance C1 =", "with %d dB of Noise' % noise_power print fig_title u", "32 bw = 2*np.pi*f t = np.arange(0, dur, dt) np.random.seed(0)", "All rights reserved. # Distributed under the terms of the", "BSD license: # http://www.opensource.org/licenses/bsd-license import sys import numpy as np", "so that plots can be generated without a # display:", "plot file names: output_name = 'iaf_pop_demo_' output_count = 0 output_ext", "'Signal Decoded Using Ideal IAF Population Decoder' print fig_title u_rec", "matplotlib backend so that plots can be generated without a", "# Test leaky IAF algorithms: b1 = 3.5 # bias", "condition not satisfied'): sys.exit() b2 = 3.4 # bias d2", "= 'IAF Input Signal with No Noise' else: fig_title =", "condition not satisfied'): sys.exit() b_list = [b1, b2] d_list =", "output_ext) output_count += 1 pl.plot_encoded(t, u, s_list[1], fig_title + '", "b_list, d_list, R_list, C_list) pl.plot_compare(t, u, u_rec, fig_title, output_name +", "= func_timer(bl.gen_band_limited)(dur, dt, f, noise_power) pl.plot_signal(t, u, fig_title, output_name +", "str(output_count) + output_ext) # Test ideal IAF algorithms: b1 =", "R_list, C_list) pl.plot_compare(t, u, u_rec, fig_title, output_name + str(output_count) +", "d1, R1, C1) except ValueError('reconstruction condition not satisfied'): sys.exit() b2", "R2 = np.inf # resistance C2 = 0.01 # capacitance", "bw = 2*np.pi*f t = np.arange(0, dur, dt) np.random.seed(0) noise_power", "output plot file names: output_name = 'iaf_pop_demo_' output_count = 0", "capacitance try: iaf.iaf_recoverable(u, bw, b2, d2, R2, C2) except ValueError('reconstruction", "np.array([d1, d2]) R_list = np.array([R1, R2]) C_list = np.array([C1, C2])", "= None if noise_power == None: fig_title = 'IAF Input", "+ output_ext) # Test leaky IAF algorithms: b1 = 3.5", "str(output_count) + output_ext) # Test leaky IAF algorithms: b1 =", "#2', output_name + str(output_count) + output_ext) output_count += 1 fig_title", "= 0.8 # threshold R2 = 9.0 # resistance C2", "pl import bionet.ted.iaf as iaf # For determining output plot", "threshold R2 = np.inf # resistance C2 = 0.01 #", "under the terms of the BSD license: # http://www.opensource.org/licenses/bsd-license import", "Set matplotlib backend so that plots can be generated without", "and input signal: dur = 0.1 dt = 1e-6 f", "= 'Signal Encoded Using Leaky IAF Encoder' print fig_title s_list", "threshold R1 = 10.0 # resistance C1 = 0.01 #", "decoding algorithms using populations of IAF neurons. \"\"\" # Copyright", "numpy as np # Set matplotlib backend so that plots", "'IAF Input Signal with %d dB of Noise' % noise_power", "# bias d1 = 0.7 # threshold R1 = 10.0", "+= 1 fig_title = 'Signal Encoded Using Leaky IAF Encoder'", "dB of Noise' % noise_power print fig_title u = func_timer(bl.gen_band_limited)(dur,", "the BSD license: # http://www.opensource.org/licenses/bsd-license import sys import numpy as", "algorithms: b1 = 3.5 # bias d1 = 0.7 #", "+ str(output_count) + output_ext) output_count += 1 pl.plot_encoded(t, u, s_list[1],", "# Distributed under the terms of the BSD license: #", "fig_title = 'IAF Input Signal with No Noise' else: fig_title", "generated without a # display: import matplotlib matplotlib.use('AGG') from bionet.utils.misc", "bl import bionet.utils.plotting as pl import bionet.ted.iaf as iaf #", "[d1, d2] R_list = [R1, R2] C_list = [C1, C2]", "= [R1, R2] C_list = [C1, C2] output_count += 1", "d2]) R_list = np.array([R1, R2]) C_list = np.array([C1, C2]) output_count", "from bionet.utils.misc import func_timer import bionet.utils.band_limited as bl import bionet.utils.plotting", "= np.inf # resistance C1 = 0.01 # capacitance try:", "0.1 dt = 1e-6 f = 32 bw = 2*np.pi*f", "np.array([b1, b2]) d_list = np.array([d1, d2]) R_list = np.array([R1, R2])", "'Signal Encoded Using Ideal IAF Encoder' print fig_title s_list =", "reserved. # Distributed under the terms of the BSD license:", "of encoding and decoding algorithms using populations of IAF neurons.", "u, s_list[0], fig_title + ' #1', output_name + str(output_count) +", "dur = 0.1 dt = 1e-6 f = 32 bw", "output_count += 1 fig_title = 'Signal Encoded Using Ideal IAF", "as bl import bionet.utils.plotting as pl import bionet.ted.iaf as iaf", "% noise_power print fig_title u = func_timer(bl.gen_band_limited)(dur, dt, f, noise_power)", "pl.plot_signal(t, u, fig_title, output_name + str(output_count) + output_ext) # Test", "For determining output plot file names: output_name = 'iaf_pop_demo_' output_count", "import matplotlib matplotlib.use('AGG') from bionet.utils.misc import func_timer import bionet.utils.band_limited as", "b_list = [b1, b2] d_list = [d1, d2] R_list =", "output_ext) # Test leaky IAF algorithms: b1 = 3.5 #", "noise_power = None if noise_power == None: fig_title = 'IAF", "names: output_name = 'iaf_pop_demo_' output_count = 0 output_ext = '.png'", "= func_timer(iaf.iaf_encode_pop)([u, u], dt, b_list, d_list, R_list, C_list) pl.plot_encoded(t, u,", "<reponame>bionet/ted.python #!/usr/bin/env python \"\"\" Demos of encoding and decoding algorithms", "determining output plot file names: output_name = 'iaf_pop_demo_' output_count =", "<NAME> # All rights reserved. # Distributed under the terms", "np.arange(0, dur, dt) np.random.seed(0) noise_power = None if noise_power ==", "R_list = [R1, R2] C_list = [C1, C2] output_count +=", "output_ext) output_count += 1 fig_title = 'Signal Decoded Using Ideal", "= np.array([d1, d2]) R_list = np.array([R1, R2]) C_list = np.array([C1,", "as pl import bionet.ted.iaf as iaf # For determining output", "and decoding algorithms using populations of IAF neurons. \"\"\" #", "[C1, C2] output_count += 1 fig_title = 'Signal Encoded Using", "d2 = 0.8 # threshold R2 = np.inf # resistance", "noise_power print fig_title u = func_timer(bl.gen_band_limited)(dur, dt, f, noise_power) pl.plot_signal(t,", "s_list[1], fig_title + ' #2', output_name + str(output_count) + output_ext)", "+ ' #1', output_name + str(output_count) + output_ext) output_count +=", "= 10.0 # resistance C1 = 0.01 # capacitance try:", "= 0.1 dt = 1e-6 f = 32 bw =", "display: import matplotlib matplotlib.use('AGG') from bionet.utils.misc import func_timer import bionet.utils.band_limited", "except ValueError('reconstruction condition not satisfied'): sys.exit() b_list = [b1, b2]", "parameters and input signal: dur = 0.1 dt = 1e-6", "d2] R_list = [R1, R2] C_list = [C1, C2] output_count", "C1) except ValueError('reconstruction condition not satisfied'): sys.exit() b2 = 3.4", "import bionet.utils.plotting as pl import bionet.ted.iaf as iaf # For", "s_list[0], fig_title + ' #1', output_name + str(output_count) + output_ext)", "d_list, R_list, C_list) pl.plot_compare(t, u, u_rec, fig_title, output_name + str(output_count)", "dt = 1e-6 f = 32 bw = 2*np.pi*f t", "ValueError('reconstruction condition not satisfied'): sys.exit() b_list = [b1, b2] d_list", "9.0 # resistance C2 = 0.01 # capacitance try: iaf.iaf_recoverable(u,", "# http://www.opensource.org/licenses/bsd-license import sys import numpy as np # Set", "Test ideal IAF algorithms: b1 = 3.5 # bias d1", "bias d1 = 0.7 # threshold R1 = 10.0 #", "capacitance try: iaf.iaf_recoverable(u, bw, b1, d1, R1, C1) except ValueError('reconstruction", "+ str(output_count) + output_ext) output_count += 1 fig_title = 'Signal", "sys.exit() b_list = np.array([b1, b2]) d_list = np.array([d1, d2]) R_list", "f = 32 bw = 2*np.pi*f t = np.arange(0, dur,", "try: iaf.iaf_recoverable(u, bw, b1, d1, R1, C1) except ValueError('reconstruction condition", "fig_title = 'Signal Decoded Using Leaky IAF Population Decoder' print", "u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur, dt, bw, b_list, d_list, R_list, C_list)", "output_count += 1 fig_title = 'Signal Decoded Using Ideal IAF", "= np.array([R1, R2]) C_list = np.array([C1, C2]) output_count += 1", "= 'IAF Input Signal with %d dB of Noise' %", "= 3.4 # bias d2 = 0.8 # threshold R2", "+ str(output_count) + output_ext) # Test leaky IAF algorithms: b1", "C_list = np.array([C1, C2]) output_count += 1 fig_title = 'Signal", "the terms of the BSD license: # http://www.opensource.org/licenses/bsd-license import sys", "of Noise' % noise_power print fig_title u = func_timer(bl.gen_band_limited)(dur, dt,", "[b1, b2] d_list = [d1, d2] R_list = [R1, R2]", "output_count += 1 fig_title = 'Signal Decoded Using Leaky IAF", "[R1, R2] C_list = [C1, C2] output_count += 1 fig_title", "not satisfied'): sys.exit() b2 = 3.4 # bias d2 =", "Input Signal with No Noise' else: fig_title = 'IAF Input", "fig_title, output_name + str(output_count) + output_ext) # Test ideal IAF", "+ ' #2', output_name + str(output_count) + output_ext) output_count +=", "'Signal Decoded Using Leaky IAF Population Decoder' print fig_title u_rec", "# Define algorithm parameters and input signal: dur = 0.1", "print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur, dt, bw, b_list, d_list,", "= [d1, d2] R_list = [R1, R2] C_list = [C1,", "R_list = np.array([R1, R2]) C_list = np.array([C1, C2]) output_count +=", "R1 = 10.0 # resistance C1 = 0.01 # capacitance", "C_list) pl.plot_encoded(t, u, s_list[0], fig_title + ' #1', output_name +", "b_list = np.array([b1, b2]) d_list = np.array([d1, d2]) R_list =", "= 3.5 # bias d1 = 0.7 # threshold R1", "t = np.arange(0, dur, dt) np.random.seed(0) noise_power = None if", "R2, C2) except ValueError('reconstruction condition not satisfied'): sys.exit() b_list =", "that plots can be generated without a # display: import", "Encoded Using Leaky IAF Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u,", "#!/usr/bin/env python \"\"\" Demos of encoding and decoding algorithms using", "leaky IAF algorithms: b1 = 3.5 # bias d1 =", "fig_title = 'IAF Input Signal with %d dB of Noise'", "2*np.pi*f t = np.arange(0, dur, dt) np.random.seed(0) noise_power = None", "\"\"\" Demos of encoding and decoding algorithms using populations of", "R1 = np.inf # resistance C1 = 0.01 # capacitance", "= 'Signal Decoded Using Leaky IAF Population Decoder' print fig_title", "http://www.opensource.org/licenses/bsd-license import sys import numpy as np # Set matplotlib", "3.5 # bias d1 = 0.7 # threshold R1 =", "C_list = [C1, C2] output_count += 1 fig_title = 'Signal", "s_list = func_timer(iaf.iaf_encode_pop)([u, u], dt, b_list, d_list, R_list, C_list) pl.plot_encoded(t,", "0.8 # threshold R2 = 9.0 # resistance C2 =", "np.array([C1, C2]) output_count += 1 fig_title = 'Signal Encoded Using", "pl.plot_encoded(t, u, s_list[0], fig_title + ' #1', output_name + str(output_count)", "algorithms using populations of IAF neurons. \"\"\" # Copyright (c)", "import bionet.utils.band_limited as bl import bionet.utils.plotting as pl import bionet.ted.iaf", "= 0.01 # capacitance try: iaf.iaf_recoverable(u, bw, b1, d1, R1,", "u, u_rec, fig_title, output_name + str(output_count) + output_ext) # Test", "matplotlib.use('AGG') from bionet.utils.misc import func_timer import bionet.utils.band_limited as bl import", "threshold R2 = 9.0 # resistance C2 = 0.01 #", "# All rights reserved. # Distributed under the terms of", "except ValueError('reconstruction condition not satisfied'): sys.exit() b_list = np.array([b1, b2])", "output_count += 1 fig_title = 'Signal Encoded Using Leaky IAF", "' #1', output_name + str(output_count) + output_ext) output_count += 1", "func_timer(iaf.iaf_encode_pop)([u, u], dt, b_list, d_list, R_list, C_list) pl.plot_encoded(t, u, s_list[0],", "IAF Encoder' print fig_title s_list = func_timer(iaf.iaf_encode_pop)([u, u], dt, b_list,", "np.random.seed(0) noise_power = None if noise_power == None: fig_title =", "+= 1 fig_title = 'Signal Decoded Using Leaky IAF Population", "sys.exit() b_list = [b1, b2] d_list = [d1, d2] R_list", "bionet.utils.band_limited as bl import bionet.utils.plotting as pl import bionet.ted.iaf as", "try: iaf.iaf_recoverable(u, bw, b2, d2, R2, C2) except ValueError('reconstruction condition", "# bias d1 = 0.7 # threshold R1 = np.inf", "= 32 bw = 2*np.pi*f t = np.arange(0, dur, dt)", "R2]) C_list = np.array([C1, C2]) output_count += 1 fig_title =", "%d dB of Noise' % noise_power print fig_title u =", "plots can be generated without a # display: import matplotlib", "== None: fig_title = 'IAF Input Signal with No Noise'", "str(output_count) + output_ext) output_count += 1 fig_title = 'Signal Decoded", "#1', output_name + str(output_count) + output_ext) output_count += 1 pl.plot_encoded(t,", "bw, b_list, d_list, R_list, C_list) pl.plot_compare(t, u, u_rec, fig_title, output_name", "= 'Signal Decoded Using Ideal IAF Population Decoder' print fig_title", "dur, dt) np.random.seed(0) noise_power = None if noise_power == None:", "satisfied'): sys.exit() b_list = np.array([b1, b2]) d_list = np.array([d1, d2])", "# For determining output plot file names: output_name = 'iaf_pop_demo_'", "0.7 # threshold R1 = np.inf # resistance C1 =", "C2] output_count += 1 fig_title = 'Signal Encoded Using Ideal", "None if noise_power == None: fig_title = 'IAF Input Signal", "Noise' else: fig_title = 'IAF Input Signal with %d dB", "Test leaky IAF algorithms: b1 = 3.5 # bias d1", "np.inf # resistance C1 = 0.01 # capacitance try: iaf.iaf_recoverable(u,", "if noise_power == None: fig_title = 'IAF Input Signal with", "without a # display: import matplotlib matplotlib.use('AGG') from bionet.utils.misc import", "+= 1 fig_title = 'Signal Encoded Using Ideal IAF Encoder'", "u, s_list[1], fig_title + ' #2', output_name + str(output_count) +", "# capacitance try: iaf.iaf_recoverable(u, bw, b1, d1, R1, C1) except", "R1, C1) except ValueError('reconstruction condition not satisfied'): sys.exit() b2 =", "Decoder' print fig_title u_rec = func_timer(iaf.iaf_decode_pop)(s_list, dur, dt, bw, b_list,", "populations of IAF neurons. \"\"\" # Copyright (c) 2009-2015, <NAME>", "= '.png' # Define algorithm parameters and input signal: dur", "d_list, R_list, C_list) pl.plot_encoded(t, u, s_list[0], fig_title + ' #1',", "noise_power == None: fig_title = 'IAF Input Signal with No", "1 fig_title = 'Signal Encoded Using Ideal IAF Encoder' print", "sys import numpy as np # Set matplotlib backend so", "= 0.7 # threshold R1 = 10.0 # resistance C1", "fig_title + ' #1', output_name + str(output_count) + output_ext) output_count", "bionet.utils.plotting as pl import bionet.ted.iaf as iaf # For determining", "ValueError('reconstruction condition not satisfied'): sys.exit() b2 = 3.4 # bias", "d2 = 0.8 # threshold R2 = 9.0 # resistance", "= [C1, C2] output_count += 1 fig_title = 'Signal Encoded", "'iaf_pop_demo_' output_count = 0 output_ext = '.png' # Define algorithm", "# threshold R2 = np.inf # resistance C2 = 0.01", "backend so that plots can be generated without a #", "a # display: import matplotlib matplotlib.use('AGG') from bionet.utils.misc import func_timer" ]
[ "function( x,y ): return x+y def main(): TestError( F(1,2) ==", "F = function( x,y ): return x+y def main(): TestError(", "expr\"\"\" F = function( x,y ): return x+y def main():", "\"\"\"func expr\"\"\" F = function( x,y ): return x+y def", "): return x+y def main(): TestError( F(1,2) == 3 )", "x,y ): return x+y def main(): TestError( F(1,2) == 3", "= function( x,y ): return x+y def main(): TestError( F(1,2)" ]
[ "if self.sortable_fields: pass # current_refresh = self.request.GET.get(REFRESH_VAR) # context.update({ #", "BaseAdminPlugin, ListAdminView SORTBY_VAR = '_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort']", "'_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort'] # Media def get_media(self,", "# 'current_refresh': current_refresh, # 'refresh_times': [{ # 'time': r, #", "# 'refresh_times': [{ # 'time': r, # 'url': self.admin_view.get_query_string({REFRESH_VAR: r}),", "current_refresh, # } for r in self.refresh_times], # }) #", "def block_top_toolbar(self, context, nodes): if self.sortable_fields: pass # current_refresh =", "media = media + self.vendor('nadmin.plugin.sortable.js') return media # Block Views", "# current_refresh = self.request.GET.get(REFRESH_VAR) # context.update({ # 'has_refresh': bool(current_refresh), #", "'selected': str(r) == current_refresh, # } for r in self.refresh_times],", "# context.update({ # 'has_refresh': bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh':", "'url': self.admin_view.get_query_string({REFRESH_VAR: r}), # 'selected': str(r) == current_refresh, # }", "self.sortable_fields and self.request.GET.get(SORTBY_VAR): media = media + self.vendor('nadmin.plugin.sortable.js') return media", "= ['sort'] # Media def get_media(self, media): if self.sortable_fields and", "= media + self.vendor('nadmin.plugin.sortable.js') return media # Block Views def", "Views def block_top_toolbar(self, context, nodes): if self.sortable_fields: pass # current_refresh", "= self.request.GET.get(REFRESH_VAR) # context.update({ # 'has_refresh': bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)),", "get_media(self, media): if self.sortable_fields and self.request.GET.get(SORTBY_VAR): media = media +", "media + self.vendor('nadmin.plugin.sortable.js') return media # Block Views def block_top_toolbar(self,", "# } for r in self.refresh_times], # }) # nodes.append(loader.render_to_string('nadmin/blocks/refresh.html',", "# 'selected': str(r) == current_refresh, # } for r in", "# Media def get_media(self, media): if self.sortable_fields and self.request.GET.get(SORTBY_VAR): media", "SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort'] # Media def get_media(self, media): if", "# 'time': r, # 'url': self.admin_view.get_query_string({REFRESH_VAR: r}), # 'selected': str(r)", "current_refresh, # 'refresh_times': [{ # 'time': r, # 'url': self.admin_view.get_query_string({REFRESH_VAR:", "r in self.refresh_times], # }) # nodes.append(loader.render_to_string('nadmin/blocks/refresh.html', context_instance=context)) site.register_plugin(SortablePlugin, ListAdminView)", "# Block Views def block_top_toolbar(self, context, nodes): if self.sortable_fields: pass", "nadmin.views import BaseAdminPlugin, ListAdminView SORTBY_VAR = '_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields", "# 'url': self.admin_view.get_query_string({REFRESH_VAR: r}), # 'selected': str(r) == current_refresh, #", "self.vendor('nadmin.plugin.sortable.js') return media # Block Views def block_top_toolbar(self, context, nodes):", "current_refresh = self.request.GET.get(REFRESH_VAR) # context.update({ # 'has_refresh': bool(current_refresh), # 'clean_refresh_url':", "# 'has_refresh': bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh, #", "Block Views def block_top_toolbar(self, context, nodes): if self.sortable_fields: pass #", "self.request.GET.get(SORTBY_VAR): media = media + self.vendor('nadmin.plugin.sortable.js') return media # Block", "and self.request.GET.get(SORTBY_VAR): media = media + self.vendor('nadmin.plugin.sortable.js') return media #", "return media # Block Views def block_top_toolbar(self, context, nodes): if", "if self.sortable_fields and self.request.GET.get(SORTBY_VAR): media = media + self.vendor('nadmin.plugin.sortable.js') return", "import site from nadmin.views import BaseAdminPlugin, ListAdminView SORTBY_VAR = '_sort_by'", "+ self.vendor('nadmin.plugin.sortable.js') return media # Block Views def block_top_toolbar(self, context,", "= '_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort'] # Media def", "from nadmin.sites import site from nadmin.views import BaseAdminPlugin, ListAdminView SORTBY_VAR", "ListAdminView SORTBY_VAR = '_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort'] #", "bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh, # 'refresh_times': [{", "r}), # 'selected': str(r) == current_refresh, # } for r", "['sort'] # Media def get_media(self, media): if self.sortable_fields and self.request.GET.get(SORTBY_VAR):", "from nadmin.views import BaseAdminPlugin, ListAdminView SORTBY_VAR = '_sort_by' class SortablePlugin(BaseAdminPlugin):", "media # Block Views def block_top_toolbar(self, context, nodes): if self.sortable_fields:", "str(r) == current_refresh, # } for r in self.refresh_times], #", "self.request.GET.get(REFRESH_VAR) # context.update({ # 'has_refresh': bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), #", "block_top_toolbar(self, context, nodes): if self.sortable_fields: pass # current_refresh = self.request.GET.get(REFRESH_VAR)", "} for r in self.refresh_times], # }) # nodes.append(loader.render_to_string('nadmin/blocks/refresh.html', context_instance=context))", "Media def get_media(self, media): if self.sortable_fields and self.request.GET.get(SORTBY_VAR): media =", "site from nadmin.views import BaseAdminPlugin, ListAdminView SORTBY_VAR = '_sort_by' class", "context, nodes): if self.sortable_fields: pass # current_refresh = self.request.GET.get(REFRESH_VAR) #", "'time': r, # 'url': self.admin_view.get_query_string({REFRESH_VAR: r}), # 'selected': str(r) ==", "'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh, # 'refresh_times': [{ # 'time':", "sortable_fields = ['sort'] # Media def get_media(self, media): if self.sortable_fields", "SORTBY_VAR = '_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort'] # Media", "media): if self.sortable_fields and self.request.GET.get(SORTBY_VAR): media = media + self.vendor('nadmin.plugin.sortable.js')", "'current_refresh': current_refresh, # 'refresh_times': [{ # 'time': r, # 'url':", "context.update({ # 'has_refresh': bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh,", "nadmin.sites import site from nadmin.views import BaseAdminPlugin, ListAdminView SORTBY_VAR =", "# 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh, # 'refresh_times': [{ #", "class SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort'] # Media def get_media(self, media):", "pass # current_refresh = self.request.GET.get(REFRESH_VAR) # context.update({ # 'has_refresh': bool(current_refresh),", "self.admin_view.get_query_string({REFRESH_VAR: r}), # 'selected': str(r) == current_refresh, # } for", "self.sortable_fields: pass # current_refresh = self.request.GET.get(REFRESH_VAR) # context.update({ # 'has_refresh':", "#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, ListAdminView", "nodes): if self.sortable_fields: pass # current_refresh = self.request.GET.get(REFRESH_VAR) # context.update({", "'refresh_times': [{ # 'time': r, # 'url': self.admin_view.get_query_string({REFRESH_VAR: r}), #", "== current_refresh, # } for r in self.refresh_times], # })", "for r in self.refresh_times], # }) # nodes.append(loader.render_to_string('nadmin/blocks/refresh.html', context_instance=context)) site.register_plugin(SortablePlugin,", "import BaseAdminPlugin, ListAdminView SORTBY_VAR = '_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields =", "def get_media(self, media): if self.sortable_fields and self.request.GET.get(SORTBY_VAR): media = media", "[{ # 'time': r, # 'url': self.admin_view.get_query_string({REFRESH_VAR: r}), # 'selected':", "self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh, # 'refresh_times': [{ # 'time': r,", "'has_refresh': bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh, # 'refresh_times':", "r, # 'url': self.admin_view.get_query_string({REFRESH_VAR: r}), # 'selected': str(r) == current_refresh," ]
[ "class AlreadyExecuting(Exception): \"\"\" Here to show when more than one", "Sentry and logs? @celery.task() def charge_cards(): lock = Lock(key=\"charge-cards-lock\") lock.acquire()", "key self.connection = redis.from_url(REDIS_URL) def acquire(self): if self.connection.get(self.key): raise AlreadyExecuting", "more than one job of the same type is running.", "Opportunity from util import send_email zone = timezone(TIMEZONE) log_level =", "job...\") three_days_ago = (datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\") today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities", "one. \"\"\" def __init__(self): self.log = list() def it(self, string):", "Lock(key=\"charge-cards-lock\") lock.acquire() log = Log() log.it(\"---Starting batch job...\") three_days_ago =", "release(self): self.connection.delete(self.key) # TODO stop sending this email and just", "import timezone import celery import redis from charges import amount_to_charge,", "= ACCOUNTING_MAIL_RECIPIENT subject = \"Batch run\" send_email(body=body, recipient=recipient, subject=subject) class", "log.it(f\"Found {len(opportunities)} opportunities available to process.\") for opportunity in opportunities:", "is running. \"\"\" pass class Lock(object): \"\"\" Claim an exclusive", "util import send_email zone = timezone(TIMEZONE) log_level = logging.getLevelName(LOG_LEVEL) root", "This encapulates sending to the console/stdout and email all in", "send_email(body=body, recipient=recipient, subject=subject) class AlreadyExecuting(Exception): \"\"\" Here to show when", "to the log. \"\"\" logging.debug(string) self.log.append(string) def send(self): \"\"\" Send", "log.it(\"---Starting batch job...\") three_days_ago = (datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\") today =", "__init__(self): self.log = list() def it(self, string): \"\"\" Add something", "recipient = ACCOUNTING_MAIL_RECIPIENT subject = \"Batch run\" send_email(body=body, recipient=recipient, subject=subject)", "from npsp import Opportunity from util import send_email zone =", "all in one. \"\"\" def __init__(self): self.log = list() def", "available to process.\") for opportunity in opportunities: if not opportunity.stripe_customer:", "ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE from datetime import datetime, timedelta from", "TIMEZONE from datetime import datetime, timedelta from pytz import timezone", "out as an email. \"\"\" body = \"\\n\".join(self.log) recipient =", "email. \"\"\" body = \"\\n\".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject =", "to process.\") for opportunity in opportunities: if not opportunity.stripe_customer: continue", "from charges import amount_to_charge, charge, ChargeException from npsp import Opportunity", "acquire(self): if self.connection.get(self.key): raise AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\", time=1200) def release(self):", "\"Batch run\" send_email(body=body, recipient=recipient, subject=subject) class AlreadyExecuting(Exception): \"\"\" Here to", "LOG_LEVEL, REDIS_URL, TIMEZONE from datetime import datetime, timedelta from pytz", "__init__(self, key): self.key = key self.connection = redis.from_url(REDIS_URL) def acquire(self):", "string): \"\"\" Add something to the log. \"\"\" logging.debug(string) self.log.append(string)", "opportunities = Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing charges...\") log.it(f\"Found {len(opportunities)} opportunities available", "subject = \"Batch run\" send_email(body=body, recipient=recipient, subject=subject) class AlreadyExecuting(Exception): \"\"\"", "\"\"\" Claim an exclusive lock. Using Redis. \"\"\" def __init__(self,", "= key self.connection = redis.from_url(REDIS_URL) def acquire(self): if self.connection.get(self.key): raise", "lock.acquire() log = Log() log.it(\"---Starting batch job...\") three_days_ago = (datetime.now(tz=zone)", "opportunity.stripe_customer: continue amount = amount_to_charge(opportunity) log.it( f\"---- Charging ${amount} to", "AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\", time=1200) def release(self): self.connection.delete(self.key) # TODO stop", "email all in one. \"\"\" def __init__(self): self.log = list()", "and just rely on Sentry and logs? @celery.task() def charge_cards():", "Claim an exclusive lock. Using Redis. \"\"\" def __init__(self, key):", "and logs? @celery.task() def charge_cards(): lock = Lock(key=\"charge-cards-lock\") lock.acquire() log", "config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE from datetime import datetime,", "datetime import datetime, timedelta from pytz import timezone import celery", "@celery.task() def charge_cards(): lock = Lock(key=\"charge-cards-lock\") lock.acquire() log = Log()", "lock = Lock(key=\"charge-cards-lock\") lock.acquire() log = Log() log.it(\"---Starting batch job...\")", "\"\\n\".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject = \"Batch run\" send_email(body=body, recipient=recipient,", "= Lock(key=\"charge-cards-lock\") lock.acquire() log = Log() log.it(\"---Starting batch job...\") three_days_ago", "today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities = Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing charges...\") log.it(f\"Found", "{opportunity.stripe_customer} ({opportunity.name})\" ) try: charge(opportunity) except ChargeException as e: logging.info(\"Batch", "self.log = list() def it(self, string): \"\"\" Add something to", "pytz import timezone import celery import redis from charges import", "\"\"\" logging.debug(string) self.log.append(string) def send(self): \"\"\" Send the assembled log", "redis.from_url(REDIS_URL) def acquire(self): if self.connection.get(self.key): raise AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\", time=1200)", "an exclusive lock. Using Redis. \"\"\" def __init__(self, key): self.key", "amount_to_charge, charge, ChargeException from npsp import Opportunity from util import", "logging.getLogger() root.setLevel(log_level) class Log(object): \"\"\" This encapulates sending to the", "\"\"\" pass class Lock(object): \"\"\" Claim an exclusive lock. Using", "charges...\") log.it(f\"Found {len(opportunities)} opportunities available to process.\") for opportunity in", "REDIS_URL, TIMEZONE from datetime import datetime, timedelta from pytz import", "log. \"\"\" logging.debug(string) self.log.append(string) def send(self): \"\"\" Send the assembled", "to {opportunity.stripe_customer} ({opportunity.name})\" ) try: charge(opportunity) except ChargeException as e:", "= Log() log.it(\"---Starting batch job...\") three_days_ago = (datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\")", "to the console/stdout and email all in one. \"\"\" def", "Send the assembled log out as an email. \"\"\" body", "self.connection.setex(name=self.key, value=\"bar\", time=1200) def release(self): self.connection.delete(self.key) # TODO stop sending", "import redis from charges import amount_to_charge, charge, ChargeException from npsp", "ACCOUNTING_MAIL_RECIPIENT subject = \"Batch run\" send_email(body=body, recipient=recipient, subject=subject) class AlreadyExecuting(Exception):", "{len(opportunities)} opportunities available to process.\") for opportunity in opportunities: if", "\"\"\" def __init__(self, key): self.key = key self.connection = redis.from_url(REDIS_URL)", "if self.connection.get(self.key): raise AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\", time=1200) def release(self): self.connection.delete(self.key)", "amount = amount_to_charge(opportunity) log.it( f\"---- Charging ${amount} to {opportunity.stripe_customer} ({opportunity.name})\"", "ChargeException from npsp import Opportunity from util import send_email zone", "\"\"\" Send the assembled log out as an email. \"\"\"", "= \"\\n\".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject = \"Batch run\" send_email(body=body,", "def acquire(self): if self.connection.get(self.key): raise AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\", time=1200) def", "def __init__(self, key): self.key = key self.connection = redis.from_url(REDIS_URL) def", "= Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing charges...\") log.it(f\"Found {len(opportunities)} opportunities available to", "this email and just rely on Sentry and logs? @celery.task()", "process.\") for opportunity in opportunities: if not opportunity.stripe_customer: continue amount", "opportunities available to process.\") for opportunity in opportunities: if not", "Charging ${amount} to {opportunity.stripe_customer} ({opportunity.name})\" ) try: charge(opportunity) except ChargeException", "body = \"\\n\".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject = \"Batch run\"", "timezone import celery import redis from charges import amount_to_charge, charge,", "type is running. \"\"\" pass class Lock(object): \"\"\" Claim an", "class Lock(object): \"\"\" Claim an exclusive lock. Using Redis. \"\"\"", "to show when more than one job of the same", "TODO stop sending this email and just rely on Sentry", "batch job...\") three_days_ago = (datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\") today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\")", "except ChargeException as e: logging.info(\"Batch charge error\") e.send_slack_notification() log.send() lock.release()", "e: logging.info(\"Batch charge error\") e.send_slack_notification() log.send() lock.release() if __name__ ==", "show when more than one job of the same type", "redis from charges import amount_to_charge, charge, ChargeException from npsp import", "job of the same type is running. \"\"\" pass class", "(datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\") today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities = Opportunity.list(begin=three_days_ago, end=today)", "not opportunity.stripe_customer: continue amount = amount_to_charge(opportunity) log.it( f\"---- Charging ${amount}", "logging from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE from datetime", "in one. \"\"\" def __init__(self): self.log = list() def it(self,", "Using Redis. \"\"\" def __init__(self, key): self.key = key self.connection", "= logging.getLevelName(LOG_LEVEL) root = logging.getLogger() root.setLevel(log_level) class Log(object): \"\"\" This", "# TODO stop sending this email and just rely on", "root = logging.getLogger() root.setLevel(log_level) class Log(object): \"\"\" This encapulates sending", "sending this email and just rely on Sentry and logs?", "log.it(\"---Processing charges...\") log.it(f\"Found {len(opportunities)} opportunities available to process.\") for opportunity", "and email all in one. \"\"\" def __init__(self): self.log =", "value=\"bar\", time=1200) def release(self): self.connection.delete(self.key) # TODO stop sending this", "log.it( f\"---- Charging ${amount} to {opportunity.stripe_customer} ({opportunity.name})\" ) try: charge(opportunity)", "logs? @celery.task() def charge_cards(): lock = Lock(key=\"charge-cards-lock\") lock.acquire() log =", "for opportunity in opportunities: if not opportunity.stripe_customer: continue amount =", "when more than one job of the same type is", "\"\"\" def __init__(self): self.log = list() def it(self, string): \"\"\"", "timedelta from pytz import timezone import celery import redis from", "\"\"\" This encapulates sending to the console/stdout and email all", "logging.debug(string) self.log.append(string) def send(self): \"\"\" Send the assembled log out", "charges import amount_to_charge, charge, ChargeException from npsp import Opportunity from", "Lock(object): \"\"\" Claim an exclusive lock. Using Redis. \"\"\" def", "timezone(TIMEZONE) log_level = logging.getLevelName(LOG_LEVEL) root = logging.getLogger() root.setLevel(log_level) class Log(object):", "the same type is running. \"\"\" pass class Lock(object): \"\"\"", "end=today) log.it(\"---Processing charges...\") log.it(f\"Found {len(opportunities)} opportunities available to process.\") for", "celery import redis from charges import amount_to_charge, charge, ChargeException from", "pass class Lock(object): \"\"\" Claim an exclusive lock. Using Redis.", "ChargeException as e: logging.info(\"Batch charge error\") e.send_slack_notification() log.send() lock.release() if", "continue amount = amount_to_charge(opportunity) log.it( f\"---- Charging ${amount} to {opportunity.stripe_customer}", "from util import send_email zone = timezone(TIMEZONE) log_level = logging.getLevelName(LOG_LEVEL)", "= timezone(TIMEZONE) log_level = logging.getLevelName(LOG_LEVEL) root = logging.getLogger() root.setLevel(log_level) class", "time=1200) def release(self): self.connection.delete(self.key) # TODO stop sending this email", "= list() def it(self, string): \"\"\" Add something to the", "the log. \"\"\" logging.debug(string) self.log.append(string) def send(self): \"\"\" Send the", "one job of the same type is running. \"\"\" pass", "Here to show when more than one job of the", "charge_cards(): lock = Lock(key=\"charge-cards-lock\") lock.acquire() log = Log() log.it(\"---Starting batch", "zone = timezone(TIMEZONE) log_level = logging.getLevelName(LOG_LEVEL) root = logging.getLogger() root.setLevel(log_level)", "as an email. \"\"\" body = \"\\n\".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT", "from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE from datetime import", "charge, ChargeException from npsp import Opportunity from util import send_email", "charge(opportunity) except ChargeException as e: logging.info(\"Batch charge error\") e.send_slack_notification() log.send()", "from pytz import timezone import celery import redis from charges", "import datetime, timedelta from pytz import timezone import celery import", "charge error\") e.send_slack_notification() log.send() lock.release() if __name__ == \"__main__\": charge_cards()", "= (datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\") today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities = Opportunity.list(begin=three_days_ago,", "amount_to_charge(opportunity) log.it( f\"---- Charging ${amount} to {opportunity.stripe_customer} ({opportunity.name})\" ) try:", "\"\"\" body = \"\\n\".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject = \"Batch", "Log(object): \"\"\" This encapulates sending to the console/stdout and email", "self.connection.delete(self.key) # TODO stop sending this email and just rely", "import celery import redis from charges import amount_to_charge, charge, ChargeException", "the assembled log out as an email. \"\"\" body =", "self.key = key self.connection = redis.from_url(REDIS_URL) def acquire(self): if self.connection.get(self.key):", "import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE from datetime import datetime, timedelta", "root.setLevel(log_level) class Log(object): \"\"\" This encapulates sending to the console/stdout", "console/stdout and email all in one. \"\"\" def __init__(self): self.log", "list() def it(self, string): \"\"\" Add something to the log.", "exclusive lock. Using Redis. \"\"\" def __init__(self, key): self.key =", "in opportunities: if not opportunity.stripe_customer: continue amount = amount_to_charge(opportunity) log.it(", "= amount_to_charge(opportunity) log.it( f\"---- Charging ${amount} to {opportunity.stripe_customer} ({opportunity.name})\" )", "logging.info(\"Batch charge error\") e.send_slack_notification() log.send() lock.release() if __name__ == \"__main__\":", "logging.getLevelName(LOG_LEVEL) root = logging.getLogger() root.setLevel(log_level) class Log(object): \"\"\" This encapulates", "def charge_cards(): lock = Lock(key=\"charge-cards-lock\") lock.acquire() log = Log() log.it(\"---Starting", "email and just rely on Sentry and logs? @celery.task() def", "f\"---- Charging ${amount} to {opportunity.stripe_customer} ({opportunity.name})\" ) try: charge(opportunity) except", "just rely on Sentry and logs? @celery.task() def charge_cards(): lock", "rely on Sentry and logs? @celery.task() def charge_cards(): lock =", "Add something to the log. \"\"\" logging.debug(string) self.log.append(string) def send(self):", "than one job of the same type is running. \"\"\"", "<filename>batch-tmp.py import logging from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE", "stop sending this email and just rely on Sentry and", "something to the log. \"\"\" logging.debug(string) self.log.append(string) def send(self): \"\"\"", "def send(self): \"\"\" Send the assembled log out as an", "datetime, timedelta from pytz import timezone import celery import redis", "encapulates sending to the console/stdout and email all in one.", "lock. Using Redis. \"\"\" def __init__(self, key): self.key = key", "({opportunity.name})\" ) try: charge(opportunity) except ChargeException as e: logging.info(\"Batch charge", "self.log.append(string) def send(self): \"\"\" Send the assembled log out as", "opportunities: if not opportunity.stripe_customer: continue amount = amount_to_charge(opportunity) log.it( f\"----", ") try: charge(opportunity) except ChargeException as e: logging.info(\"Batch charge error\")", "- timedelta(days=10)).strftime(\"%Y-%m-%d\") today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities = Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing", "import send_email zone = timezone(TIMEZONE) log_level = logging.getLevelName(LOG_LEVEL) root =", "\"\"\" Here to show when more than one job of", "Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing charges...\") log.it(f\"Found {len(opportunities)} opportunities available to process.\")", "import Opportunity from util import send_email zone = timezone(TIMEZONE) log_level", "opportunity in opportunities: if not opportunity.stripe_customer: continue amount = amount_to_charge(opportunity)", "send(self): \"\"\" Send the assembled log out as an email.", "raise AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\", time=1200) def release(self): self.connection.delete(self.key) # TODO", "same type is running. \"\"\" pass class Lock(object): \"\"\" Claim", "try: charge(opportunity) except ChargeException as e: logging.info(\"Batch charge error\") e.send_slack_notification()", "log_level = logging.getLevelName(LOG_LEVEL) root = logging.getLogger() root.setLevel(log_level) class Log(object): \"\"\"", "= logging.getLogger() root.setLevel(log_level) class Log(object): \"\"\" This encapulates sending to", "datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities = Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing charges...\") log.it(f\"Found {len(opportunities)} opportunities", "npsp import Opportunity from util import send_email zone = timezone(TIMEZONE)", "class Log(object): \"\"\" This encapulates sending to the console/stdout and", "three_days_ago = (datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\") today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities =", "recipient=recipient, subject=subject) class AlreadyExecuting(Exception): \"\"\" Here to show when more", "\"\"\" Add something to the log. \"\"\" logging.debug(string) self.log.append(string) def", "run\" send_email(body=body, recipient=recipient, subject=subject) class AlreadyExecuting(Exception): \"\"\" Here to show", "self.connection = redis.from_url(REDIS_URL) def acquire(self): if self.connection.get(self.key): raise AlreadyExecuting self.connection.setex(name=self.key,", "log = Log() log.it(\"---Starting batch job...\") three_days_ago = (datetime.now(tz=zone) -", "sending to the console/stdout and email all in one. \"\"\"", "if not opportunity.stripe_customer: continue amount = amount_to_charge(opportunity) log.it( f\"---- Charging", "send_email zone = timezone(TIMEZONE) log_level = logging.getLevelName(LOG_LEVEL) root = logging.getLogger()", "as e: logging.info(\"Batch charge error\") e.send_slack_notification() log.send() lock.release() if __name__", "= \"Batch run\" send_email(body=body, recipient=recipient, subject=subject) class AlreadyExecuting(Exception): \"\"\" Here", "self.connection.get(self.key): raise AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\", time=1200) def release(self): self.connection.delete(self.key) #", "it(self, string): \"\"\" Add something to the log. \"\"\" logging.debug(string)", "log out as an email. \"\"\" body = \"\\n\".join(self.log) recipient", "import logging from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE from", "of the same type is running. \"\"\" pass class Lock(object):", "Log() log.it(\"---Starting batch job...\") three_days_ago = (datetime.now(tz=zone) - timedelta(days=10)).strftime(\"%Y-%m-%d\") today", "AlreadyExecuting(Exception): \"\"\" Here to show when more than one job", "timedelta(days=10)).strftime(\"%Y-%m-%d\") today = datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities = Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing charges...\")", "on Sentry and logs? @celery.task() def charge_cards(): lock = Lock(key=\"charge-cards-lock\")", "running. \"\"\" pass class Lock(object): \"\"\" Claim an exclusive lock.", "def release(self): self.connection.delete(self.key) # TODO stop sending this email and", "def __init__(self): self.log = list() def it(self, string): \"\"\" Add", "def it(self, string): \"\"\" Add something to the log. \"\"\"", "= datetime.now(tz=zone).strftime(\"%Y-%m-%d\") opportunities = Opportunity.list(begin=three_days_ago, end=today) log.it(\"---Processing charges...\") log.it(f\"Found {len(opportunities)}", "the console/stdout and email all in one. \"\"\" def __init__(self):", "subject=subject) class AlreadyExecuting(Exception): \"\"\" Here to show when more than", "an email. \"\"\" body = \"\\n\".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject", "${amount} to {opportunity.stripe_customer} ({opportunity.name})\" ) try: charge(opportunity) except ChargeException as", "import amount_to_charge, charge, ChargeException from npsp import Opportunity from util", "= redis.from_url(REDIS_URL) def acquire(self): if self.connection.get(self.key): raise AlreadyExecuting self.connection.setex(name=self.key, value=\"bar\",", "key): self.key = key self.connection = redis.from_url(REDIS_URL) def acquire(self): if", "assembled log out as an email. \"\"\" body = \"\\n\".join(self.log)", "Redis. \"\"\" def __init__(self, key): self.key = key self.connection =", "from datetime import datetime, timedelta from pytz import timezone import" ]
[ "None, msg def test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert 'BTC' not in blockchain.totals", "blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value is not None assert blockchain.totals[A_BTC].amount is not", "noqa: E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 not in", "removal of blockchain accounts after the first time all balances", "as mock: # noqa: E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert", "every time. That slowed everything down (https://github.com/rotki/rotki/issues/678). This is a", "assert blockchain.totals[A_BTC].amount is not None @pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due", "'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, ) with etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], )", "import requests from rotkehlchen.chain.ethereum.manager import NodeName from rotkehlchen.constants.assets import A_BTC", "probably (1) makes more sense \"\"\" msg = 'Should be", "'blockchain.query_balances() should not have been called' addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with", "accounts after the first time all balances were queried every", "that behaviour TODO: Is this still needed? Shouldn't it just", "'0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 = '<KEY>' etherscan_patch = mock_etherscan_query( eth_map={addr1: {'ETH': 1},", "from unittest.mock import patch import pytest import requests from rotkehlchen.chain.ethereum.manager", "test_eth_connection_initial_balances( blockchain, inquirer, # pylint: disable=unused-argument ): \"\"\"TODO for this", "open node for this test. 2. If we use own", "mock_etherscan_query( eth_map={addr1: {'ETH': 1}, addr2: {'ETH': 2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[],", ") assert addr1 in blockchain.accounts.eth with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances')", "import operator import os from unittest.mock import patch import pytest", "for this test. Either: 1. Not use own chain but", "just be removed? Had to add lots of mocks to", "# noqa: E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 not", "all balances were queried every time. That slowed everything down", "contract there. But probably (1) makes more sense \"\"\" msg", "[0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to a programming mistake at addition", "Had to add lots of mocks to make it not", "etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 in blockchain.accounts.eth", "{'ETH': 1}, addr2: {'ETH': 2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[], ) ethtokens_max_chunks_patch", "NodeName from rotkehlchen.constants.assets import A_BTC from rotkehlchen.tests.utils.blockchain import mock_etherscan_query from", "testing running with geth in windows at the moment', )", "blockchain.accounts.eth assert mock.call_count == 0, 'blockchain.query_balances() should not have been", "with geth in windows at the moment', ) @pytest.mark.parametrize('have_blockchain_backend', [True])", "blockchain.modify_btc_account(account, 'append', operator.add) blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value is not None assert", "should not have been called' addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch,", "disable=unused-argument ): \"\"\"TODO for this test. Either: 1. Not use", "If we use own chain, deploy the eth-scan contract there.", "blockchain, inquirer, # pylint: disable=unused-argument ): \"\"\"TODO for this test.", "queried every time. That slowed everything down (https://github.com/rotki/rotki/issues/678). This is", "for that behaviour TODO: Is this still needed? Shouldn't it", "not None @pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to a programming", "accounts=[addr1], ) assert addr1 in blockchain.accounts.eth with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain,", "assert addr1 not in blockchain.accounts.eth assert mock.call_count == 0, 'blockchain.query_balances()", "blockchain accounts after the first time all balances were queried", "test. Either: 1. Not use own chain but use a", "def test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert 'BTC' not in blockchain.totals account =", "\"\"\"TODO for this test. Either: 1. Not use own chain", "more sense \"\"\" msg = 'Should be connected to ethereum", "the moment', ) @pytest.mark.parametrize('have_blockchain_backend', [True]) def test_eth_connection_initial_balances( blockchain, inquirer, #", "windows at the moment', ) @pytest.mark.parametrize('have_blockchain_backend', [True]) def test_eth_connection_initial_balances( blockchain,", "'<KEY>' blockchain.modify_btc_account(account, 'append', operator.add) blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value is not None", "\"\"\"Due to a programming mistake at addition and removal of", "everything down (https://github.com/rotki/rotki/issues/678). This is a regression test for that", "is a regression test for that behaviour TODO: Is this", "the eth-scan contract there. But probably (1) makes more sense", "patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, ) with etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1],", "in blockchain.accounts.eth assert mock.call_count == 0, 'blockchain.query_balances() should not have", "== 0, 'blockchain.query_balances() should not have been called' addr2 =", "0, 'blockchain.query_balances() should not have been called' addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2'", "addr1 in blockchain.accounts.eth with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock:", "eth-scan contract there. But probably (1) makes more sense \"\"\"", "): \"\"\"TODO for this test. Either: 1. Not use own", "accounts=[addr1], ) assert addr1 not in blockchain.accounts.eth assert mock.call_count ==", "rotkehlchen.tests.utils.blockchain import mock_etherscan_query from rotkehlchen.typing import SupportedBlockchain @pytest.mark.skipif( os.name ==", "pytest import requests from rotkehlchen.chain.ethereum.manager import NodeName from rotkehlchen.constants.assets import", "own chain but use a normal open node for this", "assert blockchain.totals[A_BTC].usd_value is not None assert blockchain.totals[A_BTC].amount is not None", "were queried every time. That slowed everything down (https://github.com/rotki/rotki/issues/678). This", "patch.object(blockchain, 'query_balances') as mock: # noqa: E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1],", "This is a regression test for that behaviour TODO: Is", "down (https://github.com/rotki/rotki/issues/678). This is a regression test for that behaviour", "test for that behaviour TODO: Is this still needed? Shouldn't", "addition and removal of blockchain accounts after the first time", "lots of mocks to make it not be a slow", "time. That slowed everything down (https://github.com/rotki/rotki/issues/678). This is a regression", "etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: # noqa: E501 blockchain.remove_blockchain_accounts(", "mock_etherscan_query from rotkehlchen.typing import SupportedBlockchain @pytest.mark.skipif( os.name == 'nt', reason='Not", ") with etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1", "chain, deploy the eth-scan contract there. But probably (1) makes", "None @pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to a programming mistake", "connected to ethereum node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not None, msg", "'nt', reason='Not testing running with geth in windows at the", "programming mistake at addition and removal of blockchain accounts after", ") ethtokens_max_chunks_patch = patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, ) with etherscan_patch, ethtokens_max_chunks_patch:", "2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[], ) ethtokens_max_chunks_patch = patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800,", "\"\"\" msg = 'Should be connected to ethereum node' assert", "pylint: disable=unused-argument ): \"\"\"TODO for this test. Either: 1. Not", "{'ETH': 2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[], ) ethtokens_max_chunks_patch = patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH',", "rotkehlchen.typing import SupportedBlockchain @pytest.mark.skipif( os.name == 'nt', reason='Not testing running", "for this test. 2. If we use own chain, deploy", "at the moment', ) @pytest.mark.parametrize('have_blockchain_backend', [True]) def test_eth_connection_initial_balances( blockchain, inquirer,", "not None, msg def test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert 'BTC' not in", "Is this still needed? Shouldn't it just be removed? Had", "A_BTC from rotkehlchen.tests.utils.blockchain import mock_etherscan_query from rotkehlchen.typing import SupportedBlockchain @pytest.mark.skipif(", "blockchain.totals[A_BTC].usd_value is not None assert blockchain.totals[A_BTC].amount is not None @pytest.mark.parametrize('number_of_eth_accounts',", "addr2: {'ETH': 2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[], ) ethtokens_max_chunks_patch = patch(", "but use a normal open node for this test. 2.", "not in blockchain.totals account = '<KEY>' blockchain.modify_btc_account(account, 'append', operator.add) blockchain.query_btc_balances()", "import os from unittest.mock import patch import pytest import requests", "SupportedBlockchain @pytest.mark.skipif( os.name == 'nt', reason='Not testing running with geth", "= 'Should be connected to ethereum node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is", "be connected to ethereum node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not None,", "needed? Shouldn't it just be removed? Had to add lots", "rotkehlchen.constants.assets import A_BTC from rotkehlchen.tests.utils.blockchain import mock_etherscan_query from rotkehlchen.typing import", "2. If we use own chain, deploy the eth-scan contract", "Shouldn't it just be removed? Had to add lots of", ") assert addr1 not in blockchain.accounts.eth assert mock.call_count == 0,", "'append', operator.add) blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value is not None assert blockchain.totals[A_BTC].amount", "= '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 = '<KEY>' etherscan_patch = mock_etherscan_query( eth_map={addr1: {'ETH':", "'0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: # noqa:", "node for this test. 2. If we use own chain,", "ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: # noqa: E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM,", "we use own chain, deploy the eth-scan contract there. But", "called' addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as", "assert mock.call_count == 0, 'blockchain.query_balances() should not have been called'", "patch.object(blockchain, 'query_balances') as mock: # noqa: E501 blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr2],", "this test. 2. If we use own chain, deploy the", "in windows at the moment', ) @pytest.mark.parametrize('have_blockchain_backend', [True]) def test_eth_connection_initial_balances(", "to ethereum node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not None, msg def", "etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[], ) ethtokens_max_chunks_patch = patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, )", "import SupportedBlockchain @pytest.mark.skipif( os.name == 'nt', reason='Not testing running with", "still needed? Shouldn't it just be removed? Had to add", "test \"\"\" addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 = '<KEY>' etherscan_patch =", "'query_balances') as mock: # noqa: E501 blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr2], )", "it just be removed? Had to add lots of mocks", "from rotkehlchen.tests.utils.blockchain import mock_etherscan_query from rotkehlchen.typing import SupportedBlockchain @pytest.mark.skipif( os.name", "account = '<KEY>' blockchain.modify_btc_account(account, 'append', operator.add) blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value is", "removed? Had to add lots of mocks to make it", "mocks to make it not be a slow test \"\"\"", "blockchain.totals account = '<KEY>' blockchain.modify_btc_account(account, 'append', operator.add) blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value", "this test. Either: 1. Not use own chain but use", "ethereum node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not None, msg def test_query_btc_balances(blockchain):", "E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 not in blockchain.accounts.eth", "def test_eth_connection_initial_balances( blockchain, inquirer, # pylint: disable=unused-argument ): \"\"\"TODO for", "[True]) def test_eth_connection_initial_balances( blockchain, inquirer, # pylint: disable=unused-argument ): \"\"\"TODO", "chain but use a normal open node for this test.", "import patch import pytest import requests from rotkehlchen.chain.ethereum.manager import NodeName", "node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not None, msg def test_query_btc_balances(blockchain): blockchain.query_btc_balances()", "is not None @pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to a", "makes more sense \"\"\" msg = 'Should be connected to", "test. 2. If we use own chain, deploy the eth-scan", "@pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to a programming mistake at", "'query_balances') as mock: # noqa: E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], )", "1}, addr2: {'ETH': 2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[], ) ethtokens_max_chunks_patch =", "test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to a programming mistake at addition and removal", "of mocks to make it not be a slow test", "assert addr1 in blockchain.accounts.eth with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as", "requests from rotkehlchen.chain.ethereum.manager import NodeName from rotkehlchen.constants.assets import A_BTC from", "== 'nt', reason='Not testing running with geth in windows at", "from rotkehlchen.constants.assets import A_BTC from rotkehlchen.tests.utils.blockchain import mock_etherscan_query from rotkehlchen.typing", "Either: 1. Not use own chain but use a normal", "original_requests_get=requests.get, original_queries=[], ) ethtokens_max_chunks_patch = patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, ) with", "not have been called' addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch, ethtokens_max_chunks_patch,", "with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: # noqa: E501", "the first time all balances were queried every time. That", "But probably (1) makes more sense \"\"\" msg = 'Should", "ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 in blockchain.accounts.eth with", "with etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 in", "assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not None, msg def test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert", "mistake at addition and removal of blockchain accounts after the", "ethtokens_max_chunks_patch = patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, ) with etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts(", "it not be a slow test \"\"\" addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c'", "addr2 = '<KEY>' etherscan_patch = mock_etherscan_query( eth_map={addr1: {'ETH': 1}, addr2:", "addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock:", "(https://github.com/rotki/rotki/issues/678). This is a regression test for that behaviour TODO:", "geth in windows at the moment', ) @pytest.mark.parametrize('have_blockchain_backend', [True]) def", "# pylint: disable=unused-argument ): \"\"\"TODO for this test. Either: 1.", "behaviour TODO: Is this still needed? Shouldn't it just be", "a slow test \"\"\" addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 = '<KEY>'", "blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 in blockchain.accounts.eth with etherscan_patch,", "= '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: #", "= '<KEY>' blockchain.modify_btc_account(account, 'append', operator.add) blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value is not", "mock: # noqa: E501 blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1", "eth_map={addr1: {'ETH': 1}, addr2: {'ETH': 2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get, original_queries=[], )", "reason='Not testing running with geth in windows at the moment',", "import mock_etherscan_query from rotkehlchen.typing import SupportedBlockchain @pytest.mark.skipif( os.name == 'nt',", "@pytest.mark.skipif( os.name == 'nt', reason='Not testing running with geth in", "blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not None, msg def test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert 'BTC'", "'BTC' not in blockchain.totals account = '<KEY>' blockchain.modify_btc_account(account, 'append', operator.add)", "regression test for that behaviour TODO: Is this still needed?", "blockchain.remove_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 not in blockchain.accounts.eth assert", "running with geth in windows at the moment', ) @pytest.mark.parametrize('have_blockchain_backend',", "slow test \"\"\" addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 = '<KEY>' etherscan_patch", "from rotkehlchen.typing import SupportedBlockchain @pytest.mark.skipif( os.name == 'nt', reason='Not testing", "of blockchain accounts after the first time all balances were", "normal open node for this test. 2. If we use", "That slowed everything down (https://github.com/rotki/rotki/issues/678). This is a regression test", "blockchain.accounts.eth with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: # noqa:", "original_queries=[], ) ethtokens_max_chunks_patch = patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, ) with etherscan_patch,", "None assert blockchain.totals[A_BTC].amount is not None @pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain):", "= '<KEY>' etherscan_patch = mock_etherscan_query( eth_map={addr1: {'ETH': 1}, addr2: {'ETH':", "ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: # noqa: E501 blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM,", "@pytest.mark.parametrize('have_blockchain_backend', [True]) def test_eth_connection_initial_balances( blockchain, inquirer, # pylint: disable=unused-argument ):", "test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert 'BTC' not in blockchain.totals account = '<KEY>'", "is not None assert blockchain.totals[A_BTC].amount is not None @pytest.mark.parametrize('number_of_eth_accounts', [0])", "to a programming mistake at addition and removal of blockchain", "def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to a programming mistake at addition and", "and removal of blockchain accounts after the first time all", "after the first time all balances were queried every time.", "rotkehlchen.chain.ethereum.manager import NodeName from rotkehlchen.constants.assets import A_BTC from rotkehlchen.tests.utils.blockchain import", "'Should be connected to ethereum node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN) is not", "new=800, ) with etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert", "from rotkehlchen.chain.ethereum.manager import NodeName from rotkehlchen.constants.assets import A_BTC from rotkehlchen.tests.utils.blockchain", "blockchain.totals[A_BTC].amount is not None @pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_add_remove_account_assure_all_balances_not_always_queried(blockchain): \"\"\"Due to", "use own chain but use a normal open node for", "assert 'BTC' not in blockchain.totals account = '<KEY>' blockchain.modify_btc_account(account, 'append',", "import pytest import requests from rotkehlchen.chain.ethereum.manager import NodeName from rotkehlchen.constants.assets", "not be a slow test \"\"\" addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2", "been called' addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances')", "this still needed? Shouldn't it just be removed? Had to", ") @pytest.mark.parametrize('have_blockchain_backend', [True]) def test_eth_connection_initial_balances( blockchain, inquirer, # pylint: disable=unused-argument", "sense \"\"\" msg = 'Should be connected to ethereum node'", "be removed? Had to add lots of mocks to make", "os from unittest.mock import patch import pytest import requests from", "\"\"\" addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 = '<KEY>' etherscan_patch = mock_etherscan_query(", "to make it not be a slow test \"\"\" addr1", "= mock_etherscan_query( eth_map={addr1: {'ETH': 1}, addr2: {'ETH': 2}}, etherscan=blockchain.ethereum.etherscan, original_requests_get=requests.get,", "operator import os from unittest.mock import patch import pytest import", "own chain, deploy the eth-scan contract there. But probably (1)", "mock.call_count == 0, 'blockchain.query_balances() should not have been called' addr2", "os.name == 'nt', reason='Not testing running with geth in windows", "deploy the eth-scan contract there. But probably (1) makes more", "make it not be a slow test \"\"\" addr1 =", "operator.add) blockchain.query_btc_balances() assert blockchain.totals[A_BTC].usd_value is not None assert blockchain.totals[A_BTC].amount is", "use a normal open node for this test. 2. If", "a programming mistake at addition and removal of blockchain accounts", "not in blockchain.accounts.eth assert mock.call_count == 0, 'blockchain.query_balances() should not", "have been called' addr2 = '0x78a087fCf440315b843632cFd6FDE6E5adcCc2C2' with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain,", "= patch( 'rotkehlchen.chain.ethereum.tokens.ETHERSCAN_MAX_TOKEN_CHUNK_LENGTH', new=800, ) with etherscan_patch, ethtokens_max_chunks_patch: blockchain.add_blockchain_accounts( blockchain=SupportedBlockchain.ETHEREUM,", "etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: # noqa: E501 blockchain.add_blockchain_accounts(", "TODO: Is this still needed? Shouldn't it just be removed?", "time all balances were queried every time. That slowed everything", "etherscan_patch = mock_etherscan_query( eth_map={addr1: {'ETH': 1}, addr2: {'ETH': 2}}, etherscan=blockchain.ethereum.etherscan,", "there. But probably (1) makes more sense \"\"\" msg =", "unittest.mock import patch import pytest import requests from rotkehlchen.chain.ethereum.manager import", "add lots of mocks to make it not be a", "blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 not in blockchain.accounts.eth assert mock.call_count", "'<KEY>' etherscan_patch = mock_etherscan_query( eth_map={addr1: {'ETH': 1}, addr2: {'ETH': 2}},", "addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 = '<KEY>' etherscan_patch = mock_etherscan_query( eth_map={addr1:", "at addition and removal of blockchain accounts after the first", "addr1 not in blockchain.accounts.eth assert mock.call_count == 0, 'blockchain.query_balances() should", "patch import pytest import requests from rotkehlchen.chain.ethereum.manager import NodeName from", "use own chain, deploy the eth-scan contract there. But probably", "is not None, msg def test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert 'BTC' not", "not None assert blockchain.totals[A_BTC].amount is not None @pytest.mark.parametrize('number_of_eth_accounts', [0]) def", "first time all balances were queried every time. That slowed", "balances were queried every time. That slowed everything down (https://github.com/rotki/rotki/issues/678).", "(1) makes more sense \"\"\" msg = 'Should be connected", "inquirer, # pylint: disable=unused-argument ): \"\"\"TODO for this test. Either:", "Not use own chain but use a normal open node", "slowed everything down (https://github.com/rotki/rotki/issues/678). This is a regression test for", "blockchain.query_btc_balances() assert 'BTC' not in blockchain.totals account = '<KEY>' blockchain.modify_btc_account(account,", "moment', ) @pytest.mark.parametrize('have_blockchain_backend', [True]) def test_eth_connection_initial_balances( blockchain, inquirer, # pylint:", "to add lots of mocks to make it not be", "be a slow test \"\"\" addr1 = '0xe188c6BEBB81b96A65aa20dDB9e2aef62627fa4c' addr2 =", "blockchain=SupportedBlockchain.ETHEREUM, accounts=[addr1], ) assert addr1 in blockchain.accounts.eth with etherscan_patch, ethtokens_max_chunks_patch,", "1. Not use own chain but use a normal open", "a normal open node for this test. 2. If we", "in blockchain.totals account = '<KEY>' blockchain.modify_btc_account(account, 'append', operator.add) blockchain.query_btc_balances() assert", "a regression test for that behaviour TODO: Is this still", "in blockchain.accounts.eth with etherscan_patch, ethtokens_max_chunks_patch, patch.object(blockchain, 'query_balances') as mock: #", "msg = 'Should be connected to ethereum node' assert blockchain.ethereum.web3_mapping.get(NodeName.OWN)", "import A_BTC from rotkehlchen.tests.utils.blockchain import mock_etherscan_query from rotkehlchen.typing import SupportedBlockchain", "msg def test_query_btc_balances(blockchain): blockchain.query_btc_balances() assert 'BTC' not in blockchain.totals account", "import NodeName from rotkehlchen.constants.assets import A_BTC from rotkehlchen.tests.utils.blockchain import mock_etherscan_query" ]
[ "Author: I am # # Created: 02/11/2017 # Copyright: (c)", "(c) I am 2017 # Licence: <your licence> #------------------------------------------------------------------------------- def", "I am # # Created: 02/11/2017 # Copyright: (c) I", "<your licence> #------------------------------------------------------------------------------- def main(): pass if __name__ == '__main__':", "Created: 02/11/2017 # Copyright: (c) I am 2017 # Licence:", "# # Author: I am # # Created: 02/11/2017 #", "02/11/2017 # Copyright: (c) I am 2017 # Licence: <your", "# Purpose: # # Author: I am # # Created:", "am # # Created: 02/11/2017 # Copyright: (c) I am", "# Copyright: (c) I am 2017 # Licence: <your licence>", "# # Created: 02/11/2017 # Copyright: (c) I am 2017", "am 2017 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass", "# Author: I am # # Created: 02/11/2017 # Copyright:", "licence> #------------------------------------------------------------------------------- def main(): pass if __name__ == '__main__': main()", "# Created: 02/11/2017 # Copyright: (c) I am 2017 #", "Purpose: # # Author: I am # # Created: 02/11/2017", "module1 # Purpose: # # Author: I am # #", "Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass if __name__ ==", "# Name: module1 # Purpose: # # Author: I am", "#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: I", "Copyright: (c) I am 2017 # Licence: <your licence> #-------------------------------------------------------------------------------", "Name: module1 # Purpose: # # Author: I am #", "# Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass if __name__", "I am 2017 # Licence: <your licence> #------------------------------------------------------------------------------- def main():", "2017 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass if" ]
[ "app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app,", "= Misaka() bootstrap = Bootstrap() def create_app(config_class=Config): app = Flask(__name__)", "\"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\" } metadata = MetaData(naming_convention=convention)", "Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if app.config['ELASTICSEARCH_URL'] else None from app import models", "import MetaData from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate", "app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) from", "= MetaData(naming_convention=convention) db = SQLAlchemy(metadata=metadata) migrate = Migrate() login =", "metadata = MetaData(naming_convention=convention) db = SQLAlchemy(metadata=metadata) migrate = Migrate() login", "'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) # migrate.init_app(app, db)", "\"auth.login\" moment = Moment() md = Misaka() bootstrap = Bootstrap()", "%(message)s [in %(pathname)s:%(lineno)d]\" ) ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info(\"Moviedb startup\")", "flask_moment import Moment from flask_misaka import Misaka from flask_bootstrap import", "= Migrate() login = LoginManager() login.login_view = \"auth.login\" moment =", "import bp as cli_bp app.register_blueprint(cli_bp) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if", "%(pathname)s:%(lineno)d]\" ) ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info(\"Moviedb startup\") return app", "Moment from flask_misaka import Misaka from flask_bootstrap import Bootstrap import", "app.register_blueprint(main_bp) from app.cli import bp as cli_bp app.register_blueprint(cli_bp) app.elasticsearch =", "# migrate.init_app(app, db) login.init_app(app) moment.init_app(app) md.init_app(app) bootstrap.init_app(app) from app.errors import", "from app.main import bp as main_bp app.register_blueprint(main_bp) from app.cli import", "import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as", "Bootstrap import os import logging from logging.handlers import RotatingFileHandler from", "db, render_as_batch=True) else: migrate.init_app(app, db) # migrate.init_app(app, db) login.init_app(app) moment.init_app(app)", "backupCount=10 ) file_handler.setFormatter( logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]\" )", "\"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\" } metadata =", "Bootstrap() def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) with app.app_context():", "\"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\" } metadata = MetaData(naming_convention=convention) db = SQLAlchemy(metadata=metadata)", "migrate.init_app(app, db) # migrate.init_app(app, db) login.init_app(app) moment.init_app(app) md.init_app(app) bootstrap.init_app(app) from", "\"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\" } metadata = MetaData(naming_convention=convention) db =", "SQLAlchemy(metadata=metadata) migrate = Migrate() login = LoginManager() login.login_view = \"auth.login\"", "config import Config from sqlalchemy import MetaData from flask_sqlalchemy import", "md.init_app(app) bootstrap.init_app(app) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from", "flask_bootstrap import Bootstrap import os import logging from logging.handlers import", "SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from", "file_handler = RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240, backupCount=10 ) file_handler.setFormatter( logging.Formatter( \"%(asctime)s", "from flask_misaka import Misaka from flask_bootstrap import Bootstrap import os", "maxBytes=10240, backupCount=10 ) file_handler.setFormatter( logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]\"", "%(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]\" ) ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info(\"Moviedb", "= Flask(__name__) app.config.from_object(Config) db.init_app(app) with app.app_context(): if db.engine.url.drivername == 'sqlite':", "app.config.from_object(Config) db.init_app(app) with app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db,", "with app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True) else:", "md = Misaka() bootstrap = Bootstrap() def create_app(config_class=Config): app =", "render_as_batch=True) else: migrate.init_app(app, db) # migrate.init_app(app, db) login.init_app(app) moment.init_app(app) md.init_app(app)", "as main_bp app.register_blueprint(main_bp) from app.cli import bp as cli_bp app.register_blueprint(cli_bp)", "if not app.debug and not app.testing: if not os.path.exists(\"logs\"): os.mkdir(\"logs\")", "flask_login import LoginManager from flask_moment import Moment from flask_misaka import", "'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\" }", "bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp", "migrate = Migrate() login = LoginManager() login.login_view = \"auth.login\" moment", "from elasticsearch import Elasticsearch convention = { \"ix\": 'ix_%(column_0_label)s', \"uq\":", "moment = Moment() md = Misaka() bootstrap = Bootstrap() def", "app = Flask(__name__) app.config.from_object(Config) db.init_app(app) with app.app_context(): if db.engine.url.drivername ==", "Moment() md = Misaka() bootstrap = Bootstrap() def create_app(config_class=Config): app", "from flask_bootstrap import Bootstrap import os import logging from logging.handlers", "migrate.init_app(app, db) login.init_app(app) moment.init_app(app) md.init_app(app) bootstrap.init_app(app) from app.errors import bp", "app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from", "app.config['ELASTICSEARCH_URL'] else None from app import models if not app.debug", "app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp", "moment.init_app(app) md.init_app(app) bootstrap.init_app(app) from app.errors import bp as errors_bp app.register_blueprint(errors_bp)", "Misaka() bootstrap = Bootstrap() def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config)", "if app.config['ELASTICSEARCH_URL'] else None from app import models if not", "\"ix\": 'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\"", "not os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler = RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240, backupCount=10 )", "db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) #", "from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main", "import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp", "as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp", "from flask_moment import Moment from flask_misaka import Misaka from flask_bootstrap", "else: migrate.init_app(app, db) # migrate.init_app(app, db) login.init_app(app) moment.init_app(app) md.init_app(app) bootstrap.init_app(app)", "models if not app.debug and not app.testing: if not os.path.exists(\"logs\"):", "app.testing: if not os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler = RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240,", "MetaData(naming_convention=convention) db = SQLAlchemy(metadata=metadata) migrate = Migrate() login = LoginManager()", "RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240, backupCount=10 ) file_handler.setFormatter( logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s", "app.debug and not app.testing: if not os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler =", "logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]\" ) ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler)", "import Flask from config import Config from sqlalchemy import MetaData", "sqlalchemy import MetaData from flask_sqlalchemy import SQLAlchemy from flask_migrate import", "login.login_view = \"auth.login\" moment = Moment() md = Misaka() bootstrap", "app import models if not app.debug and not app.testing: if", "= RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240, backupCount=10 ) file_handler.setFormatter( logging.Formatter( \"%(asctime)s %(levelname)s:", "Migrate() login = LoginManager() login.login_view = \"auth.login\" moment = Moment()", "app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if app.config['ELASTICSEARCH_URL'] else None from app", "convention = { \"ix\": 'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\":", "flask_migrate import Migrate from flask_login import LoginManager from flask_moment import", "Flask(__name__) app.config.from_object(Config) db.init_app(app) with app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app,", "MetaData from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from", "db.init_app(app) with app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True)", "import logging from logging.handlers import RotatingFileHandler from elasticsearch import Elasticsearch", "from app import models if not app.debug and not app.testing:", "import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager", "\"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\" } metadata", "Config from sqlalchemy import MetaData from flask_sqlalchemy import SQLAlchemy from", "= Bootstrap() def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) with", "\"logs/moviedb.log\", maxBytes=10240, backupCount=10 ) file_handler.setFormatter( logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s [in", "app.main import bp as main_bp app.register_blueprint(main_bp) from app.cli import bp", "{ \"ix\": 'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\":", "db) # migrate.init_app(app, db) login.init_app(app) moment.init_app(app) md.init_app(app) bootstrap.init_app(app) from app.errors", "LoginManager from flask_moment import Moment from flask_misaka import Misaka from", "logging.handlers import RotatingFileHandler from elasticsearch import Elasticsearch convention = {", "} metadata = MetaData(naming_convention=convention) db = SQLAlchemy(metadata=metadata) migrate = Migrate()", "from config import Config from sqlalchemy import MetaData from flask_sqlalchemy", "login = LoginManager() login.login_view = \"auth.login\" moment = Moment() md", "from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login", "import Migrate from flask_login import LoginManager from flask_moment import Moment", "== 'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) # migrate.init_app(app,", "= LoginManager() login.login_view = \"auth.login\" moment = Moment() md =", "not app.debug and not app.testing: if not os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler", "bp as cli_bp app.register_blueprint(cli_bp) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if app.config['ELASTICSEARCH_URL']", "import Misaka from flask_bootstrap import Bootstrap import os import logging", "= Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if app.config['ELASTICSEARCH_URL'] else None from app import", "import Bootstrap import os import logging from logging.handlers import RotatingFileHandler", "main_bp app.register_blueprint(main_bp) from app.cli import bp as cli_bp app.register_blueprint(cli_bp) app.elasticsearch", "LoginManager() login.login_view = \"auth.login\" moment = Moment() md = Misaka()", "auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp)", "import Elasticsearch convention = { \"ix\": 'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\":", "file_handler.setFormatter( logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]\" ) ) file_handler.setLevel(logging.INFO)", "login.init_app(app) moment.init_app(app) md.init_app(app) bootstrap.init_app(app) from app.errors import bp as errors_bp", "from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import", "create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) with app.app_context(): if db.engine.url.drivername", "else None from app import models if not app.debug and", "= Moment() md = Misaka() bootstrap = Bootstrap() def create_app(config_class=Config):", "flask import Flask from config import Config from sqlalchemy import", "def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) with app.app_context(): if", "import os import logging from logging.handlers import RotatingFileHandler from elasticsearch", "Misaka from flask_bootstrap import Bootstrap import os import logging from", "import models if not app.debug and not app.testing: if not", "elasticsearch import Elasticsearch convention = { \"ix\": 'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\",", "\"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]\" ) ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO)", "if not os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler = RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240, backupCount=10", "import bp as main_bp app.register_blueprint(main_bp) from app.cli import bp as", "RotatingFileHandler from elasticsearch import Elasticsearch convention = { \"ix\": 'ix_%(column_0_label)s',", "and not app.testing: if not os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler = RotatingFileHandler(", "bootstrap.init_app(app) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth", "cli_bp app.register_blueprint(cli_bp) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if app.config['ELASTICSEARCH_URL'] else None", "db = SQLAlchemy(metadata=metadata) migrate = Migrate() login = LoginManager() login.login_view", "= \"auth.login\" moment = Moment() md = Misaka() bootstrap =", "from flask_login import LoginManager from flask_moment import Moment from flask_misaka", "\\ if app.config['ELASTICSEARCH_URL'] else None from app import models if", "\"pk\": \"pk_%(table_name)s\" } metadata = MetaData(naming_convention=convention) db = SQLAlchemy(metadata=metadata) migrate", "as cli_bp app.register_blueprint(cli_bp) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if app.config['ELASTICSEARCH_URL'] else", ") file_handler.setFormatter( logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]\" ) )", "Flask from config import Config from sqlalchemy import MetaData from", "bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as", "os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler = RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240, backupCount=10 ) file_handler.setFormatter(", "[in %(pathname)s:%(lineno)d]\" ) ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info(\"Moviedb startup\") return", "bootstrap = Bootstrap() def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app)", "os import logging from logging.handlers import RotatingFileHandler from elasticsearch import", "app.register_blueprint(cli_bp) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\ if app.config['ELASTICSEARCH_URL'] else None from", "from flask_migrate import Migrate from flask_login import LoginManager from flask_moment", "app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import", "Elasticsearch convention = { \"ix\": 'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\",", "\"pk_%(table_name)s\" } metadata = MetaData(naming_convention=convention) db = SQLAlchemy(metadata=metadata) migrate =", "if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db)", "from sqlalchemy import MetaData from flask_sqlalchemy import SQLAlchemy from flask_migrate", "Migrate from flask_login import LoginManager from flask_moment import Moment from", "from logging.handlers import RotatingFileHandler from elasticsearch import Elasticsearch convention =", "= { \"ix\": 'ix_%(column_0_label)s', \"uq\": \"uq_%(table_name)s_%(column_0_name)s\", \"ck\": \"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\",", "flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import", "= SQLAlchemy(metadata=metadata) migrate = Migrate() login = LoginManager() login.login_view =", "as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp,", "None from app import models if not app.debug and not", "bp as main_bp app.register_blueprint(main_bp) from app.cli import bp as cli_bp", "app.cli import bp as cli_bp app.register_blueprint(cli_bp) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \\", "from flask import Flask from config import Config from sqlalchemy", "from app.cli import bp as cli_bp app.register_blueprint(cli_bp) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']])", "import Moment from flask_misaka import Misaka from flask_bootstrap import Bootstrap", "migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) # migrate.init_app(app, db) login.init_app(app)", "\"ck_%(table_name)s_%(constraint_name)s\", \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\", \"pk\": \"pk_%(table_name)s\" } metadata = MetaData(naming_convention=convention) db", "flask_misaka import Misaka from flask_bootstrap import Bootstrap import os import", "import RotatingFileHandler from elasticsearch import Elasticsearch convention = { \"ix\":", "import Config from sqlalchemy import MetaData from flask_sqlalchemy import SQLAlchemy", "url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) from app.cli", "not app.testing: if not os.path.exists(\"logs\"): os.mkdir(\"logs\") file_handler = RotatingFileHandler( \"logs/moviedb.log\",", "import LoginManager from flask_moment import Moment from flask_misaka import Misaka", "os.mkdir(\"logs\") file_handler = RotatingFileHandler( \"logs/moviedb.log\", maxBytes=10240, backupCount=10 ) file_handler.setFormatter( logging.Formatter(", "logging from logging.handlers import RotatingFileHandler from elasticsearch import Elasticsearch convention", "db) login.init_app(app) moment.init_app(app) md.init_app(app) bootstrap.init_app(app) from app.errors import bp as", "errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth')" ]
[ ":j + 1] = 1 break elif array[i, j] ==", "nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn) optim.step() optim.zero_grad() print(\"grad update: %s seconds\" %", "# 20M iters optim = ScheduledOptim( optimizer.Adam( filter(lambda p: p.requires_grad,", "= pi_mask(s) z_mask = generate_mask(s) z_batch = np.concatenate( [np.ones([(config.batch_size //", "0 elif pi[i, j, 0] == -2 or sum(pi[i, j,", "(y_true - y_pred) ** 2 pi_mask = convert(pi_mask) z_mask =", "range(len(array)): for j in range(len(array[i])): if j == len(array[i]) -", "= convert(np.array(s)).long() policy, v, cache = model(s_batch, tuple(cache)) def loss_policy(y_true,", "2 pi_mask = convert(pi_mask) z_mask = convert(z_mask) z = convert(z)", "- start_time)) checkpoint = {'state_dict': model.state_dict(), 'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint,", "np.pad(array, ((0, 0), (0, 1)), 'constant') return generate_mask(array) # pi_tmp", "pi[i, j, 0] == -1: # meaning the terminal state;", "count '''x = np.bincount(s_buffer[:,1].astype(int)) / 500000 for i in range(len(x)):", "num_segments = 8 for i in range(num_segments): tmp.append( r[(config.batch_size //", "cache += [torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch = convert(np.array(s)).long() policy,", "(config.batch_size // 2), replace=False)) else: r = np.sort( np.random.choice(list(range(0, cur_row)),", "j in range(config.max_length): if pi[i, j, 0] == -1: #", "-1: # meaning the terminal state; pi=0 new_pi[i, j, :]", "cache = [] for i in range(config.depth // config.unit_depth): cache", "in range(len(x)): if x[i] > 0.01: print(i, x[i], translate[i]) break'''", "2), config.max_length]) * (-1), np.ones([(config.batch_size // 2), config.max_length])]) def convert(x):", "# model_ckpt = config.model_path + '/model-454.pth' print(model_ckpt) if model_ckpt: checkpoint", "in range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...]) z_tmp.append(z_buffer[tmp[i], ...]) s", "= convert(z_mask) z = convert(z) pi = convert(pi) loss =", "sleep import h5py import torch import torch.nn as nn import", "df >= 1000: print('time required for 32 self-play games: ',", "# takes about 0.005s new_pi = np.zeros(((config.batch_size // 2), config.max_length,", "optim.zero_grad() print(\"grad update: %s seconds\" % (time() - t2)) print(\"iteration:", "momentum=0.9, weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) # 20M iters", "and df >= 1000: print('time required for 32 self-play games:", "= np.sort( np.random.choice(list(range(0, cur_row)), (config.batch_size // 2), replace=False)) tmp =", "j, :]) == 0: # meaning the padding; place -1", "self-play games: ', 32 * (time() - t_inf) / df)", "randomly sample rows 8 times for a dramatic speedup. num_segments", "isn't modified here, since the mask will be modified appropriately", "required for 32 self-play games: ', 32 * (time() -", "and preparing a minibatch def generate_mask(array): new_array = np.zeros_like(array) for", "z = convert(z) pi = convert(pi) loss = torch.mean(torch.sum(loss_policy(pi, policy)", "= [] z_tmp = [] df = cur_row - count", "+ '/model' + '-' + str(iter + 1) + '.pth')", "len(array[i]) - 1: new_array[i, :] = 1 elif array[i, j]", "config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch = convert(np.array(s)).long() policy, v, cache =", "for i in range((config.batch_size // 2)): for j in range(config.max_length):", "f['/z'] s_tmp = [] pi_tmp = [] z_tmp = []", "convert(pi_mask) z_mask = convert(z_mask) z = convert(z) pi = convert(pi)", "import h5py import torch import torch.nn as nn import torch.optim", "new_pi[i, j, :] = 0 elif pi[i, j, 0] ==", "// 2), replace=False)) else: r = np.sort( np.random.choice(list(range(0, cur_row)), (config.batch_size", "2) // num_segments * (i + 1)]) for i in", "= np.bincount(s_buffer[:,1].astype(int)) / 500000 for i in range(len(x)): if x[i]", "return new_array def pi_mask(array): array = array[:, 1:] array =", "model.train() cache = [] for i in range(config.depth // config.unit_depth):", "as f: cur_row = int(f['/cur_row'][0]) s_buffer = f['/s'] pi_buffer =", "cur_row t_inf = time() if count != 0 and df", "1000: print('time required for 32 self-play games: ', 32 *", "torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch = convert(np.array(s)).long() policy, v, cache = model(s_batch,", "#optim = optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200,", "% iter) #if (iter + 1) % 100000 == 0:", "count = cur_row t_inf = time() if count != 0", "checkpoint = torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter = model_ckpt.split('-')[-1].split('.')[0] start_iter =", "1)), 'constant') return generate_mask(array) # pi_tmp isn't modified here, since", "+ 1)]) for i in range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length,", "= new_pi # creating a mask for loss function and", "generate_mask(s) z_batch = np.concatenate( [np.ones([(config.batch_size // 2), config.max_length]) * (-1),", "t_inf = time() if count != 0 and df >=", "# ~ 0.1s # TODO: if error, set a lock", "initialize from Optim import ScheduledOptim # import _pickle as cPickle", "pi's # takes about 0.005s new_pi = np.zeros(((config.batch_size // 2),", "j, :] = 0 elif pi[i, j, 0] == -2", "since the mask will be modified appropriately _, pi_mask =", "2000) list_of_files = glob.glob(config.model_path + '/*') latest_file = None if", "ScheduledOptim( optimizer.Adam( filter(lambda p: p.requires_grad, model.parameters()), lr=config.lr, betas=(0.9, 0.98), eps=1e-09),", "state; pi=0 new_pi[i, j, :] = 0 elif pi[i, j,", "# Beware that np.bincount's bin is [0,1,...min_length-1] new_pi[i, j, :]", "pi=0 new_pi[i, j, :] = 0 elif pi[i, j, 0]", "new_array def pi_mask(array): array = array[:, 1:] array = np.pad(array,", "(time() - t2)) print(\"iteration: %s seconds\" % (time() - start_time))", "for iter in range(start_iter, config.total_iterations): print('iteration: %s' % iter) #if", "+ loss_value(z, v) * z_mask , 1) / torch.sum(z_mask, 1))", "range((config.batch_size // 2)): for j in range(config.max_length): if pi[i, j,", "0 count = 0 for iter in range(start_iter, config.total_iterations): print('iteration:", ":].astype(int), minlength=config.vocab_size) / config.simulation_num_per_move pi = new_pi # creating a", "0: # meaning the padding; place -1 padding new_pi[i, j,", "f: cur_row = int(f['/cur_row'][0]) s_buffer = f['/s'] pi_buffer = f['/pi']", ":j] = 1 break return new_array def pi_mask(array): array =", "appropriately _, pi_mask = pi_mask(s) z_mask = generate_mask(s) z_batch =", "np.sort( np.random.choice(list(range(0, config.buffer_size)), (config.batch_size // 2), replace=False)) else: r =", "#from scipy.stats import rankdata from lstm import Model, initialize from", "time import time, sleep import h5py import torch import torch.nn", "torch.sum(z_mask, 1)) loss.backward() gn = nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn) optim.step() optim.zero_grad()", "// num_segments * i:(config.batch_size // 2) // num_segments * (i", "config.period_token: new_array[i, :j + 1] = 1 break elif array[i,", "== 0: # meaning the padding; place -1 padding new_pi[i,", "model_ckpt = config.model_path + '/model-454.pth' print(model_ckpt) if model_ckpt: checkpoint =", "(0, 1)), 'constant') return generate_mask(array) # pi_tmp isn't modified here,", "config.unit_depth): cache += [torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch = convert(np.array(s)).long()", "in range((config.batch_size // 2)): for j in range(config.max_length): if pi[i,", "= -1 else: # Beware that np.bincount's bin is [0,1,...min_length-1]", "j, 0] == -2 or sum(pi[i, j, :]) == 0:", "((0, 0), (0, 1)), 'constant') return generate_mask(array) # pi_tmp isn't", "', 32 * (time() - t_inf) / df) t_inf =", "place -1 padding new_pi[i, j, :] = -1 else: #", "loss_value(z, v) * z_mask , 1) / torch.sum(z_mask, 1)) loss.backward()", "8 for i in range(num_segments): tmp.append( r[(config.batch_size // 2) //", "else: model.apply(initialize) start_iter = 0 count = 0 for iter", "== 0: count = cur_row t_inf = time() if count", "_, pi_mask = pi_mask(s) z_mask = generate_mask(s) z_batch = np.concatenate(", "config.hidden_dim,device=config.device)] s_batch = convert(np.array(s)).long() policy, v, cache = model(s_batch, tuple(cache))", "translate, _ = cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with h5py.File(\"buffer\", \"r\") as f:", "* pi_mask + loss_value(z, v) * z_mask , 1) /", "latest_file = max(list_of_files, key=os.path.getctime) model_ckpt = latest_file # model_ckpt =", "checkpoint = {'state_dict': model.state_dict(), 'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path +", "return torch.tensor(x.astype(np.float32), device=config.device) t2 = time() # gradient update model.train()", "// 2), config.max_length, config.vocab_size)) for i in range((config.batch_size // 2)):", "1 break elif array[i, j] == config.blank_token: new_array[i, :j] =", "torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) # 20M iters optim = ScheduledOptim( optimizer.Adam(", "32 self-play games: ', 32 * (time() - t_inf) /", "new_array = np.zeros_like(array) for i in range(len(array)): for j in", "function and preparing a minibatch def generate_mask(array): new_array = np.zeros_like(array)", "# translate, _ = cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with h5py.File(\"buffer\", \"r\") as", "model = model.to(config.device) #optim = optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler", "optim = ScheduledOptim( optimizer.Adam( filter(lambda p: p.requires_grad, model.parameters()), lr=config.lr, betas=(0.9,", "= time() count = cur_row if cur_row >= config.buffer_size: r", "rows 8 times for a dramatic speedup. num_segments = 8", "be modified appropriately _, pi_mask = pi_mask(s) z_mask = generate_mask(s)", "= np.concatenate(s_tmp, 0) pi = np.concatenate(pi_tmp, 0) z = np.concatenate(z_tmp,", "new_array[i, :j] = 1 break return new_array def pi_mask(array): array", ", 1) / torch.sum(z_mask, 1)) loss.backward() gn = nn.utils.clip_grad_norm(model.parameters(), config.clip)", "config.buffer_size)), (config.batch_size // 2), replace=False)) else: r = np.sort( np.random.choice(list(range(0,", "convert(pi) loss = torch.mean(torch.sum(loss_policy(pi, policy) * pi_mask + loss_value(z, v)", "%s seconds\" % (time() - start_time)) checkpoint = {'state_dict': model.state_dict(),", "error, set a lock # translate, _ = cPickle.load(open('save/vocab_cotra.pkl', 'rb'))", "list_of_files: latest_file = max(list_of_files, key=os.path.getctime) model_ckpt = latest_file # model_ckpt", "j, :] = np.bincount(pi[i, j, :].astype(int), minlength=config.vocab_size) / config.simulation_num_per_move pi", "cur_row if cur_row >= config.buffer_size: r = np.sort( np.random.choice(list(range(0, config.buffer_size)),", "0 and df >= 1000: print('time required for 32 self-play", "(config.batch_size // 2), replace=False)) tmp = [] # randomly sample", "loss = torch.mean(torch.sum(loss_policy(pi, policy) * pi_mask + loss_value(z, v) *", "seconds\" % (time() - t2)) print(\"iteration: %s seconds\" % (time()", "with h5py.File(\"buffer\", \"r\") as f: cur_row = int(f['/cur_row'][0]) s_buffer =", "policy) * pi_mask + loss_value(z, v) * z_mask , 1)", "== -1: # meaning the terminal state; pi=0 new_pi[i, j,", "= max(list_of_files, key=os.path.getctime) model_ckpt = latest_file # model_ckpt = config.model_path", "- start_time) # decompresses sampled pi's # takes about 0.005s", "import numpy as np import random from time import time,", "lock # translate, _ = cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with h5py.File(\"buffer\", \"r\")", "games: ', 32 * (time() - t_inf) / df) t_inf", "np.concatenate( [np.ones([(config.batch_size // 2), config.max_length]) * (-1), np.ones([(config.batch_size // 2),", "/ df) t_inf = time() count = cur_row if cur_row", "2)): for j in range(config.max_length): if pi[i, j, 0] ==", "= config.model_path + '/model-454.pth' print(model_ckpt) if model_ckpt: checkpoint = torch.load(model_ckpt)", "// 2)): for j in range(config.max_length): if pi[i, j, 0]", "= cur_row t_inf = time() if count != 0 and", "in range(config.depth // config.unit_depth): cache += [torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)]", "optimizer.Adam( filter(lambda p: p.requires_grad, model.parameters()), lr=config.lr, betas=(0.9, 0.98), eps=1e-09), config.hidden_dim,", "optim.step() optim.zero_grad() print(\"grad update: %s seconds\" % (time() - t2))", "+= [torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch = convert(np.array(s)).long() policy, v,", "= torch.mean(torch.sum(loss_policy(pi, policy) * pi_mask + loss_value(z, v) * z_mask", "new_array[i, :] = 1 elif array[i, j] == config.period_token: new_array[i,", "model_ckpt.split('-')[-1].split('.')[0] start_iter = int(start_iter) else: model.apply(initialize) start_iter = 0 count", "cur_row = int(f['/cur_row'][0]) s_buffer = f['/s'] pi_buffer = f['/pi'] z_buffer", "1) / torch.sum(z_mask, 1)) loss.backward() gn = nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn)", "glob.glob(config.model_path + '/*') latest_file = None if list_of_files: latest_file =", "int(f['/cur_row'][0]) s_buffer = f['/s'] pi_buffer = f['/pi'] z_buffer = f['/z']", "minlength=config.vocab_size) / config.simulation_num_per_move pi = new_pi # creating a mask", "v, cache = model(s_batch, tuple(cache)) def loss_policy(y_true, y_pred): return torch.sum(-y_true", "num_segments * (i + 1)]) for i in range(num_segments): s_tmp.append(s_buffer[tmp[i],", "pi_mask + loss_value(z, v) * z_mask , 1) / torch.sum(z_mask,", ":config.max_length, ...]) z_tmp.append(z_buffer[tmp[i], ...]) s = np.concatenate(s_tmp, 0) pi =", "0.1s # TODO: if error, set a lock # translate,", "np.zeros(((config.batch_size // 2), config.max_length, config.vocab_size)) for i in range((config.batch_size //", "array[i, j] == config.period_token: new_array[i, :j + 1] = 1", "{'state_dict': model.state_dict(), 'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path + '/model' +", "for 32 self-play games: ', 32 * (time() - t_inf)", "if error, set a lock # translate, _ = cPickle.load(open('save/vocab_cotra.pkl',", "8 times for a dramatic speedup. num_segments = 8 for", "(iter + 1) % 100000 == 0: # lr_scheduler.step() start_time", "optimizer import glob import os #from scipy.stats import rankdata from", "policy, v, cache = model(s_batch, tuple(cache)) def loss_policy(y_true, y_pred): return", "s_buffer = f['/s'] pi_buffer = f['/pi'] z_buffer = f['/z'] s_tmp", "p: p.requires_grad, model.parameters()), lr=config.lr, betas=(0.9, 0.98), eps=1e-09), config.hidden_dim, 2000) list_of_files", "model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter = model_ckpt.split('-')[-1].split('.')[0] start_iter = int(start_iter) else: model.apply(initialize)", "list_of_files = glob.glob(config.model_path + '/*') latest_file = None if list_of_files:", "for i in range(len(array)): for j in range(len(array[i])): if j", "#lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) # 20M iters optim =", "optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter = model_ckpt.split('-')[-1].split('.')[0] start_iter = int(start_iter) else: model.apply(initialize) start_iter", "1.0e-8), 2) def loss_value(y_true, y_pred): return (y_true - y_pred) **", "break''' if count == 0: count = cur_row t_inf =", "a mask for loss function and preparing a minibatch def", "iter) #if (iter + 1) % 100000 == 0: #", "Optim import ScheduledOptim # import _pickle as cPickle # np.set_printoptions(threshold=np.nan)", "modified here, since the mask will be modified appropriately _,", "import random from time import time, sleep import h5py import", "config.max_length]) * (-1), np.ones([(config.batch_size // 2), config.max_length])]) def convert(x): return", "config.model_path + '/model' + '-' + str(iter + 1) +", "pi = np.concatenate(pi_tmp, 0) z = np.concatenate(z_tmp, 0) # print('io", "pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...]) z_tmp.append(z_buffer[tmp[i], ...]) s = np.concatenate(s_tmp, 0) pi", "== 0: # lr_scheduler.step() start_time = time() optim.update_learning_rate(iter) # reads", "pi[i, j, 0] == -2 or sum(pi[i, j, :]) ==", "config.vocab_size)) for i in range((config.batch_size // 2)): for j in", "will be modified appropriately _, pi_mask = pi_mask(s) z_mask =", "= np.concatenate( [np.ones([(config.batch_size // 2), config.max_length]) * (-1), np.ones([(config.batch_size //", "print(\"grad update: %s seconds\" % (time() - t2)) print(\"iteration: %s", "f['/s'] pi_buffer = f['/pi'] z_buffer = f['/z'] s_tmp = []", "= convert(pi_mask) z_mask = convert(z_mask) z = convert(z) pi =", "df = cur_row - count '''x = np.bincount(s_buffer[:,1].astype(int)) / 500000", "elif array[i, j] == config.blank_token: new_array[i, :j] = 1 break", "i in range(num_segments): tmp.append( r[(config.batch_size // 2) // num_segments *", "start_iter = int(start_iter) else: model.apply(initialize) start_iter = 0 count =", "time() if count != 0 and df >= 1000: print('time", "as optimizer import glob import os #from scipy.stats import rankdata", "j, 0] == -1: # meaning the terminal state; pi=0", "torch.sum(-y_true * torch.log(y_pred + 1.0e-8), 2) def loss_value(y_true, y_pred): return", "+ '/*') latest_file = None if list_of_files: latest_file = max(list_of_files,", "t_inf = time() count = cur_row if cur_row >= config.buffer_size:", "= nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn) optim.step() optim.zero_grad() print(\"grad update: %s seconds\"", "z_tmp = [] df = cur_row - count '''x =", "meaning the padding; place -1 padding new_pi[i, j, :] =", "* (time() - t_inf) / df) t_inf = time() count", "scipy.stats import rankdata from lstm import Model, initialize from Optim", "+ 1) % 100000 == 0: # lr_scheduler.step() start_time =", "z = np.concatenate(z_tmp, 0) # print('io time: ',time() - start_time)", "np.zeros_like(array) for i in range(len(array)): for j in range(len(array[i])): if", "1] = 1 break elif array[i, j] == config.blank_token: new_array[i,", "a dramatic speedup. num_segments = 8 for i in range(num_segments):", "loss.backward() gn = nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn) optim.step() optim.zero_grad() print(\"grad update:", "2), config.max_length])]) def convert(x): return torch.tensor(x.astype(np.float32), device=config.device) t2 = time()", "1 elif array[i, j] == config.period_token: new_array[i, :j + 1]", "np import random from time import time, sleep import h5py", "lstm import Model, initialize from Optim import ScheduledOptim # import", "if list_of_files: latest_file = max(list_of_files, key=os.path.getctime) model_ckpt = latest_file #", "100000 == 0: # lr_scheduler.step() start_time = time() optim.update_learning_rate(iter) #", "import rankdata from lstm import Model, initialize from Optim import", "32 * (time() - t_inf) / df) t_inf = time()", "time: ',time() - start_time) # decompresses sampled pi's # takes", "/ config.simulation_num_per_move pi = new_pi # creating a mask for", "bin is [0,1,...min_length-1] new_pi[i, j, :] = np.bincount(pi[i, j, :].astype(int),", "torch.tensor(x.astype(np.float32), device=config.device) t2 = time() # gradient update model.train() cache", "- y_pred) ** 2 pi_mask = convert(pi_mask) z_mask = convert(z_mask)", "import torch.nn as nn import torch.optim as optimizer import glob", "elif pi[i, j, 0] == -2 or sum(pi[i, j, :])", "[0,1,...min_length-1] new_pi[i, j, :] = np.bincount(pi[i, j, :].astype(int), minlength=config.vocab_size) /", "nn import torch.optim as optimizer import glob import os #from", "optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) #", "np.ones([(config.batch_size // 2), config.max_length])]) def convert(x): return torch.tensor(x.astype(np.float32), device=config.device) t2", "import _pickle as cPickle # np.set_printoptions(threshold=np.nan) def start(config): model =", "np.sort( np.random.choice(list(range(0, cur_row)), (config.batch_size // 2), replace=False)) tmp = []", "# meaning the terminal state; pi=0 new_pi[i, j, :] =", "// 2), config.max_length])]) def convert(x): return torch.tensor(x.astype(np.float32), device=config.device) t2 =", "model = Model(config) model = model.to(config.device) #optim = optimizer.SGD(model.parameters(), lr=2e-4,", "j] == config.period_token: new_array[i, :j + 1] = 1 break", "count == 0: count = cur_row t_inf = time() if", "convert(z_mask) z = convert(z) pi = convert(pi) loss = torch.mean(torch.sum(loss_policy(pi,", "j] == config.blank_token: new_array[i, :j] = 1 break return new_array", "or sum(pi[i, j, :]) == 0: # meaning the padding;", "cur_row >= config.buffer_size: r = np.sort( np.random.choice(list(range(0, config.buffer_size)), (config.batch_size //", "random from time import time, sleep import h5py import torch", "takes about 0.005s new_pi = np.zeros(((config.batch_size // 2), config.max_length, config.vocab_size))", "% (time() - start_time)) checkpoint = {'state_dict': model.state_dict(), 'optimizer': optim.optimizer.state_dict()}", "import os #from scipy.stats import rankdata from lstm import Model,", "<gh_stars>1-10 import numpy as np import random from time import", "[] for i in range(config.depth // config.unit_depth): cache += [torch.zeros(config.batch_size,", "if count == 0: count = cur_row t_inf = time()", "start_time)) checkpoint = {'state_dict': model.state_dict(), 'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path", "// 2) // num_segments * (i + 1)]) for i", "seconds\" % (time() - start_time)) checkpoint = {'state_dict': model.state_dict(), 'optimizer':", "0: # lr_scheduler.step() start_time = time() optim.update_learning_rate(iter) # reads the", "convert(np.array(s)).long() policy, v, cache = model(s_batch, tuple(cache)) def loss_policy(y_true, y_pred):", "= array[:, 1:] array = np.pad(array, ((0, 0), (0, 1)),", "rankdata from lstm import Model, initialize from Optim import ScheduledOptim", "start_iter = model_ckpt.split('-')[-1].split('.')[0] start_iter = int(start_iter) else: model.apply(initialize) start_iter =", "i in range(config.depth // config.unit_depth): cache += [torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size,", "decompresses sampled pi's # takes about 0.005s new_pi = np.zeros(((config.batch_size", "p.requires_grad, model.parameters()), lr=config.lr, betas=(0.9, 0.98), eps=1e-09), config.hidden_dim, 2000) list_of_files =", "r[(config.batch_size // 2) // num_segments * i:(config.batch_size // 2) //", "config.blank_token: new_array[i, :j] = 1 break return new_array def pi_mask(array):", "\"r\") as f: cur_row = int(f['/cur_row'][0]) s_buffer = f['/s'] pi_buffer", "optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path + '/model' + '-' + str(iter", "= f['/pi'] z_buffer = f['/z'] s_tmp = [] pi_tmp =", "start_time) # decompresses sampled pi's # takes about 0.005s new_pi", "TODO: if error, set a lock # translate, _ =", "minibatch def generate_mask(array): new_array = np.zeros_like(array) for i in range(len(array)):", "break elif array[i, j] == config.blank_token: new_array[i, :j] = 1", "/ 500000 for i in range(len(x)): if x[i] > 0.01:", "Beware that np.bincount's bin is [0,1,...min_length-1] new_pi[i, j, :] =", "buffer # ~ 0.1s # TODO: if error, set a", "a lock # translate, _ = cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with h5py.File(\"buffer\",", "def loss_policy(y_true, y_pred): return torch.sum(-y_true * torch.log(y_pred + 1.0e-8), 2)", "= glob.glob(config.model_path + '/*') latest_file = None if list_of_files: latest_file", "padding; place -1 padding new_pi[i, j, :] = -1 else:", "for loss function and preparing a minibatch def generate_mask(array): new_array", "= np.zeros_like(array) for i in range(len(array)): for j in range(len(array[i])):", "meaning the terminal state; pi=0 new_pi[i, j, :] = 0", "t_inf) / df) t_inf = time() count = cur_row if", "1) % 100000 == 0: # lr_scheduler.step() start_time = time()", "x[i] > 0.01: print(i, x[i], translate[i]) break''' if count ==", "for i in range(num_segments): tmp.append( r[(config.batch_size // 2) // num_segments", "glob import os #from scipy.stats import rankdata from lstm import", "y_pred) ** 2 pi_mask = convert(pi_mask) z_mask = convert(z_mask) z", "* torch.log(y_pred + 1.0e-8), 2) def loss_value(y_true, y_pred): return (y_true", "replace=False)) tmp = [] # randomly sample rows 8 times", "= 8 for i in range(num_segments): tmp.append( r[(config.batch_size // 2)", "* (i + 1)]) for i in range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length])", "as cPickle # np.set_printoptions(threshold=np.nan) def start(config): model = Model(config) model", "tmp.append( r[(config.batch_size // 2) // num_segments * i:(config.batch_size // 2)", "loss_value(y_true, y_pred): return (y_true - y_pred) ** 2 pi_mask =", "2), config.max_length, config.vocab_size)) for i in range((config.batch_size // 2)): for", "model_ckpt = latest_file # model_ckpt = config.model_path + '/model-454.pth' print(model_ckpt)", "y_pred): return (y_true - y_pred) ** 2 pi_mask = convert(pi_mask)", "iters optim = ScheduledOptim( optimizer.Adam( filter(lambda p: p.requires_grad, model.parameters()), lr=config.lr,", "new_pi = np.zeros(((config.batch_size // 2), config.max_length, config.vocab_size)) for i in", "new_pi # creating a mask for loss function and preparing", "== len(array[i]) - 1: new_array[i, :] = 1 elif array[i,", "- t2)) print(\"iteration: %s seconds\" % (time() - start_time)) checkpoint", "...]) z_tmp.append(z_buffer[tmp[i], ...]) s = np.concatenate(s_tmp, 0) pi = np.concatenate(pi_tmp,", "f['/pi'] z_buffer = f['/z'] s_tmp = [] pi_tmp = []", "from time import time, sleep import h5py import torch import", "1)]) for i in range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...])", "mask will be modified appropriately _, pi_mask = pi_mask(s) z_mask", "for i in range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...]) z_tmp.append(z_buffer[tmp[i],", "= np.concatenate(pi_tmp, 0) z = np.concatenate(z_tmp, 0) # print('io time:", "range(len(x)): if x[i] > 0.01: print(i, x[i], translate[i]) break''' if", "cache = model(s_batch, tuple(cache)) def loss_policy(y_true, y_pred): return torch.sum(-y_true *", "+ '/model-454.pth' print(model_ckpt) if model_ckpt: checkpoint = torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer'])", "r = np.sort( np.random.choice(list(range(0, cur_row)), (config.batch_size // 2), replace=False)) tmp", "= 0 for iter in range(start_iter, config.total_iterations): print('iteration: %s' %", "np.bincount(pi[i, j, :].astype(int), minlength=config.vocab_size) / config.simulation_num_per_move pi = new_pi #", "cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with h5py.File(\"buffer\", \"r\") as f: cur_row = int(f['/cur_row'][0])", "= f['/z'] s_tmp = [] pi_tmp = [] z_tmp =", "# gradient update model.train() cache = [] for i in", "the mask will be modified appropriately _, pi_mask = pi_mask(s)", "= int(f['/cur_row'][0]) s_buffer = f['/s'] pi_buffer = f['/pi'] z_buffer =", "== config.blank_token: new_array[i, :j] = 1 break return new_array def", "== config.period_token: new_array[i, :j + 1] = 1 break elif", "iter in range(start_iter, config.total_iterations): print('iteration: %s' % iter) #if (iter", "randomly sampled (s,pi,z)'s from the buffer # ~ 0.1s #", "- 1: new_array[i, :] = 1 elif array[i, j] ==", "0.005s new_pi = np.zeros(((config.batch_size // 2), config.max_length, config.vocab_size)) for i", "[] # randomly sample rows 8 times for a dramatic", "r = np.sort( np.random.choice(list(range(0, config.buffer_size)), (config.batch_size // 2), replace=False)) else:", "0) z = np.concatenate(z_tmp, 0) # print('io time: ',time() -", "optim.update_learning_rate(iter) # reads the randomly sampled (s,pi,z)'s from the buffer", "pi_tmp = [] z_tmp = [] df = cur_row -", "translate[i]) break''' if count == 0: count = cur_row t_inf", "j in range(len(array[i])): if j == len(array[i]) - 1: new_array[i,", "def convert(x): return torch.tensor(x.astype(np.float32), device=config.device) t2 = time() # gradient", "None if list_of_files: latest_file = max(list_of_files, key=os.path.getctime) model_ckpt = latest_file", "dramatic speedup. num_segments = 8 for i in range(num_segments): tmp.append(", "torch import torch.nn as nn import torch.optim as optimizer import", "Model(config) model = model.to(config.device) #optim = optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c)", "- count '''x = np.bincount(s_buffer[:,1].astype(int)) / 500000 for i in", "0) pi = np.concatenate(pi_tmp, 0) z = np.concatenate(z_tmp, 0) #", "terminal state; pi=0 new_pi[i, j, :] = 0 elif pi[i,", "...]) s = np.concatenate(s_tmp, 0) pi = np.concatenate(pi_tmp, 0) z", "in range(num_segments): tmp.append( r[(config.batch_size // 2) // num_segments * i:(config.batch_size", "print(gn) optim.step() optim.zero_grad() print(\"grad update: %s seconds\" % (time() -", "= cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with h5py.File(\"buffer\", \"r\") as f: cur_row =", "= model_ckpt.split('-')[-1].split('.')[0] start_iter = int(start_iter) else: model.apply(initialize) start_iter = 0", "count = cur_row if cur_row >= config.buffer_size: r = np.sort(", ":] = 1 elif array[i, j] == config.period_token: new_array[i, :j", "= generate_mask(s) z_batch = np.concatenate( [np.ones([(config.batch_size // 2), config.max_length]) *", "from Optim import ScheduledOptim # import _pickle as cPickle #", "= convert(pi) loss = torch.mean(torch.sum(loss_policy(pi, policy) * pi_mask + loss_value(z,", "500000 for i in range(len(x)): if x[i] > 0.01: print(i,", "'/*') latest_file = None if list_of_files: latest_file = max(list_of_files, key=os.path.getctime)", "torch.mean(torch.sum(loss_policy(pi, policy) * pi_mask + loss_value(z, v) * z_mask ,", "return generate_mask(array) # pi_tmp isn't modified here, since the mask", "def start(config): model = Model(config) model = model.to(config.device) #optim =", "// 2), config.max_length]) * (-1), np.ones([(config.batch_size // 2), config.max_length])]) def", "numpy as np import random from time import time, sleep", "if model_ckpt: checkpoint = torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter = model_ckpt.split('-')[-1].split('.')[0]", ">= config.buffer_size: r = np.sort( np.random.choice(list(range(0, config.buffer_size)), (config.batch_size // 2),", "tuple(cache)) def loss_policy(y_true, y_pred): return torch.sum(-y_true * torch.log(y_pred + 1.0e-8),", "= 1 break return new_array def pi_mask(array): array = array[:,", "return torch.sum(-y_true * torch.log(y_pred + 1.0e-8), 2) def loss_value(y_true, y_pred):", "Model, initialize from Optim import ScheduledOptim # import _pickle as", "import time, sleep import h5py import torch import torch.nn as", "creating a mask for loss function and preparing a minibatch", "the buffer # ~ 0.1s # TODO: if error, set", "range(len(array[i])): if j == len(array[i]) - 1: new_array[i, :] =", "if count != 0 and df >= 1000: print('time required", "** 2 pi_mask = convert(pi_mask) z_mask = convert(z_mask) z =", "gn = nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn) optim.step() optim.zero_grad() print(\"grad update: %s", "s = np.concatenate(s_tmp, 0) pi = np.concatenate(pi_tmp, 0) z =", "* (-1), np.ones([(config.batch_size // 2), config.max_length])]) def convert(x): return torch.tensor(x.astype(np.float32),", "tmp = [] # randomly sample rows 8 times for", "if j == len(array[i]) - 1: new_array[i, :] = 1", "modified appropriately _, pi_mask = pi_mask(s) z_mask = generate_mask(s) z_batch", "new_pi[i, j, :] = -1 else: # Beware that np.bincount's", "+ 1.0e-8), 2) def loss_value(y_true, y_pred): return (y_true - y_pred)", "20M iters optim = ScheduledOptim( optimizer.Adam( filter(lambda p: p.requires_grad, model.parameters()),", "= 1 elif array[i, j] == config.period_token: new_array[i, :j +", "array[:, 1:] array = np.pad(array, ((0, 0), (0, 1)), 'constant')", "s_batch = convert(np.array(s)).long() policy, v, cache = model(s_batch, tuple(cache)) def", "pi = convert(pi) loss = torch.mean(torch.sum(loss_policy(pi, policy) * pi_mask +", "// 2), replace=False)) tmp = [] # randomly sample rows", "cur_row)), (config.batch_size // 2), replace=False)) tmp = [] # randomly", "i in range(len(x)): if x[i] > 0.01: print(i, x[i], translate[i])", ">= 1000: print('time required for 32 self-play games: ', 32", "generate_mask(array): new_array = np.zeros_like(array) for i in range(len(array)): for j", "y_pred): return torch.sum(-y_true * torch.log(y_pred + 1.0e-8), 2) def loss_value(y_true,", "the padding; place -1 padding new_pi[i, j, :] = -1", "z_tmp.append(z_buffer[tmp[i], ...]) s = np.concatenate(s_tmp, 0) pi = np.concatenate(pi_tmp, 0)", "i in range(len(array)): for j in range(len(array[i])): if j ==", "= time() if count != 0 and df >= 1000:", "np.concatenate(z_tmp, 0) # print('io time: ',time() - start_time) # decompresses", "in range(config.max_length): if pi[i, j, 0] == -1: # meaning", "# creating a mask for loss function and preparing a", "z_buffer = f['/z'] s_tmp = [] pi_tmp = [] z_tmp", "2) def loss_value(y_true, y_pred): return (y_true - y_pred) ** 2", "'/model-454.pth' print(model_ckpt) if model_ckpt: checkpoint = torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter", "preparing a minibatch def generate_mask(array): new_array = np.zeros_like(array) for i", "= time() optim.update_learning_rate(iter) # reads the randomly sampled (s,pi,z)'s from", "new_pi[i, j, :] = np.bincount(pi[i, j, :].astype(int), minlength=config.vocab_size) / config.simulation_num_per_move", "sampled (s,pi,z)'s from the buffer # ~ 0.1s # TODO:", "= 0 elif pi[i, j, 0] == -2 or sum(pi[i,", "i:(config.batch_size // 2) // num_segments * (i + 1)]) for", "model.parameters()), lr=config.lr, betas=(0.9, 0.98), eps=1e-09), config.hidden_dim, 2000) list_of_files = glob.glob(config.model_path", "config.max_length])]) def convert(x): return torch.tensor(x.astype(np.float32), device=config.device) t2 = time() #", "np.random.choice(list(range(0, cur_row)), (config.batch_size // 2), replace=False)) tmp = [] #", "= [] for i in range(config.depth // config.unit_depth): cache +=", "# randomly sample rows 8 times for a dramatic speedup.", "'rb')) with h5py.File(\"buffer\", \"r\") as f: cur_row = int(f['/cur_row'][0]) s_buffer", "-1 else: # Beware that np.bincount's bin is [0,1,...min_length-1] new_pi[i,", "from the buffer # ~ 0.1s # TODO: if error,", "_ = cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with h5py.File(\"buffer\", \"r\") as f: cur_row", "t2)) print(\"iteration: %s seconds\" % (time() - start_time)) checkpoint =", "ScheduledOptim # import _pickle as cPickle # np.set_printoptions(threshold=np.nan) def start(config):", "time, sleep import h5py import torch import torch.nn as nn", "config.total_iterations): print('iteration: %s' % iter) #if (iter + 1) %", "',time() - start_time) # decompresses sampled pi's # takes about", "latest_file # model_ckpt = config.model_path + '/model-454.pth' print(model_ckpt) if model_ckpt:", "loss_policy(y_true, y_pred): return torch.sum(-y_true * torch.log(y_pred + 1.0e-8), 2) def", "z_mask = convert(z_mask) z = convert(z) pi = convert(pi) loss", "weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) # 20M iters optim", "1:] array = np.pad(array, ((0, 0), (0, 1)), 'constant') return", "-1 padding new_pi[i, j, :] = -1 else: # Beware", "i in range((config.batch_size // 2)): for j in range(config.max_length): if", "np.concatenate(pi_tmp, 0) z = np.concatenate(z_tmp, 0) # print('io time: ',time()", "z_mask = generate_mask(s) z_batch = np.concatenate( [np.ones([(config.batch_size // 2), config.max_length])", "+ 1] = 1 break elif array[i, j] == config.blank_token:", "for j in range(len(array[i])): if j == len(array[i]) - 1:", "= None if list_of_files: latest_file = max(list_of_files, key=os.path.getctime) model_ckpt =", "time() # gradient update model.train() cache = [] for i", "config.clip) print(gn) optim.step() optim.zero_grad() print(\"grad update: %s seconds\" % (time()", "lr_scheduler.step() start_time = time() optim.update_learning_rate(iter) # reads the randomly sampled", "generate_mask(array) # pi_tmp isn't modified here, since the mask will", "j == len(array[i]) - 1: new_array[i, :] = 1 elif", "pi_buffer = f['/pi'] z_buffer = f['/z'] s_tmp = [] pi_tmp", "times for a dramatic speedup. num_segments = 8 for i", "betas=(0.9, 0.98), eps=1e-09), config.hidden_dim, 2000) list_of_files = glob.glob(config.model_path + '/*')", "'constant') return generate_mask(array) # pi_tmp isn't modified here, since the", "torch.log(y_pred + 1.0e-8), 2) def loss_value(y_true, y_pred): return (y_true -", "% 100000 == 0: # lr_scheduler.step() start_time = time() optim.update_learning_rate(iter)", "update model.train() cache = [] for i in range(config.depth //", "= cur_row - count '''x = np.bincount(s_buffer[:,1].astype(int)) / 500000 for", "[torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch = convert(np.array(s)).long() policy, v, cache", "the randomly sampled (s,pi,z)'s from the buffer # ~ 0.1s", "0.01: print(i, x[i], translate[i]) break''' if count == 0: count", "= {'state_dict': model.state_dict(), 'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path + '/model'", "[] z_tmp = [] df = cur_row - count '''x", "= latest_file # model_ckpt = config.model_path + '/model-454.pth' print(model_ckpt) if", "padding new_pi[i, j, :] = -1 else: # Beware that", "0] == -2 or sum(pi[i, j, :]) == 0: #", "# decompresses sampled pi's # takes about 0.005s new_pi =", "s_tmp = [] pi_tmp = [] z_tmp = [] df", "range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...]) z_tmp.append(z_buffer[tmp[i], ...]) s =", "range(start_iter, config.total_iterations): print('iteration: %s' % iter) #if (iter + 1)", "lr=config.lr, betas=(0.9, 0.98), eps=1e-09), config.hidden_dim, 2000) list_of_files = glob.glob(config.model_path +", "pi_mask = pi_mask(s) z_mask = generate_mask(s) z_batch = np.concatenate( [np.ones([(config.batch_size", "loss function and preparing a minibatch def generate_mask(array): new_array =", "about 0.005s new_pi = np.zeros(((config.batch_size // 2), config.max_length, config.vocab_size)) for", "for i in range(len(x)): if x[i] > 0.01: print(i, x[i],", "print(i, x[i], translate[i]) break''' if count == 0: count =", "0] == -1: # meaning the terminal state; pi=0 new_pi[i,", "= np.zeros(((config.batch_size // 2), config.max_length, config.vocab_size)) for i in range((config.batch_size", "start_iter = 0 count = 0 for iter in range(start_iter,", "2), replace=False)) else: r = np.sort( np.random.choice(list(range(0, cur_row)), (config.batch_size //", "i in range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...]) z_tmp.append(z_buffer[tmp[i], ...])", "- t_inf) / df) t_inf = time() count = cur_row", "sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path + '/model' + '-' + str(iter +", "gradient update model.train() cache = [] for i in range(config.depth", "v) * z_mask , 1) / torch.sum(z_mask, 1)) loss.backward() gn", "range(num_segments): tmp.append( r[(config.batch_size // 2) // num_segments * i:(config.batch_size //", "time() optim.update_learning_rate(iter) # reads the randomly sampled (s,pi,z)'s from the", "= Model(config) model = model.to(config.device) #optim = optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9,", "gamma=0.1) # 20M iters optim = ScheduledOptim( optimizer.Adam( filter(lambda p:", "h5py import torch import torch.nn as nn import torch.optim as", "os #from scipy.stats import rankdata from lstm import Model, initialize", "j, :] = -1 else: # Beware that np.bincount's bin", "break return new_array def pi_mask(array): array = array[:, 1:] array", "key=os.path.getctime) model_ckpt = latest_file # model_ckpt = config.model_path + '/model-454.pth'", ":] = 0 elif pi[i, j, 0] == -2 or", "cPickle # np.set_printoptions(threshold=np.nan) def start(config): model = Model(config) model =", ":] = -1 else: # Beware that np.bincount's bin is", "pi_mask(array): array = array[:, 1:] array = np.pad(array, ((0, 0),", "_pickle as cPickle # np.set_printoptions(threshold=np.nan) def start(config): model = Model(config)", "(i + 1)]) for i in range(num_segments): s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i],", "def pi_mask(array): array = array[:, 1:] array = np.pad(array, ((0,", "array = np.pad(array, ((0, 0), (0, 1)), 'constant') return generate_mask(array)", "2), replace=False)) tmp = [] # randomly sample rows 8", "max(list_of_files, key=os.path.getctime) model_ckpt = latest_file # model_ckpt = config.model_path +", "in range(len(array[i])): if j == len(array[i]) - 1: new_array[i, :]", "model.state_dict(), 'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path + '/model' + '-'", "z_mask , 1) / torch.sum(z_mask, 1)) loss.backward() gn = nn.utils.clip_grad_norm(model.parameters(),", "1 break return new_array def pi_mask(array): array = array[:, 1:]", "# TODO: if error, set a lock # translate, _", "array = array[:, 1:] array = np.pad(array, ((0, 0), (0,", "= model.to(config.device) #optim = optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler =", "config.max_length, config.vocab_size)) for i in range((config.batch_size // 2)): for j", "torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter = model_ckpt.split('-')[-1].split('.')[0] start_iter = int(start_iter) else:", "= np.concatenate(z_tmp, 0) # print('io time: ',time() - start_time) #", "import Model, initialize from Optim import ScheduledOptim # import _pickle", "0) # print('io time: ',time() - start_time) # decompresses sampled", "range(config.depth // config.unit_depth): cache += [torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch", "# import _pickle as cPickle # np.set_printoptions(threshold=np.nan) def start(config): model", "eps=1e-09), config.hidden_dim, 2000) list_of_files = glob.glob(config.model_path + '/*') latest_file =", "% (time() - t2)) print(\"iteration: %s seconds\" % (time() -", "import torch.optim as optimizer import glob import os #from scipy.stats", "# print('io time: ',time() - start_time) # decompresses sampled pi's", "torch.optim as optimizer import glob import os #from scipy.stats import", "set a lock # translate, _ = cPickle.load(open('save/vocab_cotra.pkl', 'rb')) with", "= f['/s'] pi_buffer = f['/pi'] z_buffer = f['/z'] s_tmp =", "0: count = cur_row t_inf = time() if count !=", "(time() - t_inf) / df) t_inf = time() count =", "array[i, j] == config.blank_token: new_array[i, :j] = 1 break return", "= time() # gradient update model.train() cache = [] for", "from lstm import Model, initialize from Optim import ScheduledOptim #", "h5py.File(\"buffer\", \"r\") as f: cur_row = int(f['/cur_row'][0]) s_buffer = f['/s']", "np.concatenate(s_tmp, 0) pi = np.concatenate(pi_tmp, 0) z = np.concatenate(z_tmp, 0)", "print(model_ckpt) if model_ckpt: checkpoint = torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter =", "cur_row - count '''x = np.bincount(s_buffer[:,1].astype(int)) / 500000 for i", "import torch import torch.nn as nn import torch.optim as optimizer", "else: r = np.sort( np.random.choice(list(range(0, cur_row)), (config.batch_size // 2), replace=False))", "= np.sort( np.random.choice(list(range(0, config.buffer_size)), (config.batch_size // 2), replace=False)) else: r", "2) // num_segments * i:(config.batch_size // 2) // num_segments *", "step_size=200, gamma=0.1) # 20M iters optim = ScheduledOptim( optimizer.Adam( filter(lambda", "= 1 break elif array[i, j] == config.blank_token: new_array[i, :j]", "// config.unit_depth): cache += [torch.zeros(config.batch_size, config.hidden_dim,device=config.device), torch.zeros(config.batch_size, config.hidden_dim,device=config.device)] s_batch =", "= [] # randomly sample rows 8 times for a", "print(\"iteration: %s seconds\" % (time() - start_time)) checkpoint = {'state_dict':", "num_segments * i:(config.batch_size // 2) // num_segments * (i +", "if pi[i, j, 0] == -1: # meaning the terminal", "config.simulation_num_per_move pi = new_pi # creating a mask for loss", "print('iteration: %s' % iter) #if (iter + 1) % 100000", "device=config.device) t2 = time() # gradient update model.train() cache =", "sample rows 8 times for a dramatic speedup. num_segments =", "%s seconds\" % (time() - t2)) print(\"iteration: %s seconds\" %", "1: new_array[i, :] = 1 elif array[i, j] == config.period_token:", "pi = new_pi # creating a mask for loss function", "(-1), np.ones([(config.batch_size // 2), config.max_length])]) def convert(x): return torch.tensor(x.astype(np.float32), device=config.device)", "convert(z) pi = convert(pi) loss = torch.mean(torch.sum(loss_policy(pi, policy) * pi_mask", "config.model_path + '/model-454.pth' print(model_ckpt) if model_ckpt: checkpoint = torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict'])", "df) t_inf = time() count = cur_row if cur_row >=", "= cur_row if cur_row >= config.buffer_size: r = np.sort( np.random.choice(list(range(0,", "for j in range(config.max_length): if pi[i, j, 0] == -1:", "# np.set_printoptions(threshold=np.nan) def start(config): model = Model(config) model = model.to(config.device)", "count != 0 and df >= 1000: print('time required for", "0.98), eps=1e-09), config.hidden_dim, 2000) list_of_files = glob.glob(config.model_path + '/*') latest_file", "for i in range(config.depth // config.unit_depth): cache += [torch.zeros(config.batch_size, config.hidden_dim,device=config.device),", "return (y_true - y_pred) ** 2 pi_mask = convert(pi_mask) z_mask", "def loss_value(y_true, y_pred): return (y_true - y_pred) ** 2 pi_mask", "= torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter = model_ckpt.split('-')[-1].split('.')[0] start_iter = int(start_iter)", "in range(len(array)): for j in range(len(array[i])): if j == len(array[i])", "!= 0 and df >= 1000: print('time required for 32", "= model(s_batch, tuple(cache)) def loss_policy(y_true, y_pred): return torch.sum(-y_true * torch.log(y_pred", "is [0,1,...min_length-1] new_pi[i, j, :] = np.bincount(pi[i, j, :].astype(int), minlength=config.vocab_size)", "update: %s seconds\" % (time() - t2)) print(\"iteration: %s seconds\"", "/ torch.sum(z_mask, 1)) loss.backward() gn = nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn) optim.step()", "0 for iter in range(start_iter, config.total_iterations): print('iteration: %s' % iter)", ":config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...]) z_tmp.append(z_buffer[tmp[i], ...]) s = np.concatenate(s_tmp, 0)", "# pi_tmp isn't modified here, since the mask will be", "np.set_printoptions(threshold=np.nan) def start(config): model = Model(config) model = model.to(config.device) #optim", "here, since the mask will be modified appropriately _, pi_mask", "as np import random from time import time, sleep import", ":]) == 0: # meaning the padding; place -1 padding", "speedup. num_segments = 8 for i in range(num_segments): tmp.append( r[(config.batch_size", "the terminal state; pi=0 new_pi[i, j, :] = 0 elif", "import glob import os #from scipy.stats import rankdata from lstm", "%s' % iter) #if (iter + 1) % 100000 ==", "= ScheduledOptim( optimizer.Adam( filter(lambda p: p.requires_grad, model.parameters()), lr=config.lr, betas=(0.9, 0.98),", "= int(start_iter) else: model.apply(initialize) start_iter = 0 count = 0", "pi_mask(s) z_mask = generate_mask(s) z_batch = np.concatenate( [np.ones([(config.batch_size // 2),", "replace=False)) else: r = np.sort( np.random.choice(list(range(0, cur_row)), (config.batch_size // 2),", "for a dramatic speedup. num_segments = 8 for i in", "model(s_batch, tuple(cache)) def loss_policy(y_true, y_pred): return torch.sum(-y_true * torch.log(y_pred +", "z_batch = np.concatenate( [np.ones([(config.batch_size // 2), config.max_length]) * (-1), np.ones([(config.batch_size", "t2 = time() # gradient update model.train() cache = []", "// num_segments * (i + 1)]) for i in range(num_segments):", "'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time) torch.save(checkpoint, config.model_path + '/model' + '-' +", "that np.bincount's bin is [0,1,...min_length-1] new_pi[i, j, :] = np.bincount(pi[i,", "0), (0, 1)), 'constant') return generate_mask(array) # pi_tmp isn't modified", "lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) # 20M", "reads the randomly sampled (s,pi,z)'s from the buffer # ~", "1)) loss.backward() gn = nn.utils.clip_grad_norm(model.parameters(), config.clip) print(gn) optim.step() optim.zero_grad() print(\"grad", "x[i], translate[i]) break''' if count == 0: count = cur_row", "new_array[i, :j + 1] = 1 break elif array[i, j]", "a minibatch def generate_mask(array): new_array = np.zeros_like(array) for i in", "if cur_row >= config.buffer_size: r = np.sort( np.random.choice(list(range(0, config.buffer_size)), (config.batch_size", "np.random.choice(list(range(0, config.buffer_size)), (config.batch_size // 2), replace=False)) else: r = np.sort(", "in range(start_iter, config.total_iterations): print('iteration: %s' % iter) #if (iter +", "-2 or sum(pi[i, j, :]) == 0: # meaning the", "np.bincount's bin is [0,1,...min_length-1] new_pi[i, j, :] = np.bincount(pi[i, j,", "time() count = cur_row if cur_row >= config.buffer_size: r =", "= np.bincount(pi[i, j, :].astype(int), minlength=config.vocab_size) / config.simulation_num_per_move pi = new_pi", "(time() - start_time)) checkpoint = {'state_dict': model.state_dict(), 'optimizer': optim.optimizer.state_dict()} sleep(config.training_sleep_time)", "filter(lambda p: p.requires_grad, model.parameters()), lr=config.lr, betas=(0.9, 0.98), eps=1e-09), config.hidden_dim, 2000)", "[] pi_tmp = [] z_tmp = [] df = cur_row", "print('io time: ',time() - start_time) # decompresses sampled pi's #", "start(config): model = Model(config) model = model.to(config.device) #optim = optimizer.SGD(model.parameters(),", "sum(pi[i, j, :]) == 0: # meaning the padding; place", "= np.pad(array, ((0, 0), (0, 1)), 'constant') return generate_mask(array) #", "def generate_mask(array): new_array = np.zeros_like(array) for i in range(len(array)): for", "model.to(config.device) #optim = optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim,", "= 0 count = 0 for iter in range(start_iter, config.total_iterations):", "~ 0.1s # TODO: if error, set a lock #", "elif array[i, j] == config.period_token: new_array[i, :j + 1] =", "as nn import torch.optim as optimizer import glob import os", "config.hidden_dim, 2000) list_of_files = glob.glob(config.model_path + '/*') latest_file = None", "config.buffer_size: r = np.sort( np.random.choice(list(range(0, config.buffer_size)), (config.batch_size // 2), replace=False))", "#if (iter + 1) % 100000 == 0: # lr_scheduler.step()", "mask for loss function and preparing a minibatch def generate_mask(array):", "* z_mask , 1) / torch.sum(z_mask, 1)) loss.backward() gn =", "* i:(config.batch_size // 2) // num_segments * (i + 1)])", "print('time required for 32 self-play games: ', 32 * (time()", "= optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1)", "if x[i] > 0.01: print(i, x[i], translate[i]) break''' if count", "count = 0 for iter in range(start_iter, config.total_iterations): print('iteration: %s'", "range(config.max_length): if pi[i, j, 0] == -1: # meaning the", "= convert(z) pi = convert(pi) loss = torch.mean(torch.sum(loss_policy(pi, policy) *", "= [] pi_tmp = [] z_tmp = [] df =", "(s,pi,z)'s from the buffer # ~ 0.1s # TODO: if", "import ScheduledOptim # import _pickle as cPickle # np.set_printoptions(threshold=np.nan) def", "[] df = cur_row - count '''x = np.bincount(s_buffer[:,1].astype(int)) /", "start_time = time() optim.update_learning_rate(iter) # reads the randomly sampled (s,pi,z)'s", "else: # Beware that np.bincount's bin is [0,1,...min_length-1] new_pi[i, j,", "= torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) # 20M iters optim = ScheduledOptim(", "latest_file = None if list_of_files: latest_file = max(list_of_files, key=os.path.getctime) model_ckpt", "torch.nn as nn import torch.optim as optimizer import glob import", "# meaning the padding; place -1 padding new_pi[i, j, :]", ":] = np.bincount(pi[i, j, :].astype(int), minlength=config.vocab_size) / config.simulation_num_per_move pi =", "// 2) // num_segments * i:(config.batch_size // 2) // num_segments", "j, :].astype(int), minlength=config.vocab_size) / config.simulation_num_per_move pi = new_pi # creating", "model.apply(initialize) start_iter = 0 count = 0 for iter in", "'''x = np.bincount(s_buffer[:,1].astype(int)) / 500000 for i in range(len(x)): if", "np.bincount(s_buffer[:,1].astype(int)) / 500000 for i in range(len(x)): if x[i] >", "pi_mask = convert(pi_mask) z_mask = convert(z_mask) z = convert(z) pi", "pi_tmp isn't modified here, since the mask will be modified", "# lr_scheduler.step() start_time = time() optim.update_learning_rate(iter) # reads the randomly", "s_tmp.append(s_buffer[tmp[i], :config.max_length]) pi_tmp.append(pi_buffer[tmp[i], :config.max_length, ...]) z_tmp.append(z_buffer[tmp[i], ...]) s = np.concatenate(s_tmp,", "= [] df = cur_row - count '''x = np.bincount(s_buffer[:,1].astype(int))", "# reads the randomly sampled (s,pi,z)'s from the buffer #", "sampled pi's # takes about 0.005s new_pi = np.zeros(((config.batch_size //", "== -2 or sum(pi[i, j, :]) == 0: # meaning", "> 0.01: print(i, x[i], translate[i]) break''' if count == 0:", "torch.save(checkpoint, config.model_path + '/model' + '-' + str(iter + 1)", "int(start_iter) else: model.apply(initialize) start_iter = 0 count = 0 for", "[np.ones([(config.batch_size // 2), config.max_length]) * (-1), np.ones([(config.batch_size // 2), config.max_length])])", "model_ckpt: checkpoint = torch.load(model_ckpt) model.load_state_dict(checkpoint['state_dict']) optim.optimizer.load_state_dict(checkpoint['optimizer']) start_iter = model_ckpt.split('-')[-1].split('.')[0] start_iter", "convert(x): return torch.tensor(x.astype(np.float32), device=config.device) t2 = time() # gradient update" ]
[ "code = '' if expression.op in ['&&', '||']: if expression.op", "expression.op in ['&&', '||']: if expression.op == '&&': code +=", "variables_name, vtypes): from expression import generate_expression c1, t1, tt1 =", "{NAMESPACE}:{f2}\\n' else: if ot == t1: code += c1 code", "= Int() if target is None or target == []:", "= generate_expression(None, expression.left, vtypes, variables_name, copy_strings, False) c2, t2, tt2", "= [get_temp() for _ in range(ot.size)] used_temps.extend(target) code = ''", "ttt in tt1: used_temps.remove(ttt) for ttt in tt2: used_temps.remove(ttt) ot", "'||']: if expression.op == '&&': code += c1 code +=", "f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close() code += f'execute unless score", "from c_int import Int from casting import cast from globals_consts", "target) code += ot.binary(expression.op, tt1, target, target) else: code +=", "+= c1 code += t1.cast(ot, tt1, target) code += c2", "in ['<', '>', '<=', '>=', '==', '!=', '&&']: rt =", "= '' if expression.op in ['&&', '||']: if expression.op ==", "target, target) else: code += c1 code += t1.cast(ot, tt1,", "code += c2 code += t2.cast(ot, tt2, target) code +=", "= generate_expression(None, expression.right, vtypes, variables_name, copy_strings, False) for ttt in", "f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close() code += f'execute if score", "expression.op == '&&': code += c1 code += t1.cast(ot, tt1,", "= ot if expression.op in ['<', '>', '<=', '>=', '==',", "None or target == []: target = [get_temp() for _", "code += ot.binary(expression.op, tt1, target, target) else: code += c1", "expression import generate_expression c1, t1, tt1 = generate_expression(None, expression.left, vtypes,", "cast(t1, t2) rt = ot if expression.op in ['<', '>',", "+= c1 code += c2 code += t2.cast(ot, tt2, target)", "get_temp, get_temp_func def binary_expression(copy_strings, expression, target, variables_name, vtypes): from expression", "function {NAMESPACE}:{f2}\\n' elif expression.op == '||': code += c1 code", "ttt in tt2: used_temps.remove(ttt) ot = cast(t1, t2) rt =", "[]: target = [get_temp() for _ in range(ot.size)] used_temps.extend(target) code", "code += t1.cast(ot, tt1, target) f2 = get_temp_func() f2h =", "['<', '>', '<=', '>=', '==', '!=', '&&']: rt = Int()", "'>', '<=', '>=', '==', '!=', '&&']: rt = Int() if", "t2, tt2 = generate_expression(None, expression.right, vtypes, variables_name, copy_strings, False) for", "casting import cast from globals_consts import NAMESPACE from temps import", "= cast(t1, t2) rt = ot if expression.op in ['<',", "= open(f'{f2}.mcfunction', 'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close() code +=", "c2 code += ot.binary(expression.op, target, tt2, target) return code, rt,", "in ['&&', '||']: if expression.op == '&&': code += c1", "used_temps.extend(target) code = '' if expression.op in ['&&', '||']: if", "c2, t2, tt2 = generate_expression(None, expression.right, vtypes, variables_name, copy_strings, False)", "used_temps.remove(ttt) for ttt in tt2: used_temps.remove(ttt) ot = cast(t1, t2)", "globals_consts import NAMESPACE from temps import used_temps, get_temp, get_temp_func def", "tt2, target) code += ot.binary(expression.op, tt1, target, target) else: code", "'' if expression.op in ['&&', '||']: if expression.op == '&&':", "{NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' else: if ot ==", "t1, tt1 = generate_expression(None, expression.left, vtypes, variables_name, copy_strings, False) c2,", "target) else: code += c1 code += t1.cast(ot, tt1, target)", "code += f'execute unless score {target[0]} {NAMESPACE} matches 0 run", "def binary_expression(copy_strings, expression, target, variables_name, vtypes): from expression import generate_expression", "ot if expression.op in ['<', '>', '<=', '>=', '==', '!=',", "f'execute unless score {target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n'", "'==', '!=', '&&']: rt = Int() if target is None", "generate_expression(None, expression.right, vtypes, variables_name, copy_strings, False) for ttt in tt1:", "+= t1.cast(ot, tt1, target) f2 = get_temp_func() f2h = open(f'{f2}.mcfunction',", "ot = cast(t1, t2) rt = ot if expression.op in", "matches 0 run function {NAMESPACE}:{f2}\\n' else: if ot == t1:", "target is None or target == []: target = [get_temp()", "target) code += c2 code += ot.binary(expression.op, target, tt2, target)", "in tt1: used_temps.remove(ttt) for ttt in tt2: used_temps.remove(ttt) ot =", "code += t1.cast(ot, tt1, target) code += c2 code +=", "for _ in range(ot.size)] used_temps.extend(target) code = '' if expression.op", "generate_expression(None, expression.left, vtypes, variables_name, copy_strings, False) c2, t2, tt2 =", "temps import used_temps, get_temp, get_temp_func def binary_expression(copy_strings, expression, target, variables_name,", "False) for ttt in tt1: used_temps.remove(ttt) for ttt in tt2:", "score {target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' else: if", "tt1, target) code += c2 code += ot.binary(expression.op, target, tt2,", "c1, t1, tt1 = generate_expression(None, expression.left, vtypes, variables_name, copy_strings, False)", "{NAMESPACE}:{f2}\\n' elif expression.op == '||': code += c1 code +=", "f2h.close() code += f'execute if score {target[0]} {NAMESPACE} matches 0", "rt = ot if expression.op in ['<', '>', '<=', '>=',", "score {target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' elif expression.op", "or target == []: target = [get_temp() for _ in", "_ in range(ot.size)] used_temps.extend(target) code = '' if expression.op in", "'!=', '&&']: rt = Int() if target is None or", "rt = Int() if target is None or target ==", "target)) f2h.close() code += f'execute if score {target[0]} {NAMESPACE} matches", "from globals_consts import NAMESPACE from temps import used_temps, get_temp, get_temp_func", "'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close() code += f'execute unless", "f2h.close() code += f'execute unless score {target[0]} {NAMESPACE} matches 0", "+= t1.cast(ot, tt1, target) code += c2 code += ot.binary(expression.op,", "= get_temp_func() f2h = open(f'{f2}.mcfunction', 'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2, target))", "expression, target, variables_name, vtypes): from expression import generate_expression c1, t1,", "used_temps, get_temp, get_temp_func def binary_expression(copy_strings, expression, target, variables_name, vtypes): from", "target = [get_temp() for _ in range(ot.size)] used_temps.extend(target) code =", "import cast from globals_consts import NAMESPACE from temps import used_temps,", "code += t2.cast(ot, tt2, target) code += ot.binary(expression.op, tt1, target,", "generate_expression c1, t1, tt1 = generate_expression(None, expression.left, vtypes, variables_name, copy_strings,", "for ttt in tt2: used_temps.remove(ttt) ot = cast(t1, t2) rt", "if expression.op in ['&&', '||']: if expression.op == '&&': code", "from temps import used_temps, get_temp, get_temp_func def binary_expression(copy_strings, expression, target,", "== '||': code += c1 code += t1.cast(ot, tt1, target)", "+= c2 code += t2.cast(ot, tt2, target) code += ot.binary(expression.op,", "import generate_expression c1, t1, tt1 = generate_expression(None, expression.left, vtypes, variables_name,", "tt2 = generate_expression(None, expression.right, vtypes, variables_name, copy_strings, False) for ttt", "else: code += c1 code += t1.cast(ot, tt1, target) code", "+= c1 code += t1.cast(ot, tt1, target) f2 = get_temp_func()", "is None or target == []: target = [get_temp() for", "unless score {target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' elif", "vtypes): from expression import generate_expression c1, t1, tt1 = generate_expression(None,", "Int from casting import cast from globals_consts import NAMESPACE from", "t1.cast(ot, tt1, target) code += c2 code += ot.binary(expression.op, target,", "if expression.op == '&&': code += c1 code += t1.cast(ot,", "target, variables_name, vtypes): from expression import generate_expression c1, t1, tt1", "tt2: used_temps.remove(ttt) ot = cast(t1, t2) rt = ot if", "in range(ot.size)] used_temps.extend(target) code = '' if expression.op in ['&&',", "{NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' elif expression.op == '||':", "t2.cast(ot, tt2, target) code += ot.binary(expression.op, tt1, target, target) else:", "ot == t1: code += c1 code += c2 code", "False) c2, t2, tt2 = generate_expression(None, expression.right, vtypes, variables_name, copy_strings,", "code += c1 code += t1.cast(ot, tt1, target) f2 =", "code += c2 code += ot.binary(expression.op, target, tt2, target) return", "import NAMESPACE from temps import used_temps, get_temp, get_temp_func def binary_expression(copy_strings,", "['&&', '||']: if expression.op == '&&': code += c1 code", "target) f2 = get_temp_func() f2h = open(f'{f2}.mcfunction', 'w') f2h.write(c2) f2h.write(t2.cast(ot,", "f2h.write(t2.cast(ot, tt2, target)) f2h.close() code += f'execute if score {target[0]}", "copy_strings, False) c2, t2, tt2 = generate_expression(None, expression.right, vtypes, variables_name,", "tt1 = generate_expression(None, expression.left, vtypes, variables_name, copy_strings, False) c2, t2,", "tt1, target) f2 = get_temp_func() f2h = open(f'{f2}.mcfunction', 'w') f2h.write(c2)", "f2 = get_temp_func() f2h = open(f'{f2}.mcfunction', 'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2,", "c2 code += t2.cast(ot, tt2, target) code += ot.binary(expression.op, tt1,", "code += f'execute if score {target[0]} {NAMESPACE} matches 0 run", "f2h = open(f'{f2}.mcfunction', 'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close() code", "import used_temps, get_temp, get_temp_func def binary_expression(copy_strings, expression, target, variables_name, vtypes):", "from expression import generate_expression c1, t1, tt1 = generate_expression(None, expression.left,", "elif expression.op == '||': code += c1 code += t1.cast(ot,", "get_temp_func() f2h = open(f'{f2}.mcfunction', 'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close()", "used_temps.remove(ttt) ot = cast(t1, t2) rt = ot if expression.op", "cast from globals_consts import NAMESPACE from temps import used_temps, get_temp,", "Int() if target is None or target == []: target", "{target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' elif expression.op ==", "0 run function {NAMESPACE}:{f2}\\n' elif expression.op == '||': code +=", "+= t2.cast(ot, tt2, target) code += ot.binary(expression.op, tt1, target, target)", "expression.right, vtypes, variables_name, copy_strings, False) for ttt in tt1: used_temps.remove(ttt)", "+= ot.binary(expression.op, tt1, target, target) else: code += c1 code", "'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close() code += f'execute if", "if score {target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' else:", "vtypes, variables_name, copy_strings, False) for ttt in tt1: used_temps.remove(ttt) for", "else: if ot == t1: code += c1 code +=", "tt2, target)) f2h.close() code += f'execute unless score {target[0]} {NAMESPACE}", "from casting import cast from globals_consts import NAMESPACE from temps", "expression.left, vtypes, variables_name, copy_strings, False) c2, t2, tt2 = generate_expression(None,", "+= f'execute if score {target[0]} {NAMESPACE} matches 0 run function", "tt1: used_temps.remove(ttt) for ttt in tt2: used_temps.remove(ttt) ot = cast(t1,", "t1.cast(ot, tt1, target) f2 = get_temp_func() f2h = open(f'{f2}.mcfunction', 'w')", "function {NAMESPACE}:{f2}\\n' else: if ot == t1: code += c1", "[get_temp() for _ in range(ot.size)] used_temps.extend(target) code = '' if", "target)) f2h.close() code += f'execute unless score {target[0]} {NAMESPACE} matches", "'<=', '>=', '==', '!=', '&&']: rt = Int() if target", "NAMESPACE from temps import used_temps, get_temp, get_temp_func def binary_expression(copy_strings, expression,", "tt1, target, target) else: code += c1 code += t1.cast(ot,", "if expression.op in ['<', '>', '<=', '>=', '==', '!=', '&&']:", "== '&&': code += c1 code += t1.cast(ot, tt1, target)", "'&&']: rt = Int() if target is None or target", "vtypes, variables_name, copy_strings, False) c2, t2, tt2 = generate_expression(None, expression.right,", "== []: target = [get_temp() for _ in range(ot.size)] used_temps.extend(target)", "range(ot.size)] used_temps.extend(target) code = '' if expression.op in ['&&', '||']:", "t2) rt = ot if expression.op in ['<', '>', '<=',", "{target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n' else: if ot", "open(f'{f2}.mcfunction', 'w') f2h.write(c2) f2h.write(t2.cast(ot, tt2, target)) f2h.close() code += f'execute", "c1 code += t1.cast(ot, tt1, target) code += c2 code", "copy_strings, False) for ttt in tt1: used_temps.remove(ttt) for ttt in", "c1 code += t1.cast(ot, tt1, target) f2 = get_temp_func() f2h", "c_int import Int from casting import cast from globals_consts import", "'&&': code += c1 code += t1.cast(ot, tt1, target) f2", "expression.op == '||': code += c1 code += t1.cast(ot, tt1,", "target == []: target = [get_temp() for _ in range(ot.size)]", "if target is None or target == []: target =", "0 run function {NAMESPACE}:{f2}\\n' else: if ot == t1: code", "== t1: code += c1 code += c2 code +=", "variables_name, copy_strings, False) c2, t2, tt2 = generate_expression(None, expression.right, vtypes,", "f'execute if score {target[0]} {NAMESPACE} matches 0 run function {NAMESPACE}:{f2}\\n'", "for ttt in tt1: used_temps.remove(ttt) for ttt in tt2: used_temps.remove(ttt)", "f2h.write(t2.cast(ot, tt2, target)) f2h.close() code += f'execute unless score {target[0]}", "+= c2 code += ot.binary(expression.op, target, tt2, target) return code,", "in tt2: used_temps.remove(ttt) ot = cast(t1, t2) rt = ot", "matches 0 run function {NAMESPACE}:{f2}\\n' elif expression.op == '||': code", "code += c1 code += c2 code += t2.cast(ot, tt2,", "code += ot.binary(expression.op, target, tt2, target) return code, rt, target", "ot.binary(expression.op, tt1, target, target) else: code += c1 code +=", "binary_expression(copy_strings, expression, target, variables_name, vtypes): from expression import generate_expression c1,", "'||': code += c1 code += t1.cast(ot, tt1, target) f2", "get_temp_func def binary_expression(copy_strings, expression, target, variables_name, vtypes): from expression import", "import Int from casting import cast from globals_consts import NAMESPACE", "tt2, target)) f2h.close() code += f'execute if score {target[0]} {NAMESPACE}", "c1 code += c2 code += t2.cast(ot, tt2, target) code", "expression.op in ['<', '>', '<=', '>=', '==', '!=', '&&']: rt", "'>=', '==', '!=', '&&']: rt = Int() if target is", "t1: code += c1 code += c2 code += t2.cast(ot,", "code += c1 code += t1.cast(ot, tt1, target) code +=", "+= f'execute unless score {target[0]} {NAMESPACE} matches 0 run function", "run function {NAMESPACE}:{f2}\\n' elif expression.op == '||': code += c1", "variables_name, copy_strings, False) for ttt in tt1: used_temps.remove(ttt) for ttt", "if ot == t1: code += c1 code += c2", "run function {NAMESPACE}:{f2}\\n' else: if ot == t1: code +=" ]
[ "break for line in in_file: if re.match(\"Contents of section .text:\",", "i = 0 except KeyError: pass if ((i % 4)", "opts: if o in (\"-h\", \"--help\"): usage() sys.exit() elif o", "except: print >> sys.stderr, \"#error: can't create file: %s\" %", "sym[addr]) i = 0 except KeyError: pass if ((i %", "can't open file: '%s'\" % in_fname sys.exit(1) try: c_file =", "usage() sys.exit() elif o in (\"-o\", \"--output\"): out_fname = a", "a ) i = i + 1; addr = addr", "sys.stderr, \"\" print >> sys.stderr, \"#error:\", msg usage() sys.exit(2) def", "basename + '.' + 'c' dirname, fname = os.path.split(out_fname) basename,", "can't create file: %s\" % hdr_fname sys.exit(1) i = 0", "c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\") addr = 0 i = 0", "try: out_fname except NameError: dirname, fname = os.path.split(in_fname) basename, extension", "0: error(\"missing fname\") if len(args) > 1: error(\"too many arguments\")", "def error(msg): print >> sys.stderr, \"\" print >> sys.stderr, \"#error:\",", "b + a ) i = i + 1; addr", "of section .text:\", line): break token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\")", "try: opts, args = getopt(sys.argv[1:], \"ho:\", \\ [\"help\", \"output=\"]) except", "--help show this help message and exit\" print >> sys.stderr,", "% out_fname sys.exit(1) try: h_file = open(hdr_fname, mode='w') except: print", "\"unhandled option\" if len(args) == 0: error(\"missing fname\") if len(args)", "mk_codelet(in_fname, out_fname, hdr_fname): try: in_file = open(in_fname, mode='r') except: print", "from getopt import * import sys import os import re", "for line in in_file: for a, b, c, d in", "fname\" print >> sys.stderr, \"\" print >> sys.stderr, \"Options\" print", "* import sys import os import re def usage(): global", "re.match(\"Contents of section .text:\", line): break token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include", "in (\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"):", "'.' + 'c' dirname, fname = os.path.split(out_fname) basename, extension =", "m = s_pat.findall(line) if m: addr = int(m[0][0], 16) name", "* from getopt import * import sys import os import", "error(str(err)) for o, a in opts: if o in (\"-h\",", "print >> sys.stderr, \"#error: can't create file: %s\" % out_fname", "sys.stderr, \"#error:\", msg usage() sys.exit(2) def mk_codelet(in_fname, out_fname, hdr_fname): try:", ">> sys.stderr, \"#error: can't create file: %s\" % out_fname sys.exit(1)", "error(\"missing fname\") if len(args) > 1: error(\"too many arguments\") in_fname", "if m: addr = int(m[0][0], 16) name = m[0][1] sym[addr]", "== 0): if (i > 0): c_file.write(\",\") c_file.write(\"\\n\\t0x\" + d", "break s_pat = re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym = {} for", "0x\" + d + c + b + a )", "sys.argv[0] try: opts, args = getopt(sys.argv[1:], \"ho:\", \\ [\"help\", \"output=\"])", ">> sys.stderr, \" Usage:\", progname, \"[options] fname\" print >> sys.stderr,", "struct import * from getopt import * import sys import", "(\"-o\", \"--output\"): out_fname = a else: assert False, \"unhandled option\"", "os.path.splitext(fname) hdr_fname = basename + '.' + 'h' mk_codelet(in_fname, out_fname,", "a in opts: if o in (\"-h\", \"--help\"): usage() sys.exit()", "if re.match(\"SYMBOL TABLE:\", line): break s_pat = re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\")", "'c' dirname, fname = os.path.split(out_fname) basename, extension = os.path.splitext(fname) hdr_fname", "dirname, fname = os.path.split(out_fname) basename, extension = os.path.splitext(fname) hdr_fname =", "= basename + '.' + 'h' mk_codelet(in_fname, out_fname, hdr_fname) if", "c, d in token_pat.findall(line): try: sym[addr] if (i > 0):", "except: print >> sys.stderr, \"#error: can't open file: '%s'\" %", "out_fname = a else: assert False, \"unhandled option\" if len(args)", "+ 'h' mk_codelet(in_fname, out_fname, hdr_fname) if __name__ == \"__main__\": main()", "..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym = {} for line in in_file: m", "open(out_fname, mode='w') except: print >> sys.stderr, \"#error: can't create file:", "0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t %s[] = {\" % sym[addr]) h_file.write(\"extern", "= 0 for line in in_file: if re.match(\"SYMBOL TABLE:\", line):", "else: assert False, \"unhandled option\" if len(args) == 0: error(\"missing", "+ d + c + b + a) else: c_file.write(\",", "([.A-Za-z_][A-Za-z_0-9]*)\") sym = {} for line in in_file: m =", "h_file.write(\"extern const uint32_t %s[];\\n\\n\" % sym[addr]) i = 0 except", "const uint32_t %s[];\\n\\n\" % sym[addr]) i = 0 except KeyError:", "a) else: c_file.write(\", 0x\" + d + c + b", "in_fname = args[0] try: out_fname except NameError: dirname, fname =", "out_fname except NameError: dirname, fname = os.path.split(in_fname) basename, extension =", "+ 'c' dirname, fname = os.path.split(out_fname) basename, extension = os.path.splitext(fname)", "% 4) == 0): if (i > 0): c_file.write(\",\") c_file.write(\"\\n\\t0x\"", "getopt(sys.argv[1:], \"ho:\", \\ [\"help\", \"output=\"]) except GetoptError, err: error(str(err)) for", "for o, a in opts: if o in (\"-h\", \"--help\"):", "name = m[0][1] sym[addr] = name else: break for line", "int(m[0][0], 16) name = m[0][1] sym[addr] = name else: break", "print >> sys.stderr, \"\" def error(msg): print >> sys.stderr, \"\"", "len(args) == 0: error(\"missing fname\") if len(args) > 1: error(\"too", "c_file.write(\",\") c_file.write(\"\\n\\t0x\" + d + c + b + a)", "try: h_file = open(hdr_fname, mode='w') except: print >> sys.stderr, \"#error:", "\"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"): out_fname =", "= name else: break for line in in_file: if re.match(\"Contents", "out_fname, hdr_fname): try: in_file = open(in_fname, mode='r') except: print >>", ">> sys.stderr, \"#error: can't open file: '%s'\" % in_fname sys.exit(1)", "= basename + '.' + 'c' dirname, fname = os.path.split(out_fname)", "print >> sys.stderr, \" -o FILENAME, --addr=FILENAME\" print >> sys.stderr,", "+ c + b + a ) i = i", "s_pat.findall(line) if m: addr = int(m[0][0], 16) name = m[0][1]", "c_file.close() h_file.close() return def main(): global progname progname = sys.argv[0]", "line in in_file: m = s_pat.findall(line) if m: addr =", "% hdr_fname sys.exit(1) i = 0 for line in in_file:", "4) == 0): if (i > 0): c_file.write(\",\") c_file.write(\"\\n\\t0x\" +", "c_file.write(\"\\n};\\n\") in_file.close() c_file.close() h_file.close() return def main(): global progname progname", "c + b + a ) i = i +", "sys import os import re def usage(): global progname print", "re.match(\"SYMBOL TABLE:\", line): break s_pat = re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym", "\"#error: can't create file: %s\" % out_fname sys.exit(1) try: h_file", "+ a ) i = i + 1; addr =", "\"Options\" print >> sys.stderr, \" -h, --help show this help", "= 0 except KeyError: pass if ((i % 4) ==", "%s[] = {\" % sym[addr]) h_file.write(\"extern const uint32_t %s[];\\n\\n\" %", "in in_file: if re.match(\"SYMBOL TABLE:\", line): break s_pat = re.compile(\"([0-9a-f]{8})", ".text:\", line): break token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\")", "o in (\"-o\", \"--output\"): out_fname = a else: assert False,", "file: %s\" % out_fname sys.exit(1) try: h_file = open(hdr_fname, mode='w')", "if o in (\"-h\", \"--help\"): usage() sys.exit() elif o in", "file: '%s'\" % in_fname sys.exit(1) try: c_file = open(out_fname, mode='w')", "0 for line in in_file: for a, b, c, d", "+ b + a ) i = i + 1;", "sys.stderr, \" Usage:\", progname, \"[options] fname\" print >> sys.stderr, \"\"", "re def usage(): global progname print >> sys.stderr, \"\" print", "in_file = open(in_fname, mode='r') except: print >> sys.stderr, \"#error: can't", "{\" % sym[addr]) h_file.write(\"extern const uint32_t %s[];\\n\\n\" % sym[addr]) i", "sym[addr]) h_file.write(\"extern const uint32_t %s[];\\n\\n\" % sym[addr]) i = 0", "+ '.' + 'c' dirname, fname = os.path.split(out_fname) basename, extension", "+ 4 c_file.write(\"\\n};\\n\") in_file.close() c_file.close() h_file.close() return def main(): global", "sym = {} for line in in_file: m = s_pat.findall(line)", "in_file: if re.match(\"SYMBOL TABLE:\", line): break s_pat = re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8}", "TABLE:\", line): break s_pat = re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym =", "4 c_file.write(\"\\n};\\n\") in_file.close() c_file.close() h_file.close() return def main(): global progname", "i = i + 1; addr = addr + 4", "(\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"): out_fname", "\"\" print >> sys.stderr, \"#error:\", msg usage() sys.exit(2) def mk_codelet(in_fname,", "i + 1; addr = addr + 4 c_file.write(\"\\n};\\n\") in_file.close()", "{} for line in in_file: m = s_pat.findall(line) if m:", "uint32_t %s[];\\n\\n\" % sym[addr]) i = 0 except KeyError: pass", "d + c + b + a) else: c_file.write(\", 0x\"", "def usage(): global progname print >> sys.stderr, \"\" print >>", "out_fname = basename + '.' + 'c' dirname, fname =", "line in in_file: if re.match(\"Contents of section .text:\", line): break", "in in_file: if re.match(\"Contents of section .text:\", line): break token_pat", "= re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\") addr = 0 i", "pass if ((i % 4) == 0): if (i >", "if ((i % 4) == 0): if (i > 0):", "\" Usage:\", progname, \"[options] fname\" print >> sys.stderr, \"\" print", "c + b + a) else: c_file.write(\", 0x\" + d", ">> sys.stderr, \"#error: can't create file: %s\" % hdr_fname sys.exit(1)", "%s\" % hdr_fname sys.exit(1) i = 0 for line in", "% sym[addr]) i = 0 except KeyError: pass if ((i", "hdr_fname = basename + '.' + 'h' mk_codelet(in_fname, out_fname, hdr_fname)", "help message and exit\" print >> sys.stderr, \" -o FILENAME,", "0 i = 0 for line in in_file: for a,", "print >> sys.stderr, \"\" print >> sys.stderr, \"Options\" print >>", "args[0] try: out_fname except NameError: dirname, fname = os.path.split(in_fname) basename,", "<stdint.h>\\n\\n\") addr = 0 i = 0 for line in", "error(msg): print >> sys.stderr, \"\" print >> sys.stderr, \"#error:\", msg", "try: sym[addr] if (i > 0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t %s[]", "opts, args = getopt(sys.argv[1:], \"ho:\", \\ [\"help\", \"output=\"]) except GetoptError,", "in token_pat.findall(line): try: sym[addr] if (i > 0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const", "getopt import * import sys import os import re def", "a else: assert False, \"unhandled option\" if len(args) == 0:", "\"[options] fname\" print >> sys.stderr, \"\" print >> sys.stderr, \"Options\"", "args = getopt(sys.argv[1:], \"ho:\", \\ [\"help\", \"output=\"]) except GetoptError, err:", "print >> sys.stderr, \" Usage:\", progname, \"[options] fname\" print >>", "msg usage() sys.exit(2) def mk_codelet(in_fname, out_fname, hdr_fname): try: in_file =", "c_file.write(\"\\n\\t0x\" + d + c + b + a) else:", ">> sys.stderr, \"Options\" print >> sys.stderr, \" -h, --help show", "exit\" print >> sys.stderr, \" -o FILENAME, --addr=FILENAME\" print >>", "this help message and exit\" print >> sys.stderr, \" -o", "0): c_file.write(\",\") c_file.write(\"\\n\\t0x\" + d + c + b +", "show this help message and exit\" print >> sys.stderr, \"", "sys.exit(1) i = 0 for line in in_file: if re.match(\"SYMBOL", "re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym = {} for line in in_file:", "addr = 0 i = 0 for line in in_file:", "many arguments\") in_fname = args[0] try: out_fname except NameError: dirname,", "a, b, c, d in token_pat.findall(line): try: sym[addr] if (i", "os import re def usage(): global progname print >> sys.stderr,", "c_file.write(\", 0x\" + d + c + b + a", "progname progname = sys.argv[0] try: opts, args = getopt(sys.argv[1:], \"ho:\",", ">> sys.stderr, \"\" def error(msg): print >> sys.stderr, \"\" print", "= i + 1; addr = addr + 4 c_file.write(\"\\n};\\n\")", "sys.exit() elif o in (\"-o\", \"--output\"): out_fname = a else:", ">> sys.stderr, \" -o FILENAME, --addr=FILENAME\" print >> sys.stderr, \"\"", "addr = addr + 4 c_file.write(\"\\n};\\n\") in_file.close() c_file.close() h_file.close() return", "else: break for line in in_file: if re.match(\"Contents of section", "= sys.argv[0] try: opts, args = getopt(sys.argv[1:], \"ho:\", \\ [\"help\",", "\"#error: can't create file: %s\" % hdr_fname sys.exit(1) i =", "import re def usage(): global progname print >> sys.stderr, \"\"", "[\"help\", \"output=\"]) except GetoptError, err: error(str(err)) for o, a in", ">> sys.stderr, \" -h, --help show this help message and", "hdr_fname sys.exit(1) i = 0 for line in in_file: if", "\\ [\"help\", \"output=\"]) except GetoptError, err: error(str(err)) for o, a", "sys.exit(1) try: h_file = open(hdr_fname, mode='w') except: print >> sys.stderr,", "out_fname sys.exit(1) try: h_file = open(hdr_fname, mode='w') except: print >>", "in in_file: m = s_pat.findall(line) if m: addr = int(m[0][0],", "import sys import os import re def usage(): global progname", "GetoptError, err: error(str(err)) for o, a in opts: if o", "fname = os.path.split(in_fname) basename, extension = os.path.splitext(fname) out_fname = basename", "error(\"too many arguments\") in_fname = args[0] try: out_fname except NameError:", "return def main(): global progname progname = sys.argv[0] try: opts,", ") i = i + 1; addr = addr +", "hdr_fname): try: in_file = open(in_fname, mode='r') except: print >> sys.stderr,", "import os import re def usage(): global progname print >>", "open(hdr_fname, mode='w') except: print >> sys.stderr, \"#error: can't create file:", "basename + '.' + 'h' mk_codelet(in_fname, out_fname, hdr_fname) if __name__", "% sym[addr]) h_file.write(\"extern const uint32_t %s[];\\n\\n\" % sym[addr]) i =", "and exit\" print >> sys.stderr, \" -o FILENAME, --addr=FILENAME\" print", "(i > 0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t %s[] = {\" %", "= os.path.split(out_fname) basename, extension = os.path.splitext(fname) hdr_fname = basename +", "line in in_file: if re.match(\"SYMBOL TABLE:\", line): break s_pat =", "sys.stderr, \"\" def error(msg): print >> sys.stderr, \"\" print >>", "open(in_fname, mode='r') except: print >> sys.stderr, \"#error: can't open file:", "if len(args) == 0: error(\"missing fname\") if len(args) > 1:", "can't create file: %s\" % out_fname sys.exit(1) try: h_file =", "import * from getopt import * import sys import os", "token_pat.findall(line): try: sym[addr] if (i > 0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t", "d in token_pat.findall(line): try: sym[addr] if (i > 0): c_file.write(\"\\n};\\n\\n\")", "16) name = m[0][1] sym[addr] = name else: break for", "sym[addr] if (i > 0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t %s[] =", "elif o in (\"-o\", \"--output\"): out_fname = a else: assert", "create file: %s\" % out_fname sys.exit(1) try: h_file = open(hdr_fname,", "d + c + b + a ) i =", "sys.stderr, \" -o FILENAME, --addr=FILENAME\" print >> sys.stderr, \"\" def", "= re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym = {} for line in", "(i > 0): c_file.write(\",\") c_file.write(\"\\n\\t0x\" + d + c +", "= int(m[0][0], 16) name = m[0][1] sym[addr] = name else:", "NameError: dirname, fname = os.path.split(in_fname) basename, extension = os.path.splitext(fname) out_fname", "-o FILENAME, --addr=FILENAME\" print >> sys.stderr, \"\" def error(msg): print", ">> sys.stderr, \"\" print >> sys.stderr, \" Usage:\", progname, \"[options]", "'%s'\" % in_fname sys.exit(1) try: c_file = open(out_fname, mode='w') except:", "fname = os.path.split(out_fname) basename, extension = os.path.splitext(fname) hdr_fname = basename", "in_fname sys.exit(1) try: c_file = open(out_fname, mode='w') except: print >>", "line): break s_pat = re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym = {}", "\"\" print >> sys.stderr, \"Options\" print >> sys.stderr, \" -h,", "in (\"-o\", \"--output\"): out_fname = a else: assert False, \"unhandled", "for line in in_file: if re.match(\"SYMBOL TABLE:\", line): break s_pat", "re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\") addr = 0 i =", "0): if (i > 0): c_file.write(\",\") c_file.write(\"\\n\\t0x\" + d +", "os.path.split(out_fname) basename, extension = os.path.splitext(fname) hdr_fname = basename + '.'", "False, \"unhandled option\" if len(args) == 0: error(\"missing fname\") if", "if (i > 0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t %s[] = {\"", "print >> sys.stderr, \" -h, --help show this help message", "sys.stderr, \"Options\" print >> sys.stderr, \" -h, --help show this", "main(): global progname progname = sys.argv[0] try: opts, args =", "in opts: if o in (\"-h\", \"--help\"): usage() sys.exit() elif", "sys.stderr, \"\" print >> sys.stderr, \"Options\" print >> sys.stderr, \"", "for line in in_file: m = s_pat.findall(line) if m: addr", "os.path.split(in_fname) basename, extension = os.path.splitext(fname) out_fname = basename + '.'", "message and exit\" print >> sys.stderr, \" -o FILENAME, --addr=FILENAME\"", "> 0): c_file.write(\",\") c_file.write(\"\\n\\t0x\" + d + c + b", "sys.exit(2) def mk_codelet(in_fname, out_fname, hdr_fname): try: in_file = open(in_fname, mode='r')", "1; addr = addr + 4 c_file.write(\"\\n};\\n\") in_file.close() c_file.close() h_file.close()", "h_file.close() return def main(): global progname progname = sys.argv[0] try:", "m[0][1] sym[addr] = name else: break for line in in_file:", "0 except KeyError: pass if ((i % 4) == 0):", "-h, --help show this help message and exit\" print >>", "assert False, \"unhandled option\" if len(args) == 0: error(\"missing fname\")", "file: %s\" % hdr_fname sys.exit(1) i = 0 for line", "print >> sys.stderr, \"\" print >> sys.stderr, \" Usage:\", progname,", "b + a) else: c_file.write(\", 0x\" + d + c", "line in in_file: for a, b, c, d in token_pat.findall(line):", "try: c_file = open(out_fname, mode='w') except: print >> sys.stderr, \"#error:", "mode='w') except: print >> sys.stderr, \"#error: can't create file: %s\"", "create file: %s\" % hdr_fname sys.exit(1) i = 0 for", "> 1: error(\"too many arguments\") in_fname = args[0] try: out_fname", "\"\" print >> sys.stderr, \" Usage:\", progname, \"[options] fname\" print", "progname = sys.argv[0] try: opts, args = getopt(sys.argv[1:], \"ho:\", \\", "\"output=\"]) except GetoptError, err: error(str(err)) for o, a in opts:", "in_file: for a, b, c, d in token_pat.findall(line): try: sym[addr]", "= 0 i = 0 for line in in_file: for", "sys.stderr, \"#error: can't create file: %s\" % out_fname sys.exit(1) try:", "in_file: m = s_pat.findall(line) if m: addr = int(m[0][0], 16)", "= {} for line in in_file: m = s_pat.findall(line) if", "m: addr = int(m[0][0], 16) name = m[0][1] sym[addr] =", "basename, extension = os.path.splitext(fname) hdr_fname = basename + '.' +", "> 0): c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t %s[] = {\" % sym[addr])", "= open(out_fname, mode='w') except: print >> sys.stderr, \"#error: can't create", "%s[];\\n\\n\" % sym[addr]) i = 0 except KeyError: pass if", "b, c, d in token_pat.findall(line): try: sym[addr] if (i >", "sys.exit(1) try: c_file = open(out_fname, mode='w') except: print >> sys.stderr,", "from struct import * from getopt import * import sys", "if (i > 0): c_file.write(\",\") c_file.write(\"\\n\\t0x\" + d + c", "for a, b, c, d in token_pat.findall(line): try: sym[addr] if", "+ c + b + a) else: c_file.write(\", 0x\" +", "sys.stderr, \" -h, --help show this help message and exit\"", "o in (\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\",", "= s_pat.findall(line) if m: addr = int(m[0][0], 16) name =", "addr + 4 c_file.write(\"\\n};\\n\") in_file.close() c_file.close() h_file.close() return def main():", "section .text:\", line): break token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include", "= m[0][1] sym[addr] = name else: break for line in", "= a else: assert False, \"unhandled option\" if len(args) ==", "fname\") if len(args) > 1: error(\"too many arguments\") in_fname =", "else: c_file.write(\", 0x\" + d + c + b +", "i = 0 for line in in_file: for a, b,", "in_file.close() c_file.close() h_file.close() return def main(): global progname progname =", "Usage:\", progname, \"[options] fname\" print >> sys.stderr, \"\" print >>", "except KeyError: pass if ((i % 4) == 0): if", "print >> sys.stderr, \"Options\" print >> sys.stderr, \" -h, --help", "+ a) else: c_file.write(\", 0x\" + d + c +", "\" -o FILENAME, --addr=FILENAME\" print >> sys.stderr, \"\" def error(msg):", "open file: '%s'\" % in_fname sys.exit(1) try: c_file = open(out_fname,", "dirname, fname = os.path.split(in_fname) basename, extension = os.path.splitext(fname) out_fname =", "sym[addr] = name else: break for line in in_file: if", "usage() sys.exit(2) def mk_codelet(in_fname, out_fname, hdr_fname): try: in_file = open(in_fname,", "= getopt(sys.argv[1:], \"ho:\", \\ [\"help\", \"output=\"]) except GetoptError, err: error(str(err))", "extension = os.path.splitext(fname) out_fname = basename + '.' + 'c'", "except GetoptError, err: error(str(err)) for o, a in opts: if", "= os.path.splitext(fname) hdr_fname = basename + '.' + 'h' mk_codelet(in_fname,", "print >> sys.stderr, \"#error:\", msg usage() sys.exit(2) def mk_codelet(in_fname, out_fname,", "\"ho:\", \\ [\"help\", \"output=\"]) except GetoptError, err: error(str(err)) for o,", "i = 0 for line in in_file: if re.match(\"SYMBOL TABLE:\",", "h_file.write(\"#include <stdint.h>\\n\\n\") addr = 0 i = 0 for line", "'.' + 'h' mk_codelet(in_fname, out_fname, hdr_fname) if __name__ == \"__main__\":", "% in_fname sys.exit(1) try: c_file = open(out_fname, mode='w') except: print", "print >> sys.stderr, \"#error: can't create file: %s\" % hdr_fname", "sys.stderr, \"#error: can't open file: '%s'\" % in_fname sys.exit(1) try:", "+ b + a) else: c_file.write(\", 0x\" + d +", "line): break token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\") addr", "\" -h, --help show this help message and exit\" print", "c_file.write(\"\\n};\\n\\n\") c_file.write(\"const uint32_t %s[] = {\" % sym[addr]) h_file.write(\"extern const", "h_file = open(hdr_fname, mode='w') except: print >> sys.stderr, \"#error: can't", "def mk_codelet(in_fname, out_fname, hdr_fname): try: in_file = open(in_fname, mode='r') except:", "+ '.' + 'h' mk_codelet(in_fname, out_fname, hdr_fname) if __name__ ==", "uint32_t %s[] = {\" % sym[addr]) h_file.write(\"extern const uint32_t %s[];\\n\\n\"", "in in_file: for a, b, c, d in token_pat.findall(line): try:", "except NameError: dirname, fname = os.path.split(in_fname) basename, extension = os.path.splitext(fname)", ">> sys.stderr, \"\" print >> sys.stderr, \"Options\" print >> sys.stderr,", "os.path.splitext(fname) out_fname = basename + '.' + 'c' dirname, fname", "= addr + 4 c_file.write(\"\\n};\\n\") in_file.close() c_file.close() h_file.close() return def", "mode='r') except: print >> sys.stderr, \"#error: can't open file: '%s'\"", "== 0: error(\"missing fname\") if len(args) > 1: error(\"too many", "global progname print >> sys.stderr, \"\" print >> sys.stderr, \"", "arguments\") in_fname = args[0] try: out_fname except NameError: dirname, fname", "<stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\") addr = 0 i = 0 for", "extension = os.path.splitext(fname) hdr_fname = basename + '.' + 'h'", "1: error(\"too many arguments\") in_fname = args[0] try: out_fname except", "global progname progname = sys.argv[0] try: opts, args = getopt(sys.argv[1:],", "0 for line in in_file: if re.match(\"SYMBOL TABLE:\", line): break", "s_pat = re.compile(\"([0-9a-f]{8}) ..*[0-9a-f]{8} ([.A-Za-z_][A-Za-z_0-9]*)\") sym = {} for line", "name else: break for line in in_file: if re.match(\"Contents of", "sys.stderr, \"\" print >> sys.stderr, \" Usage:\", progname, \"[options] fname\"", "= {\" % sym[addr]) h_file.write(\"extern const uint32_t %s[];\\n\\n\" % sym[addr])", "in_file: if re.match(\"Contents of section .text:\", line): break token_pat =", "progname print >> sys.stderr, \"\" print >> sys.stderr, \" Usage:\",", "= os.path.splitext(fname) out_fname = basename + '.' + 'c' dirname,", "usage(): global progname print >> sys.stderr, \"\" print >> sys.stderr,", "\"#error:\", msg usage() sys.exit(2) def mk_codelet(in_fname, out_fname, hdr_fname): try: in_file", "print >> sys.stderr, \"#error: can't open file: '%s'\" % in_fname", "= 0 for line in in_file: for a, b, c,", "option\" if len(args) == 0: error(\"missing fname\") if len(args) >", "+ d + c + b + a ) i", "import * import sys import os import re def usage():", "#!/usr/bin/python from struct import * from getopt import * import", "def main(): global progname progname = sys.argv[0] try: opts, args", "\"--output\"): out_fname = a else: assert False, \"unhandled option\" if", "err: error(str(err)) for o, a in opts: if o in", "print >> sys.stderr, \"\" print >> sys.stderr, \"#error:\", msg usage()", "= open(hdr_fname, mode='w') except: print >> sys.stderr, \"#error: can't create", "\"\" def error(msg): print >> sys.stderr, \"\" print >> sys.stderr,", "addr = int(m[0][0], 16) name = m[0][1] sym[addr] = name", "KeyError: pass if ((i % 4) == 0): if (i", "\"#error: can't open file: '%s'\" % in_fname sys.exit(1) try: c_file", "o, a in opts: if o in (\"-h\", \"--help\"): usage()", "<gh_stars>1-10 #!/usr/bin/python from struct import * from getopt import *", "progname, \"[options] fname\" print >> sys.stderr, \"\" print >> sys.stderr,", "c_file.write(\"const uint32_t %s[] = {\" % sym[addr]) h_file.write(\"extern const uint32_t", "+ 1; addr = addr + 4 c_file.write(\"\\n};\\n\") in_file.close() c_file.close()", "break token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\") addr =", ">> sys.stderr, \"#error:\", msg usage() sys.exit(2) def mk_codelet(in_fname, out_fname, hdr_fname):", "token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\") c_file.write(\"#include <stdint.h>\\n\\n\") h_file.write(\"#include <stdint.h>\\n\\n\") addr = 0", "for line in in_file: if re.match(\"Contents of section .text:\", line):", "try: in_file = open(in_fname, mode='r') except: print >> sys.stderr, \"#error:", "c_file = open(out_fname, mode='w') except: print >> sys.stderr, \"#error: can't", "%s\" % out_fname sys.exit(1) try: h_file = open(hdr_fname, mode='w') except:", "= open(in_fname, mode='r') except: print >> sys.stderr, \"#error: can't open", ">> sys.stderr, \"\" print >> sys.stderr, \"#error:\", msg usage() sys.exit(2)", "sys.stderr, \"#error: can't create file: %s\" % hdr_fname sys.exit(1) i", "= args[0] try: out_fname except NameError: dirname, fname = os.path.split(in_fname)", "basename, extension = os.path.splitext(fname) out_fname = basename + '.' +", "= os.path.split(in_fname) basename, extension = os.path.splitext(fname) out_fname = basename +", "((i % 4) == 0): if (i > 0): c_file.write(\",\")", "--addr=FILENAME\" print >> sys.stderr, \"\" def error(msg): print >> sys.stderr,", "len(args) > 1: error(\"too many arguments\") in_fname = args[0] try:", "if re.match(\"Contents of section .text:\", line): break token_pat = re.compile(\"([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\")", "FILENAME, --addr=FILENAME\" print >> sys.stderr, \"\" def error(msg): print >>", "if len(args) > 1: error(\"too many arguments\") in_fname = args[0]" ]
[ "in \"%s\"' % under_test.imgfolder ) def test_take_screenshot(mocker: MockerFixture, under_test: x3270):", "logger from Mainframe3270.x3270 import x3270 def test_set_screenshot_folder(under_test: x3270): path =", "def test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test: x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path = os.path.join(os.getcwd(),", "== os.getcwd() def test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test: x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path", "robot.api import logger from Mainframe3270.x3270 import x3270 def test_set_screenshot_folder(under_test: x3270):", "<reponame>MichaelSeeburger/Robot-Framework-Mainframe-3270-Library<gh_stars>1-10 import os from pytest_mock import MockerFixture from robot.api import", "os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots path \"%s\" does not exist'", "\"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots path \"%s\" does not exist' %", "'Screenshots will be saved in \"%s\"' % under_test.imgfolder ) def", "assert under_test.imgfolder == os.getcwd() def test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test: x3270): mocker.patch(\"robot.api.logger.error\")", "os from pytest_mock import MockerFixture from robot.api import logger from", "mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500, 500) logger.write.assert_called_with( '<iframe src=\"./screenshot_1000.html\" height=\"500\"", "% under_test.imgfolder ) def test_take_screenshot(mocker: MockerFixture, under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\")", "under_test: x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path = os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given", "be saved in \"%s\"' % under_test.imgfolder ) def test_take_screenshot(mocker: MockerFixture,", "MockerFixture, under_test: x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path = os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path)", "from pytest_mock import MockerFixture from robot.api import logger from Mainframe3270.x3270", "= os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder == os.getcwd() def test_set_screenshot_folder_nonexistent(mocker: MockerFixture,", "os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder == os.getcwd() def test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test:", "% path) logger.warn.assert_called_with( 'Screenshots will be saved in \"%s\"' %", "saved in \"%s\"' % under_test.imgfolder ) def test_take_screenshot(mocker: MockerFixture, under_test:", "x3270): path = os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder == os.getcwd() def", "not exist' % path) logger.warn.assert_called_with( 'Screenshots will be saved in", "import MockerFixture from robot.api import logger from Mainframe3270.x3270 import x3270", "test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test: x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path = os.path.join(os.getcwd(), \"nonexistent\")", "screenshots path \"%s\" does not exist' % path) logger.warn.assert_called_with( 'Screenshots", "under_test.imgfolder ) def test_take_screenshot(mocker: MockerFixture, under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\",", "import x3270 def test_set_screenshot_folder(under_test: x3270): path = os.getcwd() under_test.set_screenshot_folder(path) assert", "MockerFixture, under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500, 500) logger.write.assert_called_with(", "from robot.api import logger from Mainframe3270.x3270 import x3270 def test_set_screenshot_folder(under_test:", ") def test_take_screenshot(mocker: MockerFixture, under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0)", "mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500, 500) logger.write.assert_called_with( '<iframe src=\"./screenshot_1000.html\" height=\"500\" width=\"500\"></iframe>', level=\"INFO\",", "logger.warn.assert_called_with( 'Screenshots will be saved in \"%s\"' % under_test.imgfolder )", "path \"%s\" does not exist' % path) logger.warn.assert_called_with( 'Screenshots will", "path) logger.warn.assert_called_with( 'Screenshots will be saved in \"%s\"' % under_test.imgfolder", "test_set_screenshot_folder(under_test: x3270): path = os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder == os.getcwd()", "path = os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots path \"%s\" does", "from Mainframe3270.x3270 import x3270 def test_set_screenshot_folder(under_test: x3270): path = os.getcwd()", "import logger from Mainframe3270.x3270 import x3270 def test_set_screenshot_folder(under_test: x3270): path", "under_test.take_screenshot(500, 500) logger.write.assert_called_with( '<iframe src=\"./screenshot_1000.html\" height=\"500\" width=\"500\"></iframe>', level=\"INFO\", html=True, )", "return_value=1.0) under_test.take_screenshot(500, 500) logger.write.assert_called_with( '<iframe src=\"./screenshot_1000.html\" height=\"500\" width=\"500\"></iframe>', level=\"INFO\", html=True,", "mocker.patch(\"robot.api.logger.warn\") path = os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots path \"%s\"", "mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500, 500) logger.write.assert_called_with( '<iframe src=\"./screenshot_1000.html\" height=\"500\" width=\"500\"></iframe>',", "does not exist' % path) logger.warn.assert_called_with( 'Screenshots will be saved", "def test_take_screenshot(mocker: MockerFixture, under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500,", "import os from pytest_mock import MockerFixture from robot.api import logger", "under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots path \"%s\" does not exist' % path)", "exist' % path) logger.warn.assert_called_with( 'Screenshots will be saved in \"%s\"'", "def test_set_screenshot_folder(under_test: x3270): path = os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder ==", "MockerFixture from robot.api import logger from Mainframe3270.x3270 import x3270 def", "os.getcwd() def test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test: x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path =", "logger.error.assert_called_with('Given screenshots path \"%s\" does not exist' % path) logger.warn.assert_called_with(", "test_take_screenshot(mocker: MockerFixture, under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500, 500)", "\"%s\" does not exist' % path) logger.warn.assert_called_with( 'Screenshots will be", "under_test.imgfolder == os.getcwd() def test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test: x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\")", "will be saved in \"%s\"' % under_test.imgfolder ) def test_take_screenshot(mocker:", "x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500, 500) logger.write.assert_called_with( '<iframe src=\"./screenshot_1000.html\"", "path = os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder == os.getcwd() def test_set_screenshot_folder_nonexistent(mocker:", "\"%s\"' % under_test.imgfolder ) def test_take_screenshot(mocker: MockerFixture, under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\")", "under_test: x3270): mocker.patch(\"Mainframe3270.py3270.Emulator.save_screen\") mocker.patch(\"robot.api.logger.write\") mocker.patch(\"time.time\", return_value=1.0) under_test.take_screenshot(500, 500) logger.write.assert_called_with( '<iframe", "x3270): mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path = os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots", "pytest_mock import MockerFixture from robot.api import logger from Mainframe3270.x3270 import", "under_test.set_screenshot_folder(path) assert under_test.imgfolder == os.getcwd() def test_set_screenshot_folder_nonexistent(mocker: MockerFixture, under_test: x3270):", "Mainframe3270.x3270 import x3270 def test_set_screenshot_folder(under_test: x3270): path = os.getcwd() under_test.set_screenshot_folder(path)", "= os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots path \"%s\" does not", "mocker.patch(\"robot.api.logger.error\") mocker.patch(\"robot.api.logger.warn\") path = os.path.join(os.getcwd(), \"nonexistent\") under_test.set_screenshot_folder(path) logger.error.assert_called_with('Given screenshots path", "x3270 def test_set_screenshot_folder(under_test: x3270): path = os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder" ]
[ "u # standard units from astropy import constants as const", "to SED spectrum ''' pass ##################################################### ############### MAGNITUDE CLASS ###############", "def filterMag(sp,filt,*args,**kwargs): ''' :Purpose: Determine the photometric magnitude of a", "folder containing the filter transmission files **vegaFile** = 'vega_kurucz.txt': name", "sp.fluxCalibrate('2MASS J',14.5) >>> spphot.filterMag(sp,'MKO J') (14.345894376898123, 0.027596454828421831) ''' # keyword", "of filter names if isinstance(filt[0],str): for f in filt: fc", "0. dm,em = [],[] for f in list(mags1.keys()): if f", "using an Amoeba (Nelder-Mead) wrapper, and choose the closest match", "try: val.to(return_unit) err.to(return_unit) # except: # print('\\nWarning: unit {} is", "import copy import os # imports - external import numpy", "else: return output def filterProperties(filt,**kwargs): ''' :Purpose: Returns a dictionary", "pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this code compares a set of", "# Read in filter if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans =", ":Output: astropy quantity in flux density units (default = erg/cm2/s/micron)", "folder containing the filter transmission files (optional, default = splat.FILTER_FOLDER)", "isinstance(filt[0],list): xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve') legend", "val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check that requested filter is in", "return report def magToFlux(mag,filt,**kwargs): ''' :Purpose: Converts a magnitude into", "micron >>> data = splat.filterProperties('2MASS X') Filter 2MASS X not", "elif ab == True: fconst = 3631*u.jansky ftrans = (ftrans*fconst).to(u.erg/(u.cm**2", "models else: if verbose==True: print('\\nWarning: data values in range of", "SEDVisualize(verbose=True): ''' Visualizes magnitudes on SED scale (flux = lam", "units from astropy import constants as const # physical constants", "> numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: spectrum for {} does not", "filter or provided (required) :param filter: name of filter, must", "notch = kwargs.get('notch',False) base_unit = u.erg/(u.cm**2 * u.s) return_unit =", "H-band FOURSTAR H LONG: FOURSTAR H long FOURSTAR H SHORT:", "filter transmission files **vegaFile** = 'vega_kurucz.txt': name of file containing", "based on filter design if 'ab' in FILTERS[filt]['method']: ab =", "trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i in numpy.arange(nsamples): a =", "xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter", "Filter 2MASS J: 2MASS J-band Zeropoint = 1594.0 Jy Pivot", "wavelength: = {:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength: = {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point: =", "check filter and rename if necessary self.knownfilter = True fflag", "wavelengths and transmissions for a custom filter **notch** = None:", "interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result = [] if (vega): # Read in Vega", "specify AB magnitudes, photon flux or energy flux. :Required Parameters:", "k in fname: f = checkFilterName(k) if f != False:", "= False: compute energy flux **photon** = False: compute photon", "NEEDS TO BE COMPLETED else: print('passed') pass # check that", "preference) :param rsr: magnitude is on the Vega system (optional,", "e_mag=e_mag*mag.unit # check that requested filter is in list filt", "in enumerate(filt): fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if len(xra) == 0:", "not among the available filters: 2MASS H: 2MASS H-band 2MASS", "mag: magnitude on whatever system is defined for the filter", "'{}-{}'.format(self.filter,other.filter) return out def flux(self,type='fnu',samp=1000): ''' :Purpose: Report the equivalent", "**energy** = False: compute energy flux **photon** = False: compute", "density of a magnitude :Output: astropy quantity in flux density", "= copy.deepcopy(filters) wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single filter name if", "not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit # check that", "``filter`` input. By default this filter is also convolved with", "numpy.arange(nsamples): if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons): outunit =", "if len(kys) == 1: return output[kys[0]] else: return output def", "not isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem reading in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave = fwave[~numpy.isnan(ftrans)]*u.micron", "else: a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit", "Returns two arrays: the filter wavelength and filter transmission curve.", "out.magnitude = self.magnitude+other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises if", "- external import numpy from astropy import units as u", "[],[] for f in list(mags1.keys()): if f in list(mags2.keys()) and", "a notch filter (100% transmission within, 0% transmission without) **vega**", "= FILTERS[filt]['description'] report['zeropoint'] = FILTERS[filt]['zeropoint'] report['method'] = FILTERS[filt]['method'] report['rsr'] =", "of one of the predefined filters listed in splat.FILTERS.keys() (required)", "specifies the lower and upper wavelengths for a notch filter", "and {} are not the same'.format(self.filter,other.filter)) # make a copy", "filter names available **verbose** = True: List the predefined filter", "vwave = vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron))", "legend.append('Filter {}'.format(i+1)) else: raise ValueError('Could not parse input {}'.format(filt)) #", "filterMag(sp,filt,*args,**kwargs): ''' :Purpose: Determine the photometric magnitude of a source", "= {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if", "= checkFilterName(filt) if filt == False: return numpy.nan, numpy.nan #", "{}'.format(sp.name,filt)) # interpolate spectrum onto filter wavelength function wgood =", "= 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s) # calculate uncertainty if e_mag.value >", "= kwargs.get('ylabel','Transmission Curve') legend = [] fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for", "if isinstance(fwave,u.quantity.Quantity) == False: fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity) == True: ftrans=ftrans.value", "for models else: if verbose==True: print('\\nWarning: data values in range", "must be one of the specifed filters given by splat.FILTERS.keys()", "filter: required :param verbose: print out information about filter to", "* u.s * u.micron),equivalencies=u.spectral_density(fwave)) if rsr: fact = trapz(ftrans.value*fwave.value,fwave.value) else:", "= filterProfile(f,**kwargs) try: fwave = fwave.to(u.micron) except: fwave = fwave*u.micron", "**info** = False: List the predefined filter names available **verbose**", "one of the specifed filters given by splat.FILTERS.keys() :type filter:", "various statistics ''' pass def SEDFitMCMC(verbose=True): ''' this code will", "ftrans = ftrans[~numpy.isnan(ftrans)] return fwave,ftrans def filterMag(sp,filt,*args,**kwargs): ''' :Purpose: Determine", "energy flux # try: # mag.to(base_unit) # e_mag.to(base_unit) # except:", "= trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] =", "fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw)) # print(trapz(fw*ft,fw)) report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw)", "= fwave[~numpy.isnan(ftrans)] ftrans = ftrans[~numpy.isnan(ftrans)] result = [] err =", "filter; some functions may not work'.format(filt)) self.knownfilter = False else:", "= splat.FILTER_FOLDER) :Example: >>> import splat >>> import splat.photometry as", "calculate uncertainty if e_mag.value > 0.: for i in numpy.arange(nsamples):", "!= 0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val =", "('NaN','nan'), filling_values = (numpy.nan)) vwave = vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2", "== False: fname = [fname] output = {} for k", "# print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray)) if not isinstance(fwave,numpy.ndarray) or", "= trapz(ftrans.value,fwave.value) val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s) # calculate uncertainty", "photons: energy = False if energy: photons = False #", "True: List the predefined filter names available :Example: >>> import", "filter if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans = filterProfile(filt,**kwargs) # notch", "isinstance(custom,bool) and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans", "= {:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report def magToFlux(mag,filt,**kwargs): ''' :Purpose:", "**vegaFile** = 'vega_kurucz.txt': name of file containing Vega flux file,", "vega: magnitude is on the Vega system (optional, default =", "isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray)) if not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray):", "= u.erg/(u.cm**2 * u.s) return_unit = kwargs.get('unit',base_unit) e_mag = kwargs.get('uncertainty',0.)", "raise ValueError('magnitudes filters {} and {} are not the same'.format(self.filter,other.filter))", "kwargs.get('ab',True) vega = not ab if 'vega' in FILTERS[filt]['method']: vega", "self.magnitude = magnitude self.uncertainty = uncertainty self.type = magtype #", "= kwargs.get('notch',False) base_unit = u.erg/(u.cm**2 * u.s) return_unit = kwargs.get('unit',base_unit)", "energy if kwargs.get('reverse',False) == False: if vega == True: #", "a model set's SED models saves to file that could", "on top of a spectrum WARNING: THIS CODE IS CURRENTLY", "**vega** = True: compute Vega magnitudes (may be set by", "-*- from __future__ import print_function, division \"\"\" .. note:: These", "numpy.nanmax(fwave) < numpy.nanmin(sp.wave) or numpy.nanmin(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning:", "KS: 2MASS Ks-band BESSEL I: Bessel I-band FOURSTAR H: FOURSTAR", ">>> import splat >>> data = splat.filterProperties('2MASS J') Filter 2MASS", "= trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value", "[] fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans =", "ranges if numpy.nanmax(fwave) < numpy.nanmin(sp.wave) or numpy.nanmin(fwave) > numpy.nanmax(sp.wave): if", "data values in range of filter {} have no uncertainties'.format(filt))", "choose the closest match based on various statistics ''' pass", "else: fwave = fwave*wave_unit if kwargs.get('normalize',False): ftrans = ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans)", "structure for a magnitude value ''' def __init__(self, magnitude, filt,", "statistics ''' chi = 0. dm,em = [],[] for f", "= magnitude self.uncertainty = uncertainty self.type = magtype # check", "{}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000): ''' :Purpose: A representation of addition for", "= kwargs.get('wave_unit',fwave.unit) xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve')", "into an energy, and vice versa. :param mag: magnitude on", "function has been obseleted def checkFilter(filt,verbose=True): output = False f", "Vega system (optional, default = filter preference) :param units: units", "units if isinstance(fwave,u.quantity.Quantity) == True: fwave = fwave.to(u.micron) else: fwave", "of the predefined filters listed in splat.FILTERS.keys() (required) :param filterFolder:", "fwave = fwave.to(u.micron) else: fwave = fwave*u.micron # check that", "= ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if len(xra) == 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)]", "numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1+m2 out.uncertainty = numpy.nanstd(val)", "methods based on filter design if 'ab' in FILTERS[filt]['method']: ab", "system is defined for the filter or provided (required) :param", "checkFilter(filt,verbose=True): output = False f = copy.deepcopy(filt) f = f.replace('", "trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs): ''' :Purpose: Prints out the", "interpolateMagnitudes(verbose=True): ''' produces an interpolated value for a grid set", "kwargs.get('photon',photons) energy = kwargs.get('energy',False) energy = kwargs.get('flux',energy) if (photons or", "report['rsr'] = FILTERS[filt]['rsr'] fwave,ftrans = filterProfile(filt,**kwargs) try: fwave = fwave.to(u.micron)", "using one of several statistics ''' chi = 0. dm,em", "{} report['name'] = filt report['description'] = FILTERS[filt]['description'] report['zeropoint'] = FILTERS[filt]['zeropoint']", "return '{} magnitude of {}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000): ''' :Purpose: A", "output def filterProfile(filt,**kwargs): ''' :Purpose: Retrieve the filter profile for", "Parameters: **sp**: Spectrum class object, which should contain wave, flux", "if self.uncertainty != 0. and numpy.isfinite(self.uncertainty): return '{} magnitude of", "model magnitudes using an Amoeba (Nelder-Mead) wrapper, and choose the", "numerical integration from scipy.interpolate import interp1d # splat functions and", "{:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report def", "''' this will be a code that calculates a set", "fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000)", "which should contain wave, flux and noise array elements. **filter**:", "Pivot point: = 1.252 micron FWHM = 0.323 micron Wavelength", "upper wavelengths for a notch filter (100% transmission within, 0%", "rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) custom = kwargs.get('custom',False) notch", "for a model set's SED models saves to file that", "= fwave report['transmission'] = ftrans # report values out if", "= SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile','vega_kurucz.txt') vega = kwargs.get('vega',True) ab =", "by filter) **energy** = False: compute energy flux **photon** =", "report values out if kwargs.get('verbose',False): print('\\nFilter '+filt+': '+report['description']) print('Zeropoint =", "to desired energy units # try: val.to(return_unit) err.to(return_unit) # except:", "if isinstance(ftrans,u.quantity.Quantity) == True: ftrans=ftrans.value fwave = fwave[~numpy.isnan(ftrans)] ftrans =", "= (a/b * c/b).to(outunit).value for i in numpy.arange(nsamples): if rsr:", "SHORT: FOURSTAR H short ... ''' filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if", "magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty = self.uncertainty+other.uncertainty", "not the same'.format(self.filter,other.filter)) # make a copy and fill in", "True: print('filter {} is not a standard filter; some functions", "a flux unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose: Plots a filter", "filter {}: not included in SPLAT'.format(f)) else: filt.insert(len(filt),fc) if len(filt)", "'rsr' in FILTERS[filt]['method']: rsr = kwargs.get('rsr',True) # Read in filter", ":Output: A new magnitude object equal to the equivalent sum", "''' verbose = kwargs.get('verbose',True) if len(args) > 0: fname =", "(a/b * c/b).to(outunit).value for i in numpy.arange(nsamples): if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value)", "import splat >>> data = splat.filterProperties('2MASS J') Filter 2MASS J:", "return out def flux(self,type='fnu',samp=1000): ''' :Purpose: Report the equivalent flux", "astropy import units as u # standard units from astropy", "fname = list(args) elif kwargs.get('filter',False) != False: fname = kwargs['filter']", "''' pass ##################################################### ############### MAGNITUDE CLASS ############### ##################################################### class Magnitude(object):", "object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s def __repr__(self):", "False: List the predefined filter names available **verbose** = True:", "catch for models else: if verbose==True: print('\\nWarning: data values in", "FILTERS[f]['description'] output[f]['zeropoint'] = FILTERS[f]['zeropoint'] fwave,ftrans = filterProfile(f,**kwargs) try: fwave =", "name of filter, must be one of the specifed filters", "A representation of addition for magnitudes (addition of fluxes) :Output:", "coding: utf-8 -*- from __future__ import print_function, division \"\"\" ..", "**filterFolder** = splat.FILTER_FOLDER: folder containing the filter transmission files **vegaFile**", "numpy.nanmin(fwave) < numpy.nanmin(sp.wave) or numpy.nanmax(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning:", "''' # check filter agreement if self.filter != other.filter: raise", "(vega): # Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#',", "kwargs.get('notch',False) base_unit = u.erg/(u.cm**2 * u.s) return_unit = kwargs.get('unit',base_unit) e_mag", "val.to(return_unit) err.to(return_unit) # except: # print('\\nWarning: unit {} is not", "list of filter names if isinstance(filt[0],str): for f in filt:", "nu = vwave.to('Hz',equivalencies=u.spectral()) fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst", "dm = numpy.array(dm) em = numpy.array(em) offset = numpy.sum(dm/em**2)/numpy.sum (1./em**2)", "the available filters: 2MASS H: 2MASS H-band 2MASS J: 2MASS", "in filt: fc = checkFilterName(f) filt.remove(f) if fc == False:", "f in list(unc.keys()) and f not in ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f])", "i,f in enumerate(filt): fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if len(xra) ==", "some things that are based on presets if self.knownfilter ==", "the filter or provided (required) :param filter: name of filter,", "outunit = 1./u.s/u.cm**2 convert = const.h.to('erg s')*const.c.to('micron/s') val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value", "= kwargs.get('uncertainty',0.) e_mag = kwargs.get('unc',e_mag) e_mag = kwargs.get('e_mag',e_mag) if not", "report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] = numpy.min(fw) report['lambda_max']", "= [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1))", "and fill in combined magnitude out = copy.deepcopy(self) out.magnitude =", "(1./em**2) dmo = numpy.array([m-offset for m in dm]) return numpy.sum((dmo/em)**2),", "= kwargs.get('flux',energy) if (photons or energy): vega = False ab", "= trapz(ftrans.value*fwave.value,fwave.value) else: fact = trapz(ftrans.value,fwave.value) val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 *", "= kwargs.get('info',False) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) vega =", "and filter {}'.format(sp.name,filt)) return numpy.nan, numpy.nan if numpy.nanmin(fwave) < numpy.nanmin(sp.wave)", "in numpy.arange(nsamples): a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit = 1. elif", "{} Jy'.format(output[f]['zeropoint'])) print('Central wavelength: = {:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength: = {:.3f}'.format(output[f]['lambda_mean']))", "# catch for models else: if verbose==True: print('\\nWarning: data values", "fwave,ftrans = custom[0],custom[1] # units if isinstance(fwave,u.quantity.Quantity) == True: fwave", "fwave = fwave*wave_unit if kwargs.get('normalize',False): ftrans = ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if", "fwave report['transmission'] = ftrans # report values out if kwargs.get('verbose',False):", "if verbose==True: print('\\nWarning: data values in range of filter {}", "file = kwargs.get('filename',file) file = kwargs.get('output',file) if file != '':", "# magnitude -> energy if kwargs.get('reverse',False) == False: if vega", "plt.legend(legend) # save if desired file = kwargs.get('file','') file =", "the wavelengths and transmissions for a custom filter **notch** =", "optional, default = True :Example: >>> import splat >>> data", "* u.s * u.micron)) # trim spectrum vflux = vflux[vwave>=numpy.nanmin(fwave)]", "a set of magnitudes using one of several statistics '''", "= vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # trim spectrum vflux", "isinstance(filt,list): # list of filter names if isinstance(filt[0],str): for f", "contact '+EMAIL+'\\n') filterInfo() return output def filterProfile(filt,**kwargs): ''' :Purpose: Retrieve", "is an energy flux # try: # mag.to(base_unit) # e_mag.to(base_unit)", ":Purpose: Determine the photometric magnitude of a source based on", "predefined filters listed in splat.FILTERS.keys() or a custom filter name", "splat.photometry as spphot >>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',14.5)", "0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1+m2", "m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-2.5*numpy.log10(1.+10.**(-0.4*(m2-m1))) out.uncertainty = numpy.nanstd(val) return", "fluxes are convolved with the filter profile specified by the", "of model magnitudes ''' pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this code", "filt: fc = checkFilterName(f) filt.remove(f) if fc == False: if", "FILTERS[filt]['description'] report['zeropoint'] = FILTERS[filt]['zeropoint'] report['method'] = FILTERS[filt]['method'] report['rsr'] = FILTERS[filt]['rsr']", "FWHM = 0.323 micron Wavelength range = 1.066 to 1.442", "SED models saves to file that could be uploaded pre-save", "= lam x F_lam), with option of also comparing to", "code will compare a set of magnitudes to a grid", "if isinstance(filt[0],str): for f in filt: fc = checkFilterName(f) filt.remove(f)", "list of notch ranges if isinstance(filt[0],list): xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit))", "astropy.units variable; if this conversion does not work, the conversion", "0.027596454828421831) ''' # keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not", "that requested filter is in list f0 = checkFilterName(filt, verbose=True)", "a model of Vega to extract Vega magnitudes, but the", "ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))] = 1. # custom filter", "def __init__(self, magnitude, filt, uncertainty=0., magtype='apparent', verbose=False,**kwargs): self.magnitude = magnitude", "standard units from astropy import constants as const # physical", "== True: ftrans=ftrans.value fwave = fwave[~numpy.isnan(ftrans)] ftrans = ftrans[~numpy.isnan(ftrans)] result", "info = kwargs.get('info',False) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) vega", "0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] = numpy.min(fw) report['lambda_max'] = numpy.max(fw)", "MAY BE COMMON ''' filt = copy.deepcopy(filters) wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT)", "onto filter wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: val", "and transmissions for a custom filter **notch** = None: A", "{}'.format(i+1)) else: raise ValueError('Could not parse input {}'.format(filt)) # add", "source based on its spectrum. Spectral fluxes are convolved with", "output == False and verbose == True: print('\\nFilter '+filt+' not", "kwargs.get('vega',True) ab = not vega if 'rsr' in FILTERS[filt]['method']: rsr", "default = erg/cm2/s) :param verbose: print out information about filter", "noise array elements. **filter**: String giving name of filter, which", "\"\"\" # imports - internal import copy import os #", "legend = [] fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt):", "= self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty = self.uncertainty+other.uncertainty # combine noises if self.uncertainty", "missing_values = ('NaN','nan'), filling_values = (numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or", "and rename if necessary self.knownfilter = True fflag = checkFilterName(filt,verbose=verbose)", "dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave", "dmo = numpy.array([m-offset for m in dm]) return numpy.sum((dmo/em)**2), offset", "* u.s) # calculate uncertainty if e_mag.value > 0.: for", "if self.filter != other.filter: out.filter = '{}+{}'.format(self.filter,other.filter) return out def", "### ######################################### # plan: def modelMagnitudes(verbose=True): ''' this will be", "energy: photons = False # Read in filter if isinstance(custom,bool)", "verbose ==True: print(' Filter {} not in SPLAT filter list'.format(k))", "and verbose == True: print('\\nFilter '+filt+' not currently available for", "= [filt] # list of notch ranges if isinstance(filt[0],list): xl", "Magnitude object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s def", "= f0 # read in filter fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#',", "= kwargs.get('photon',photons) energy = kwargs.get('energy',False) energy = kwargs.get('flux',energy) if (photons", ">>> data = splat.filterProperties('2MASS X') Filter 2MASS X not among", "a SPLAT filter. Returns two arrays: the filter wavelength and", "missing_values = ('NaN','nan'), filling_values = (numpy.nan)) vwave = vwave[~numpy.isnan(vflux)]*u.micron vflux", "= numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] =", "fwave,ftrans def filterMag(sp,filt,*args,**kwargs): ''' :Purpose: Determine the photometric magnitude of", "ValueError filt = f0 # read in filter fwave,ftrans =", "filt = copy.deepcopy(filters) wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single filter name", "# imports - external import numpy from astropy import units", "custom[0],custom[1] # units if isinstance(fwave,u.quantity.Quantity) == True: fwave = fwave.to(u.micron)", "if verbose==True: print('Removed filter {}: not included in SPLAT'.format(f)) else:", "def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check that requested filter is in list", "**notch** = None: A 2 element array that specifies the", "> 0.01*numpy.nanmax(ftrans))] ft = ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans", "ab = not vega if 'rsr' in FILTERS[filt]['method']: rsr =", "val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i in numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if", "= False: List the predefined filter names available **verbose** =", "rsr = kwargs.get('rsr',True) # Read in filter if isinstance(custom,bool) and", "a copy and fill in combined magnitude out = copy.deepcopy(self)", "* u.micron),equivalencies=u.spectral_density(fwave)) if rsr: fact = trapz(ftrans.value*fwave.value,fwave.value) else: fact =", ".initialize import * from .utilities import * ##################################################### ############### SPECTROPHOTOMETRY", "Vega onto filter wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr:", "else: err = 0.*u.erg/(u.cm**2 * u.s) elif ab == True:", "the conversion is ignored (optional, default = erg/cm2/s) :param verbose:", "in list filt = checkFilterName(filt) if filt == False: return", "isinstance(notch,bool): fwave,ftrans = filterProfile(filt,**kwargs) # notch filter elif isinstance(custom,bool) and", "kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) custom =", "else: filt = fflag self.filter = filt # some things", "ft = ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))]", "CODE IS CURRENTLY UNDER DEVELOPMENT, BUGS MAY BE COMMON '''", "filters listed in splat.FILTERS.keys() (required) :param filterFolder: folder containing the", "fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst", "0% transmission without) **vega** = True: compute Vega magnitudes (may", "else: fwave,ftrans = custom[0],custom[1] # units if isinstance(fwave,u.quantity.Quantity) == True:", "# calculate uncertainty if e_mag.value > 0.: for i in", "a set of magnitudes to model magnitudes using an Amoeba", "to the sum of values ''' # make a copy", "FILTERS[filt]['rsr'] # Read in filter if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans", "= numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True, missing_values = ('NaN','nan'), filling_values = (numpy.nan))", "required :param verbose: print out information about filter to screen", "ftrans = ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if len(xra) == 0: xra =", "to use in Monte Carlo error estimation **info** = False:", "== False: if vega == True: # Read in Vega", "= {:.3f}'.format(report['lambda_pivot'])) print('FWHM = {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range = {:.3f} to", "and filter transmission curve. :param filter: String giving the name", "if rsr: fact = trapz(ftrans.value*fwave.value,fwave.value) else: fact = trapz(ftrans.value,fwave.value) val", "function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else:", "= not ab if 'vega' in FILTERS[filt]['method']: vega = kwargs.get('vega',True)", "else: if verbose ==True: print(' Filter {} not in SPLAT", "These are the spectrophotometry functions for SPLAT \"\"\" # imports", "u.micron)) # interpolate Vega onto filter wavelength function v =", "of values ''' # make a copy and fill in", "WARNING: THESE ARE EXPERIMENTAL!! ### ######################################### # plan: def modelMagnitudes(verbose=True):", "f.replace(' ','_').upper() for k in list(FILTERS.keys()): if f==k.upper() or f.lower()", "= kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) verbose = kwargs.get('verbose',False) # check", "print(trapz(fw*ft,fw)) report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw))", "lower and upper wavelengths for a notch filter (100% transmission", "trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value else:", "val = (a/b * c/b).to(outunit).value else: a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b", "m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-m2 out.uncertainty", "[numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr']", "splat.FILTERS.keys() :type filter: required :param verbose: print out information about", "ab method specified') # convert to desired energy units #", "representation of subtraction for Magnitude classes that takes into account", "of the specifed filters given by splat.FILTERS.keys() (required) :param reverse:", "possibilities photons = kwargs.get('photons',False) photons = kwargs.get('photon',photons) energy = kwargs.get('energy',False)", "spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'),", "True: print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra = [yra[0],yra[1]*1.1] #", "files **vegaFile** = 'vega_kurucz.txt': name of file containing Vega flux", "in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err = (numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else: err", "list(mags1.keys()): if f in list(mags2.keys()) and f in list(unc.keys()) and", "copy.deepcopy(self) out.magnitude = self.magnitude-other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises", "fwave = fwave[~numpy.isnan(ftrans)]*u.micron ftrans = ftrans[~numpy.isnan(ftrans)] return fwave,ftrans def filterMag(sp,filt,*args,**kwargs):", "vflux = vflux[vwave>=numpy.nanmin(fwave)] vwave = vwave[vwave>=numpy.nanmin(fwave)] vflux = vflux[vwave<=numpy.nanmax(fwave)] vwave", "##################################################### class Magnitude(object): ''' :Description: This is a class data", "Spectral fluxes are convolved with the filter profile specified by", "photon flux or energy flux. :Required Parameters: **sp**: Spectrum class", "J',14.5) >>> spphot.filterMag(sp,'MKO J') (14.345894376898123, 0.027596454828421831) ''' # keyword parameters", "current list of filters in the SPLAT reference library. '''", ":type verbose: optional, default = True :Example: >>> import splat", "return fig ######################################### ######## SED FITTING TOOLS ######### ### WARNING:", "not included in SPLAT'.format(f)) else: filt.insert(len(filt),fc) if len(filt) == 0:", "result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err = (numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else: err = 0.*u.erg/(u.cm**2", "filt = f0 # read in filter fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']),", "== True: fconst = 3631*u.jansky ftrans = (ftrans*fconst).to(u.erg/(u.cm**2 * u.s", "NameError('\\nfilterMag not given a correct physical quantity (vega, ab, energy,", "# read in filter fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True, missing_values", "= custom[0],custom[1] # Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile),", "H: 2MASS H-band 2MASS J: 2MASS J-band 2MASS KS: 2MASS", "filterProfile(filt,**kwargs): ''' :Purpose: Retrieve the filter profile for a SPLAT", "if photons: energy = False if energy: photons = False", "best scale factor dm = numpy.array(dm) em = numpy.array(em) offset", "filt == False: return numpy.nan, numpy.nan # reset filter calculation", "True: print('\\nFilter '+filt+' not currently available for SPLAT; contact '+EMAIL+'\\n')", "verbose== True: print('filter {} is not a standard filter; some", "self.wave,self.transmission = filterProfile(self.filter) info = filterProperties(self.filter) for k in info.keys():", "# plan: def modelMagnitudes(verbose=True): ''' this will be a code", "sp = kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum) == True: print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8))", "magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-other.magnitude out.uncertainty = self.uncertainty+other.uncertainty", "= kwargs.get('notch',False) vega = kwargs.get('vega',True) ab = kwargs.get('ab',not vega) rsr", "######################################### ######## SED FITTING TOOLS ######### ### WARNING: THESE ARE", "plan: def modelMagnitudes(verbose=True): ''' this will be a code that", "= not vega rsr = FILTERS[filt]['rsr'] # other possibilities photons", "ignored (optional, default = erg/cm2/s) :param verbose: print out information", "''' :Purpose: Make a copy of a Magnitude object '''", "fwave.to(wave_unit) else: fwave = fwave*wave_unit if kwargs.get('normalize',False): ftrans = ftrans/numpy.nanmax(ftrans)", "TO BE COMPLETED else: print('passed') pass # check that input", "fwave = fwave*u.micron # check that spectrum and filter cover", "or f.lower() in FILTERS[k]['altnames']: output = k if output ==", "filter: name of filter, must be one of the specifed", "[] if (vega): # Read in Vega spectrum vwave,vflux =", "arrays: the filter wavelength and filter transmission curve. :param filter:", "magnitude # THIS NEEDS TO BE COMPLETED else: print('passed') pass", "class data structure for a magnitude value ''' def __init__(self,", "(photons): outunit = 1./u.s/u.cm**2 convert = const.h.to('erg s')*const.c.to('micron/s') val =", "print('FWHM = {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return", "== True: print('\\nFilter '+filt+' not currently available for SPLAT; contact", "# check that requested filter is in list f0 =", "in SI units import matplotlib.patches as patches import matplotlib.pyplot as", "verbose==True: print('\\nWarning: spectrum for {} does not span full filter", "that are based on presets if self.knownfilter == True: self.wave,self.transmission", "and isinstance(notch,bool): f0 = checkFilterName(filt,verbose=True) if f0 == False: return", "check filter agreement if self.filter != other.filter: raise ValueError('magnitudes filters", "== False: return numpy.nan, numpy.nan filt = f0 rsr =", "kwargs.get('wave_unit',fwave.unit) xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve') legend", "closest match based on various statistics ''' pass def SEDFitMCMC(verbose=True):", "models saves to file that could be uploaded pre-save some", "[yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr'] == True: yl = kwargs.get('ylabel','Transmission Curve')", "numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: no overlap between spectrum for {}", "else: fname = sorted(list(FILTERS.keys())) if isinstance(fname,list) == False: fname =", "custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) vega = kwargs.get('vega',True) ab", "if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile','vega_kurucz.txt') vega", "= u.erg/u.s/u.cm**2 if rsr: a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit", "= FILTERS[filt]['zeropoint'] report['method'] = FILTERS[filt]['method'] report['rsr'] = FILTERS[filt]['rsr'] fwave,ftrans =", ":Purpose: Retrieve the filter profile for a SPLAT filter. Returns", "0: d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch for", "if numpy.nanmin(fwave) < numpy.nanmin(sp.wave) or numpy.nanmax(fwave) > numpy.nanmax(sp.wave): if verbose==True:", "wavelength ranges if numpy.nanmax(fwave) < numpy.nanmin(sp.wave) or numpy.nanmin(fwave) > numpy.nanmax(sp.wave):", "(optional, default = False) WARNING: THIS CODE IS ONLY PARTIALLY", "fwave = fwave.to(u.micron) except: fwave = fwave*u.micron fw = fwave[numpy.where(ftrans", "> 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw)", "A 2 element array that specifies the lower and upper", "model of Vega to extract Vega magnitudes, but the user", "= vflux[vwave>=numpy.nanmin(fwave)] vwave = vwave[vwave>=numpy.nanmin(fwave)] vflux = vflux[vwave<=numpy.nanmax(fwave)] vwave =", "[] err = 0. # magnitude -> energy if kwargs.get('reverse',False)", "find best scale factor dm = numpy.array(dm) em = numpy.array(em)", "if isinstance(sp,splat.core.Spectrum) == True: print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra", "the predefined filters listed in splat.FILTERS.keys() or a custom filter", "a standard filter; some functions may not work'.format(filt)) self.knownfilter =", "a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val", "b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs): ''' :Purpose: Prints", "(ftrans*fconst).to(u.erg/(u.cm**2 * u.s * u.micron),equivalencies=u.spectral_density(fwave)) if rsr: fact = trapz(ftrans.value*fwave.value,fwave.value)", "print('\\nFilter '+filt+' not currently available for SPLAT; contact '+EMAIL+'\\n') filterInfo()", "s')*const.c.to('micron/s') val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else:", "best/average/distribution of parameters ''' pass def SEDFitAmoeba(verbose=True): ''' this code", "filter design if 'ab' in FILTERS[filt]['method']: ab = kwargs.get('ab',True) vega", "range = 1.066 to 1.442 micron >>> data = splat.filterProperties('2MASS", "splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',14.5) >>> spphot.filterMag(sp,'MKO J') (14.345894376898123, 0.027596454828421831) '''", "numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True, missing_values = ('NaN','nan'), filling_values = (numpy.nan)) #", "screen :type verbose: optional, default = True :Example: >>> import", "val = numpy.nanmean(result)*outunit err = numpy.nanstd(result) if len(sp.wave[wgood]) == 0:", "in list(mags1.keys()): if f in list(mags2.keys()) and f in list(unc.keys())", "splat.FILTERS.keys() (required) :param filterFolder: folder containing the filter transmission files", "in FILTERS[filt]['method']: ab = kwargs.get('ab',True) vega = not ab if", "as patches import matplotlib.pyplot as plt from scipy.integrate import trapz", "def SEDFitMCMC(verbose=True): ''' this code will conduct a comparison of", "x F_lam), with option of also comparing to SED spectrum", "# list of notch ranges if isinstance(filt[0],int) or isinstance(filt[0],float): filt", "= False: compute AB magnitudes (may be set by filter)", "the filter transmission files (optional, default = splat.FILTER_FOLDER) :Example: >>>", "= erg/cm2/s/micron) ''' pass def addFlux(self,other,samp=1000): ''' :Purpose: A representation", "vwave[vwave>=numpy.nanmin(fwave)] vflux = vflux[vwave<=numpy.nanmax(fwave)] vwave = vwave[vwave<=numpy.nanmax(fwave)] # convert to", "numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-m2 out.uncertainty = numpy.nanstd(val)", "# custom filter else: fwave,ftrans = custom[0],custom[1] # units if", "plt from scipy.integrate import trapz # for numerical integration from", "for a particular filter. :param filter: name of filter, must", "False f = copy.deepcopy(filt) f = f.replace(' ','_').upper() for k", "interpolate spectrum onto filter wavelength function wgood = numpy.where(~numpy.isnan(sp.noise)) if", "also convolved with a model of Vega to extract Vega", "copy.deepcopy(self) out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty = self.uncertainty+other.uncertainty # combine noises", "listed in splat.FILTERS.keys() (required) :param filterFolder: folder containing the filter", "verbose ==True: print(f.replace('_',' ')+': '+output[f]['zeropoint']) print('Zeropoint = {} Jy'.format(output[f]['zeropoint'])) print('Central", "= {} Jy'.format(report['zeropoint'])) print('Pivot point: = {:.3f}'.format(report['lambda_pivot'])) print('FWHM = {:.3f}'.format(report['lambda_fwhm']))", "'{}+{}'.format(self.filter,other.filter) return out def __sub__(self,other,samp=1000): ''' :Purpose: A representation of", "predefined filters listed in splat.FILTERS.keys() (required) :param filterFolder: folder containing", "in list(FILTERS.keys()): if f==k.upper() or f.lower() in FILTERS[k]['altnames']: output =", "filter is also convolved with a model of Vega to", "BESSEL I: Bessel I-band FOURSTAR H: FOURSTAR H-band FOURSTAR H", "''' :Purpose: A representation of addition for magnitudes (addition of", "if verbose ==True: print(' Filter {} not in SPLAT filter", "output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm']", "print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra = [yra[0],yra[1]*1.1] # finish", "and isinstance(notch,bool): fwave,ftrans = filterProfile(filt,**kwargs) # notch filter elif isinstance(custom,bool)", "= kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve') legend = []", "WARNING: THIS CODE IS CURRENTLY UNDER DEVELOPMENT, BUGS MAY BE", "span full filter profile for {}'.format(sp.name,filt)) # interpolate spectrum onto", "False: return numpy.nan, numpy.nan filt = f0 rsr = FILTERS[filt]['rsr']", "(optional, default = False) :param ab: magnitude is on the", "rsr: fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact = trapz(ftrans*v(fwave.value),fwave.value) val =", "False: compute AB magnitudes (may be set by filter) **energy**", "the lower and upper wavelengths for a notch filter (100%", "the predefined filter names available :Example: >>> import splat >>>", "magnitude is on the AB system (optional, default = filter", "rsr: magnitude is on the Vega system (optional, default =", "magnitude of a source based on its spectrum. Spectral fluxes", "f0 = checkFilterName(filt, verbose=True) if f0 == False: raise ValueError", "convert = const.h.to('erg s')*const.c.to('micron/s') val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i in", "fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <=", "vega == True: # Read in Vega spectrum vwave,vflux =", "from astropy import constants as const # physical constants in", "# check that input is an energy flux # try:", "dm]) return numpy.sum((dmo/em)**2), offset def SEDFitGrid(verbose=True): ''' this code will", "in filter if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans = filterProfile(filt,**kwargs) #", "= fwave*u.micron fw = fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] ft = ftrans[numpy.where(ftrans", "magnitude instead (optional, default = False) :param ab: magnitude is", "[numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1)) else: raise ValueError('Could not", ":type filter: required :param verbose: print out information about filter", "code will conduct a comparison of a set of magnitudes", "up plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend) # save if desired", "flux density of a magnitude :Output: astropy quantity in flux", "flux unit'.format(base_unit)) return numpy.nan, numpy.nan return val, err # energy", "for numerical integration from scipy.interpolate import interp1d # splat functions", "for i in numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else:", "output[f] = {} output[f]['description'] = FILTERS[f]['description'] output[f]['zeropoint'] = FILTERS[f]['zeropoint'] fwave,ftrans", "f0 # read in filter fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True,", "= vflux[vwave<=numpy.nanmax(fwave)] vwave = vwave[vwave<=numpy.nanmax(fwave)] # convert to fnu nu", "1.442 micron >>> data = splat.filterProperties('2MASS X') Filter 2MASS X", "vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate", "# finish up plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend) # save", "DEVELOPMENT, BUGS MAY BE COMMON ''' filt = copy.deepcopy(filters) wave_unit", "nsamples = kwargs.get('nsamples',100) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) base_unit", "list(unc.keys()) and f not in ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f]) # find", "particular filter. :param filter: name of filter, must be one", "provided (required) :param filter: name of filter, must be one", "vega or ab method specified') # convert to desired energy", "{}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return '{} magnitude of {}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000): '''", "ftrans=ftrans.value fwave = fwave[~numpy.isnan(ftrans)] ftrans = ftrans[~numpy.isnan(ftrans)] result = []", "filter: String giving the name of one of the predefined", "len(args) > 0: fname = list(args) elif kwargs.get('filter',False) != False:", "currently available for SPLAT; contact '+EMAIL+'\\n') filterInfo() return output def", "trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05)", "is on the AB system (optional, default = filter preference)", "yl = kwargs.get('ylabel','Transmission Curve') # list of notch ranges if", "Jy'.format(output[f]['zeropoint'])) print('Central wavelength: = {:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength: = {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot", "of several statistics ''' chi = 0. dm,em = [],[]", "... ''' filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder =", "a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit = 1. elif (energy): outunit", "[fname] output = {} for k in fname: f =", ":param rsr: magnitude is on the Vega system (optional, default", "equivalent sum of fluxes ''' # check filter agreement if", "set of magnitudes using one of several statistics ''' chi", "\\ missing_values = ('NaN','nan'), filling_values = (numpy.nan)) vwave = vwave[~numpy.isnan(vflux)]*u.micron", "1. # custom filter else: fwave,ftrans = custom[0],custom[1] # Read", "lam x F_lam), with option of also comparing to SED", "False: return numpy.nan, numpy.nan # reset filter calculation methods based", "Converts a magnitude into an energy, and vice versa. :param", "in combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-other.magnitude out.uncertainty", "name :Optional Parameters: **custom** = None: A 2 x N", "energy = False if energy: photons = False # Read", "False: compute photon flux **filterFolder** = splat.FILTER_FOLDER: folder containing the", "const # physical constants in SI units import matplotlib.patches as", "filter else: fwave,ftrans = custom[0],custom[1] # Read in Vega spectrum", "energy, photons) to compute photometry\\n\\n') # val = numpy.nanmean(result)*outunit err", "'+report['description']) print('Zeropoint = {} Jy'.format(report['zeropoint'])) print('Pivot point: = {:.3f}'.format(report['lambda_pivot'])) print('FWHM", "if e_mag.value > 0.: for i in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err", "a grid of model magnitudes and choose the closest match", "in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise NameError('\\nfilterMag not given a correct", "# energy -> magnitude # THIS NEEDS TO BE COMPLETED", "filter profiles, optionally on top of a spectrum WARNING: THIS", "is in list filt = checkFilterName(filt) if filt == False:", "FILTERS[filt]['method'] report['rsr'] = FILTERS[filt]['rsr'] fwave,ftrans = filterProfile(filt,**kwargs) try: fwave =", "* u.s) return_unit = kwargs.get('unit',base_unit) e_mag = kwargs.get('uncertainty',0.) e_mag =", "# except: # raise ValueError('\\nInput quantity unit {} is not", "trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b", "IS ONLY PARTIALLY COMPLETE ''' # keyword parameters filterFolder =", "splat >>> import splat.photometry as spphot >>> sp = splat.getSpectrum(shortname='1507-1627')[0]", "if energy: photons = False # Read in filter if", "= kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) custom", "elif isinstance(custom,bool) and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)", "profile for a SPLAT filter. Returns two arrays: the filter", "info.keys(): setattr(self,k,info[k]) def __copy__(self): ''' :Purpose: Make a copy of", "import units as u # standard units from astropy import", "= False: compute photon flux **filterFolder** = splat.FILTER_FOLDER: folder containing", "Parameters: **custom** = None: A 2 x N vector array", "interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))", "or energy flux. :Required Parameters: **sp**: Spectrum class object, which", "parse input {}'.format(filt)) # add a comparison spectrum sp =", "plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if", "f==k.upper() or f.lower() in FILTERS[k]['altnames']: output = k if output", "u.s) return_unit = kwargs.get('unit',base_unit) e_mag = kwargs.get('uncertainty',0.) e_mag = kwargs.get('unc',e_mag)", "equivalent flux density of a magnitude :Output: astropy quantity in", "isinstance(custom,bool) and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans", "''' :Purpose: Returns a dictionary containing key parameters for a", "* u.s) else: raise ValueError('\\nmagToFlux needs vega or ab method", "v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact", "= filterProfile(f,**kwargs) if isUnit(fwave): wave_unit = kwargs.get('wave_unit',fwave.unit) xl = kwargs.get('xlabel','Wavelength", "info = filterProperties(self.filter) for k in info.keys(): setattr(self,k,info[k]) def __copy__(self):", "return s # backup version def copy(self): ''' :Purpose: Make", "self.uncertainty+other.uncertainty # combine noises if self.uncertainty != 0 and other.uncertainty", "em = numpy.array(em) offset = numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo = numpy.array([m-offset", "plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend) # save if desired file = kwargs.get('file','')", "FOURSTAR H LONG: FOURSTAR H long FOURSTAR H SHORT: FOURSTAR", "(trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise NameError('\\nfilterMag not", "Magnitude object equal to the diffence of values ''' #", "fwave*wave_unit if kwargs.get('normalize',False): ftrans = ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if len(xra) ==", "on whatever system is defined for the filter or provided", "set of filter profiles, optionally on top of a spectrum", "magnitudes to model magnitudes using an Amoeba (Nelder-Mead) wrapper, and", "will compare a set of magnitudes to a grid of", "not a flux unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose: Plots a", "List the predefined filter names available :Example: >>> import splat", "try: fwave = fwave.to(u.micron) except: fwave = fwave*u.micron fw =", "instead (optional, default = False) :param ab: magnitude is on", "== False: fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity) == True: ftrans=ftrans.value fwave =", "= (numpy.nan)) vwave = vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s", "False: compute energy flux **photon** = False: compute photon flux", "== False: if verbose== True: print('filter {} is not a", "out def __sub__(self,other,samp=1000): ''' :Purpose: A representation of subtraction for", "# mag.to(base_unit) # e_mag.to(base_unit) # except: # raise ValueError('\\nInput quantity", "== False: raise ValueError filt = f0 # read in", "representation of the Spectrum object ''' if self.uncertainty != 0.", "I: Bessel I-band FOURSTAR H: FOURSTAR H-band FOURSTAR H LONG:", "= interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val =", "= interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch for models else:", "if output == False and verbose == True: print('\\nFilter '+filt+'", "trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value else: a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit", "xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1)) else: raise", "agreement if self.filter != other.filter: out.filter = '{}+{}'.format(self.filter,other.filter) return out", "between spectrum for {} and filter {}'.format(sp.name,filt)) return numpy.nan, numpy.nan", "filter else: fwave,ftrans = custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity) == False: fwave=fwave*u.micron", "in ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f]) # find best scale factor dm", "= ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean']", "0 and other.uncertainty != 0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 =", "if kwargs.get('reverse',False) == False: if vega == True: # Read", "notch ranges if isinstance(filt[0],int) or isinstance(filt[0],float): filt = [filt] #", "import interp1d # splat functions and constants from .initialize import", "one of the predefined filters listed in splat.FILTERS.keys() (required) :param", "= (ftrans*fconst).to(u.erg/(u.cm**2 * u.s * u.micron),equivalencies=u.spectral_density(fwave)) if rsr: fact =", "else: print('passed') pass # check that input is an energy", "numpy.array(dm) em = numpy.array(em) offset = numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo =", "SPLAT_URL+FILTER_FOLDER # check that requested filter is in list f0", "a set of magnitudes to a grid of model magnitudes", ">>> sp.fluxCalibrate('2MASS J',14.5) >>> spphot.filterMag(sp,'MKO J') (14.345894376898123, 0.027596454828421831) ''' #", "False: output[f] = {} output[f]['description'] = FILTERS[f]['description'] output[f]['zeropoint'] = FILTERS[f]['zeropoint']", "= FILTERS[f]['description'] output[f]['zeropoint'] = FILTERS[f]['zeropoint'] fwave,ftrans = filterProfile(f,**kwargs) try: fwave", "0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw)) # print(trapz(fw*ft,fw))", "filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b", "comparing to SED spectrum ''' pass ##################################################### ############### MAGNITUDE CLASS", "2MASS J: 2MASS J-band Zeropoint = 1594.0 Jy Pivot point:", "specified by the ``filter`` input. By default this filter is", "isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans = filterProfile(filt,**kwargs) # notch filter elif", "= filt # some things that are based on presets", "filter wavelength function wgood = numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood]) > 0:", "visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose: Plots a filter profile or set of", "# check filter and rename if necessary self.knownfilter = True", "numpy.nanstd(val) # check filter agreement if self.filter != other.filter: out.filter", "u.s) else: err = 0.*u.erg/(u.cm**2 * u.s) elif ab ==", "could be uploaded pre-save some model magnitudes ''' pass def", "outunit = 1. elif (ab): nu = sp.wave.to('Hz',equivalencies=u.spectral()) fnu =", "len(filt) == 0: raise ValueError('Did not recognize any of the", "# result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit = 1.", "magnitudes for a model set's SED models saves to file", "= 1. # custom filter else: fwave,ftrans = custom[0],custom[1] if", "return numpy.nan, numpy.nan filt = f0 rsr = FILTERS[filt]['rsr'] #", "numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'), filling_values = (numpy.nan))", "fnu nu = vwave.to('Hz',equivalencies=u.spectral()) fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu = fwave.to('Hz',equivalencies=u.spectral())", "trapz(ftrans.value,fwave.value) val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s) # calculate uncertainty if", "of Vega to extract Vega magnitudes, but the user can", "a set of magnitudes for a model set's SED models", "convolved with the filter profile specified by the ``filter`` input.", "filters listed in splat.FILTERS.keys() or a custom filter name :Optional", "**ab** = False: compute AB magnitudes (may be set by", "# make a copy and fill in combined magnitude out", ":param mag: magnitude on whatever system is defined for the", "in FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab = not vega rsr", "filt = checkFilterName(filt) if filt == False: return None report", "= numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-2.5*numpy.log10(1.+10.**(-0.4*(m2-m1))) out.uncertainty = numpy.nanstd(val) return out", "report['zeropoint'] = FILTERS[filt]['zeropoint'] report['method'] = FILTERS[filt]['method'] report['rsr'] = FILTERS[filt]['rsr'] fwave,ftrans", "######## SED FITTING TOOLS ######### ### WARNING: THESE ARE EXPERIMENTAL!!", "SED FITTING TOOLS ######### ### WARNING: THESE ARE EXPERIMENTAL!! ###", "numpy.nan, numpy.nan filt = f0 rsr = FILTERS[filt]['rsr'] # Read", "in SPLAT'.format(f)) else: filt.insert(len(filt),fc) if len(filt) == 0: raise ValueError('Did", "copy.deepcopy(filters) wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single filter name if isinstance(filt,str):", "os # imports - external import numpy from astropy import", "checkFilterName(filt,verbose=verbose) if fflag == False: if verbose== True: print('filter {}", "By default this filter is also convolved with a model", "fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): fwave.to(wave_unit) else: fwave = fwave*wave_unit", "magnitude -> energy if kwargs.get('reverse',False) == False: if vega ==", "print('Removed filter {}: not included in SPLAT'.format(f)) else: filt.insert(len(filt),fc) if", "(default = erg/cm2/s/micron) ''' pass def addFlux(self,other,samp=1000): ''' :Purpose: A", "(numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else: err = 0.*u.erg/(u.cm**2 * u.s) elif", "Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True, \\", "other.filter: raise ValueError('magnitudes filters {} and {} are not the", "# check that requested filter is in list if isinstance(custom,bool)", "output[f]['lambda_min'] = numpy.min(fw) output[f]['lambda_max'] = numpy.max(fw) if verbose ==True: print(f.replace('_','", "spectrophotometry functions for SPLAT \"\"\" # imports - internal import", "verbose == True: print('\\nFilter '+filt+' not currently available for SPLAT;", "file that could be uploaded pre-save some model magnitudes '''", "# splat functions and constants from .initialize import * from", "= FILTERS[f]['zeropoint'] fwave,ftrans = filterProfile(f,**kwargs) try: fwave = fwave.to(u.micron) except:", "check filter agreement if self.filter != other.filter: out.filter = '{}-{}'.format(self.filter,other.filter)", "output = False f = copy.deepcopy(filt) f = f.replace(' ','_').upper()", "filterFolder = SPLAT_URL+FILTER_FOLDER # check that requested filter is in", "magnitude into an energy, and vice versa. :param mag: magnitude", "if desired file = kwargs.get('file','') file = kwargs.get('filename',file) file =", "kwargs.get('vegaFile','vega_kurucz.txt') vega = kwargs.get('vega',True) ab = kwargs.get('ab',not vega) rsr =", "that requested filter is in list if isinstance(custom,bool) and isinstance(notch,bool):", "fwave = fwave*u.micron fw = fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] ft =", "parameters fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): wave_unit = kwargs.get('wave_unit',fwave.unit) xl", "overlap between spectrum for {} and filter {}'.format(sp.name,filt)) return numpy.nan,", "'{} magnitude of {}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000): ''' :Purpose: A representation", "J-band Zeropoint = 1594.0 Jy Pivot point: = 1.252 micron", "= checkFilterName(f) filt.remove(f) if fc == False: if verbose==True: print('Removed", "= numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))] = 1. #", "magnitudes on SED scale (flux = lam x F_lam), with", "interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch for models else: if verbose==True: print('\\nWarning: data", "{:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report def magToFlux(mag,filt,**kwargs): ''' :Purpose: Converts a magnitude", "predefined filter names available :Example: >>> import splat >>> import", "trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value for i in numpy.arange(nsamples):", "import matplotlib.patches as patches import matplotlib.pyplot as plt from scipy.integrate", "''' :Purpose: Retrieve the filter profile for a SPLAT filter.", "A representation of addition for Magnitude classes that takes into", "result = [] if (vega): # Read in Vega spectrum", "its spectrum. Spectral fluxes are convolved with the filter profile", "spectrum for {} does not span full filter profile for", "kwargs['filter'] else: fname = sorted(list(FILTERS.keys())) if isinstance(fname,list) == False: fname", "kwargs.get('normalize',False): ftrans = ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if len(xra) == 0: xra", "filterProfile(f,**kwargs) try: fwave = fwave.to(u.micron) except: fwave = fwave*u.micron fw", "notch[0],fwave <= notch[1]))] = 1. # custom filter else: fwave,ftrans", "the equivalent sum of fluxes ''' # check filter agreement", "elif kwargs.get('filter',False) != False: fname = kwargs['filter'] else: fname =", "const.h.to('erg s')*const.c.to('micron/s') val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value)", "= fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw))", ":Purpose: Plots a filter profile or set of filter profiles,", "fwave,ftrans = filterProfile(filt,**kwargs) try: fwave = fwave.to(u.micron) except: fwave =", "Vega magnitudes, but the user can also specify AB magnitudes,", "default = False) :param ab: magnitude is on the AB", "False: fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity) == True: ftrans=ftrans.value fwave = fwave[~numpy.isnan(ftrans)]", "== True: print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra = [yra[0],yra[1]*1.1]", "plt.plot(fwave,ftrans) if len(xra) == 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra =", "the diffence of values ''' # make a copy and", "FITTING TOOLS ######### ### WARNING: THESE ARE EXPERIMENTAL!! ### #########################################", "numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit =", "''' this code compares a set of magnitudes using one", "data structure for a magnitude value ''' def __init__(self, magnitude,", "rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons): outunit = 1./u.s/u.cm**2 convert", "Visualizes magnitudes on SED scale (flux = lam x F_lam),", "of samples to use in Monte Carlo error estimation **info**", "print('Zeropoint = {} Jy'.format(report['zeropoint'])) print('Pivot point: = {:.3f}'.format(report['lambda_pivot'])) print('FWHM =", "as spphot >>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',14.5) >>>", ":param verbose: print out information about filter to screen :type", "magnitudes (may be set by filter) **energy** = False: compute", "0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-m2", "compares a set of magnitudes using one of several statistics", "combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude+other.magnitude out.uncertainty =", "for k in fname: f = checkFilterName(k) if f !=", "for a custom filter **notch** = None: A 2 element", "FILTERS[filt]['zeropoint'] report['method'] = FILTERS[filt]['method'] report['rsr'] = FILTERS[filt]['rsr'] fwave,ftrans = filterProfile(filt,**kwargs)", "specifed filters given by splat.FILTERS.keys() :type filter: required :param verbose:", "object equal to the sum of values ''' # make", "verbose: print out information about filter to screen :type verbose:", "other.uncertainty != 0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val", "energy flux unit'.format(return_unit)) try: val.to(base_unit) err.to(base_unit) except: print('\\nWarning: cannot convert", "i in numpy.arange(nsamples): if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons):", "UNDER DEVELOPMENT, BUGS MAY BE COMMON ''' filt = copy.deepcopy(filters)", "= splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',14.5) >>> spphot.filterMag(sp,'MKO J') (14.345894376898123, 0.027596454828421831)", "# print('\\nWarning: unit {} is not an energy flux unit'.format(return_unit))", "__future__ import print_function, division \"\"\" .. note:: These are the", "= vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) #", "import trapz # for numerical integration from scipy.interpolate import interp1d", "d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val", "if necessary self.knownfilter = True fflag = checkFilterName(filt,verbose=verbose) if fflag", "or provided (required) :param filter: name of filter, must be", "filter profile specified by the ``filter`` input. By default this", "default = True :Example: >>> import splat >>> data =", "= numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))]", "a Magnitude object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s", "# units if isinstance(fwave,u.quantity.Quantity) == True: fwave = fwave.to(u.micron) else:", "imports - internal import copy import os # imports -", "{:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if verbose ==True: print(' Filter {}", "False: if verbose== True: print('filter {} is not a standard", "can also specify AB magnitudes, photon flux or energy flux.", "samples to use in Monte Carlo error estimation **info** =", "= splat.filterProperties('2MASS J') Filter 2MASS J: 2MASS J-band Zeropoint =", "the specifed filters given by splat.FILTERS.keys() (required) :param reverse: convert", "ftrans[~numpy.isnan(ftrans)] result = [] err = 0. # magnitude ->", "0.*u.erg/(u.cm**2 * u.s) else: raise ValueError('\\nmagToFlux needs vega or ab", "kwargs.get('energy',False) energy = kwargs.get('flux',energy) if (photons or energy): vega =", "True: yl = kwargs.get('ylabel','Transmission Curve') # list of notch ranges", "the user can also specify AB magnitudes, photon flux or", "return numpy.nan, numpy.nan # reset filter calculation methods based on", "= {:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if verbose ==True: print(' Filter", "u.erg/u.s/u.cm**2 if rsr: a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c", "else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons): outunit = 1./u.s/u.cm**2 convert = const.h.to('erg", "if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit = 1. elif (ab):", "True: self.wave,self.transmission = filterProfile(self.filter) info = filterProperties(self.filter) for k in", "= f.replace(' ','_').upper() for k in list(FILTERS.keys()): if f==k.upper() or", "True :Example: >>> import splat >>> data = splat.filterProperties('2MASS J')", "def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this code compares a set of magnitudes", "custom filter else: fwave,ftrans = custom[0],custom[1] # units if isinstance(fwave,u.quantity.Quantity)", "rsr: a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit", "verbose==True: print('\\nWarning: no overlap between spectrum for {} and filter", "filterInfo(*args,**kwargs): ''' :Purpose: Prints out the current list of filters", "= numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-m2 out.uncertainty = numpy.nanstd(val) # check", "compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this code compares a set of magnitudes using", "wavelength: = {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point: = {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm']))", "{} not in SPLAT filter list'.format(k)) kys = list(output.keys()) if", "or numpy.nanmax(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: spectrum for {}", "dm.append(mags1[f]-mags2[f]) em.append(unc[f]) # find best scale factor dm = numpy.array(dm)", "that takes into account uncertainties :Output: A new Magnitude object", "(optional, default = filter preference) :param vega: magnitude is on", "verbose==True: print('Removed filter {}: not included in SPLAT'.format(f)) else: filt.insert(len(filt),fc)", "= trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val =", "not isinstance(ftrans,numpy.ndarray)) if not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem", "0: err = 0. return val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check", "(notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave", "if fc == False: if verbose==True: print('Removed filter {}: not", "and choose best/average/distribution of parameters ''' pass def SEDFitAmoeba(verbose=True): '''", "magnitude, filt, uncertainty=0., magtype='apparent', verbose=False,**kwargs): self.magnitude = magnitude self.uncertainty =", "* u.s) else: err = 0.*u.erg/(u.cm**2 * u.s) elif ab", "''' :Purpose: A representation of addition for Magnitude classes that", "quantity in flux density units (default = erg/cm2/s/micron) ''' pass", "flux density units (default = erg/cm2/s/micron) ''' pass def addFlux(self,other,samp=1000):", "for f in filt: fc = checkFilterName(f) filt.remove(f) if fc", "= (a/b * c/b).to(outunit).value else: a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b =", "closest match ''' pass def SEDVisualize(verbose=True): ''' Visualizes magnitudes on", "(required) :param reverse: convert energy into magnitude instead (optional, default", "of file containing Vega flux file, must be within ``filterFolder``", "= fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] ft = ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05", "numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood]) > 0: d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n =", "= {} output[f]['description'] = FILTERS[f]['description'] output[f]['zeropoint'] = FILTERS[f]['zeropoint'] fwave,ftrans =", "= type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s # backup version def copy(self):", "of filter, which can either be one of the predefined", "<filename>splat/photometry.py # -*- coding: utf-8 -*- from __future__ import print_function,", "u.micron)) # trim spectrum vflux = vflux[vwave>=numpy.nanmin(fwave)] vwave = vwave[vwave>=numpy.nanmin(fwave)]", "to 1.442 micron >>> data = splat.filterProperties('2MASS X') Filter 2MASS", "(optional, default = filter preference) :param rsr: magnitude is on", "print('\\nFilter '+filt+': '+report['description']) print('Zeropoint = {} Jy'.format(report['zeropoint'])) print('Pivot point: =", "''' :Purpose: A simple representation of the Spectrum object '''", "short ... ''' filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder", "out.filter = '{}-{}'.format(self.filter,other.filter) return out def flux(self,type='fnu',samp=1000): ''' :Purpose: Report", "vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # interpolate", "== 1: return output[kys[0]] else: return output def filterProperties(filt,**kwargs): '''", "functions may not work'.format(filt)) self.knownfilter = False else: filt =", "not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit # check that requested filter is in", "vega = kwargs.get('vega',True) ab = kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False)", "xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr'] ==", "custom filter name :Optional Parameters: **custom** = None: A 2", "in list(mags2.keys()) and f in list(unc.keys()) and f not in", "= trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value for i in", "def SEDVisualize(verbose=True): ''' Visualizes magnitudes on SED scale (flux =", "work'.format(filt)) self.knownfilter = False else: filt = fflag self.filter =", "mag=mag*u.s/u.s if not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit # check that requested filter", "= numpy.array([m-offset for m in dm]) return numpy.sum((dmo/em)**2), offset def", "range of filter {} have no uncertainties'.format(filt)) d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.)", "Magnitude object equal to the sum of values ''' #", "in list if isinstance(custom,bool) and isinstance(notch,bool): f0 = checkFilterName(filt,verbose=True) if", "numpy.nan filt = f0 # reset filter calculation methods based", "# find best scale factor dm = numpy.array(dm) em =", "wrapper, and choose the closest match ''' pass def SEDVisualize(verbose=True):", "else: raise ValueError('\\nmagToFlux needs vega or ab method specified') #", "not in ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f]) # find best scale factor", "result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit = 1. elif", "factor dm = numpy.array(dm) em = numpy.array(em) offset = numpy.sum(dm/em**2)/numpy.sum", "ab: magnitude is on the AB system (optional, default =", "photon flux **filterFolder** = splat.FILTER_FOLDER: folder containing the filter transmission", "= 0. dm,em = [],[] for f in list(mags1.keys()): if", "filter is in list f0 = checkFilterName(filt, verbose=True) if f0", "i in numpy.arange(nsamples): a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit = 1.", "correct physical quantity (vega, ab, energy, photons) to compute photometry\\n\\n')", "if not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem reading in", "**custom** = None: A 2 x N vector array specifying", "of addition for Magnitude classes that takes into account uncertainties", "point: = {:.3f}'.format(report['lambda_pivot'])) print('FWHM = {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range = {:.3f}", "ValueError('\\nProblem reading in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave = fwave[~numpy.isnan(ftrans)]*u.micron ftrans = ftrans[~numpy.isnan(ftrans)]", "SPLAT'.format(f)) else: filt.insert(len(filt),fc) if len(filt) == 0: raise ValueError('Did not", "f in list(mags2.keys()) and f in list(unc.keys()) and f not", "* u.micron)) # trim spectrum vflux = vflux[vwave>=numpy.nanmin(fwave)] vwave =", "2 x N vector array specifying the wavelengths and transmissions", "= 'vega_kurucz.txt': name of file containing Vega flux file, must", "versa. :param mag: magnitude on whatever system is defined for", "convolved with a model of Vega to extract Vega magnitudes,", "plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend) # save if desired file =", "''' # make a copy and fill in combined magnitude", "vice versa. :param mag: magnitude on whatever system is defined", "verbose: optional, default = True :Example: >>> import splat >>>", "val.to(base_unit) err.to(base_unit) except: print('\\nWarning: cannot convert result to an energy", "= k if output == False and verbose == True:", "### WARNING: THESE ARE EXPERIMENTAL!! ### ######################################### # plan: def", "custom[0],custom[1] # Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#',", "> 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] =", "= False f = copy.deepcopy(filt) f = f.replace(' ','_').upper() for", "astropy quantity in flux density units (default = erg/cm2/s/micron) '''", "filters given by splat.FILTERS.keys() :type filter: required :param verbose: print", "isinstance(filt[0],int) or isinstance(filt[0],float): filt = [filt] # list of notch", "# add a comparison spectrum sp = kwargs.get('spectrum',None) sp =", "check that spectrum and filter cover the same wavelength ranges", "choose best/average/distribution of parameters ''' pass def SEDFitAmoeba(verbose=True): ''' this", "been obseleted def checkFilter(filt,verbose=True): output = False f = copy.deepcopy(filt)", "= interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch for models else: if verbose==True: print('\\nWarning:", "for a notch filter (100% transmission within, 0% transmission without)", "design if 'ab' in FILTERS[filt]['method']: ab = kwargs.get('ab',True) vega =", "code compares a set of magnitudes using one of several", "0: fname = list(args) elif kwargs.get('filter',False) != False: fname =", "takes into account uncertainties :Output: A new Magnitude object equal", "out.uncertainty = self.uncertainty+other.uncertainty # combine noises if self.uncertainty != 0", "kwargs.get('spectrum',None) sp = kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum) == True: print(xra) sp.normalize(xra)", "and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans =", "raise ValueError filt = f0 # read in filter fwave,ftrans", "**sp**: Spectrum class object, which should contain wave, flux and", "= kwargs.get('vega',True) ab = kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False) nsamples", "kwargs.get('uncertainty',0.) e_mag = kwargs.get('unc',e_mag) e_mag = kwargs.get('e_mag',e_mag) if not isinstance(mag,u.quantity.Quantity):", "= 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b)", "==True: print(' Filter {} not in SPLAT filter list'.format(k)) kys", "print('Pivot point: = {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range =", "Determine the photometric magnitude of a source based on its", "ab, energy, photons) to compute photometry\\n\\n') # val = numpy.nanmean(result)*outunit", "wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value)", "fluxes) :Output: A new magnitude object equal to the equivalent", "pass def SEDVisualize(verbose=True): ''' Visualizes magnitudes on SED scale (flux", "= 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] = numpy.min(fw) output[f]['lambda_max'] =", "pre-save some model magnitudes ''' pass def interpolateMagnitudes(verbose=True): ''' produces", "of magnitudes to a grid of model magnitudes and choose", "= kwargs.get('spectrum',None) sp = kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum) == True: print(xra)", "= vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave))", "ftrans = (ftrans*fconst).to(u.erg/(u.cm**2 * u.s * u.micron),equivalencies=u.spectral_density(fwave)) if rsr: fact", "micron FWHM = 0.323 micron Wavelength range = 1.066 to", "fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity) == True: ftrans=ftrans.value fwave = fwave[~numpy.isnan(ftrans)] ftrans", "== 0: raise ValueError('Did not recognize any of the input", "and other.uncertainty != 0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp)", "photons = False # Read in filter if isinstance(custom,bool) and", "if isinstance(filt[0],int) or isinstance(filt[0],float): filt = [filt] # list of", "in info.keys(): setattr(self,k,info[k]) def __copy__(self): ''' :Purpose: Make a copy", "print('\\nWarning: cannot convert result to an energy flux unit'.format(base_unit)) return", "things that are based on presets if self.knownfilter == True:", ":param units: units for energy as an astropy.units variable; if", "-2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i in numpy.arange(nsamples): a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit", "= False # Read in filter if isinstance(custom,bool) and isinstance(notch,bool):", "density units (default = erg/cm2/s/micron) ''' pass def addFlux(self,other,samp=1000): '''", "for i in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err = (numpy.nanstd(result))*u.erg/(u.cm**2 * u.s)", "kwargs.get('custom',False) notch = kwargs.get('notch',False) base_unit = u.erg/(u.cm**2 * u.s) return_unit", "vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # interpolate Vega onto filter", "output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] = numpy.min(fw) output[f]['lambda_max'] = numpy.max(fw) if", "this will be a code that calculates a set of", "= (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >=", "= interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val =", "1: return output[kys[0]] else: return output def filterProperties(filt,**kwargs): ''' :Purpose:", "for k in info.keys(): setattr(self,k,info[k]) def __copy__(self): ''' :Purpose: Make", "is in list f0 = checkFilterName(filt, verbose=True) if f0 ==", "d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs):", "class object, which should contain wave, flux and noise array", "numpy.sum((dmo/em)**2), offset def SEDFitGrid(verbose=True): ''' this code will compare a", "numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'), filling_values = (numpy.nan))", "if f != False: output[f] = {} output[f]['description'] = FILTERS[f]['description']", "this conversion does not work, the conversion is ignored (optional,", "COMPLETED else: print('passed') pass # check that input is an", "with a model of Vega to extract Vega magnitudes, but", "trapz(ftrans.value*fwave.value,fwave.value) else: fact = trapz(ftrans.value,fwave.value) val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s)", "fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans = filterProfile(f,**kwargs)", "to the equivalent sum of fluxes ''' # check filter", "= 1.252 micron FWHM = 0.323 micron Wavelength range =", "curve. :param filter: String giving the name of one of", "{} have no uncertainties'.format(filt)) d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.)", "= ('NaN','nan'), filling_values = (numpy.nan)) vwave = vwave[~numpy.isnan(vflux)]*u.micron vflux =", "verbose=True) if f0 == False: raise ValueError filt = f0", "for a magnitude value ''' def __init__(self, magnitude, filt, uncertainty=0.,", "numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1+m2 out.uncertainty = numpy.nanstd(val) # check filter", "import splat.photometry as spphot >>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS", "finish up plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend) # save if", "= trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact = trapz(ftrans*v(fwave.value),fwave.value) val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 *", "filter {} have no uncertainties'.format(filt)) d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n =", "if self.knownfilter == True: self.wave,self.transmission = filterProfile(self.filter) info = filterProperties(self.filter)", "{:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max']))", "self.knownfilter = False else: filt = fflag self.filter = filt", "the predefined filters listed in splat.FILTERS.keys() (required) :param filterFolder: folder", "a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val", "specifed filters given by splat.FILTERS.keys() (required) :param reverse: convert energy", "isUnit(fwave): wave_unit = kwargs.get('wave_unit',fwave.unit) xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl =", ":Optional Parameters: **custom** = None: A 2 x N vector", "agreement if self.filter != other.filter: raise ValueError('magnitudes filters {} and", "dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave", "== True: yl = kwargs.get('ylabel','Transmission Curve') # list of notch", "combine noises if self.uncertainty != 0 and other.uncertainty != 0:", "n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for", "flux. :Required Parameters: **sp**: Spectrum class object, which should contain", "in splat.FILTERS.keys() or a custom filter name :Optional Parameters: **custom**", "filterProfile(filt,**kwargs) try: fwave = fwave.to(u.micron) except: fwave = fwave*u.micron fw", "to model magnitudes using an MCMC wrapper, and choose best/average/distribution", "filterProfile(f,**kwargs) if isUnit(fwave): wave_unit = kwargs.get('wave_unit',fwave.unit) xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit))", "'vega_kurucz.txt': name of file containing Vega flux file, must be", "set of magnitudes for a model set's SED models saves", "filt.insert(len(filt),fc) if len(filt) == 0: raise ValueError('Did not recognize any", "(may be set by filter) **energy** = False: compute energy", "filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile", "= kwargs.get('vega',True) ab = not vega if 'rsr' in FILTERS[filt]['method']:", "if (vega): # Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile),", "FOURSTAR H short ... ''' filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not", "name if isinstance(filt,str): filt = [filt] if isinstance(filt,list): # list", "fill in combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude)))", "= True :Example: >>> import splat >>> data = splat.filterProperties('2MASS", "True: ftrans=ftrans.value fwave = fwave[~numpy.isnan(ftrans)] ftrans = ftrans[~numpy.isnan(ftrans)] result =", "# for numerical integration from scipy.interpolate import interp1d # splat", "profile specified by the ``filter`` input. By default this filter", "Jy Pivot point: = 1.252 micron FWHM = 0.323 micron", "default this filter is also convolved with a model of", "for the filter or provided (required) :param filter: name of", "report['transmission'] = ftrans # report values out if kwargs.get('verbose',False): print('\\nFilter", "numpy.nanmean(result)*outunit err = numpy.nanstd(result) if len(sp.wave[wgood]) == 0: err =", "1./u.s/u.cm**2 convert = const.h.to('erg s')*const.c.to('micron/s') val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i", "is a class data structure for a magnitude value '''", "self.uncertainty != 0. and numpy.isfinite(self.uncertainty): return '{} magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty)", "x N vector array specifying the wavelengths and transmissions for", "# interpolate Vega onto filter wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.)", "fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value)", "f.lower() in FILTERS[k]['altnames']: output = k if output == False", "data = splat.filterProperties('2MASS X') Filter 2MASS X not among the", "FILTERS[f]['rsr'] == True: yl = kwargs.get('ylabel','Transmission Curve') # list of", "convert to fnu nu = vwave.to('Hz',equivalencies=u.spectral()) fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu", "numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))] = 1. # custom", "new Magnitude object equal to the sum of values '''", "[yra[0],yra[1]*1.1] # finish up plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend) #", "profile for {}'.format(sp.name,filt)) # interpolate spectrum onto filter wavelength function", "notch filter elif isinstance(custom,bool) and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave", "ab == True: fconst = 3631*u.jansky ftrans = (ftrans*fconst).to(u.erg/(u.cm**2 *", "0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])]", "numpy.array([m-offset for m in dm]) return numpy.sum((dmo/em)**2), offset def SEDFitGrid(verbose=True):", "model magnitudes ''' pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this code compares", "numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] = numpy.min(fw)", "print('Pivot point: = {:.3f}'.format(report['lambda_pivot'])) print('FWHM = {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range =", "profiles, optionally on top of a spectrum WARNING: THIS CODE", "filt.remove(f) if fc == False: if verbose==True: print('Removed filter {}:", "__copy__(self): ''' :Purpose: Make a copy of a Magnitude object", "of {}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000): ''' :Purpose: A representation of addition", "vflux[vwave<=numpy.nanmax(fwave)] vwave = vwave[vwave<=numpy.nanmax(fwave)] # convert to fnu nu =", ":Purpose: Make a copy of a Magnitude object ''' s", "for a grid set of model magnitudes ''' pass def", "wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))", "checkFilterName(filt) if filt == False: return numpy.nan, numpy.nan # reset", "Vega to extract Vega magnitudes, but the user can also", "information about filter to screen :type verbose: optional, default =", "kwargs.get('nsamples',100) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) base_unit = u.erg/(u.cm**2", "ValueError('\\nmagToFlux needs vega or ab method specified') # convert to", "the closest match ''' pass def SEDVisualize(verbose=True): ''' Visualizes magnitudes", "scale (flux = lam x F_lam), with option of also", "ValueError('Could not parse input {}'.format(filt)) # add a comparison spectrum", "= magtype # check filter and rename if necessary self.knownfilter", "checkFilterName(filt) if filt == False: return None report = {}", "result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit = 1. elif (ab): nu =", "given by splat.FILTERS.keys() :type filter: required :param verbose: print out", "1.066 to 1.442 micron >>> data = splat.filterProperties('2MASS X') Filter", "convert energy into magnitude instead (optional, default = False) :param", "= [] if (vega): # Read in Vega spectrum vwave,vflux", "# Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True,", "> numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: no overlap between spectrum for", "numpy.max(fw) report['wave'] = fwave report['transmission'] = ftrans # report values", "result = [] err = 0. # magnitude -> energy", "= 1. elif (ab): nu = sp.wave.to('Hz',equivalencies=u.spectral()) fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave))", "copy.deepcopy(self) out.magnitude = self.magnitude+other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises", "= not vega if 'rsr' in FILTERS[filt]['method']: rsr = kwargs.get('rsr',True)", "True fflag = checkFilterName(filt,verbose=verbose) if fflag == False: if verbose==", "fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw)) # print(trapz(fw*ft,fw)) report['lambda_mean']", "BUGS MAY BE COMMON ''' filt = copy.deepcopy(filters) wave_unit =", "X not among the available filters: 2MASS H: 2MASS H-band", "unpack=True, \\ missing_values = ('NaN','nan'), filling_values = (numpy.nan)) vwave =", "if filt == False: return numpy.nan, numpy.nan # reset filter", "noises if self.uncertainty != 0 and other.uncertainty != 0: m1", "range = {:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if verbose ==True: print('", "available for SPLAT; contact '+EMAIL+'\\n') filterInfo() return output def filterProfile(filt,**kwargs):", "flux and noise array elements. **filter**: String giving name of", "not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile',VEGAFILE) info =", "splat.filterProperties('2MASS X') Filter 2MASS X not among the available filters:", "array elements. **filter**: String giving name of filter, which can", "if len(filt) == 0: raise ValueError('Did not recognize any of", "* from .utilities import * ##################################################### ############### SPECTROPHOTOMETRY ############### #####################################################", "Prints out the current list of filters in the SPLAT", "**nsamples** = 100: number of samples to use in Monte", "range = {:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report def magToFlux(mag,filt,**kwargs): '''", "= splat.filterProperties('2MASS X') Filter 2MASS X not among the available", "kwargs.get('custom',False) notch = kwargs.get('notch',False) vega = kwargs.get('vega',True) ab = kwargs.get('ab',not", "''' this code will compare a set of magnitudes to", ":param vega: magnitude is on the Vega system (optional, default", "some model magnitudes ''' pass def interpolateMagnitudes(verbose=True): ''' produces an", "2MASS Ks-band BESSEL I: Bessel I-band FOURSTAR H: FOURSTAR H-band", "FOURSTAR H long FOURSTAR H SHORT: FOURSTAR H short ...", ":Required Parameters: **sp**: Spectrum class object, which should contain wave,", "# trim spectrum vflux = vflux[vwave>=numpy.nanmin(fwave)] vwave = vwave[vwave>=numpy.nanmin(fwave)] vflux", "print('Zeropoint = {} Jy'.format(output[f]['zeropoint'])) print('Central wavelength: = {:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength:", "False if photons: energy = False if energy: photons =", "legend.append(sp.name) yra = [yra[0],yra[1]*1.1] # finish up plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl)", "list if isinstance(custom,bool) and isinstance(notch,bool): f0 = checkFilterName(filt,verbose=True) if f0", "report['lambda_min'] = numpy.min(fw) report['lambda_max'] = numpy.max(fw) report['wave'] = fwave report['transmission']", "the name of one of the predefined filters listed in", "or not isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem reading in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave =", "interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b)", "= [fname] output = {} for k in fname: f", "contain wave, flux and noise array elements. **filter**: String giving", "unit'.format(base_unit)) return numpy.nan, numpy.nan return val, err # energy ->", "calculates a set of magnitudes for a model set's SED", "# check filter agreement if self.filter != other.filter: raise ValueError('magnitudes", "i in numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)))", "output = k if output == False and verbose ==", "2MASS X not among the available filters: 2MASS H: 2MASS", "print('\\nWarning: data values in range of filter {} have no", "'ab' in FILTERS[filt]['method']: ab = kwargs.get('ab',True) vega = not ab", "= '{}+{}'.format(self.filter,other.filter) return out def __sub__(self,other,samp=1000): ''' :Purpose: A representation", "flux unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose: Plots a filter profile", "vector array specifying the wavelengths and transmissions for a custom", "Magnitude object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s #", "vwave[vwave<=numpy.nanmax(fwave)] # convert to fnu nu = vwave.to('Hz',equivalencies=u.spectral()) fnu =", "f0 # reset filter calculation methods based on filter design", "the same'.format(self.filter,other.filter)) # make a copy and fill in combined", "{}'.format(filters)) # prep parameters fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): wave_unit", "check that requested filter is in list filt = checkFilterName(filt)", "return val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check that requested filter is", "class Magnitude(object): ''' :Description: This is a class data structure", "magnitudes (addition of fluxes) :Output: A new magnitude object equal", "vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.)", "MAGNITUDE CLASS ############### ##################################################### class Magnitude(object): ''' :Description: This is", "filters {} and {} are not the same'.format(self.filter,other.filter)) # make", "u.s) elif ab == True: fconst = 3631*u.jansky ftrans =", "= vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # interpolate Vega onto", "SI units import matplotlib.patches as patches import matplotlib.pyplot as plt", ":param verbose: print out information about filter to screen (optional,", "from .initialize import * from .utilities import * ##################################################### ###############", "for i in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise NameError('\\nfilterMag not given", "fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] ft = ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 =", "# custom filter else: fwave,ftrans = custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity) ==", "default = filter preference) :param units: units for energy as", "notch filter (100% transmission within, 0% transmission without) **vega** =", "0.*u.erg/(u.cm**2 * u.s) elif ab == True: fconst = 3631*u.jansky", "= f0 rsr = FILTERS[filt]['rsr'] # Read in filter if", "# e_mag.to(base_unit) # except: # raise ValueError('\\nInput quantity unit {}", "output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] = numpy.min(fw) output[f]['lambda_max']", "= filter preference) :param units: units for energy as an", "in enumerate(filt): fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): fwave.to(wave_unit) else: fwave", "Curve') # list of notch ranges if isinstance(filt[0],int) or isinstance(filt[0],float):", "are not the same'.format(self.filter,other.filter)) # make a copy and fill", "3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def", "modelMagnitudes(verbose=True): ''' this will be a code that calculates a", "on SED scale (flux = lam x F_lam), with option", "Vega system (optional, default = filter preference) :param rsr: magnitude", "enumerate(filt): fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if len(xra) == 0: xra", "for magnitudes (addition of fluxes) :Output: A new magnitude object", "custom filter else: fwave,ftrans = custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity) == False:", "elif (energy): outunit = u.erg/u.s/u.cm**2 if rsr: a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit", "produces an interpolated value for a grid set of model", "AB system (optional, default = filter preference) :param vega: magnitude", "magnitude value ''' def __init__(self, magnitude, filt, uncertainty=0., magtype='apparent', verbose=False,**kwargs):", "name of one of the predefined filters listed in splat.FILTERS.keys()", "plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave):", "is not an energy flux unit'.format(return_unit)) try: val.to(base_unit) err.to(base_unit) except:", "parameters for a particular filter. :param filter: name of filter,", "result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit = 1. elif (ab): nu = sp.wave.to('Hz',equivalencies=u.spectral()) fnu", "or set of filter profiles, optionally on top of a", "{}: not included in SPLAT'.format(f)) else: filt.insert(len(filt),fc) if len(filt) ==", "= ftrans[~numpy.isnan(ftrans)] result = [] err = 0. # magnitude", "self.filter != other.filter: out.filter = '{}-{}'.format(self.filter,other.filter) return out def flux(self,type='fnu',samp=1000):", "that input is an energy flux # try: # mag.to(base_unit)", "output def filterProperties(filt,**kwargs): ''' :Purpose: Returns a dictionary containing key", "else: fact = trapz(ftrans.value,fwave.value) val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s) #", "quantity unit {} is not a flux unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs):", "report['wave'] = fwave report['transmission'] = ftrans # report values out", "legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr'] == True: yl = kwargs.get('ylabel','Transmission Curve') #", "# Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True,", "vegaFile = kwargs.get('vegaFile',VEGAFILE) info = kwargs.get('info',False) custom = kwargs.get('custom',False) notch", "of a source based on its spectrum. Spectral fluxes are", "if len(xra) == 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])]", "return '{} magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return '{} magnitude of", "= fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b =", "a copy of a Magnitude object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty)", "not given a correct physical quantity (vega, ab, energy, photons)", "yra = [yra[0],yra[1]*1.1] # finish up plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl)", "m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-2.5*numpy.log10(1.+10.**(-0.4*(m2-m1))) out.uncertainty", "A new magnitude object equal to the equivalent sum of", "# -*- coding: utf-8 -*- from __future__ import print_function, division", "= checkFilterName(filt) if filt == False: return None report =", "filter wavelength and filter transmission curve. :param filter: String giving", "fconst = 3631*u.jansky ftrans = (ftrans*fconst).to(u.erg/(u.cm**2 * u.s * u.micron),equivalencies=u.spectral_density(fwave))", "kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False)", "is not a flux unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose: Plots", "ONLY PARTIALLY COMPLETE ''' # keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER)", "numpy.nanmin(sp.wave) or numpy.nanmax(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: spectrum for", "!= other.filter: raise ValueError('magnitudes filters {} and {} are not", "**verbose** = True: List the predefined filter names available :Example:", "filter elif isinstance(custom,bool) and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave =", "* u.micron)) # interpolate Vega onto filter wavelength function v", "ab = not vega rsr = FILTERS[filt]['rsr'] # other possibilities", "the photometric magnitude of a source based on its spectrum.", "**filter**: String giving name of filter, which can either be", "(required) :param filterFolder: folder containing the filter transmission files (optional,", "0. and numpy.isfinite(self.uncertainty): return '{} magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return", "{} is not a flux unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose:", "filter. Returns two arrays: the filter wavelength and filter transmission", "FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab = not vega rsr =", "available filters: 2MASS H: 2MASS H-band 2MASS J: 2MASS J-band", "rsr: fact = trapz(ftrans.value*fwave.value,fwave.value) else: fact = trapz(ftrans.value,fwave.value) val =", "list'.format(k)) kys = list(output.keys()) if len(kys) == 1: return output[kys[0]]", "''' :Description: This is a class data structure for a", "addFlux(self,other,samp=1000): ''' :Purpose: A representation of addition for magnitudes (addition", "based on its spectrum. Spectral fluxes are convolved with the", "in the SPLAT reference library. ''' verbose = kwargs.get('verbose',True) if", "method specified') # convert to desired energy units # try:", "if 'rsr' in FILTERS[filt]['method']: rsr = kwargs.get('rsr',True) # Read in", "# reset filter calculation methods based on filter design if", "constants as const # physical constants in SI units import", "filter and rename if necessary self.knownfilter = True fflag =", "by filter) **ab** = False: compute AB magnitudes (may be", "of also comparing to SED spectrum ''' pass ##################################################### ###############", "'{} magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return '{} magnitude of {}'.format(self.filter,self.magnitude)", "numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] = numpy.min(fw) report['lambda_max'] = numpy.max(fw) report['wave'] = fwave", ":param filter: String giving the name of one of the", "that requested filter is in list filt = checkFilterName(filt) if", "vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # trim spectrum vflux =", "{} and {} are not the same'.format(self.filter,other.filter)) # make a", "list filt = checkFilterName(filt) if filt == False: return numpy.nan,", "False: raise ValueError filt = f0 # read in filter", "isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit # check that requested", "s.__dict__.update(self.__dict__) return s def __repr__(self): ''' :Purpose: A simple representation", "############### SPECTROPHOTOMETRY ############### ##################################################### # this function has been obseleted", "convert result to an energy flux unit'.format(base_unit)) return numpy.nan, numpy.nan", "spphot >>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',14.5) >>> spphot.filterMag(sp,'MKO", "rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) verbose = kwargs.get('verbose',False) #", "# other possibilities photons = kwargs.get('photons',False) photons = kwargs.get('photon',photons) energy", "print(' Filter {} not in SPLAT filter list'.format(k)) kys =", "kwargs.get('vega',True) ab = not vega rsr = FILTERS[filt]['rsr'] # other", "numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise NameError('\\nfilterMag not given a correct physical", "= custom[0],custom[1] # units if isinstance(fwave,u.quantity.Quantity) == True: fwave =", "outunit = u.erg/u.s/u.cm**2 if rsr: a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b =", "not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem reading in {}'.format(filterFolder+FILTERS[filt]['file']))", "containing Vega flux file, must be within ``filterFolder`` **nsamples** =", "= sorted(list(FILTERS.keys())) if isinstance(fname,list) == False: fname = [fname] output", "or a custom filter name :Optional Parameters: **custom** = None:", "PARTIALLY COMPLETE ''' # keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if", "m1+m2 out.uncertainty = numpy.nanstd(val) # check filter agreement if self.filter", "!= other.filter: out.filter = '{}-{}'.format(self.filter,other.filter) return out def flux(self,type='fnu',samp=1000): '''", "work, the conversion is ignored (optional, default = erg/cm2/s) :param", "{:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if verbose", "< numpy.nanmin(sp.wave) or numpy.nanmin(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: no", "grid of model magnitudes and choose the closest match based", "print('filter {} is not a standard filter; some functions may", "on various statistics ''' pass def SEDFitMCMC(verbose=True): ''' this code", "= False) WARNING: THIS CODE IS ONLY PARTIALLY COMPLETE '''", "= numpy.max(fw) if verbose ==True: print(f.replace('_',' ')+': '+output[f]['zeropoint']) print('Zeropoint =", "fwave = fwave[~numpy.isnan(ftrans)] ftrans = ftrans[~numpy.isnan(ftrans)] result = [] err", "= numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1+m2 out.uncertainty =", "if f0 == False: return numpy.nan, numpy.nan filt = f0", "BE COMPLETED else: print('passed') pass # check that input is", "other.filter: out.filter = '{}+{}'.format(self.filter,other.filter) return out def __sub__(self,other,samp=1000): ''' :Purpose:", "# try: val.to(return_unit) err.to(return_unit) # except: # print('\\nWarning: unit {}", "= kwargs.get('ylabel','Transmission Curve') # list of notch ranges if isinstance(filt[0],int)", "the filter profile specified by the ``filter`` input. By default", "fflag == False: if verbose== True: print('filter {} is not", "imports - external import numpy from astropy import units as", "verbose=False,**kwargs): self.magnitude = magnitude self.uncertainty = uncertainty self.type = magtype", "filterFolder: folder containing the filter transmission files (optional, default =", "given by splat.FILTERS.keys() (required) :param reverse: convert energy into magnitude", "of the input filters {}'.format(filters)) # prep parameters fwave,ftrans =", "trapz(ftrans*v(fwave.value),fwave.value) val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s) # calculate uncertainty if", "return None report = {} report['name'] = filt report['description'] =", "== False: return None report = {} report['name'] = filt", "magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return '{} magnitude of {}'.format(self.filter,self.magnitude) def", "None report = {} report['name'] = filt report['description'] = FILTERS[filt]['description']", "''' :Purpose: Determine the photometric magnitude of a source based", "= fwave*wave_unit if kwargs.get('normalize',False): ftrans = ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if len(xra)", "splat.FILTER_FOLDER) :Example: >>> import splat >>> import splat.photometry as spphot", "= {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range = {:.3f} to", "copy.deepcopy(filt) f = f.replace(' ','_').upper() for k in list(FILTERS.keys()): if", "= trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val =", "= numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-m2 out.uncertainty =", "uploaded pre-save some model magnitudes ''' pass def interpolateMagnitudes(verbose=True): '''", "equal to the equivalent sum of fluxes ''' # check", "= trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i in numpy.arange(nsamples): a", "offset def SEDFitGrid(verbose=True): ''' this code will compare a set", "reset filter calculation methods based on filter design if 'ab'", "calculation methods based on filter design if 'ab' in FILTERS[filt]['method']:", "numpy.nanstd(result) if len(sp.wave[wgood]) == 0: err = 0. return val*outunit,err*outunit", "e_mag = kwargs.get('unc',e_mag) e_mag = kwargs.get('e_mag',e_mag) if not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s", "FILTERS[filt]['method']: rsr = kwargs.get('rsr',True) # Read in filter if isinstance(custom,bool)", "sp.wave.to('Hz',equivalencies=u.spectral()) fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu = fwave.to('Hz',equivalencies=u.spectral())", "simple representation of the Spectrum object ''' if self.uncertainty !=", "for SPLAT; contact '+EMAIL+'\\n') filterInfo() return output def filterProfile(filt,**kwargs): '''", "True: # Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#',", "conversion is ignored (optional, default = erg/cm2/s) :param verbose: print", "vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # interpolate Vega", "list filt = checkFilterName(filt) if filt == False: return None", "A simple representation of the Spectrum object ''' if self.uncertainty", "EXPERIMENTAL!! ### ######################################### # plan: def modelMagnitudes(verbose=True): ''' this will", "pass def SEDFitMCMC(verbose=True): ''' this code will conduct a comparison", "AB magnitudes, photon flux or energy flux. :Required Parameters: **sp**:", "if isinstance(filt,str): filt = [filt] if isinstance(filt,list): # list of", "to model magnitudes using an Amoeba (Nelder-Mead) wrapper, and choose", "= trapz(ftrans*v(fwave.value),fwave.value) val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s) # calculate uncertainty", "fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return", "kwargs.get('e_mag',e_mag) if not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit #", "numpy.array(em) offset = numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo = numpy.array([m-offset for m", "filter) **energy** = False: compute energy flux **photon** = False:", "using an MCMC wrapper, and choose best/average/distribution of parameters '''", "type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s def __repr__(self): ''' :Purpose: A simple", "SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile','vega_kurucz.txt') vega = kwargs.get('vega',True) ab = kwargs.get('ab',not", "# keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder", "u.s * u.micron),equivalencies=u.spectral_density(fwave)) if rsr: fact = trapz(ftrans.value*fwave.value,fwave.value) else: fact", "result to an energy flux unit'.format(base_unit)) return numpy.nan, numpy.nan return", "filter is in list filt = checkFilterName(filt) if filt ==", "note:: These are the spectrophotometry functions for SPLAT \"\"\" #", "else: err = 0.*u.erg/(u.cm**2 * u.s) else: raise ValueError('\\nmagToFlux needs", "fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <=", "should contain wave, flux and noise array elements. **filter**: String", "in FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab = not vega if", "val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise", "c/b).to(outunit).value else: a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans,fwave.value)*sp.wave.unit c =", "desired file = kwargs.get('file','') file = kwargs.get('filename',file) file = kwargs.get('output',file)", "= numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo = numpy.array([m-offset for m in dm])", ":Purpose: Prints out the current list of filters in the", "= None: A 2 element array that specifies the lower", "object ''' if self.uncertainty != 0. and numpy.isfinite(self.uncertainty): return '{}", "for Magnitude classes that takes into account uncertainties :Output: A", "compute Vega magnitudes (may be set by filter) **ab** =", "number of samples to use in Monte Carlo error estimation", "Filter {} not in SPLAT filter list'.format(k)) kys = list(output.keys())", "unit {} is not a flux unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): '''", "{} for k in fname: f = checkFilterName(k) if f", "f not in ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f]) # find best scale", "= kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum) == True: print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5))", "unit'.format(return_unit)) try: val.to(base_unit) err.to(base_unit) except: print('\\nWarning: cannot convert result to", "and choose the closest match ''' pass def SEDVisualize(verbose=True): '''", "division \"\"\" .. note:: These are the spectrophotometry functions for", "= kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile =", "of magnitudes for a model set's SED models saves to", "trapz # for numerical integration from scipy.interpolate import interp1d #", "= self.magnitude+other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises if self.uncertainty", "= numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'), filling_values =", "vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) #", "numpy.nan, numpy.nan return val, err # energy -> magnitude #", "u.micron),equivalencies=u.spectral_density(fwave)) if rsr: fact = trapz(ftrans.value*fwave.value,fwave.value) else: fact = trapz(ftrans.value,fwave.value)", "= sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst =", "if vega == True: # Read in Vega spectrum vwave,vflux", "u.s * u.micron)) # interpolate Vega onto filter wavelength function", "not a standard filter; some functions may not work'.format(filt)) self.knownfilter", "for m in dm]) return numpy.sum((dmo/em)**2), offset def SEDFitGrid(verbose=True): '''", "for energy as an astropy.units variable; if this conversion does", "interpolated value for a grid set of model magnitudes '''", "err = 0.*u.erg/(u.cm**2 * u.s) else: raise ValueError('\\nmagToFlux needs vega", "a magnitude :Output: astropy quantity in flux density units (default", "return output def filterProfile(filt,**kwargs): ''' :Purpose: Retrieve the filter profile", "available **verbose** = True: List the predefined filter names available", "False: return None report = {} report['name'] = filt report['description']", "nsamples = kwargs.get('nsamples',100) verbose = kwargs.get('verbose',False) # check that requested", "top of a spectrum WARNING: THIS CODE IS CURRENTLY UNDER", "''' :Purpose: Report the equivalent flux density of a magnitude", "**photon** = False: compute photon flux **filterFolder** = splat.FILTER_FOLDER: folder", "else: raise ValueError('Could not parse input {}'.format(filt)) # add a", "= ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] #", "Wavelength range = 1.066 to 1.442 micron >>> data =", "splat.FILTERS.keys() (required) :param reverse: convert energy into magnitude instead (optional,", "based on various statistics ''' pass def SEDFitMCMC(verbose=True): ''' this", "name of file containing Vega flux file, must be within", "result.append(-2.5*numpy.log10(a/b)) outunit = 1. elif (energy): outunit = u.erg/u.s/u.cm**2 if", "= FILTERS[filt]['rsr'] # Read in filter if isinstance(custom,bool) and isinstance(notch,bool):", "(optional, default = splat.FILTER_FOLDER) :Example: >>> import splat >>> import", "to screen (optional, default = False) WARNING: THIS CODE IS", "is not a standard filter; some functions may not work'.format(filt))", "comments='#', unpack=True, \\ missing_values = ('NaN','nan'), filling_values = (numpy.nan)) vwave", "= splat.FILTER_FOLDER: folder containing the filter transmission files **vegaFile** =", "= self.magnitude-other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises if self.uncertainty", "isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans = numpy.zeros(len(fwave))", "if f in list(mags2.keys()) and f in list(unc.keys()) and f", "fact = trapz(ftrans*v(fwave.value),fwave.value) val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s) # calculate", "sp = kwargs.get('spectrum',None) sp = kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum) == True:", ":Purpose: Converts a magnitude into an energy, and vice versa.", "estimation **info** = False: List the predefined filter names available", "set of magnitudes to model magnitudes using an MCMC wrapper,", "report def magToFlux(mag,filt,**kwargs): ''' :Purpose: Converts a magnitude into an", "photons = kwargs.get('photon',photons) energy = kwargs.get('energy',False) energy = kwargs.get('flux',energy) if", "= fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n =", "else: fwave,ftrans = custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity) == False: fwave=fwave*u.micron if", "read in filter fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True, missing_values =", "keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder =", "kwargs.get('ylabel','Transmission Curve') legend = [] fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f", "__repr__(self): ''' :Purpose: A simple representation of the Spectrum object", "if filt == False: return None report = {} report['name']", "the AB system (optional, default = filter preference) :param vega:", "Report the equivalent flux density of a magnitude :Output: astropy", "array specifying the wavelengths and transmissions for a custom filter", "of magnitudes to model magnitudes using an MCMC wrapper, and", "(optional, default = erg/cm2/s) :param verbose: print out information about", "# report values out if kwargs.get('verbose',False): print('\\nFilter '+filt+': '+report['description']) print('Zeropoint", "10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s) # calculate uncertainty if e_mag.value > 0.:", "based on presets if self.knownfilter == True: self.wave,self.transmission = filterProfile(self.filter)", "\"\"\" .. note:: These are the spectrophotometry functions for SPLAT", "{}'.format(filterFolder+FILTERS[filt]['file'])) fwave = fwave[~numpy.isnan(ftrans)]*u.micron ftrans = ftrans[~numpy.isnan(ftrans)] return fwave,ftrans def", "filterProfile(f,**kwargs) if isUnit(fwave): fwave.to(wave_unit) else: fwave = fwave*wave_unit if kwargs.get('normalize',False):", "not parse input {}'.format(filt)) # add a comparison spectrum sp", "interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs): ''' :Purpose:", "= type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s def __repr__(self): ''' :Purpose: A", "def addFlux(self,other,samp=1000): ''' :Purpose: A representation of addition for magnitudes", "will conduct a comparison of a set of magnitudes to", "= kwargs.get('energy',False) energy = kwargs.get('flux',energy) if (photons or energy): vega", "= copy.deepcopy(filt) f = f.replace(' ','_').upper() for k in list(FILTERS.keys()):", "''' produces an interpolated value for a grid set of", "if not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit # check that requested filter is", "spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'),", "fill in combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-other.magnitude", "sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.)", "fwave,ftrans = filterProfile(filt,**kwargs) # notch filter elif isinstance(custom,bool) and isinstance(notch,list):", "magnitudes ''' pass def interpolateMagnitudes(verbose=True): ''' produces an interpolated value", "fname = sorted(list(FILTERS.keys())) if isinstance(fname,list) == False: fname = [fname]", "{} Jy'.format(report['zeropoint'])) print('Pivot point: = {:.3f}'.format(report['lambda_pivot'])) print('FWHM = {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength", "u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate Vega onto filter wavelength function v", "= '{}-{}'.format(self.filter,other.filter) return out def flux(self,type='fnu',samp=1000): ''' :Purpose: Report the", "if not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit # check", "= numpy.max(fw) report['wave'] = fwave report['transmission'] = ftrans # report", "False: if verbose==True: print('Removed filter {}: not included in SPLAT'.format(f))", "values ''' # make a copy and fill in combined", "out if kwargs.get('verbose',False): print('\\nFilter '+filt+': '+report['description']) print('Zeropoint = {} Jy'.format(report['zeropoint']))", "in numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit", "0: raise ValueError('Did not recognize any of the input filters", "A representation of subtraction for Magnitude classes that takes into", "''' this code will conduct a comparison of a set", "vega = not ab if 'vega' in FILTERS[filt]['method']: vega =", "= kwargs.get('nsamples',100) verbose = kwargs.get('verbose',False) # check that requested filter", "else: fwave = fwave*u.micron # check that spectrum and filter", "em.append(unc[f]) # find best scale factor dm = numpy.array(dm) em", "for i in numpy.arange(nsamples): a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit =", "magtype # check filter and rename if necessary self.knownfilter =", "elements. **filter**: String giving name of filter, which can either", "photons = kwargs.get('photons',False) photons = kwargs.get('photon',photons) energy = kwargs.get('energy',False) energy", "report['lambda_max'] = numpy.max(fw) report['wave'] = fwave report['transmission'] = ftrans #", "pass # check that input is an energy flux #", "0.01*numpy.nanmax(ftrans))] ft = ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans >", "some functions may not work'.format(filt)) self.knownfilter = False else: filt", "if f==k.upper() or f.lower() in FILTERS[k]['altnames']: output = k if", "SEDFitGrid(verbose=True): ''' this code will compare a set of magnitudes", "filter is in list if isinstance(custom,bool) and isinstance(notch,bool): f0 =", "= const.h.to('erg s')*const.c.to('micron/s') val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i in numpy.arange(nsamples):", "onto filter wavelength function wgood = numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood]) >", "-> energy if kwargs.get('reverse',False) == False: if vega == True:", "the predefined filter names available **verbose** = True: List the", "trapz(ftrans,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value for", "be one of the specifed filters given by splat.FILTERS.keys() :type", "name of filter, which can either be one of the", "kwargs.get('verbose',False) # check that requested filter is in list if", "for {}'.format(sp.name,filt)) # interpolate spectrum onto filter wavelength function wgood", "ab = False if photons: energy = False if energy:", "= SPLAT_URL+FILTER_FOLDER # check that requested filter is in list", "preference) :param vega: magnitude is on the Vega system (optional,", "numpy.nan, numpy.nan filt = f0 # reset filter calculation methods", "matplotlib.pyplot as plt from scipy.integrate import trapz # for numerical", "no overlap between spectrum for {} and filter {}'.format(sp.name,filt)) return", "0. return val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check that requested filter", "('NaN','nan'), filling_values = (numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray))", "equal to the diffence of values ''' # make a", "filt # some things that are based on presets if", "Zeropoint = 1594.0 Jy Pivot point: = 1.252 micron FWHM", "H SHORT: FOURSTAR H short ... ''' filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER)", "######################################### # plan: def modelMagnitudes(verbose=True): ''' this will be a", "out.filter = '{}+{}'.format(self.filter,other.filter) return out def __sub__(self,other,samp=1000): ''' :Purpose: A", "elif (photons): outunit = 1./u.s/u.cm**2 convert = const.h.to('erg s')*const.c.to('micron/s') val", "ranges if isinstance(filt[0],int) or isinstance(filt[0],float): filt = [filt] # list", "system (optional, default = filter preference) :param rsr: magnitude is", "1594.0 Jy Pivot point: = 1.252 micron FWHM = 0.323", "kwargs.get('photons',False) photons = kwargs.get('photon',photons) energy = kwargs.get('energy',False) energy = kwargs.get('flux',energy)", "this code will compare a set of magnitudes to a", "if isinstance(fname,list) == False: fname = [fname] output = {}", "``filterFolder`` **nsamples** = 100: number of samples to use in", "kwargs.get('unc',e_mag) e_mag = kwargs.get('e_mag',e_mag) if not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if not", "False) WARNING: THIS CODE IS ONLY PARTIALLY COMPLETE ''' #", "{} output[f]['description'] = FILTERS[f]['description'] output[f]['zeropoint'] = FILTERS[f]['zeropoint'] fwave,ftrans = filterProfile(f,**kwargs)", "vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # trim spectrum", "== 0: err = 0. return val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): #", ">>> spphot.filterMag(sp,'MKO J') (14.345894376898123, 0.027596454828421831) ''' # keyword parameters filterFolder", "ab = kwargs.get('ab',True) vega = not ab if 'vega' in", "compute energy flux **photon** = False: compute photon flux **filterFolder**", "raise ValueError('Could not parse input {}'.format(filt)) # add a comparison", "return numpy.sum((dmo/em)**2), offset def SEDFitGrid(verbose=True): ''' this code will compare", "energy units # try: val.to(return_unit) err.to(return_unit) # except: # print('\\nWarning:", "no uncertainties'.format(filt)) d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result =", "filter list'.format(k)) kys = list(output.keys()) if len(kys) == 1: return", "u.erg/(u.cm**2 * u.s) return_unit = kwargs.get('unit',base_unit) e_mag = kwargs.get('uncertainty',0.) e_mag", "if isUnit(fwave): fwave.to(wave_unit) else: fwave = fwave*wave_unit if kwargs.get('normalize',False): ftrans", "!= other.filter: out.filter = '{}+{}'.format(self.filter,other.filter) return out def __sub__(self,other,samp=1000): '''", "= fwave*u.micron # check that spectrum and filter cover the", "one of the predefined filters listed in splat.FILTERS.keys() or a", "vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate Vega onto filter wavelength function v =", "may not work'.format(filt)) self.knownfilter = False else: filt = fflag", "= False if energy: photons = False # Read in", "comparison spectrum sp = kwargs.get('spectrum',None) sp = kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum)", "SEDFitMCMC(verbose=True): ''' this code will conduct a comparison of a", "energy = kwargs.get('energy',False) energy = kwargs.get('flux',energy) if (photons or energy):", "= SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile',VEGAFILE) info = kwargs.get('info',False) custom =", "CURRENTLY UNDER DEVELOPMENT, BUGS MAY BE COMMON ''' filt =", "SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile',VEGAFILE) info = kwargs.get('info',False) custom = kwargs.get('custom',False)", "filter transmission curve. :param filter: String giving the name of", "from scipy.integrate import trapz # for numerical integration from scipy.interpolate", "requested filter is in list f0 = checkFilterName(filt, verbose=True) if", "fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.)", "= 0. # magnitude -> energy if kwargs.get('reverse',False) == False:", "checkFilterName(filt, verbose=True) if f0 == False: raise ValueError filt =", "in SPLAT filter list'.format(k)) kys = list(output.keys()) if len(kys) ==", "k in list(FILTERS.keys()): if f==k.upper() or f.lower() in FILTERS[k]['altnames']: output", "either be one of the predefined filters listed in splat.FILTERS.keys()", "long FOURSTAR H SHORT: FOURSTAR H short ... ''' filterFolder", "ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))] = 1.", "spectrum for {} and filter {}'.format(sp.name,filt)) return numpy.nan, numpy.nan if", "0.323 micron Wavelength range = 1.066 to 1.442 micron >>>", "0.: for i in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err = (numpy.nanstd(result))*u.erg/(u.cm**2 *", "vflux = vflux[vwave<=numpy.nanmax(fwave)] vwave = vwave[vwave<=numpy.nanmax(fwave)] # convert to fnu", "account uncertainties :Output: A new Magnitude object equal to the", "physical constants in SI units import matplotlib.patches as patches import", "fig ######################################### ######## SED FITTING TOOLS ######### ### WARNING: THESE", "list(mags2.keys()) and f in list(unc.keys()) and f not in ignore:", "{} and filter {}'.format(sp.name,filt)) return numpy.nan, numpy.nan if numpy.nanmin(fwave) <", ".utilities import * ##################################################### ############### SPECTROPHOTOMETRY ############### ##################################################### # this", "and filter cover the same wavelength ranges if numpy.nanmax(fwave) <", "val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s) # calculate uncertainty if e_mag.value", "= numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] = numpy.min(fw) output[f]['lambda_max'] = numpy.max(fw) if verbose", "* u.s) else: err = 0.*u.erg/(u.cm**2 * u.s) else: raise", "in list(unc.keys()) and f not in ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f]) #", "plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend) # save if desired file", "in dm]) return numpy.sum((dmo/em)**2), offset def SEDFitGrid(verbose=True): ''' this code", "object, which should contain wave, flux and noise array elements.", "kwargs.get('nsamples',100) verbose = kwargs.get('verbose',False) # check that requested filter is", "rsr = FILTERS[filt]['rsr'] # other possibilities photons = kwargs.get('photons',False) photons", "filt = [filt] if isinstance(filt,list): # list of filter names", "ab = kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100)", "numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))] =", "= checkFilterName(k) if f != False: output[f] = {} output[f]['description']", "############### MAGNITUDE CLASS ############### ##################################################### class Magnitude(object): ''' :Description: This", "filt = fflag self.filter = filt # some things that", "wavelength and filter transmission curve. :param filter: String giving the", "= fflag self.filter = filt # some things that are", "filter, which can either be one of the predefined filters", "else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit = 1. elif (ab): nu = sp.wave.to('Hz',equivalencies=u.spectral())", "= checkFilterName(filt,verbose=True) if f0 == False: return numpy.nan, numpy.nan filt", "the spectrophotometry functions for SPLAT \"\"\" # imports - internal", "point: = 1.252 micron FWHM = 0.323 micron Wavelength range", "requested filter is in list filt = checkFilterName(filt) if filt", "= [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1)) else: raise ValueError('Could not parse input", "# prep parameters fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): wave_unit =", "(numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray)) if not isinstance(fwave,numpy.ndarray)", "giving name of filter, which can either be one of", "file = kwargs.get('file','') file = kwargs.get('filename',file) file = kwargs.get('output',file) if", "fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] =", "physical quantity (vega, ab, energy, photons) to compute photometry\\n\\n') #", "from scipy.interpolate import interp1d # splat functions and constants from", "val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i in numpy.arange(nsamples): a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value)", "an interpolated value for a grid set of model magnitudes", "import matplotlib.pyplot as plt from scipy.integrate import trapz # for", "isinstance(filt,str): filt = [filt] if isinstance(filt,list): # list of filter", "True: compute Vega magnitudes (may be set by filter) **ab**", "''' if self.uncertainty != 0. and numpy.isfinite(self.uncertainty): return '{} magnitude", "self.magnitude-other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises if self.uncertainty !=", "if kwargs.get('normalize',False): ftrans = ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if len(xra) == 0:", "else: fwave,ftrans = custom[0],custom[1] # Read in Vega spectrum vwave,vflux", "filter cover the same wavelength ranges if numpy.nanmax(fwave) < numpy.nanmin(sp.wave)", "diffence of values ''' # make a copy and fill", "numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-2.5*numpy.log10(1.+10.**(-0.4*(m2-m1))) out.uncertainty = numpy.nanstd(val)", "energy flux **photon** = False: compute photon flux **filterFolder** =", "{:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point: = {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range", "presets if self.knownfilter == True: self.wave,self.transmission = filterProfile(self.filter) info =", "an astropy.units variable; if this conversion does not work, the", "a code that calculates a set of magnitudes for a", "names available :Example: >>> import splat >>> import splat.photometry as", "scale factor dm = numpy.array(dm) em = numpy.array(em) offset =", "return numpy.nan, numpy.nan return val, err # energy -> magnitude", "m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-m2 out.uncertainty = numpy.nanstd(val) #", "filter profile for a SPLAT filter. Returns two arrays: the", "this code compares a set of magnitudes using one of", "print('\\nWarning: no overlap between spectrum for {} and filter {}'.format(sp.name,filt))", "in FILTERS[k]['altnames']: output = k if output == False and", "= kwargs.get('file','') file = kwargs.get('filename',file) file = kwargs.get('output',file) if file", "any of the input filters {}'.format(filters)) # prep parameters fwave,ftrans", "fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d", "internal import copy import os # imports - external import", "val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s) # calculate uncertainty if e_mag.value", "filter transmission files (optional, default = splat.FILTER_FOLDER) :Example: >>> import", "type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s # backup version def copy(self): '''", "system (optional, default = filter preference) :param units: units for", "a magnitude value ''' def __init__(self, magnitude, filt, uncertainty=0., magtype='apparent',", "equal to the sum of values ''' # make a", "= {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report", "2MASS J-band 2MASS KS: 2MASS Ks-band BESSEL I: Bessel I-band", "listed in splat.FILTERS.keys() or a custom filter name :Optional Parameters:", "of filter {} have no uncertainties'.format(filt)) d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n", "report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm']", "(ab): nu = sp.wave.to('Hz',equivalencies=u.spectral()) fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave))", "a grid set of model magnitudes ''' pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True):", "return output[kys[0]] else: return output def filterProperties(filt,**kwargs): ''' :Purpose: Returns", "uncertainty=0., magtype='apparent', verbose=False,**kwargs): self.magnitude = magnitude self.uncertainty = uncertainty self.type", "of notch ranges if isinstance(filt[0],int) or isinstance(filt[0],float): filt = [filt]", "try: # mag.to(base_unit) # e_mag.to(base_unit) # except: # raise ValueError('\\nInput", "def flux(self,type='fnu',samp=1000): ''' :Purpose: Report the equivalent flux density of", "does not work, the conversion is ignored (optional, default =", "yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr'] == True: yl =", "of fluxes) :Output: A new magnitude object equal to the", "-2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs): ''' :Purpose: Prints out the current list", "fflag = checkFilterName(filt,verbose=verbose) if fflag == False: if verbose== True:", "= True fflag = checkFilterName(filt,verbose=verbose) if fflag == False: if", "set of magnitudes to model magnitudes using an Amoeba (Nelder-Mead)", "A new Magnitude object equal to the sum of values", "kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) verbose = kwargs.get('verbose',False) # check that", "that calculates a set of magnitudes for a model set's", "* u.s * u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate Vega onto filter", "be uploaded pre-save some model magnitudes ''' pass def interpolateMagnitudes(verbose=True):", "values out if kwargs.get('verbose',False): print('\\nFilter '+filt+': '+report['description']) print('Zeropoint = {}", "CLASS ############### ##################################################### class Magnitude(object): ''' :Description: This is a", "isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem reading in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave = fwave[~numpy.isnan(ftrans)]*u.micron ftrans", "= checkFilterName(filt,verbose=verbose) if fflag == False: if verbose== True: print('filter", "which can either be one of the predefined filters listed", "= interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result = [] if (vega):", "flux unit'.format(return_unit)) try: val.to(base_unit) err.to(base_unit) except: print('\\nWarning: cannot convert result", "= trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value else: a =", "def magToFlux(mag,filt,**kwargs): ''' :Purpose: Converts a magnitude into an energy,", "kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single filter name if isinstance(filt,str): filt = [filt]", "None: A 2 x N vector array specifying the wavelengths", "filter fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True, missing_values = ('NaN','nan'), filling_values", "the SPLAT reference library. ''' verbose = kwargs.get('verbose',True) if len(args)", "representation of addition for Magnitude classes that takes into account", "Carlo error estimation **info** = False: List the predefined filter", "wavelength function wgood = numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood]) > 0: d", "return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs): ''' :Purpose: Prints out the current", "units (default = erg/cm2/s/micron) ''' pass def addFlux(self,other,samp=1000): ''' :Purpose:", "__init__(self, magnitude, filt, uncertainty=0., magtype='apparent', verbose=False,**kwargs): self.magnitude = magnitude self.uncertainty", "uncertainty self.type = magtype # check filter and rename if", "uncertainty if e_mag.value > 0.: for i in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact)", "= interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact =", "numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if len(xra) == 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra", "return fwave,ftrans def filterMag(sp,filt,*args,**kwargs): ''' :Purpose: Determine the photometric magnitude", "sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra = [yra[0],yra[1]*1.1] # finish up", "cover the same wavelength ranges if numpy.nanmax(fwave) < numpy.nanmin(sp.wave) or", "= self.uncertainty+other.uncertainty # combine noises if self.uncertainty != 0 and", "an MCMC wrapper, and choose best/average/distribution of parameters ''' pass", "############### ##################################################### class Magnitude(object): ''' :Description: This is a class", "isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans = numpy.zeros(len(fwave))", "set of model magnitudes ''' pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this", "''' :Purpose: Plots a filter profile or set of filter", "= [] fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans", "filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile','vega_kurucz.txt') vega = kwargs.get('vega',True) ab", "{}'.format(sp.name,filt)) return numpy.nan, numpy.nan if numpy.nanmin(fwave) < numpy.nanmin(sp.wave) or numpy.nanmax(fwave)", "J-band 2MASS KS: 2MASS Ks-band BESSEL I: Bessel I-band FOURSTAR", "parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER", "or energy): vega = False ab = False if photons:", "output[kys[0]] else: return output def filterProperties(filt,**kwargs): ''' :Purpose: Returns a", "and upper wavelengths for a notch filter (100% transmission within,", "Spectrum class object, which should contain wave, flux and noise", "= kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER # check", "vegaFile = kwargs.get('vegaFile','vega_kurucz.txt') vega = kwargs.get('vega',True) ab = kwargs.get('ab',not vega)", "file != '': plt.savefig(file) return fig ######################################### ######## SED FITTING", "standard filter; some functions may not work'.format(filt)) self.knownfilter = False", "energy = kwargs.get('flux',energy) if (photons or energy): vega = False", "constants from .initialize import * from .utilities import * #####################################################", "''' chi = 0. dm,em = [],[] for f in", "the closest match based on various statistics ''' pass def", "in fname: f = checkFilterName(k) if f != False: output[f]", "= True: compute Vega magnitudes (may be set by filter)", "= kwargs.get('rsr',True) # Read in filter if isinstance(custom,bool) and isinstance(notch,bool):", "THESE ARE EXPERIMENTAL!! ### ######################################### # plan: def modelMagnitudes(verbose=True): '''", "energy flux. :Required Parameters: **sp**: Spectrum class object, which should", "= trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit = 1. elif (energy): outunit =", "filt == False: return None report = {} report['name'] =", "enumerate(filt): fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): fwave.to(wave_unit) else: fwave =", "kwargs.get('filename',file) file = kwargs.get('output',file) if file != '': plt.savefig(file) return", "match based on various statistics ''' pass def SEDFitMCMC(verbose=True): '''", "out.uncertainty = numpy.nanstd(val) # check filter agreement if self.filter !=", "splat.FILTER_FOLDER: folder containing the filter transmission files **vegaFile** = 'vega_kurucz.txt':", "= filterProfile(filt,**kwargs) try: fwave = fwave.to(u.micron) except: fwave = fwave*u.micron", "{} is not a standard filter; some functions may not", "val = (a/b * c/b).to(outunit).value for i in numpy.arange(nsamples): if", "rename if necessary self.knownfilter = True fflag = checkFilterName(filt,verbose=verbose) if", "= f0 # reset filter calculation methods based on filter", "rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value))) else: result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value))) outunit = 1. elif (ab): nu", "compute AB magnitudes (may be set by filter) **energy** =", "= numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-2.5*numpy.log10(1.+10.**(-0.4*(m2-m1))) out.uncertainty =", "chi = 0. dm,em = [],[] for f in list(mags1.keys()):", "# list of filter names if isinstance(filt[0],str): for f in", "does not span full filter profile for {}'.format(sp.name,filt)) # interpolate", "report['name'] = filt report['description'] = FILTERS[filt]['description'] report['zeropoint'] = FILTERS[filt]['zeropoint'] report['method']", "the input filters {}'.format(filters)) # prep parameters fwave,ftrans = filterProfile(f,**kwargs)", "List the predefined filter names available **verbose** = True: List", "> 0: fname = list(args) elif kwargs.get('filter',False) != False: fname", "# check that spectrum and filter cover the same wavelength", "fluxes ''' # check filter agreement if self.filter != other.filter:", "= {} Jy'.format(output[f]['zeropoint'])) print('Central wavelength: = {:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength: =", "numpy.nanmin(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: no overlap between spectrum", "for i,f in enumerate(filt): fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if len(xra)", "if verbose== True: print('filter {} is not a standard filter;", "2MASS H: 2MASS H-band 2MASS J: 2MASS J-band 2MASS KS:", "except: # print('\\nWarning: unit {} is not an energy flux", "= -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i in numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr:", "0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-2.5*numpy.log10(1.+10.**(-0.4*(m2-m1)))", "!= 0 and other.uncertainty != 0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2", "u.s * u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate Vega onto filter wavelength", "H-band 2MASS J: 2MASS J-band 2MASS KS: 2MASS Ks-band BESSEL", "self.uncertainty != 0 and other.uncertainty != 0: m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp)", "with the filter profile specified by the ``filter`` input. By", "= vwave.to('Hz',equivalencies=u.spectral()) fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst =", "= sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d =", "micron Wavelength range = 1.066 to 1.442 micron >>> data", "filter (100% transmission within, 0% transmission without) **vega** = True:", "LONG: FOURSTAR H long FOURSTAR H SHORT: FOURSTAR H short", "Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True, \\", "= {:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength: = {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point: = {:.3f}'.format(output[f]['lambda_pivot']))", "isinstance(ftrans,u.quantity.Quantity) == True: ftrans=ftrans.value fwave = fwave[~numpy.isnan(ftrans)] ftrans = ftrans[~numpy.isnan(ftrans)]", "but the user can also specify AB magnitudes, photon flux", "list(output.keys()) if len(kys) == 1: return output[kys[0]] else: return output", "IS CURRENTLY UNDER DEVELOPMENT, BUGS MAY BE COMMON ''' filt", "1. # custom filter else: fwave,ftrans = custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity)", "isinstance(fwave,u.quantity.Quantity) == False: fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity) == True: ftrans=ftrans.value fwave", "predefined filter names available **verbose** = True: List the predefined", "and choose the closest match based on various statistics '''", "xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve') legend =", "''' filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER", "u.s) # calculate uncertainty if e_mag.value > 0.: for i", "names available **verbose** = True: List the predefined filter names", "== True: # Read in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile),", "err = 0.*u.erg/(u.cm**2 * u.s) elif ab == True: fconst", "THIS CODE IS CURRENTLY UNDER DEVELOPMENT, BUGS MAY BE COMMON", "two arrays: the filter wavelength and filter transmission curve. :param", "> 0: d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch", "''' pass def interpolateMagnitudes(verbose=True): ''' produces an interpolated value for", "raise NameError('\\nfilterMag not given a correct physical quantity (vega, ab,", "magtype='apparent', verbose=False,**kwargs): self.magnitude = magnitude self.uncertainty = uncertainty self.type =", "photometry\\n\\n') # val = numpy.nanmean(result)*outunit err = numpy.nanstd(result) if len(sp.wave[wgood])", "energy into magnitude instead (optional, default = False) :param ab:", "= trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] =", "magnitude of {}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000): ''' :Purpose: A representation of", "e_mag = kwargs.get('uncertainty',0.) e_mag = kwargs.get('unc',e_mag) e_mag = kwargs.get('e_mag',e_mag) if", "return out def __sub__(self,other,samp=1000): ''' :Purpose: A representation of subtraction", "vega = kwargs.get('vega',True) ab = not vega rsr = FILTERS[filt]['rsr']", "MCMC wrapper, and choose best/average/distribution of parameters ''' pass def", "if self.filter != other.filter: raise ValueError('magnitudes filters {} and {}", "vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'), filling_values", "import os # imports - external import numpy from astropy", "in FILTERS[filt]['method']: rsr = kwargs.get('rsr',True) # Read in filter if", "defined for the filter or provided (required) :param filter: name", "1. elif (energy): outunit = u.erg/u.s/u.cm**2 if rsr: a =", "be set by filter) **ab** = False: compute AB magnitudes", "that specifies the lower and upper wavelengths for a notch", "or numpy.nanmin(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: no overlap between", "i in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err = (numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else:", "'+output[f]['zeropoint']) print('Zeropoint = {} Jy'.format(output[f]['zeropoint'])) print('Central wavelength: = {:.3f}'.format(output[f]['lambda_central'])) print('Mean", "about filter to screen (optional, default = False) WARNING: THIS", "= {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point: = {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength", "magnitude object equal to the equivalent sum of fluxes '''", "FILTERS[f]['zeropoint'] fwave,ftrans = filterProfile(f,**kwargs) try: fwave = fwave.to(u.micron) except: fwave", "a comparison spectrum sp = kwargs.get('spectrum',None) sp = kwargs.get('comparison',sp) if", "magnitudes to a grid of model magnitudes and choose the", "list(FILTERS.keys()): if f==k.upper() or f.lower() in FILTERS[k]['altnames']: output = k", "__sub__(self,other,samp=1000): ''' :Purpose: A representation of subtraction for Magnitude classes", ":Purpose: Returns a dictionary containing key parameters for a particular", "False ab = False if photons: energy = False if", "photons) to compute photometry\\n\\n') # val = numpy.nanmean(result)*outunit err =", "out information about filter to screen (optional, default = False)", "input. By default this filter is also convolved with a", "vega = kwargs.get('vega',True) ab = not vega if 'rsr' in", "functions and constants from .initialize import * from .utilities import", "False: fname = [fname] output = {} for k in", "print('passed') pass # check that input is an energy flux", "2MASS H-band 2MASS J: 2MASS J-band 2MASS KS: 2MASS Ks-band", "else: if verbose==True: print('\\nWarning: data values in range of filter", "result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise NameError('\\nfilterMag not given a correct physical quantity", "default = splat.FILTER_FOLDER) :Example: >>> import splat >>> import splat.photometry", "fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b", "containing key parameters for a particular filter. :param filter: name", "the filter profile for a SPLAT filter. Returns two arrays:", "* ##################################################### ############### SPECTROPHOTOMETRY ############### ##################################################### # this function has", "Jy'.format(report['zeropoint'])) print('Pivot point: = {:.3f}'.format(report['lambda_pivot'])) print('FWHM = {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range", "whatever system is defined for the filter or provided (required)", "fname = [fname] output = {} for k in fname:", "specifying the wavelengths and transmissions for a custom filter **notch**", "numpy.nan return val, err # energy -> magnitude # THIS", "= numpy.array(em) offset = numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo = numpy.array([m-offset for", "grid set of model magnitudes ''' pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): '''", "magnitude self.uncertainty = uncertainty self.type = magtype # check filter", "reference library. ''' verbose = kwargs.get('verbose',True) if len(args) > 0:", "filling_values = (numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray)) if", "units as u # standard units from astropy import constants", "isinstance(ftrans,numpy.ndarray)) if not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem reading", "= [yra[0],yra[1]*1.1] # finish up plt.xlim(xra) plt.ylim(yra) plt.xlabel(xl) plt.ylabel(yl) plt.legend(legend)", "wgood = numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood]) > 0: d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.)", "and vice versa. :param mag: magnitude on whatever system is", "SPLAT_URL+FILTER_FOLDER # check that requested filter is in list filt", "custom filter **notch** = None: A 2 element array that", "ranges if isinstance(filt[0],list): xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission", "def modelMagnitudes(verbose=True): ''' this will be a code that calculates", "into account uncertainties :Output: A new Magnitude object equal to", "fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): wave_unit = kwargs.get('wave_unit',fwave.unit) xl =", "fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central']", "wave_unit = kwargs.get('wave_unit',fwave.unit) xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission", "(14.345894376898123, 0.027596454828421831) ''' # keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if", "filter to screen (optional, default = False) WARNING: THIS CODE", "self.filter = filt # some things that are based on", "of a Magnitude object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return", "e_mag = kwargs.get('e_mag',e_mag) if not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if not isinstance(e_mag,u.quantity.Quantity):", "agreement if self.filter != other.filter: out.filter = '{}-{}'.format(self.filter,other.filter) return out", "for i in numpy.arange(nsamples): if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif", "__add__(self,other,samp=1000): ''' :Purpose: A representation of addition for Magnitude classes", "len(sp.wave[wgood]) > 0: d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) #", "False: return numpy.nan, numpy.nan filt = f0 # reset filter", ":param reverse: convert energy into magnitude instead (optional, default =", "utf-8 -*- from __future__ import print_function, division \"\"\" .. note::", "String giving the name of one of the predefined filters", "{:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength: = {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point: = {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM", "= (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >=", "interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i in", "in Monte Carlo error estimation **info** = False: List the", "spectrum and filter cover the same wavelength ranges if numpy.nanmax(fwave)", "same wavelength ranges if numpy.nanmax(fwave) < numpy.nanmin(sp.wave) or numpy.nanmin(fwave) >", "filterProperties(filt,**kwargs): ''' :Purpose: Returns a dictionary containing key parameters for", "filters in the SPLAT reference library. ''' verbose = kwargs.get('verbose',True)", ":param ab: magnitude is on the AB system (optional, default", "element array that specifies the lower and upper wavelengths for", "if isinstance(custom,bool) and isinstance(notch,bool): f0 = checkFilterName(filt,verbose=True) if f0 ==", "self.knownfilter = True fflag = checkFilterName(filt,verbose=verbose) if fflag == False:", "A 2 x N vector array specifying the wavelengths and", "energy): vega = False ab = False if photons: energy", "numpy.max(fw) if verbose ==True: print(f.replace('_',' ')+': '+output[f]['zeropoint']) print('Zeropoint = {}", "''' :Purpose: Converts a magnitude into an energy, and vice", "scipy.integrate import trapz # for numerical integration from scipy.interpolate import", "print('Wavelength range = {:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report def magToFlux(mag,filt,**kwargs):", "= 0.323 micron Wavelength range = 1.066 to 1.442 micron", "-*- coding: utf-8 -*- from __future__ import print_function, division \"\"\"", "this code will conduct a comparison of a set of", "SPLAT reference library. ''' verbose = kwargs.get('verbose',True) if len(args) >", "filter calculation methods based on filter design if 'ab' in", "make a copy and fill in combined magnitude out =", "self.uncertainty = uncertainty self.type = magtype # check filter and", "import print_function, division \"\"\" .. note:: These are the spectrophotometry", "out = copy.deepcopy(self) out.magnitude = self.magnitude-other.magnitude out.uncertainty = self.uncertainty+other.uncertainty #", "within ``filterFolder`` **nsamples** = 100: number of samples to use", "= (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for i in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise NameError('\\nfilterMag", "of magnitudes using one of several statistics ''' chi =", "a dictionary containing key parameters for a particular filter. :param", "report = {} report['name'] = filt report['description'] = FILTERS[filt]['description'] report['zeropoint']", "kwargs.get('vegaFile',VEGAFILE) info = kwargs.get('info',False) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False)", "without) **vega** = True: compute Vega magnitudes (may be set", "numpy.min(fw) report['lambda_max'] = numpy.max(fw) report['wave'] = fwave report['transmission'] = ftrans", "err = numpy.nanstd(result) if len(sp.wave[wgood]) == 0: err = 0.", "= kwargs.get('unc',e_mag) e_mag = kwargs.get('e_mag',e_mag) if not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if", "of addition for magnitudes (addition of fluxes) :Output: A new", "an energy flux unit'.format(return_unit)) try: val.to(base_unit) err.to(base_unit) except: print('\\nWarning: cannot", "FILTERS[filt]['method']: ab = kwargs.get('ab',True) vega = not ab if 'vega'", "= plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans)", "2MASS KS: 2MASS Ks-band BESSEL I: Bessel I-band FOURSTAR H:", "filt = checkFilterName(filt) if filt == False: return numpy.nan, numpy.nan", ":param filterFolder: folder containing the filter transmission files (optional, default", "user can also specify AB magnitudes, photon flux or energy", "as const # physical constants in SI units import matplotlib.patches", "not in SPLAT filter list'.format(k)) kys = list(output.keys()) if len(kys)", "error estimation **info** = False: List the predefined filter names", "2MASS J: 2MASS J-band 2MASS KS: 2MASS Ks-band BESSEL I:", "filter preference) :param vega: magnitude is on the Vega system", "filter, must be one of the specifed filters given by", "{:.3f}'.format(report['lambda_pivot'])) print('FWHM = {:.3f}'.format(report['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max']))", "a custom filter **notch** = None: A 2 element array", "(Nelder-Mead) wrapper, and choose the closest match ''' pass def", "Vega magnitudes (may be set by filter) **ab** = False:", ":Example: >>> import splat >>> import splat.photometry as spphot >>>", "transmission files (optional, default = splat.FILTER_FOLDER) :Example: >>> import splat", "not ab if 'vega' in FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab", "os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER # check that requested filter is", "# imports - internal import copy import os # imports", "numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))] =", "fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True, missing_values = ('NaN','nan'), filling_values =", "fwave.to(u.micron) else: fwave = fwave*u.micron # check that spectrum and", "spectrum vflux = vflux[vwave>=numpy.nanmin(fwave)] vwave = vwave[vwave>=numpy.nanmin(fwave)] vflux = vflux[vwave<=numpy.nanmax(fwave)]", "recognize any of the input filters {}'.format(filters)) # prep parameters", "######### ### WARNING: THESE ARE EXPERIMENTAL!! ### ######################################### # plan:", "if len(sp.wave[wgood]) == 0: err = 0. return val*outunit,err*outunit def", "= numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if len(xra) == 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)]", "This is a class data structure for a magnitude value", "= kwargs.get('ab',True) vega = not ab if 'vega' in FILTERS[filt]['method']:", "conduct a comparison of a set of magnitudes to model", "# check that requested filter is in list filt =", "err = 0. # magnitude -> energy if kwargs.get('reverse',False) ==", "fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact = trapz(ftrans*v(fwave.value),fwave.value) val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2", "not span full filter profile for {}'.format(sp.name,filt)) # interpolate spectrum", "of model magnitudes and choose the closest match based on", "== False: if verbose==True: print('Removed filter {}: not included in", "numpy.nan, numpy.nan if numpy.nanmin(fwave) < numpy.nanmin(sp.wave) or numpy.nanmax(fwave) > numpy.nanmax(sp.wave):", "isinstance(custom,bool) and isinstance(notch,bool): f0 = checkFilterName(filt,verbose=True) if f0 == False:", "input filters {}'.format(filters)) # prep parameters fwave,ftrans = filterProfile(f,**kwargs) if", "!= 0. and numpy.isfinite(self.uncertainty): return '{} magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else:", "TOOLS ######### ### WARNING: THESE ARE EXPERIMENTAL!! ### ######################################### #", "f0 == False: raise ValueError filt = f0 # read", "patches import matplotlib.pyplot as plt from scipy.integrate import trapz #", "splat.FILTERS.keys() or a custom filter name :Optional Parameters: **custom** =", "= numpy.nanstd(result) if len(sp.wave[wgood]) == 0: err = 0. return", "print('Central wavelength: = {:.3f}'.format(output[f]['lambda_central'])) print('Mean wavelength: = {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point:", "= interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result = [] if (vega): # Read in", "a spectrum WARNING: THIS CODE IS CURRENTLY UNDER DEVELOPMENT, BUGS", "a set of magnitudes to model magnitudes using an MCMC", "!= False: output[f] = {} output[f]['description'] = FILTERS[f]['description'] output[f]['zeropoint'] =", "subtraction for Magnitude classes that takes into account uncertainties :Output:", "= interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs): '''", "filling_values = (numpy.nan)) vwave = vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 *", "list(args) elif kwargs.get('filter',False) != False: fname = kwargs['filter'] else: fname", "to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report def magToFlux(mag,filt,**kwargs): ''' :Purpose: Converts a", "and f not in ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f]) # find best", "on the Vega system (optional, default = filter preference) :param", "file = kwargs.get('output',file) if file != '': plt.savefig(file) return fig", "def __sub__(self,other,samp=1000): ''' :Purpose: A representation of subtraction for Magnitude", "will be a code that calculates a set of magnitudes", "'vega' in FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab = not vega", "of subtraction for Magnitude classes that takes into account uncertainties", "out def flux(self,type='fnu',samp=1000): ''' :Purpose: Report the equivalent flux density", "False) :param ab: magnitude is on the AB system (optional,", "function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else:", "kwargs.get('unit',base_unit) e_mag = kwargs.get('uncertainty',0.) e_mag = kwargs.get('unc',e_mag) e_mag = kwargs.get('e_mag',e_mag)", "ValueError('magnitudes filters {} and {} are not the same'.format(self.filter,other.filter)) #", "kwargs.get('flux',energy) if (photons or energy): vega = False ab =", "= (numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray)) if not", "to file that could be uploaded pre-save some model magnitudes", "os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile','vega_kurucz.txt') vega = kwargs.get('vega',True)", "= custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity) == False: fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity) ==", "spphot.filterMag(sp,'MKO J') (14.345894376898123, 0.027596454828421831) ''' # keyword parameters filterFolder =", "isinstance(filt[0],str): for f in filt: fc = checkFilterName(f) filt.remove(f) if", "use in Monte Carlo error estimation **info** = False: List", "==True: print(f.replace('_',' ')+': '+output[f]['zeropoint']) print('Zeropoint = {} Jy'.format(output[f]['zeropoint'])) print('Central wavelength:", "kwargs.get('ylabel','Transmission Curve') # list of notch ranges if isinstance(filt[0],int) or", "for a SPLAT filter. Returns two arrays: the filter wavelength", "filters {}'.format(filters)) # prep parameters fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave):", "a magnitude into an energy, and vice versa. :param mag:", "for {} does not span full filter profile for {}'.format(sp.name,filt))", "''' filt = copy.deepcopy(filters) wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single filter", "(100% transmission within, 0% transmission without) **vega** = True: compute", "return s def __repr__(self): ''' :Purpose: A simple representation of", "Magnitude(object): ''' :Description: This is a class data structure for", "= kwargs.get('verbose',False) # check that requested filter is in list", "of a spectrum WARNING: THIS CODE IS CURRENTLY UNDER DEVELOPMENT,", "copy import os # imports - external import numpy from", ":Purpose: Report the equivalent flux density of a magnitude :Output:", "ftrans # report values out if kwargs.get('verbose',False): print('\\nFilter '+filt+': '+report['description'])", "in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave = fwave[~numpy.isnan(ftrans)]*u.micron ftrans = ftrans[~numpy.isnan(ftrans)] return fwave,ftrans", "d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch for models", "vflux[vwave>=numpy.nanmin(fwave)] vwave = vwave[vwave>=numpy.nanmin(fwave)] vflux = vflux[vwave<=numpy.nanmax(fwave)] vwave = vwave[vwave<=numpy.nanmax(fwave)]", "files (optional, default = splat.FILTER_FOLDER) :Example: >>> import splat >>>", "and constants from .initialize import * from .utilities import *", "* c/b).to(outunit).value else: a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans,fwave.value)*sp.wave.unit c", "{:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if verbose ==True: print(' Filter {} not in", "astropy import constants as const # physical constants in SI", "numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] = numpy.min(fw)", "containing the filter transmission files **vegaFile** = 'vega_kurucz.txt': name of", "print('\\nWarning: unit {} is not an energy flux unit'.format(return_unit)) try:", "convert to desired energy units # try: val.to(return_unit) err.to(return_unit) #", "f0 == False: return numpy.nan, numpy.nan filt = f0 #", "object equal to the diffence of values ''' # make", "units import matplotlib.patches as patches import matplotlib.pyplot as plt from", "kwargs.get('verbose',True) if len(args) > 0: fname = list(args) elif kwargs.get('filter',False)", "is defined for the filter or provided (required) :param filter:", "THIS CODE IS ONLY PARTIALLY COMPLETE ''' # keyword parameters", "magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude+other.magnitude out.uncertainty = self.uncertainty+other.uncertainty", "H short ... ''' filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder):", "for i,f in enumerate(filt): fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): fwave.to(wave_unit)", "fwave,ftrans = custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity) == False: fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity)", "Monte Carlo error estimation **info** = False: List the predefined", "set by filter) **energy** = False: compute energy flux **photon**", "flux file, must be within ``filterFolder`` **nsamples** = 100: number", "filter profile for {}'.format(sp.name,filt)) # interpolate spectrum onto filter wavelength", "units # try: val.to(return_unit) err.to(return_unit) # except: # print('\\nWarning: unit", "spectrum WARNING: THIS CODE IS CURRENTLY UNDER DEVELOPMENT, BUGS MAY", "in list f0 = checkFilterName(filt, verbose=True) if f0 == False:", "fact = trapz(ftrans.value*fwave.value,fwave.value) else: fact = trapz(ftrans.value,fwave.value) val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2", "set of magnitudes to a grid of model magnitudes and", "def SEDFitAmoeba(verbose=True): ''' this code will conduct a comparison of", "= numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] =", "in combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty", "-> magnitude # THIS NEEDS TO BE COMPLETED else: print('passed')", "and noise array elements. **filter**: String giving name of filter,", "1.252 micron FWHM = 0.323 micron Wavelength range = 1.066", "SPLAT filter. Returns two arrays: the filter wavelength and filter", "n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch for models else: if verbose==True:", "unit'.format(mag.unit)) def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose: Plots a filter profile or", "fill in combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude+other.magnitude", "None: A 2 element array that specifies the lower and", "0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] = numpy.min(fw) output[f]['lambda_max'] = numpy.max(fw)", "verbose==True: print('\\nWarning: data values in range of filter {} have", "nu = sp.wave.to('Hz',equivalencies=u.spectral()) fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu", "in splat.FILTERS.keys() (required) :param filterFolder: folder containing the filter transmission", "magnitudes, but the user can also specify AB magnitudes, photon", "100: number of samples to use in Monte Carlo error", "flux or energy flux. :Required Parameters: **sp**: Spectrum class object,", "a correct physical quantity (vega, ab, energy, photons) to compute", "kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER # check that", "# physical constants in SI units import matplotlib.patches as patches", "= kwargs.get('nsamples',100) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) base_unit =", "m in dm]) return numpy.sum((dmo/em)**2), offset def SEDFitGrid(verbose=True): ''' this", "the same wavelength ranges if numpy.nanmax(fwave) < numpy.nanmin(sp.wave) or numpy.nanmin(fwave)", "vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) # trim", "if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER # check that requested", "= 0.*u.erg/(u.cm**2 * u.s) elif ab == True: fconst =", "import splat >>> import splat.photometry as spphot >>> sp =", "False and verbose == True: print('\\nFilter '+filt+' not currently available", ":Purpose: A representation of subtraction for Magnitude classes that takes", "== False and verbose == True: print('\\nFilter '+filt+' not currently", "fname: f = checkFilterName(k) if f != False: output[f] =", "xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description'])", "choose the closest match ''' pass def SEDVisualize(verbose=True): ''' Visualizes", "photometric magnitude of a source based on its spectrum. Spectral", "numpy.nanmin(sp.wave) or numpy.nanmin(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: no overlap", "of fluxes ''' # check filter agreement if self.filter !=", "fwave,ftrans = custom[0],custom[1] # Read in Vega spectrum vwave,vflux =", "by splat.FILTERS.keys() (required) :param reverse: convert energy into magnitude instead", "from .utilities import * ##################################################### ############### SPECTROPHOTOMETRY ############### ##################################################### #", "on the AB system (optional, default = filter preference) :param", "vega) rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) verbose = kwargs.get('verbose',False)", "input is an energy flux # try: # mag.to(base_unit) #", "if file != '': plt.savefig(file) return fig ######################################### ######## SED", "erg/cm2/s) :param verbose: print out information about filter to screen", "saves to file that could be uploaded pre-save some model", "# val = numpy.nanmean(result)*outunit err = numpy.nanstd(result) if len(sp.wave[wgood]) ==", "about filter to screen :type verbose: optional, default = True", "optionally on top of a spectrum WARNING: THIS CODE IS", "plt.savefig(file) return fig ######################################### ######## SED FITTING TOOLS ######### ###", "e_mag.value > 0.: for i in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err =", "raise ValueError('\\nProblem reading in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave = fwave[~numpy.isnan(ftrans)]*u.micron ftrans =", "is in list if isinstance(custom,bool) and isinstance(notch,bool): f0 = checkFilterName(filt,verbose=True)", "numpy.isfinite(self.uncertainty): return '{} magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return '{} magnitude", "check that input is an energy flux # try: #", "return_unit = kwargs.get('unit',base_unit) e_mag = kwargs.get('uncertainty',0.) e_mag = kwargs.get('unc',e_mag) e_mag", "spectrum. Spectral fluxes are convolved with the filter profile specified", "SED scale (flux = lam x F_lam), with option of", "'+filt+': '+report['description']) print('Zeropoint = {} Jy'.format(report['zeropoint'])) print('Pivot point: = {:.3f}'.format(report['lambda_pivot']))", "if FILTERS[f]['rsr'] == True: yl = kwargs.get('ylabel','Transmission Curve') # list", "a class data structure for a magnitude value ''' def", "= numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood]) > 0: d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n", "reading in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave = fwave[~numpy.isnan(ftrans)]*u.micron ftrans = ftrans[~numpy.isnan(ftrans)] return", "numpy.nan filt = f0 rsr = FILTERS[filt]['rsr'] # Read in", "unit {} is not an energy flux unit'.format(return_unit)) try: val.to(base_unit)", "= -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i in numpy.arange(nsamples): a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b))", "a filter profile or set of filter profiles, optionally on", "filter name if isinstance(filt,str): filt = [filt] if isinstance(filt,list): #", "= 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b =", "filter agreement if self.filter != other.filter: out.filter = '{}+{}'.format(self.filter,other.filter) return", "filter agreement if self.filter != other.filter: out.filter = '{}-{}'.format(self.filter,other.filter) return", "trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05)", "report['method'] = FILTERS[filt]['method'] report['rsr'] = FILTERS[filt]['rsr'] fwave,ftrans = filterProfile(filt,**kwargs) try:", "magnitude is on the Vega system (optional, default = filter", "ValueError('Did not recognize any of the input filters {}'.format(filters)) #", "to compute photometry\\n\\n') # val = numpy.nanmean(result)*outunit err = numpy.nanstd(result)", "SEDFitAmoeba(verbose=True): ''' this code will conduct a comparison of a", "isinstance(fname,list) == False: fname = [fname] output = {} for", "= erg/cm2/s) :param verbose: print out information about filter to", "= fwave.to(u.micron) else: fwave = fwave*u.micron # check that spectrum", "sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra = [yra[0],yra[1]*1.1] # finish up plt.xlim(xra)", "COMPLETE ''' # keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not", "check filter agreement if self.filter != other.filter: out.filter = '{}+{}'.format(self.filter,other.filter)", "print('\\nWarning: spectrum for {} does not span full filter profile", "the ``filter`` input. By default this filter is also convolved", "= kwargs.get('verbose',True) if len(args) > 0: fname = list(args) elif", "(flux = lam x F_lam), with option of also comparing", "cannot convert result to an energy flux unit'.format(base_unit)) return numpy.nan,", "trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit = 1. elif (energy): outunit = u.erg/u.s/u.cm**2", "notch ranges if isinstance(filt[0],list): xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl =", "system (optional, default = filter preference) :param vega: magnitude is", "values in range of filter {} have no uncertainties'.format(filt)) d", "H: FOURSTAR H-band FOURSTAR H LONG: FOURSTAR H long FOURSTAR", "3631*u.jansky ftrans = (ftrans*fconst).to(u.erg/(u.cm**2 * u.s * u.micron),equivalencies=u.spectral_density(fwave)) if rsr:", "''' pass def SEDFitMCMC(verbose=True): ''' this code will conduct a", ">>> import splat >>> import splat.photometry as spphot >>> sp", "result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons): outunit = 1./u.s/u.cm**2 convert = const.h.to('erg s')*const.c.to('micron/s')", "= 0. return val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check that requested", "output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) output[f]['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min']", "also comparing to SED spectrum ''' pass ##################################################### ############### MAGNITUDE", "= (numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else: err = 0.*u.erg/(u.cm**2 * u.s)", "kwargs.get('output',file) if file != '': plt.savefig(file) return fig ######################################### ########", "Returns a dictionary containing key parameters for a particular filter.", "uncertainties :Output: A new Magnitude object equal to the diffence", "FILTERS[k]['altnames']: output = k if output == False and verbose", "with option of also comparing to SED spectrum ''' pass", "this filter is also convolved with a model of Vega", "* c/b).to(outunit).value for i in numpy.arange(nsamples): if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else:", "[filt] if isinstance(filt,list): # list of filter names if isinstance(filt[0],str):", "= interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i", "if rsr: val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for", "= filterProfile(f,**kwargs) if isUnit(fwave): fwave.to(wave_unit) else: fwave = fwave*wave_unit if", "N vector array specifying the wavelengths and transmissions for a", "== False: return numpy.nan, numpy.nan # reset filter calculation methods", "filter agreement if self.filter != other.filter: raise ValueError('magnitudes filters {}", "s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s # backup version def", "return val, err # energy -> magnitude # THIS NEEDS", "from __future__ import print_function, division \"\"\" .. note:: These are", "')+': '+output[f]['zeropoint']) print('Zeropoint = {} Jy'.format(output[f]['zeropoint'])) print('Central wavelength: = {:.3f}'.format(output[f]['lambda_central']))", "FILTERS[filt]['rsr'] fwave,ftrans = filterProfile(filt,**kwargs) try: fwave = fwave.to(u.micron) except: fwave", "kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile','vega_kurucz.txt')", "spectrum sp = kwargs.get('spectrum',None) sp = kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum) ==", "plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra = [yra[0],yra[1]*1.1] # finish up plt.xlim(xra) plt.ylim(yra)", "Read in filter if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans = filterProfile(filt,**kwargs)", "''' pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this code compares a set", "conversion does not work, the conversion is ignored (optional, default", "to extract Vega magnitudes, but the user can also specify", "interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result = [] if (vega): #", "e_mag.to(base_unit) # except: # raise ValueError('\\nInput quantity unit {} is", "transmission curve. :param filter: String giving the name of one", "and numpy.isfinite(self.uncertainty): return '{} magnitude of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return '{}", "filter to screen :type verbose: optional, default = True :Example:", "''' pass def addFlux(self,other,samp=1000): ''' :Purpose: A representation of addition", "os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile',VEGAFILE) info = kwargs.get('info',False)", "information about filter to screen (optional, default = False) WARNING:", "m1-m2 out.uncertainty = numpy.nanstd(val) # check filter agreement if self.filter", "trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b", "compare a set of magnitudes to a grid of model", "dm,em = [],[] for f in list(mags1.keys()): if f in", "filterProperties(self.filter) for k in info.keys(): setattr(self,k,info[k]) def __copy__(self): ''' :Purpose:", "H long FOURSTAR H SHORT: FOURSTAR H short ... '''", "magnitudes (may be set by filter) **ab** = False: compute", "# combine noises if self.uncertainty != 0 and other.uncertainty !=", "= kwargs.get('photons',False) photons = kwargs.get('photon',photons) energy = kwargs.get('energy',False) energy =", "False: if vega == True: # Read in Vega spectrum", "s # backup version def copy(self): ''' :Purpose: Make a", "= sp.wave.to('Hz',equivalencies=u.spectral()) fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu =", "have no uncertainties'.format(filt)) d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result", "filter. :param filter: name of filter, must be one of", "vega rsr = FILTERS[filt]['rsr'] # other possibilities photons = kwargs.get('photons',False)", "# try: # mag.to(base_unit) # e_mag.to(base_unit) # except: # raise", "self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty = self.uncertainty+other.uncertainty # combine noises if self.uncertainty !=", "= numpy.min(fw) output[f]['lambda_max'] = numpy.max(fw) if verbose ==True: print(f.replace('_',' ')+':", "return numpy.nan, numpy.nan filt = f0 # reset filter calculation", "X') Filter 2MASS X not among the available filters: 2MASS", "classes that takes into account uncertainties :Output: A new Magnitude", "vega if 'rsr' in FILTERS[filt]['method']: rsr = kwargs.get('rsr',True) # Read", "= kwargs.get('filename',file) file = kwargs.get('output',file) if file != '': plt.savefig(file)", "= kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) custom = kwargs.get('custom',False) notch =", "for f in list(mags1.keys()): if f in list(mags2.keys()) and f", "input {}'.format(filt)) # add a comparison spectrum sp = kwargs.get('spectrum',None)", "== False: return numpy.nan, numpy.nan filt = f0 # reset", "< numpy.nanmin(sp.wave) or numpy.nanmax(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: spectrum", "flux # try: # mag.to(base_unit) # e_mag.to(base_unit) # except: #", "addition for magnitudes (addition of fluxes) :Output: A new magnitude", "filter name :Optional Parameters: **custom** = None: A 2 x", "interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0) # catch for models else: if", "isinstance(sp,splat.core.Spectrum) == True: print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name) yra =", "transmissions for a custom filter **notch** = None: A 2", "Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True, \\ missing_values =", "len(xra) == 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra", "of notch ranges if isinstance(filt[0],list): xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl", "fwave[~numpy.isnan(ftrans)]*u.micron ftrans = ftrans[~numpy.isnan(ftrans)] return fwave,ftrans def filterMag(sp,filt,*args,**kwargs): ''' :Purpose:", "try: val.to(base_unit) err.to(base_unit) except: print('\\nWarning: cannot convert result to an", "= kwargs.get('vega',True) ab = not vega rsr = FILTERS[filt]['rsr'] #", "fflag self.filter = filt # some things that are based", "same'.format(self.filter,other.filter)) # make a copy and fill in combined magnitude", "if len(args) > 0: fname = list(args) elif kwargs.get('filter',False) !=", "not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER # check that requested filter", "uncertainties :Output: A new Magnitude object equal to the sum", "val = m1+m2 out.uncertainty = numpy.nanstd(val) # check filter agreement", "output[f]['zeropoint'] = FILTERS[f]['zeropoint'] fwave,ftrans = filterProfile(f,**kwargs) try: fwave = fwave.to(u.micron)", "= kwargs['filter'] else: fname = sorted(list(FILTERS.keys())) if isinstance(fname,list) == False:", "magnitude on whatever system is defined for the filter or", "ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw))", "spectrum ''' pass ##################################################### ############### MAGNITUDE CLASS ############### ##################################################### class", "= numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'), filling_values =", "i,f in enumerate(filt): fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): fwave.to(wave_unit) else:", "* u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate Vega onto filter wavelength function", "err = 0. return val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check that", "erg/cm2/s/micron) ''' pass def addFlux(self,other,samp=1000): ''' :Purpose: A representation of", "an energy, and vice versa. :param mag: magnitude on whatever", "ab if 'vega' in FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab =", "a comparison of a set of magnitudes to model magnitudes", "if this conversion does not work, the conversion is ignored", "extract Vega magnitudes, but the user can also specify AB", "sum of values ''' # make a copy and fill", "0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot']", "''' pass def SEDFitAmoeba(verbose=True): ''' this code will conduct a", "new magnitude object equal to the equivalent sum of fluxes", "containing the filter transmission files (optional, default = splat.FILTER_FOLDER) :Example:", "integration from scipy.interpolate import interp1d # splat functions and constants", "can either be one of the predefined filters listed in", "notch = kwargs.get('notch',False) vega = kwargs.get('vega',True) ab = kwargs.get('ab',not vega)", "numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo = numpy.array([m-offset for m in dm]) return", "b = trapz(ftrans,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b *", "> 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw)) #", "fc == False: if verbose==True: print('Removed filter {}: not included", "a custom filter name :Optional Parameters: **custom** = None: A", "notch[1]))] = 1. # custom filter else: fwave,ftrans = custom[0],custom[1]", "'': plt.savefig(file) return fig ######################################### ######## SED FITTING TOOLS #########", "k if output == False and verbose == True: print('\\nFilter", "numpy.max(fw05)-numpy.min(fw05) output[f]['lambda_min'] = numpy.min(fw) output[f]['lambda_max'] = numpy.max(fw) if verbose ==True:", "filters: 2MASS H: 2MASS H-band 2MASS J: 2MASS J-band 2MASS", "filter preference) :param rsr: magnitude is on the Vega system", "= list(output.keys()) if len(kys) == 1: return output[kys[0]] else: return", "n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result = [] if (vega): # Read", "for k in list(FILTERS.keys()): if f==k.upper() or f.lower() in FILTERS[k]['altnames']:", "wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single filter name if isinstance(filt,str): filt", "within, 0% transmission without) **vega** = True: compute Vega magnitudes", "= 1594.0 Jy Pivot point: = 1.252 micron FWHM =", "= checkFilterName(filt, verbose=True) if f0 == False: raise ValueError filt", "are based on presets if self.knownfilter == True: self.wave,self.transmission =", "report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) report['lambda_min']", "object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s # backup", "f = f.replace(' ','_').upper() for k in list(FILTERS.keys()): if f==k.upper()", "value ''' def __init__(self, magnitude, filt, uncertainty=0., magtype='apparent', verbose=False,**kwargs): self.magnitude", "and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans =", "filter **notch** = None: A 2 element array that specifies", "out.magnitude = self.magnitude-other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises if", "# list of notch ranges if isinstance(filt[0],list): xl = kwargs.get('xlabel','Wavelength", "Spectrum object ''' if self.uncertainty != 0. and numpy.isfinite(self.uncertainty): return", "fwave*u.micron fw = fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] ft = ftrans[numpy.where(ftrans >", "Ks-band BESSEL I: Bessel I-band FOURSTAR H: FOURSTAR H-band FOURSTAR", "verbose: print out information about filter to screen (optional, default", "model magnitudes and choose the closest match based on various", "included in SPLAT'.format(f)) else: filt.insert(len(filt),fc) if len(filt) == 0: raise", "# save if desired file = kwargs.get('file','') file = kwargs.get('filename',file)", "specified') # convert to desired energy units # try: val.to(return_unit)", "== True: self.wave,self.transmission = filterProfile(self.filter) info = filterProperties(self.filter) for k", "sorted(list(FILTERS.keys())) if isinstance(fname,list) == False: fname = [fname] output =", "if self.filter != other.filter: out.filter = '{}-{}'.format(self.filter,other.filter) return out def", "kwargs.get('verbose',False): print('\\nFilter '+filt+': '+report['description']) print('Zeropoint = {} Jy'.format(report['zeropoint'])) print('Pivot point:", "on presets if self.knownfilter == True: self.wave,self.transmission = filterProfile(self.filter) info", "fname = kwargs['filter'] else: fname = sorted(list(FILTERS.keys())) if isinstance(fname,list) ==", ":Output: A new Magnitude object equal to the sum of", "out = copy.deepcopy(self) out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty = self.uncertainty+other.uncertainty #", "interpolate Vega onto filter wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if", "of parameters ''' pass def SEDFitAmoeba(verbose=True): ''' this code will", "# convert to desired energy units # try: val.to(return_unit) err.to(return_unit)", "except: print('\\nWarning: cannot convert result to an energy flux unit'.format(base_unit))", "a source based on its spectrum. Spectral fluxes are convolved", "def __repr__(self): ''' :Purpose: A simple representation of the Spectrum", "of filter, must be one of the specifed filters given", "f != False: output[f] = {} output[f]['description'] = FILTERS[f]['description'] output[f]['zeropoint']", "> 0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw)) # print(trapz(fw*ft,fw)) report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot']", "are the spectrophotometry functions for SPLAT \"\"\" # imports -", "############### ##################################################### # this function has been obseleted def checkFilter(filt,verbose=True):", "be one of the predefined filters listed in splat.FILTERS.keys() or", "# interpolate spectrum onto filter wavelength function wgood = numpy.where(~numpy.isnan(sp.noise))", "= filter preference) :param rsr: magnitude is on the Vega", "the Spectrum object ''' if self.uncertainty != 0. and numpy.isfinite(self.uncertainty):", "dictionary containing key parameters for a particular filter. :param filter:", "an energy flux unit'.format(base_unit)) return numpy.nan, numpy.nan return val, err", "f = copy.deepcopy(filt) f = f.replace(' ','_').upper() for k in", "combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-other.magnitude out.uncertainty =", "if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile',VEGAFILE) info", "report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] = numpy.min(fw) report['lambda_max'] = numpy.max(fw) report['wave']", "kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile',VEGAFILE)", "== True: fwave = fwave.to(u.micron) else: fwave = fwave*u.micron #", "list of filters in the SPLAT reference library. ''' verbose", "vwave = vwave[vwave<=numpy.nanmax(fwave)] # convert to fnu nu = vwave.to('Hz',equivalencies=u.spectral())", "output = {} for k in fname: f = checkFilterName(k)", "the Vega system (optional, default = filter preference) :param rsr:", "= copy.deepcopy(self) out.magnitude = self.magnitude-other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine", "# standard units from astropy import constants as const #", "import * ##################################################### ############### SPECTROPHOTOMETRY ############### ##################################################### # this function", "given a correct physical quantity (vega, ab, energy, photons) to", "base_unit = u.erg/(u.cm**2 * u.s) return_unit = kwargs.get('unit',base_unit) e_mag =", "to an energy flux unit'.format(base_unit)) return numpy.nan, numpy.nan return val,", "kwargs.get('notch',False) vega = kwargs.get('vega',True) ab = kwargs.get('ab',not vega) rsr =", "isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray): raise ValueError('\\nProblem reading in {}'.format(filterFolder+FILTERS[filt]['file'])) fwave", "several statistics ''' chi = 0. dm,em = [],[] for", "isinstance(fwave,u.quantity.Quantity) == True: fwave = fwave.to(u.micron) else: fwave = fwave*u.micron", "= 1./u.s/u.cm**2 convert = const.h.to('erg s')*const.c.to('micron/s') val = (trapz(ftrans*fwave.value*convert.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value for", "uncertainties'.format(filt)) d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result = []", "0. # magnitude -> energy if kwargs.get('reverse',False) == False: if", "transmission files **vegaFile** = 'vega_kurucz.txt': name of file containing Vega", "if f0 == False: raise ValueError filt = f0 #", "plt.ylabel(yl) plt.legend(legend) # save if desired file = kwargs.get('file','') file", "self.type = magtype # check filter and rename if necessary", "(10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s) # calculate uncertainty if e_mag.value > 0.:", "else: filt.insert(len(filt),fc) if len(filt) == 0: raise ValueError('Did not recognize", "except: fwave = fwave*u.micron fw = fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] ft", "model set's SED models saves to file that could be", "report['description'] = FILTERS[filt]['description'] report['zeropoint'] = FILTERS[filt]['zeropoint'] report['method'] = FILTERS[filt]['method'] report['rsr']", "function wgood = numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood]) > 0: d =", "= trapz(ftrans,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value", "(vega, ab, energy, photons) to compute photometry\\n\\n') # val =", "filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER #", "f0 = checkFilterName(filt,verbose=True) if f0 == False: return numpy.nan, numpy.nan", "def __add__(self,other,samp=1000): ''' :Purpose: A representation of addition for Magnitude", "if isinstance(filt[0],list): xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve')", "also specify AB magnitudes, photon flux or energy flux. :Required", "be a code that calculates a set of magnitudes for", "in flux density units (default = erg/cm2/s/micron) ''' pass def", "or ab method specified') # convert to desired energy units", "of a magnitude :Output: astropy quantity in flux density units", "J: 2MASS J-band Zeropoint = 1594.0 Jy Pivot point: =", "SED spectrum ''' pass ##################################################### ############### MAGNITUDE CLASS ############### #####################################################", "among the available filters: 2MASS H: 2MASS H-band 2MASS J:", "isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit # check that requested filter is in list", "(a/b * c/b).to(outunit).value else: a = trapz(ftrans*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans,fwave.value)*sp.wave.unit", "= ftrans # report values out if kwargs.get('verbose',False): print('\\nFilter '+filt+':", "pass def interpolateMagnitudes(verbose=True): ''' produces an interpolated value for a", "magnitudes using one of several statistics ''' chi = 0.", "as plt from scipy.integrate import trapz # for numerical integration", "comments='#', unpack=True, missing_values = ('NaN','nan'), filling_values = (numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not", "if verbose ==True: print(f.replace('_',' ')+': '+output[f]['zeropoint']) print('Zeropoint = {} Jy'.format(output[f]['zeropoint']))", "isUnit(fwave): fwave.to(wave_unit) else: fwave = fwave*wave_unit if kwargs.get('normalize',False): ftrans =", "[filt] # list of notch ranges if isinstance(filt[0],list): xl =", "interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact = trapz(ftrans*v(fwave.value),fwave.value)", "a particular filter. :param filter: name of filter, must be", "A new Magnitude object equal to the diffence of values", "= kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) verbose", "Filter 2MASS X not among the available filters: 2MASS H:", "out the current list of filters in the SPLAT reference", "if isinstance(fwave,u.quantity.Quantity) == True: fwave = fwave.to(u.micron) else: fwave =", "True: fwave = fwave.to(u.micron) else: fwave = fwave*u.micron # check", "set's SED models saves to file that could be uploaded", "''' :Purpose: A representation of subtraction for Magnitude classes that", "def filterInfo(*args,**kwargs): ''' :Purpose: Prints out the current list of", "print(f.replace('_',' ')+': '+output[f]['zeropoint']) print('Zeropoint = {} Jy'.format(output[f]['zeropoint'])) print('Central wavelength: =", "preference) :param units: units for energy as an astropy.units variable;", "= numpy.array(dm) em = numpy.array(em) offset = numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo", "f in filt: fc = checkFilterName(f) filt.remove(f) if fc ==", "kwargs.get('rsr',True) # Read in filter if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans", "= False if photons: energy = False if energy: photons", "= fwave[~numpy.isnan(ftrans)]*u.micron ftrans = ftrans[~numpy.isnan(ftrans)] return fwave,ftrans def filterMag(sp,filt,*args,**kwargs): '''", "magnitudes and choose the closest match based on various statistics", "True: fconst = 3631*u.jansky ftrans = (ftrans*fconst).to(u.erg/(u.cm**2 * u.s *", "print(trapz(ft,fw)) # print(trapz(fw*ft,fw)) report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central']", "= copy.deepcopy(self) out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty = self.uncertainty+other.uncertainty # combine", "= fwave.to(u.micron) except: fwave = fwave*u.micron fw = fwave[numpy.where(ftrans >", "m1 = numpy.random.normal(self.magnitude,self.uncertainty,samp) m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1+m2 out.uncertainty", "model magnitudes ''' pass def interpolateMagnitudes(verbose=True): ''' produces an interpolated", "!= False: fname = kwargs['filter'] else: fname = sorted(list(FILTERS.keys())) if", "= False else: filt = fflag self.filter = filt #", "k in info.keys(): setattr(self,k,info[k]) def __copy__(self): ''' :Purpose: Make a", "1. # custom filter else: fwave,ftrans = custom[0],custom[1] # units", "energy flux unit'.format(base_unit)) return numpy.nan, numpy.nan return val, err #", "elif isinstance(custom,bool) and isinstance(notch,list): dn = (notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron", "s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s def __repr__(self): ''' :Purpose:", "BE COMMON ''' filt = copy.deepcopy(filters) wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) #", "vwave = vwave[vwave>=numpy.nanmin(fwave)] vflux = vflux[vwave<=numpy.nanmax(fwave)] vwave = vwave[vwave<=numpy.nanmax(fwave)] #", "output[f]['description'] = FILTERS[f]['description'] output[f]['zeropoint'] = FILTERS[f]['zeropoint'] fwave,ftrans = filterProfile(f,**kwargs) try:", "F_lam), with option of also comparing to SED spectrum '''", "= numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] = numpy.min(fw) report['lambda_max'] = numpy.max(fw) report['wave'] =", "isinstance(notch,bool): f0 = checkFilterName(filt,verbose=True) if f0 == False: return numpy.nan,", "numpy.min(fw) output[f]['lambda_max'] = numpy.max(fw) if verbose ==True: print(f.replace('_',' ')+': '+output[f]['zeropoint'])", ">>> import splat.photometry as spphot >>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>>", "import * from .utilities import * ##################################################### ############### SPECTROPHOTOMETRY ###############", "u.s * u.micron)) # trim spectrum vflux = vflux[vwave>=numpy.nanmin(fwave)] vwave", "checkFilterName(filt,verbose=True) if f0 == False: return numpy.nan, numpy.nan filt =", "I-band FOURSTAR H: FOURSTAR H-band FOURSTAR H LONG: FOURSTAR H", "units for energy as an astropy.units variable; if this conversion", "f0 == False: return numpy.nan, numpy.nan filt = f0 rsr", "energy as an astropy.units variable; if this conversion does not", "constants in SI units import matplotlib.patches as patches import matplotlib.pyplot", "to fnu nu = vwave.to('Hz',equivalencies=u.spectral()) fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu =", "variable; if this conversion does not work, the conversion is", "= [],[] for f in list(mags1.keys()): if f in list(mags2.keys())", "raise ValueError('Did not recognize any of the input filters {}'.format(filters))", "magnitudes, photon flux or energy flux. :Required Parameters: **sp**: Spectrum", "offset = numpy.sum(dm/em**2)/numpy.sum (1./em**2) dmo = numpy.array([m-offset for m in", "Amoeba (Nelder-Mead) wrapper, and choose the closest match ''' pass", "magToFlux(mag,filt,**kwargs): ''' :Purpose: Converts a magnitude into an energy, and", "copy and fill in combined magnitude out = copy.deepcopy(self) out.magnitude", "file containing Vega flux file, must be within ``filterFolder`` **nsamples**", "filter else: fwave,ftrans = custom[0],custom[1] # units if isinstance(fwave,u.quantity.Quantity) ==", "kwargs.get('filter',False) != False: fname = kwargs['filter'] else: fname = sorted(list(FILTERS.keys()))", "(may be set by filter) **ab** = False: compute AB", "= kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single filter name if isinstance(filt,str): filt =", "transmission without) **vega** = True: compute Vega magnitudes (may be", "= kwargs.get('e_mag',e_mag) if not isinstance(mag,u.quantity.Quantity): mag=mag*u.s/u.s if not isinstance(e_mag,u.quantity.Quantity): e_mag=e_mag*mag.unit", "= vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate Vega", "checkFilterName(k) if f != False: output[f] = {} output[f]['description'] =", "filters given by splat.FILTERS.keys() (required) :param reverse: convert energy into", "except: # raise ValueError('\\nInput quantity unit {} is not a", "##################################################### ############### MAGNITUDE CLASS ############### ##################################################### class Magnitude(object): ''' :Description:", "not recognize any of the input filters {}'.format(filters)) # prep", "magnitudes to model magnitudes using an MCMC wrapper, and choose", "= filterProperties(self.filter) for k in info.keys(): setattr(self,k,info[k]) def __copy__(self): '''", "Retrieve the filter profile for a SPLAT filter. Returns two", "to screen :type verbose: optional, default = True :Example: >>>", "FOURSTAR H SHORT: FOURSTAR H short ... ''' filterFolder =", "filt report['description'] = FILTERS[filt]['description'] report['zeropoint'] = FILTERS[filt]['zeropoint'] report['method'] = FILTERS[filt]['method']", "','_').upper() for k in list(FILTERS.keys()): if f==k.upper() or f.lower() in", "c/b).to(outunit).value for i in numpy.arange(nsamples): if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value)", "object equal to the equivalent sum of fluxes ''' #", "<= notch[1]))] = 1. # custom filter else: fwave,ftrans =", "representation of addition for magnitudes (addition of fluxes) :Output: A", "if 'vega' in FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab = not", "# print(trapz(fw*ft,fw)) report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) report['lambda_central'] =", "THIS NEEDS TO BE COMPLETED else: print('passed') pass # check", "library. ''' verbose = kwargs.get('verbose',True) if len(args) > 0: fname", "to a grid of model magnitudes and choose the closest", "= fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw)) # print(trapz(fw*ft,fw)) report['lambda_mean'] =", "COMMON ''' filt = copy.deepcopy(filters) wave_unit = kwargs.get('wave_unit',DEFAULT_WAVE_UNIT) # single", "code that calculates a set of magnitudes for a model", "is also convolved with a model of Vega to extract", "if (photons or energy): vega = False ab = False", "filter wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: val =", "val = m1-m2 out.uncertainty = numpy.nanstd(val) # check filter agreement", "c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value else: a", "array that specifies the lower and upper wavelengths for a", "an Amoeba (Nelder-Mead) wrapper, and choose the closest match '''", "fc = checkFilterName(f) filt.remove(f) if fc == False: if verbose==True:", "filterProfile(self.filter) info = filterProperties(self.filter) for k in info.keys(): setattr(self,k,info[k]) def", "# single filter name if isinstance(filt,str): filt = [filt] if", "- internal import copy import os # imports - external", "sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky", "external import numpy from astropy import units as u #", "copy of a Magnitude object ''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__)", "ftrans[~numpy.isnan(ftrans)] return fwave,ftrans def filterMag(sp,filt,*args,**kwargs): ''' :Purpose: Determine the photometric", "default = filter preference) :param rsr: magnitude is on the", "filt, uncertainty=0., magtype='apparent', verbose=False,**kwargs): self.magnitude = magnitude self.uncertainty = uncertainty", "has been obseleted def checkFilter(filt,verbose=True): output = False f =", "wave, flux and noise array elements. **filter**: String giving name", "= [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr'] == True: yl = kwargs.get('ylabel','Transmission", "copy(self): ''' :Purpose: Make a copy of a Magnitude object", "flux(self,type='fnu',samp=1000): ''' :Purpose: Report the equivalent flux density of a", "= filt report['description'] = FILTERS[filt]['description'] report['zeropoint'] = FILTERS[filt]['zeropoint'] report['method'] =", "filterInfo() return output def filterProfile(filt,**kwargs): ''' :Purpose: Retrieve the filter", "print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range = {:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else:", "= FILTERS[filt]['method'] report['rsr'] = FILTERS[filt]['rsr'] fwave,ftrans = filterProfile(filt,**kwargs) try: fwave", "giving the name of one of the predefined filters listed", "({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve') legend = [] fig =", "of a set of magnitudes to model magnitudes using an", "if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans = filterProfile(filt,**kwargs) # notch filter", "numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: spectrum for {} does not span", "self.filter != other.filter: out.filter = '{}+{}'.format(self.filter,other.filter) return out def __sub__(self,other,samp=1000):", "if isinstance(filt,list): # list of filter names if isinstance(filt[0],str): for", "checkFilterName(f) filt.remove(f) if fc == False: if verbose==True: print('Removed filter", "kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl = kwargs.get('ylabel','Transmission Curve') legend = [] fig", "fwave[~numpy.isnan(ftrans)] ftrans = ftrans[~numpy.isnan(ftrans)] result = [] err = 0.", "functions for SPLAT \"\"\" # imports - internal import copy", "String giving name of filter, which can either be one", ":param filter: name of filter, must be one of the", "def copy(self): ''' :Purpose: Make a copy of a Magnitude", "1. elif (ab): nu = sp.wave.to('Hz',equivalencies=u.spectral()) fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu", "the specifed filters given by splat.FILTERS.keys() :type filter: required :param", "d = interp1d(sp.wave.value,sp.flux.value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave.value,sp.flux.value*1.e-9,bounds_error=False,fill_value=0.) result = [] if", "profile or set of filter profiles, optionally on top of", "filt = f0 rsr = FILTERS[filt]['rsr'] # Read in filter", "!= '': plt.savefig(file) return fig ######################################### ######## SED FITTING TOOLS", "print('Wavelength range = {:.3f} to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if verbose ==True:", "# raise ValueError('\\nInput quantity unit {} is not a flux", "= numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn)*u.micron ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave <= notch[1]))]", "to the diffence of values ''' # make a copy", "outunit = 1. elif (energy): outunit = u.erg/u.s/u.cm**2 if rsr:", "one of the specifed filters given by splat.FILTERS.keys() (required) :param", "backup version def copy(self): ''' :Purpose: Make a copy of", "kwargs.get('reverse',False) == False: if vega == True: # Read in", "s def __repr__(self): ''' :Purpose: A simple representation of the", "raise ValueError('\\nmagToFlux needs vega or ab method specified') # convert", "{} does not span full filter profile for {}'.format(sp.name,filt)) #", "pass def addFlux(self,other,samp=1000): ''' :Purpose: A representation of addition for", "f0 rsr = FILTERS[filt]['rsr'] # Read in filter if isinstance(custom,bool)", "import constants as const # physical constants in SI units", "= numpy.min(fw) report['lambda_max'] = numpy.max(fw) report['wave'] = fwave report['transmission'] =", "self.filter != other.filter: raise ValueError('magnitudes filters {} and {} are", "* u.s) elif ab == True: fconst = 3631*u.jansky ftrans", "= FILTERS[filt]['rsr'] # other possibilities photons = kwargs.get('photons',False) photons =", "False # Read in filter if isinstance(custom,bool) and isinstance(notch,bool): fwave,ftrans", "= filterProfile(filt,**kwargs) # notch filter elif isinstance(custom,bool) and isinstance(notch,list): dn", "= ('NaN','nan'), filling_values = (numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or not", "WARNING: THIS CODE IS ONLY PARTIALLY COMPLETE ''' # keyword", "magnitudes using an MCMC wrapper, and choose best/average/distribution of parameters", "(required) :param filter: name of filter, must be one of", "vwave.to('Hz',equivalencies=u.spectral()) fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky", "if len(sp.wave[wgood]) > 0: d = interp1d(sp.wave[wgood].value,sp.flux[wgood].value,bounds_error=False,fill_value=0.) n = interp1d(sp.wave[wgood].value,sp.noise[wgood].value,bounds_error=False,fill_value=0)", "energy -> magnitude # THIS NEEDS TO BE COMPLETED else:", "if fflag == False: if verbose== True: print('filter {} is", "= kwargs.get('output',file) if file != '': plt.savefig(file) return fig #########################################", "''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s # backup version", "= kwargs.get('vegaFile',VEGAFILE) info = kwargs.get('info',False) custom = kwargs.get('custom',False) notch =", "-2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i in numpy.arange(nsamples): #", ":Description: This is a class data structure for a magnitude", "is on the Vega system (optional, default = filter preference)", "if verbose==True: print('\\nWarning: no overlap between spectrum for {} and", "numpy.arange(nsamples): a = trapz(ftrans*(d(filtnu.value)+numpy.random.normal(0,1)*n(filtnu.value))/filtnu.value,filtnu.value) result.append(-2.5*numpy.log10(a/b)) outunit = 1. elif (energy):", "{:.3f} to {:.3f}\\n'.format(report['lambda_min'],report['lambda_max'])) return report def magToFlux(mag,filt,**kwargs): ''' :Purpose: Converts", "from astropy import units as u # standard units from", "False: fname = kwargs['filter'] else: fname = sorted(list(FILTERS.keys())) if isinstance(fname,list)", "compute photon flux **filterFolder** = splat.FILTER_FOLDER: folder containing the filter", "the sum of values ''' # make a copy and", "''' pass def SEDVisualize(verbose=True): ''' Visualizes magnitudes on SED scale", "yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1)) else: raise ValueError('Could not parse", "vega) rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) custom = kwargs.get('custom',False)", "SPLAT filter list'.format(k)) kys = list(output.keys()) if len(kys) == 1:", "magnitude :Output: astropy quantity in flux density units (default =", "FOURSTAR H-band FOURSTAR H LONG: FOURSTAR H long FOURSTAR H", "err.to(base_unit) except: print('\\nWarning: cannot convert result to an energy flux", "m2 = numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1+m2 out.uncertainty = numpy.nanstd(val) #", "must be within ``filterFolder`` **nsamples** = 100: number of samples", "filter) **ab** = False: compute AB magnitudes (may be set", "# convert to fnu nu = vwave.to('Hz',equivalencies=u.spectral()) fnu = vflux.to('Jy',equivalencies=u.spectral_density(vwave))", "(photons or energy): vega = False ab = False if", "one of several statistics ''' chi = 0. dm,em =", "be one of the specifed filters given by splat.FILTERS.keys() (required)", "available :Example: >>> import splat >>> import splat.photometry as spphot", "verbose = kwargs.get('verbose',False) # check that requested filter is in", "= m1+m2 out.uncertainty = numpy.nanstd(val) # check filter agreement if", "= 3631*u.jansky ftrans = (ftrans*fconst).to(u.erg/(u.cm**2 * u.s * u.micron),equivalencies=u.spectral_density(fwave)) if", "combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty =", "if 'ab' in FILTERS[filt]['method']: ab = kwargs.get('ab',True) vega = not", "by splat.FILTERS.keys() :type filter: required :param verbose: print out information", "ignore: dm.append(mags1[f]-mags2[f]) em.append(unc[f]) # find best scale factor dm =", "not work'.format(filt)) self.knownfilter = False else: filt = fflag self.filter", "# THIS NEEDS TO BE COMPLETED else: print('passed') pass #", "scipy.interpolate import interp1d # splat functions and constants from .initialize", "spectrum onto filter wavelength function wgood = numpy.where(~numpy.isnan(sp.noise)) if len(sp.wave[wgood])", "fwave,ftrans = filterProfile(f,**kwargs) try: fwave = fwave.to(u.micron) except: fwave =", "in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterfolder+vegafile), comments='#', unpack=True, \\ missing_values", "custom[0],custom[1] if isinstance(fwave,u.quantity.Quantity) == False: fwave=fwave*u.micron if isinstance(ftrans,u.quantity.Quantity) == True:", "units: units for energy as an astropy.units variable; if this", "on its spectrum. Spectral fluxes are convolved with the filter", "def checkFilter(filt,verbose=True): output = False f = copy.deepcopy(filt) f =", "Curve') legend = [] fig = plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in", "verbose = kwargs.get('verbose',True) if len(args) > 0: fname = list(args)", "return output def filterProperties(filt,**kwargs): ''' :Purpose: Returns a dictionary containing", "flux **photon** = False: compute photon flux **filterFolder** = splat.FILTER_FOLDER:", "screen (optional, default = False) WARNING: THIS CODE IS ONLY", "u.s) else: raise ValueError('\\nmagToFlux needs vega or ab method specified')", "pass ##################################################### ############### MAGNITUDE CLASS ############### ##################################################### class Magnitude(object): '''", "magnitudes ''' pass def compareMagnitudes(mags1,mags2,unc=None,unc2=None,ignore=[],verbose=True): ''' this code compares a", "if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons): outunit = 1./u.s/u.cm**2", "if kwargs.get('verbose',False): print('\\nFilter '+filt+': '+report['description']) print('Zeropoint = {} Jy'.format(report['zeropoint'])) print('Pivot", "filter {}'.format(sp.name,filt)) return numpy.nan, numpy.nan if numpy.nanmin(fwave) < numpy.nanmin(sp.wave) or", "in numpy.arange(nsamples): if rsr: result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons): outunit", "= trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) return -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) def filterInfo(*args,**kwargs): ''' :Purpose: Prints out", "not an energy flux unit'.format(return_unit)) try: val.to(base_unit) err.to(base_unit) except: print('\\nWarning:", "raise ValueError('\\nInput quantity unit {} is not a flux unit'.format(mag.unit))", "J') Filter 2MASS J: 2MASS J-band Zeropoint = 1594.0 Jy", "numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1-m2 out.uncertainty = numpy.nanstd(val) # check filter", "as u # standard units from astropy import constants as", "quantity (vega, ab, energy, photons) to compute photometry\\n\\n') # val", "comparison of a set of magnitudes to model magnitudes using", "print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray)) if not isinstance(fwave,numpy.ndarray) or not", "vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True, \\ missing_values = ('NaN','nan'), filling_values", "= numpy.nanmean(result)*outunit err = numpy.nanstd(result) if len(sp.wave[wgood]) == 0: err", "= [filt] if isinstance(filt,list): # list of filter names if", "0.5*numpy.nanmax(ftrans))] # print(trapz(ft,fw)) # print(trapz(fw*ft,fw)) report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] =", "u.s) else: err = 0.*u.erg/(u.cm**2 * u.s) else: raise ValueError('\\nmagToFlux", "necessary self.knownfilter = True fflag = checkFilterName(filt,verbose=verbose) if fflag ==", "len(sp.wave[wgood]) == 0: err = 0. return val*outunit,err*outunit def vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs):", "sum of fluxes ''' # check filter agreement if self.filter", "filter names if isinstance(filt[0],str): for f in filt: fc =", "# this function has been obseleted def checkFilter(filt,verbose=True): output =", "unpack=True, missing_values = ('NaN','nan'), filling_values = (numpy.nan)) # print(type(fwave),type(ftrans),isinstance(fwave,numpy.ndarray),isinstance(ftrans,numpy.ndarray),not isinstance(fwave,numpy.ndarray)", "filterProfile(filt,**kwargs) # notch filter elif isinstance(custom,bool) and isinstance(notch,list): dn =", "and f in list(unc.keys()) and f not in ignore: dm.append(mags1[f]-mags2[f])", "# backup version def copy(self): ''' :Purpose: Make a copy", "else: fact = trapz(ftrans*v(fwave.value),fwave.value) val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s) #", "not currently available for SPLAT; contact '+EMAIL+'\\n') filterInfo() return output", "return numpy.nan, numpy.nan if numpy.nanmin(fwave) < numpy.nanmin(sp.wave) or numpy.nanmax(fwave) >", "names if isinstance(filt[0],str): for f in filt: fc = checkFilterName(f)", "= numpy.nanstd(val) # check filter agreement if self.filter != other.filter:", "be within ``filterFolder`` **nsamples** = 100: number of samples to", "filter names available :Example: >>> import splat >>> import splat.photometry", "value for a grid set of model magnitudes ''' pass", "the equivalent flux density of a magnitude :Output: astropy quantity", "(addition of fluxes) :Output: A new magnitude object equal to", "the current list of filters in the SPLAT reference library.", "val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i in", "as an astropy.units variable; if this conversion does not work,", "of the specifed filters given by splat.FILTERS.keys() :type filter: required", "vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron)) vflux.to(sp.flux_unit,equivalencies=u.spectral_density(vwave)) # interpolate Vega onto", "of the Spectrum object ''' if self.uncertainty != 0. and", "obseleted def checkFilter(filt,verbose=True): output = False f = copy.deepcopy(filt) f", "= ftrans[~numpy.isnan(ftrans)] return fwave,ftrans def filterMag(sp,filt,*args,**kwargs): ''' :Purpose: Determine the", "= m1-m2 out.uncertainty = numpy.nanstd(val) # check filter agreement if", "self.knownfilter == True: self.wave,self.transmission = filterProfile(self.filter) info = filterProperties(self.filter) for", "(notch[1]-notch[0])/1000 fwave = numpy.arange(notch[0]-5.*dn,notch[1]+5.*dn,dn) ftrans = numpy.zeros(len(fwave)) ftrans[numpy.where(numpy.logical_and(fwave >= notch[0],fwave", "if rsr: fact = trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact = trapz(ftrans*v(fwave.value),fwave.value) val", "False if energy: photons = False # Read in filter", "filter preference) :param units: units for energy as an astropy.units", "== 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra =", "b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value) val = -2.5*numpy.log10(trapz(ftrans*d(filtnu.value)/filtnu.value,filtnu.value)/b) for i in numpy.arange(nsamples):", ":Output: A new Magnitude object equal to the diffence of", "* u.s * u.micron)) # interpolate Vega onto filter wavelength", "SPECTROPHOTOMETRY ############### ##################################################### # this function has been obseleted def", "rsr = FILTERS[filt]['rsr'] # Read in filter if isinstance(custom,bool) and", "{} are not the same'.format(self.filter,other.filter)) # make a copy and", "kwargs.get('vega',True) ab = kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False) nsamples =", "into magnitude instead (optional, default = False) :param ab: magnitude", ":Purpose: A representation of addition for magnitudes (addition of fluxes)", "= False ab = False if photons: energy = False", "of {}+/-{}'.format(self.filter,self.magnitude,self.uncertainty) else: return '{} magnitude of {}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000):", "point: = {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM = {:.3f}'.format(output[f]['lambda_fwhm'])) print('Wavelength range = {:.3f}", "on filter design if 'ab' in FILTERS[filt]['method']: ab = kwargs.get('ab',True)", "elif (ab): nu = sp.wave.to('Hz',equivalencies=u.spectral()) fnu = sp.flux.to('Jy',equivalencies=u.spectral_density(sp.wave)) noisenu =", "c = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b * c/b).to(outunit).value for i", "= filter preference) :param vega: magnitude is on the Vega", ">>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',14.5) >>> spphot.filterMag(sp,'MKO J')", "err.to(return_unit) # except: # print('\\nWarning: unit {} is not an", "splat >>> data = splat.filterProperties('2MASS J') Filter 2MASS J: 2MASS", "= plt.figure(figsize=kwargs.get('figsize',[5,4])) for i,f in enumerate(filt): fwave,ftrans = filterProfile(f,**kwargs) if", "if rsr: a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c =", "SPLAT \"\"\" # imports - internal import copy import os", "(optional, default = filter preference) :param units: units for energy", "= [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1)) else: raise ValueError('Could", "= {} report['name'] = filt report['description'] = FILTERS[filt]['description'] report['zeropoint'] =", "not os.path.exists(filterFolder): filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile','vega_kurucz.txt') vega =", "''' :Purpose: Prints out the current list of filters in", "default = filter preference) :param vega: magnitude is on the", "match ''' pass def SEDVisualize(verbose=True): ''' Visualizes magnitudes on SED", "''' def __init__(self, magnitude, filt, uncertainty=0., magtype='apparent', verbose=False,**kwargs): self.magnitude =", "val, err # energy -> magnitude # THIS NEEDS TO", "the filter wavelength and filter transmission curve. :param filter: String", "= 100: number of samples to use in Monte Carlo", "of the predefined filters listed in splat.FILTERS.keys() or a custom", "set by filter) **ab** = False: compute AB magnitudes (may", "2MASS J-band Zeropoint = 1594.0 Jy Pivot point: = 1.252", "numpy.nan if numpy.nanmin(fwave) < numpy.nanmin(sp.wave) or numpy.nanmax(fwave) > numpy.nanmax(sp.wave): if", "flux **filterFolder** = splat.FILTER_FOLDER: folder containing the filter transmission files", "err = (numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else: err = 0.*u.erg/(u.cm**2 *", "interp1d # splat functions and constants from .initialize import *", "self.magnitude+other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine noises if self.uncertainty !=", ".. note:: These are the spectrophotometry functions for SPLAT \"\"\"", "# notch filter elif isinstance(custom,bool) and isinstance(notch,list): dn = (notch[1]-notch[0])/1000", "vegaToAB(filt,vegafile=VEGAFILE,filterfolder=SPLAT_PATH+FILTER_FOLDER,custom=False,notch=False,rsr=False,**kwargs): # check that requested filter is in list if", "prep parameters fwave,ftrans = filterProfile(f,**kwargs) if isUnit(fwave): wave_unit = kwargs.get('wave_unit',fwave.unit)", "check that requested filter is in list if isinstance(custom,bool) and", "b = trapz(ftrans*fwave.value,fwave.value)*sp.wave.unit c = trapz(ftrans*fwave.value*fwave.value,fwave.value)*sp.wave.unit*sp.wave.unit val = (a/b *", "not work, the conversion is ignored (optional, default = erg/cm2/s)", "def interpolateMagnitudes(verbose=True): ''' produces an interpolated value for a grid", "fw = fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] ft = ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))]", "def __copy__(self): ''' :Purpose: Make a copy of a Magnitude", "print out information about filter to screen :type verbose: optional,", "output[f]['lambda_max'] = numpy.max(fw) if verbose ==True: print(f.replace('_',' ')+': '+output[f]['zeropoint']) print('Zeropoint", "fact = trapz(ftrans.value,fwave.value) val = (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s) # calculate", "this function has been obseleted def checkFilter(filt,verbose=True): output = False", "reverse: convert energy into magnitude instead (optional, default = False)", "= {} for k in fname: f = checkFilterName(k) if", "yl = kwargs.get('ylabel','Transmission Curve') legend = [] fig = plt.figure(figsize=kwargs.get('figsize',[5,4]))", "= vflux.to('Jy',equivalencies=u.spectral_density(vwave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d =", "numpy from astropy import units as u # standard units", "an energy flux # try: # mag.to(base_unit) # e_mag.to(base_unit) #", "Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True, \\ missing_values =", "save if desired file = kwargs.get('file','') file = kwargs.get('filename',file) file", "2 element array that specifies the lower and upper wavelengths", "other possibilities photons = kwargs.get('photons',False) photons = kwargs.get('photon',photons) energy =", "# some things that are based on presets if self.knownfilter", "Magnitude classes that takes into account uncertainties :Output: A new", "if self.uncertainty != 0 and other.uncertainty != 0: m1 =", "if isUnit(fwave): wave_unit = kwargs.get('wave_unit',fwave.unit) xl = kwargs.get('xlabel','Wavelength ({})'.format(wave_unit)) yl", "ARE EXPERIMENTAL!! ### ######################################### # plan: def modelMagnitudes(verbose=True): ''' this", "energy, and vice versa. :param mag: magnitude on whatever system", "(energy): outunit = u.erg/u.s/u.cm**2 if rsr: a = trapz(ftrans*fwave.value*d(fwave.value),fwave.value)*sp.wave.unit*sp.flux.unit b", "= False) :param ab: magnitude is on the AB system", "= None: A 2 x N vector array specifying the", "add a comparison spectrum sp = kwargs.get('spectrum',None) sp = kwargs.get('comparison',sp)", "J') (14.345894376898123, 0.027596454828421831) ''' # keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER)", "pass def SEDFitAmoeba(verbose=True): ''' this code will conduct a comparison", "'+EMAIL+'\\n') filterInfo() return output def filterProfile(filt,**kwargs): ''' :Purpose: Retrieve the", "J: 2MASS J-band 2MASS KS: 2MASS Ks-band BESSEL I: Bessel", "in range of filter {} have no uncertainties'.format(filt)) d =", "onto filter wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: fact", "filt = f0 # reset filter calculation methods based on", "Plots a filter profile or set of filter profiles, optionally", "model magnitudes using an MCMC wrapper, and choose best/average/distribution of", "= [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if", "matplotlib.patches as patches import matplotlib.pyplot as plt from scipy.integrate import", "False else: filt = fflag self.filter = filt # some", "splat.filterProperties('2MASS J') Filter 2MASS J: 2MASS J-band Zeropoint = 1594.0", "single filter name if isinstance(filt,str): filt = [filt] if isinstance(filt,list):", "= numpy.random.normal(other.magnitude,other.uncertainty,samp) val = m1+m2 out.uncertainty = numpy.nanstd(val) # check", "AB magnitudes (may be set by filter) **energy** = False:", "-2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i in numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave))) if rsr: result.append(-2.5*numpy.log10(trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)))", "else: raise NameError('\\nfilterMag not given a correct physical quantity (vega,", "[yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1)) else: raise ValueError('Could not parse input {}'.format(filt))", "sp = splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',14.5) >>> spphot.filterMag(sp,'MKO J') (14.345894376898123,", "or not isinstance(ftrans,numpy.ndarray)) if not isinstance(fwave,numpy.ndarray) or not isinstance(ftrans,numpy.ndarray): raise", "filter profile or set of filter profiles, optionally on top", "= kwargs.get('custom',False) notch = kwargs.get('notch',False) vega = kwargs.get('vega',True) ab =", "import numpy from astropy import units as u # standard", "ftrans/numpy.nanmax(ftrans) plt.plot(fwave,ftrans) if len(xra) == 0: xra = [numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra", "[numpy.nanmin(fwave.value),numpy.nanmax(fwave.value)] xra = [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append('Filter {}'.format(i+1)) else:", "not vega rsr = FILTERS[filt]['rsr'] # other possibilities photons =", "compute photometry\\n\\n') # val = numpy.nanmean(result)*outunit err = numpy.nanstd(result) if", "numpy.nan, numpy.nan # reset filter calculation methods based on filter", "if verbose==True: print('\\nWarning: spectrum for {} does not span full", "print out information about filter to screen (optional, default =", "= kwargs.get('custom',False) notch = kwargs.get('notch',False) base_unit = u.erg/(u.cm**2 * u.s)", "new Magnitude object equal to the diffence of values '''", "out = copy.deepcopy(self) out.magnitude = self.magnitude+other.magnitude out.uncertainty = self.uncertainty+other.uncertainty #", "kwargs.get('info',False) custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) vega = kwargs.get('vega',True)", "out.magnitude = self.magnitude-2.5*numpy.log10(1.+10.**(-0.4*(other.magnitude-self.magnitude))) out.uncertainty = self.uncertainty+other.uncertainty # combine noises if", "numpy.nanmax(fwave) > numpy.nanmax(sp.wave): if verbose==True: print('\\nWarning: spectrum for {} does", "print('Mean wavelength: = {:.3f}'.format(output[f]['lambda_mean'])) print('Pivot point: = {:.3f}'.format(output[f]['lambda_pivot'])) print('FWHM =", "SPLAT; contact '+EMAIL+'\\n') filterInfo() return output def filterProfile(filt,**kwargs): ''' :Purpose:", "ValueError('\\nInput quantity unit {} is not a flux unit'.format(mag.unit)) def", "vega = False ab = False if photons: energy =", ":Example: >>> import splat >>> data = splat.filterProperties('2MASS J') Filter", "kwargs.get('ab',not vega) rsr = kwargs.get('rsr',False) nsamples = kwargs.get('nsamples',100) verbose =", "not vega if 'rsr' in FILTERS[filt]['method']: rsr = kwargs.get('rsr',True) #", "(numpy.nan)) vwave = vwave[~numpy.isnan(vflux)]*u.micron vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s *", "be set by filter) **energy** = False: compute energy flux", "Make a copy of a Magnitude object ''' s =", "s.__dict__.update(self.__dict__) return s # backup version def copy(self): ''' :Purpose:", "filterFolder = SPLAT_URL+FILTER_FOLDER vegaFile = kwargs.get('vegaFile',VEGAFILE) info = kwargs.get('info',False) custom", "is ignored (optional, default = erg/cm2/s) :param verbose: print out", "magnitudes using an Amoeba (Nelder-Mead) wrapper, and choose the closest", "print_function, division \"\"\" .. note:: These are the spectrophotometry functions", "or isinstance(filt[0],float): filt = [filt] # list of notch ranges", "rsr: val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i", "else: return '{} magnitude of {}'.format(self.filter,self.magnitude) def __add__(self,other,samp=1000): ''' :Purpose:", "that spectrum and filter cover the same wavelength ranges if", "= 1.066 to 1.442 micron >>> data = splat.filterProperties('2MASS X')", "wrapper, and choose best/average/distribution of parameters ''' pass def SEDFitAmoeba(verbose=True):", "err # energy -> magnitude # THIS NEEDS TO BE", "= 0.5*(numpy.max(fw)+numpy.min(fw)) report['lambda_fwhm'] = numpy.max(fw05)-numpy.min(fw05) report['lambda_min'] = numpy.min(fw) report['lambda_max'] =", "= list(args) elif kwargs.get('filter',False) != False: fname = kwargs['filter'] else:", "trapz(ftrans*fwave.value*v(fwave.value),fwave.value) else: fact = trapz(ftrans*v(fwave.value),fwave.value) val = 10.**(-0.4*mag.value)*fact*u.erg/(u.cm**2 * u.s)", "for {} and filter {}'.format(sp.name,filt)) return numpy.nan, numpy.nan if numpy.nanmin(fwave)", "CODE IS ONLY PARTIALLY COMPLETE ''' # keyword parameters filterFolder", "to {:.3f}\\n'.format(output[f]['lambda_min'],output[f]['lambda_max'])) else: if verbose ==True: print(' Filter {} not", "= kwargs.get('vegaFile','vega_kurucz.txt') vega = kwargs.get('vega',True) ab = kwargs.get('ab',not vega) rsr", "= vwave[vwave<=numpy.nanmax(fwave)] # convert to fnu nu = vwave.to('Hz',equivalencies=u.spectral()) fnu", "def filterProfile(filt,**kwargs): ''' :Purpose: Retrieve the filter profile for a", "f = checkFilterName(k) if f != False: output[f] = {}", "addition for Magnitude classes that takes into account uncertainties :Output:", "= True: List the predefined filter names available :Example: >>>", "the Vega system (optional, default = filter preference) :param units:", "transmission within, 0% transmission without) **vega** = True: compute Vega", "# print(trapz(ft,fw)) # print(trapz(fw*ft,fw)) report['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) report['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw))", "##################################################### ############### SPECTROPHOTOMETRY ############### ##################################################### # this function has been", "> 0.: for i in numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err = (numpy.nanstd(result))*u.erg/(u.cm**2", "out information about filter to screen :type verbose: optional, default", "kwargs.get('comparison',sp) if isinstance(sp,splat.core.Spectrum) == True: print(xra) sp.normalize(xra) sp.scale(numpy.nanmax(ftrans)*kwargs.get('comparison_scale',0.8)) plt.plot(sp.wave,sp.flux,color=kwargs.get('comparison_color','k'),alpha=kwargs.get('comparison_alpha',0.5)) legend.append(sp.name)", "file, must be within ``filterFolder`` **nsamples** = 100: number of", ">>> data = splat.filterProperties('2MASS J') Filter 2MASS J: 2MASS J-band", "isinstance(filt[0],float): filt = [filt] # list of notch ranges if", "of magnitudes to model magnitudes using an Amoeba (Nelder-Mead) wrapper,", "def SEDFitGrid(verbose=True): ''' this code will compare a set of", ":Purpose: A representation of addition for Magnitude classes that takes", "0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] = trapz(ft*fw,fw)/trapz(ft,fw) output[f]['lambda_pivot'] = numpy.sqrt(trapz(fw*ft,fw)/trapz(ft/fw,fw)) output[f]['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw))", "wavelengths for a notch filter (100% transmission within, 0% transmission", "list of notch ranges if isinstance(filt[0],int) or isinstance(filt[0],float): filt =", "= kwargs.get('unit',base_unit) e_mag = kwargs.get('uncertainty',0.) e_mag = kwargs.get('unc',e_mag) e_mag =", "= copy.deepcopy(self) out.magnitude = self.magnitude+other.magnitude out.uncertainty = self.uncertainty+other.uncertainty # combine", "parameters ''' pass def SEDFitAmoeba(verbose=True): ''' this code will conduct", "{} is not an energy flux unit'.format(return_unit)) try: val.to(base_unit) err.to(base_unit)", "''' s = type(self)(self.magnitude,self.filter,uncertainty=self.uncertainty) s.__dict__.update(self.__dict__) return s def __repr__(self): '''", "setattr(self,k,info[k]) def __copy__(self): ''' :Purpose: Make a copy of a", "statistics ''' pass def SEDFitMCMC(verbose=True): ''' this code will conduct", "full filter profile for {}'.format(sp.name,filt)) # interpolate spectrum onto filter", "(numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else: err = 0.*u.erg/(u.cm**2 * u.s) else:", "FOURSTAR H: FOURSTAR H-band FOURSTAR H LONG: FOURSTAR H long", "= [] err = 0. # magnitude -> energy if", "by the ``filter`` input. By default this filter is also", "len(kys) == 1: return output[kys[0]] else: return output def filterProperties(filt,**kwargs):", "needs vega or ab method specified') # convert to desired", "= 1. # custom filter else: fwave,ftrans = custom[0],custom[1] #", "{}'.format(filt)) # add a comparison spectrum sp = kwargs.get('spectrum',None) sp", "key parameters for a particular filter. :param filter: name of", "# except: # print('\\nWarning: unit {} is not an energy", "of filter profiles, optionally on top of a spectrum WARNING:", "filter wavelength function v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: fact =", "trim spectrum vflux = vflux[vwave>=numpy.nanmin(fwave)] vwave = vwave[vwave>=numpy.nanmin(fwave)] vflux =", "f in list(mags1.keys()): if f in list(mags2.keys()) and f in", "in Vega spectrum vwave,vflux = numpy.genfromtxt(os.path.normpath(filterFolder+vegaFile), comments='#', unpack=True, \\ missing_values", "= filterProfile(self.filter) info = filterProperties(self.filter) for k in info.keys(): setattr(self,k,info[k])", "''' # keyword parameters filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER) if not os.path.exists(filterFolder):", ">= notch[0],fwave <= notch[1]))] = 1. # custom filter else:", "kwargs.get('file','') file = kwargs.get('filename',file) file = kwargs.get('output',file) if file !=", "i in numpy.arange(nsamples): result.append((trapz(ftrans*fwave.value*convert.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit*convert.unit).to(outunit).value) else: raise NameError('\\nfilterMag not given a", "option of also comparing to SED spectrum ''' pass #####################################################", "= FILTERS[filt]['rsr'] fwave,ftrans = filterProfile(filt,**kwargs) try: fwave = fwave.to(u.micron) except:", "Bessel I-band FOURSTAR H: FOURSTAR H-band FOURSTAR H LONG: FOURSTAR", "data = splat.filterProperties('2MASS J') Filter 2MASS J: 2MASS J-band Zeropoint", "= (10.**(-0.4*mag.value)*fact)*u.erg/(u.cm**2 * u.s) # calculate uncertainty if e_mag.value >", "##################################################### # this function has been obseleted def checkFilter(filt,verbose=True): output", "''' Visualizes magnitudes on SED scale (flux = lam x", "other.filter: out.filter = '{}-{}'.format(self.filter,other.filter) return out def flux(self,type='fnu',samp=1000): ''' :Purpose:", "FILTERS[filt]['method']: vega = kwargs.get('vega',True) ab = not vega if 'rsr'", "the filter transmission files **vegaFile** = 'vega_kurucz.txt': name of file", "custom filter else: fwave,ftrans = custom[0],custom[1] # Read in Vega", "for SPLAT \"\"\" # imports - internal import copy import", "= 0.*u.erg/(u.cm**2 * u.s) else: raise ValueError('\\nmagToFlux needs vega or", "v = interp1d(vwave.value,vflux.value,bounds_error=False,fill_value=0.) if rsr: val = -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val", "# check filter agreement if self.filter != other.filter: out.filter =", "= vwave[vwave>=numpy.nanmin(fwave)] vflux = vflux[vwave<=numpy.nanmax(fwave)] vwave = vwave[vwave<=numpy.nanmax(fwave)] # convert", "numpy.nan # reset filter calculation methods based on filter design", "check that requested filter is in list f0 = checkFilterName(filt,", "= -2.5*numpy.log10(trapz(ftrans*fwave.value*d(fwave.value),fwave.value)/trapz(ftrans*fwave.value*v(fwave.value),fwave.value)) else: val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i in numpy.arange(nsamples):", "list f0 = checkFilterName(filt, verbose=True) if f0 == False: raise", "filt = [filt] # list of notch ranges if isinstance(filt[0],list):", "version def copy(self): ''' :Purpose: Make a copy of a", "fwave*u.micron # check that spectrum and filter cover the same", "= 1. elif (energy): outunit = u.erg/u.s/u.cm**2 if rsr: a", "ftrans = ftrans[~numpy.isnan(ftrans)] result = [] err = 0. #", "filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n", "ftrans[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))] fw05 = fwave[numpy.where(ftrans > 0.5*numpy.nanmax(ftrans))] output[f]['lambda_mean'] =", "of filters in the SPLAT reference library. ''' verbose =", "in combined magnitude out = copy.deepcopy(self) out.magnitude = self.magnitude+other.magnitude out.uncertainty", "kys = list(output.keys()) if len(kys) == 1: return output[kys[0]] else:", "def filterProperties(filt,**kwargs): ''' :Purpose: Returns a dictionary containing key parameters", "Vega flux file, must be within ``filterFolder`` **nsamples** = 100:", "if numpy.nanmax(fwave) < numpy.nanmin(sp.wave) or numpy.nanmin(fwave) > numpy.nanmax(sp.wave): if verbose==True:", "H LONG: FOURSTAR H long FOURSTAR H SHORT: FOURSTAR H", "else: val = -2.5*numpy.log10(trapz(ftrans*d(fwave.value),fwave.value)/trapz(ftrans*v(fwave.value),fwave.value)) for i in numpy.arange(nsamples): # result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.flux_unit,fwave)/trapz(ftrans*v(fwave)*sp.flux_unit,fwave)))", "FILTERS[filt]['rsr'] # other possibilities photons = kwargs.get('photons',False) photons = kwargs.get('photon',photons)", "def visualizeFilter(filters,verbose=True,xra=[],yra=[0,1.2],**kwargs): ''' :Purpose: Plots a filter profile or set", "custom = kwargs.get('custom',False) notch = kwargs.get('notch',False) base_unit = u.erg/(u.cm**2 *", "3631*u.jansky d = interp1d(nu.value,fnu.value,bounds_error=False,fill_value=0.) n = interp1d(nu.value,noisenu.value,bounds_error=False,fill_value=0.) b = trapz((ftrans/filtnu.value)*fconst.value,filtnu.value)", ":Purpose: A simple representation of the Spectrum object ''' if", "= uncertainty self.type = magtype # check filter and rename", "numpy.arange(nsamples): result.append(10.**(-0.4*(mag.value+numpy.random.normal(0,1.)*e_mag.value))*fact) err = (numpy.nanstd(result))*u.erg/(u.cm**2 * u.s) else: err =", "# custom filter else: fwave,ftrans = custom[0],custom[1] # Read in", "'+filt+' not currently available for SPLAT; contact '+EMAIL+'\\n') filterInfo() return", "noisenu = sp.noise.to('Jy',equivalencies=u.spectral_density(sp.wave)) filtnu = fwave.to('Hz',equivalencies=u.spectral()) fconst = 3631*u.jansky d", "in filter fwave,ftrans = numpy.genfromtxt(os.path.normpath(filterFolder+FILTERS[filt]['file']), comments='#', unpack=True, missing_values = ('NaN','nan'),", "mag.to(base_unit) # e_mag.to(base_unit) # except: # raise ValueError('\\nInput quantity unit", "= [numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr'] == True:", "fwave,ftrans = numpy.linspace(f[0],f[1],1000)*wave_unit,numpy.ones(1000) plt.plot(fwave,ftrans) if len(xra) == 0: xra =", "requested filter is in list if isinstance(custom,bool) and isinstance(notch,bool): f0", "that could be uploaded pre-save some model magnitudes ''' pass", "fwave.to(u.micron) except: fwave = fwave*u.micron fw = fwave[numpy.where(ftrans > 0.01*numpy.nanmax(ftrans))]", "splat functions and constants from .initialize import * from .utilities", "result.append((trapz(ftrans*fwave.value*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) else: result.append((trapz(ftrans*(d(fwave.value)+numpy.random.normal(0,1.)*n(fwave.value)),fwave.value)*sp.wave.unit*sp.flux.unit).to(outunit).value) elif (photons): outunit = 1./u.s/u.cm**2 convert =", "[numpy.nanmin([xra[0],numpy.nanmin(fwave.value)]),numpy.nanmax([xra[1],numpy.nanmax(fwave.value)])] yra = [yra[0],numpy.nanmax([yra[1],numpy.nanmax(ftrans)])] legend.append(FILTERS[f]['description']) if FILTERS[f]['rsr'] == True: yl", "desired energy units # try: val.to(return_unit) err.to(return_unit) # except: #", "are convolved with the filter profile specified by the ``filter``", "default = False) WARNING: THIS CODE IS ONLY PARTIALLY COMPLETE" ]
[ "60.0) def to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date): print(date.timestamp()) return int(date.timestamp())", "def days(days): return int(days * 86400.0) def hours(hours): return int(hours", "86400.0) def hours(hours): return int(hours * 3600.0) def minutes(minutes): return", "return int(minutes * 60.0) def to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date):", "hours(hours): return int(hours * 3600.0) def minutes(minutes): return int(minutes *", "return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date): print(date.timestamp()) return int(date.timestamp()) def to_minutes(duration): return", "datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date): print(date.timestamp()) return int(date.timestamp()) def to_minutes(duration): return duration", "<reponame>mandalorian-101/badger-system import datetime ONE_MINUTE = 60 ONE_HOUR = 3600 ONE_DAY", "return int(date.timestamp()) def to_minutes(duration): return duration / ONE_MINUTE def to_days(duration):", "import datetime ONE_MINUTE = 60 ONE_HOUR = 3600 ONE_DAY =", "minutes(minutes): return int(minutes * 60.0) def to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def", "int(date.timestamp()) def to_minutes(duration): return duration / ONE_MINUTE def to_days(duration): return", "def hours(hours): return int(hours * 3600.0) def minutes(minutes): return int(minutes", "to_days(duration): return duration / ONE_DAY def to_hours(duration): return duration /", "= 60 ONE_HOUR = 3600 ONE_DAY = 24 * ONE_HOUR", "ONE_YEAR = 1 * 365 * ONE_DAY def days(days): return", "to_minutes(duration): return duration / ONE_MINUTE def to_days(duration): return duration /", "def to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date): print(date.timestamp()) return int(date.timestamp()) def", "* 3600.0) def minutes(minutes): return int(minutes * 60.0) def to_utc_date(timestamp):", "def to_days(duration): return duration / ONE_DAY def to_hours(duration): return duration", "* ONE_DAY def days(days): return int(days * 86400.0) def hours(hours):", "return int(days * 86400.0) def hours(hours): return int(hours * 3600.0)", "/ ONE_MINUTE def to_days(duration): return duration / ONE_DAY def to_hours(duration):", "def to_timestamp(date): print(date.timestamp()) return int(date.timestamp()) def to_minutes(duration): return duration /", "ONE_MINUTE = 60 ONE_HOUR = 3600 ONE_DAY = 24 *", "1 * 365 * ONE_DAY def days(days): return int(days *", "return int(hours * 3600.0) def minutes(minutes): return int(minutes * 60.0)", "print(date.timestamp()) return int(date.timestamp()) def to_minutes(duration): return duration / ONE_MINUTE def", "int(hours * 3600.0) def minutes(minutes): return int(minutes * 60.0) def", "60 ONE_HOUR = 3600 ONE_DAY = 24 * ONE_HOUR ONE_YEAR", "ONE_MINUTE def to_days(duration): return duration / ONE_DAY def to_hours(duration): return", "to_timestamp(date): print(date.timestamp()) return int(date.timestamp()) def to_minutes(duration): return duration / ONE_MINUTE", "= 24 * ONE_HOUR ONE_YEAR = 1 * 365 *", "return duration / ONE_DAY def to_hours(duration): return duration / ONE_HOUR", "ONE_HOUR ONE_YEAR = 1 * 365 * ONE_DAY def days(days):", "int(days * 86400.0) def hours(hours): return int(hours * 3600.0) def", "3600.0) def minutes(minutes): return int(minutes * 60.0) def to_utc_date(timestamp): return", "to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date): print(date.timestamp()) return int(date.timestamp()) def to_minutes(duration):", "24 * ONE_HOUR ONE_YEAR = 1 * 365 * ONE_DAY", "def to_minutes(duration): return duration / ONE_MINUTE def to_days(duration): return duration", "* ONE_HOUR ONE_YEAR = 1 * 365 * ONE_DAY def", "def minutes(minutes): return int(minutes * 60.0) def to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\")", "int(minutes * 60.0) def to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date): print(date.timestamp())", "3600 ONE_DAY = 24 * ONE_HOUR ONE_YEAR = 1 *", "return duration / ONE_MINUTE def to_days(duration): return duration / ONE_DAY", "= 1 * 365 * ONE_DAY def days(days): return int(days", "ONE_DAY = 24 * ONE_HOUR ONE_YEAR = 1 * 365", "days(days): return int(days * 86400.0) def hours(hours): return int(hours *", "ONE_DAY def days(days): return int(days * 86400.0) def hours(hours): return", "ONE_HOUR = 3600 ONE_DAY = 24 * ONE_HOUR ONE_YEAR =", "* 86400.0) def hours(hours): return int(hours * 3600.0) def minutes(minutes):", "= 3600 ONE_DAY = 24 * ONE_HOUR ONE_YEAR = 1", "duration / ONE_MINUTE def to_days(duration): return duration / ONE_DAY def", "365 * ONE_DAY def days(days): return int(days * 86400.0) def", "datetime ONE_MINUTE = 60 ONE_HOUR = 3600 ONE_DAY = 24", "* 365 * ONE_DAY def days(days): return int(days * 86400.0)", "* 60.0) def to_utc_date(timestamp): return datetime.datetime.utcfromtimestamp(timestamp).strftime(\"%Y-%m-%dT%H:%M:%SZ\") def to_timestamp(date): print(date.timestamp()) return" ]
[ "etc. save_plot = False # Masking out grid cells that", "[-15, 9.5] # Longitude bounds latbounds = [45, 64] #", "each subplot. The season_suffixes will be added to var_name #", "and flatten axis array f, a = coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r,", "set title pc = a_flat[ii].pcolormesh( ds.longitude, ds.latitude, data, cmap=cmap, vmin=clim[0],", "Scatter and set title pc = a_flat[ii].pcolormesh( ds.longitude, ds.latitude, data,", "where to select season etc. save_plot = False # Masking", "and horizontal padding between plots fig_pad = (0.075, 0.075, 0.1,", "Discretize colormap cmap_levels = 14 # Labels and Titles fig_title", "to use for labelling plots subtitle_fontsize = 11 # Fontsize", "will be added to var_name # for each subplot panel.", "will be plotted # on each axis of the plot", "\"both\" in extend_cbar: extend = \"both\" elif \"max\" in extend_cbar", "extend the colorbar for this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1])) #", "name_of_count_variable data = ds[var_ii].values count_var = ds[N_var] data[count_var < min_points_in_average]", "(0.075, 0.075, 0.1, 0.1) # Figure padding (left, top, right,", "fn_list = [ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ] # Filename for the", "for labelling plots subtitle_fontsize = 11 # Fontsize for dataset", "with seasonal # variables on each subplot. The season_suffixes will", "top to bottom. A colorbar will be placed right of", "and \"min\" in extend_cbar: extend = \"both\" elif \"max\" in", "if \"both\" in extend_cbar: extend = \"both\" elif \"max\" in", "top=(1 - fig_pad[3])) # Handle colorbar -- will we extend", "Masking out grid cells that don't contain many points min_points_in_average", "\"~/transfer/test_grid.nc\", ] # Filename for the output fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name)", "Fontweight to use for title dataset_names = [\"CO9p0\", \"CO9p0\", \"CO9p0\"]", "= \"normal\" # Fontweight for dataset subtitles # PLOT SEASONS.", "fig_pad[2] + fig_pad[2] * 0.15), 0.15, 0.025, 0.7]) f.colorbar(pc, cax=cbar_ax,", "list ds_list = [xr.open_dataset(dd) for dd in fn_list] n_ds =", "elif \"min\" in extend_cbar: extend = \"min\" else: extend =", "plot the provided list of netcdf datasets from left to", "1) # Color limits for normal points discrete_cmap = True", "placed right of the figure. \"\"\" import xarray as xr", "name in analysis file to plot # If you used", "of netcdf files and mess with the options to get", "this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1])) # Set Figure title f.suptitle(fig_title,", "opts marker_size = 3 # Marker size cmap = \"bwr\"", "or not extend_cbar = [] # Loop over dataset for", "bottom) # Leave some space on right for colorbar #", "on each axis of the plot fn_list = [ \"~/transfer/test_grid.nc\",", "Figure size lonbounds = [-15, 9.5] # Longitude bounds latbounds", "= ds_list[ii] var_ii = var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var =", "a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var = name_of_count_variable data = ds[var_ii].values count_var", "plotted # on each axis of the plot fn_list =", "plot and flatten axis array f, a = coast.plot_util.create_geo_subplots(lonbounds, latbounds,", "dataset will be plotted, with seasonal # variables on each", "= \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General Plot Settings var_name = \"abs_diff_temperature\" #", "pandas as pd #%% File settings run_name = \"test\" #", "\"max\" in extend_cbar and \"min\" in extend_cbar: extend = \"both\"", "Colormap for normal points clim = (-1, 1) # Color", "save_plot = False # Masking out grid cells that don't", "- fig_pad[2]), top=(1 - fig_pad[3])) # Handle colorbar -- will", "labelling plots subtitle_fontsize = 11 # Fontsize for dataset subtitles", "extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1])) # Set Figure title f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight)", "# Names to use for labelling plots subtitle_fontsize = 11", "vmin=clim[0], vmax=clim[1], ) # Will we extend the colorbar for", "cbar_ax = f.add_axes([(1 - fig_pad[2] + fig_pad[2] * 0.15), 0.15,", "\"both\" elif \"max\" in extend_cbar: extend = \"max\" elif \"min\"", "var_name + \"_{0}\".format(season_suffixes[ii]) N_var = \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05, 1.02, season_suffixes[ii],", "to var_name # for each subplot panel. plot_seasons = True", "# Fontsize for dataset subtitles subtitle_fontweight = \"normal\" # Fontweight", "size lonbounds = [-15, 9.5] # Longitude bounds latbounds =", "bounds subplot_padding = 0.5 # Amount of vertical and horizontal", "\"max\" in extend_cbar: extend = \"max\" elif \"min\" in extend_cbar:", "Make sure n_r = 2 and n_c = 2 #", "ds_list = [xr.open_dataset(dd) for dd in fn_list] n_ds = len(ds_list)", "extend_cbar: extend = \"max\" elif \"min\" in extend_cbar: extend =", "as np import sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast import pandas as", "\"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General Plot Settings var_name = \"abs_diff_temperature\" # Variable", "datasets into list ds_list = [xr.open_dataset(dd) for dd in fn_list]", "fontweight=subtitle_fontweight) N_var = name_of_count_variable data = ds[var_ii].values count_var = ds[N_var]", "= 5 name_of_count_variable = \"grid_N\" # Subplot axes settings n_r", "points min_points_in_average = 5 name_of_count_variable = \"grid_N\" # Subplot axes", "= True season_suffixes = [\"DJF\", \"MAM\", \"JJA\", \"SON\"] #%% Read", "for title dataset_names = [\"CO9p0\", \"CO9p0\", \"CO9p0\"] # Names to", "points discrete_cmap = True # Discretize colormap cmap_levels = 14", "in extend_cbar: extend = \"max\" elif \"min\" in extend_cbar: extend", "only the first dataset will be plotted, with seasonal #", "- fig_pad[3])) # Handle colorbar -- will we extend it?", "object with no z_dim (vertical dimension). Provide an array of", "many rows and columns the plot will have. This script", "colorbar for this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1])) # Set Figure", "figsize = (10, 5) # Figure size lonbounds = [-15,", "for ii in range(n_ax): ur_index = np.unravel_index(ii, (n_r, n_c)) #", "figsize=figsize) a_flat = a.flatten() # Dicretize colormap maybe if discrete_cmap:", "var_name = \"abs_diff_temperature\" # Variable name in analysis file to", "season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\") else: ds = ds_list[ii] var_ii = var_name", "file to plot # If you used var modified to", "Longitude bounds latbounds = [45, 64] # Latitude bounds subplot_padding", "Number of subplot rows n_c = 2 # Number of", "0.075, 0.1, 0.1) # Figure padding (left, top, right, bottom)", "= (0.075, 0.075, 0.1, 0.1) # Figure padding (left, top,", "Provide an array of netcdf files and mess with the", "\"\"\" import xarray as xr import matplotlib.pyplot as plt import", "from a profile object with no z_dim (vertical dimension). Provide", "the first dataset will be plotted, with seasonal # variables", "Marker size cmap = \"bwr\" # Colormap for normal points", "# Set Figure title f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight) # Set tight", "points clim = (-1, 1) # Color limits for normal", "with the options to get a figure you like. You", "an array of netcdf files and mess with the options", "to bottom. A colorbar will be placed right of the", "modified to make gridded data # then this is where", "into list ds_list = [xr.open_dataset(dd) for dd in fn_list] n_ds", "\"SST Errors\" # Whole figure title title_fontsize = 13 #", "right and top to bottom. A colorbar will be placed", "dataset subtitles # PLOT SEASONS. Make sure n_r = 2", "cmap=cmap, vmin=clim[0], vmax=clim[1], ) # Will we extend the colorbar", "clim = (-1, 1) # Color limits for normal points", "this option is true, only the first dataset will be", "n_r = 2 # Number of subplot rows n_c =", "subtitles subtitle_fontweight = \"normal\" # Fontweight for dataset subtitles #", "to plot # If you used var modified to make", "files and mess with the options to get a figure", "if plot_seasons: ds = ds_list[0] var_ii = var_name + \"_{0}\".format(season_suffixes[ii])", "= ds[var_ii].values count_var = ds[N_var] data[count_var < min_points_in_average] = np.nan", "array f, a = coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r, n_c, figsize=figsize) a_flat", "\"_{0}\".format(season_suffixes[ii]) N_var = \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05, 1.02, season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\")", "colormap cmap_levels = 14 # Labels and Titles fig_title =", "# Create plot and flatten axis array f, a =", "define how many rows and columns the plot will have.", "from each will be plotted # on each axis of", "3 # Marker size cmap = \"bwr\" # Colormap for", "ds[N_var] data[count_var < min_points_in_average] = np.nan # Scatter and set", "# Handle colorbar -- will we extend it? if \"both\"", "11 # Fontsize for dataset subtitles subtitle_fontweight = \"normal\" #", "use for title dataset_names = [\"CO9p0\", \"CO9p0\", \"CO9p0\"] # Names", "Fontweight for dataset subtitles # PLOT SEASONS. Make sure n_r", "Latitude bounds subplot_padding = 0.5 # Amount of vertical and", "if we will extend the colormap or not extend_cbar =", "\"test\" # List of analysis output files. Profiles from each", "the plot will have. This script will plot the provided", "netcdf datasets from left to right and top to bottom.", "used var modified to make gridded data # then this", "axes settings n_r = 2 # Number of subplot rows", "space on right for colorbar # Scatter opts marker_size =", "extend = \"both\" elif \"max\" in extend_cbar and \"min\" in", "\"CO9p0\", \"CO9p0\"] # Names to use for labelling plots subtitle_fontsize", "n_ax = n_r * n_c # Create plot and flatten", "plot will have. This script will plot the provided list", "discrete_cmap: cmap = plt.cm.get_cmap(cmap, cmap_levels) # Determine if we will", "# Select season if required if plot_seasons: ds = ds_list[0]", "figure. \"\"\" import xarray as xr import matplotlib.pyplot as plt", "get a figure you like. You can define how many", "and plotdata # Read all datasets into list ds_list =", "[45, 64] # Latitude bounds subplot_padding = 0.5 # Amount", "you like. You can define how many rows and columns", "bottom (or any fixed level) errors from a profile object", "on right for colorbar # Scatter opts marker_size = 3", "= plt.cm.get_cmap(cmap, cmap_levels) # Determine if we will extend the", "1.02, season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\") else: ds = ds_list[ii] var_ii =", "\"neither\" cbar_ax = f.add_axes([(1 - fig_pad[2] + fig_pad[2] * 0.15),", "f.colorbar(pc, cax=cbar_ax, extend=extend) # Save plot maybe if save_plot: f.savefig(fn_out)", "Plot up surface or bottom (or any fixed level) errors", "dimension). Provide an array of netcdf files and mess with", "a.flatten() # Dicretize colormap maybe if discrete_cmap: cmap = plt.cm.get_cmap(cmap,", "# Figure size lonbounds = [-15, 9.5] # Longitude bounds", "sure n_r = 2 and n_c = 2 # If", "= 0.5 # Amount of vertical and horizontal padding between", "-- will we extend it? if \"both\" in extend_cbar: extend", "cells that don't contain many points min_points_in_average = 5 name_of_count_variable", "= [-15, 9.5] # Longitude bounds latbounds = [45, 64]", "array of netcdf files and mess with the options to", "2 # If this option is true, only the first", "Read and plotdata # Read all datasets into list ds_list", "datasets from left to right and top to bottom. A", "# List of analysis output files. Profiles from each will", "pd #%% File settings run_name = \"test\" # List of", "f.add_axes([(1 - fig_pad[2] + fig_pad[2] * 0.15), 0.15, 0.025, 0.7])", "64] # Latitude bounds subplot_padding = 0.5 # Amount of", "\"MAM\", \"JJA\", \"SON\"] #%% Read and plotdata # Read all", "title f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight) # Set tight figure layout f.tight_layout(w_pad=subplot_padding,", "we extend it? if \"both\" in extend_cbar: extend = \"both\"", "var_name # for each subplot panel. plot_seasons = True season_suffixes", "= 14 # Labels and Titles fig_title = \"SST Errors\"", "extend it? if \"both\" in extend_cbar: extend = \"both\" elif", "some space on right for colorbar # Scatter opts marker_size", "the colorbar for this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1])) # Set", "normal points discrete_cmap = True # Discretize colormap cmap_levels =", "will extend the colormap or not extend_cbar = [] #", "and set title pc = a_flat[ii].pcolormesh( ds.longitude, ds.latitude, data, cmap=cmap,", "\"max\" elif \"min\" in extend_cbar: extend = \"min\" else: extend", "= \"neither\" cbar_ax = f.add_axes([(1 - fig_pad[2] + fig_pad[2] *", "for dataset subtitles # PLOT SEASONS. Make sure n_r =", "added to var_name # for each subplot panel. plot_seasons =", "and top to bottom. A colorbar will be placed right", "colorbar # Scatter opts marker_size = 3 # Marker size", "Errors\" # Whole figure title title_fontsize = 13 # Fontsize", "< min_points_in_average] = np.nan # Scatter and set title pc", "grid cells that don't contain many points min_points_in_average = 5", "and n_c = 2 # If this option is true,", "each will be plotted # on each axis of the", "data, cmap=cmap, vmin=clim[0], vmax=clim[1], ) # Will we extend the", "don't contain many points min_points_in_average = 5 name_of_count_variable = \"grid_N\"", "\"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05, 1.02, season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\") else: ds =", "import pandas as pd #%% File settings run_name = \"test\"", "# on each axis of the plot fn_list = [", "= 2 # If this option is true, only the", "= \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05, 1.02, season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\") else: ds", "will have. This script will plot the provided list of", "data # then this is where to select season etc.", "options to get a figure you like. You can define", "= \"bold\" # Fontweight to use for title dataset_names =", "# Filename for the output fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General", "(or any fixed level) errors from a profile object with", "plot_seasons = True season_suffixes = [\"DJF\", \"MAM\", \"JJA\", \"SON\"] #%%", "subplot_padding = 0.5 # Amount of vertical and horizontal padding", "extend = \"max\" elif \"min\" in extend_cbar: extend = \"min\"", "list of netcdf datasets from left to right and top", "[] # Loop over dataset for ii in range(n_ax): ur_index", "2 # Number of subplot columns figsize = (10, 5)", "# Fontweight for dataset subtitles # PLOT SEASONS. Make sure", "the options to get a figure you like. You can", "vmax=clim[1], ) # Will we extend the colorbar for this", "plt import numpy as np import sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast", "variables on each subplot. The season_suffixes will be added to", "else: ds = ds_list[ii] var_ii = var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight)", "title dataset_names = [\"CO9p0\", \"CO9p0\", \"CO9p0\"] # Names to use", "subplot columns figsize = (10, 5) # Figure size lonbounds", "Loop over dataset for ii in range(n_ax): ur_index = np.unravel_index(ii,", "for normal points discrete_cmap = True # Discretize colormap cmap_levels", "The season_suffixes will be added to var_name # for each", "in fn_list] n_ds = len(ds_list) n_ax = n_r * n_c", "\"both\" elif \"max\" in extend_cbar and \"min\" in extend_cbar: extend", "True season_suffixes = [\"DJF\", \"MAM\", \"JJA\", \"SON\"] #%% Read and", "0.1, 0.1) # Figure padding (left, top, right, bottom) #", "A colorbar will be placed right of the figure. \"\"\"", "Fontsize of title title_fontweight = \"bold\" # Fontweight to use", "season_suffixes[ii]) a_flat[ii].text(0.05, 1.02, season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\") else: ds = ds_list[ii]", "* 0.15), 0.15, 0.025, 0.7]) f.colorbar(pc, cax=cbar_ax, extend=extend) # Save", "season_suffixes will be added to var_name # for each subplot", "for normal points clim = (-1, 1) # Color limits", "- fig_pad[2] + fig_pad[2] * 0.15), 0.15, 0.025, 0.7]) f.colorbar(pc,", "\"CO9p0\"] # Names to use for labelling plots subtitle_fontsize =", "2 and n_c = 2 # If this option is", "mess with the options to get a figure you like.", "will we extend it? if \"both\" in extend_cbar: extend =", "subtitle_fontsize = 11 # Fontsize for dataset subtitles subtitle_fontweight =", "= var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var = name_of_count_variable data =", "# Set tight figure layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1", "to select season etc. save_plot = False # Masking out", "# Masking out grid cells that don't contain many points", "discrete_cmap = True # Discretize colormap cmap_levels = 14 #", "will plot the provided list of netcdf datasets from left", "extend the colormap or not extend_cbar = [] # Loop", "ii in range(n_ax): ur_index = np.unravel_index(ii, (n_r, n_c)) # Select", "Leave some space on right for colorbar # Scatter opts", "plot fn_list = [ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ] # Filename for", "(vertical dimension). Provide an array of netcdf files and mess", "elif \"max\" in extend_cbar: extend = \"max\" elif \"min\" in", "# If this option is true, only the first dataset", "plt.cm.get_cmap(cmap, cmap_levels) # Determine if we will extend the colormap", "will be plotted, with seasonal # variables on each subplot.", "Figure title f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight) # Set tight figure layout", "\"SON\"] #%% Read and plotdata # Read all datasets into", "from left to right and top to bottom. A colorbar", "be plotted # on each axis of the plot fn_list", "plots fig_pad = (0.075, 0.075, 0.1, 0.1) # Figure padding", "top, right, bottom) # Leave some space on right for", "= len(ds_list) n_ax = n_r * n_c # Create plot", "select season etc. save_plot = False # Masking out grid", "n_c)) # Select season if required if plot_seasons: ds =", "required if plot_seasons: ds = ds_list[0] var_ii = var_name +", "can define how many rows and columns the plot will", "Labels and Titles fig_title = \"SST Errors\" # Whole figure", "9.5] # Longitude bounds latbounds = [45, 64] # Latitude", "with no z_dim (vertical dimension). Provide an array of netcdf", "Settings var_name = \"abs_diff_temperature\" # Variable name in analysis file", "5) # Figure size lonbounds = [-15, 9.5] # Longitude", "of title title_fontweight = \"bold\" # Fontweight to use for", "# Fontsize of title title_fontweight = \"bold\" # Fontweight to", "dd in fn_list] n_ds = len(ds_list) n_ax = n_r *", "colorbar -- will we extend it? if \"both\" in extend_cbar:", "or bottom (or any fixed level) errors from a profile", "extend_cbar: extend = \"min\" else: extend = \"neither\" cbar_ax =", "(10, 5) # Figure size lonbounds = [-15, 9.5] #", "extend_cbar = [] # Loop over dataset for ii in", "settings run_name = \"test\" # List of analysis output files.", "latbounds = [45, 64] # Latitude bounds subplot_padding = 0.5", "If you used var modified to make gridded data #", "season if required if plot_seasons: ds = ds_list[0] var_ii =", "Variable name in analysis file to plot # If you", "analysis file to plot # If you used var modified", "the output fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General Plot Settings var_name", "horizontal padding between plots fig_pad = (0.075, 0.075, 0.1, 0.1)", "seasonal # variables on each subplot. The season_suffixes will be", "True # Discretize colormap cmap_levels = 14 # Labels and", "= (10, 5) # Figure size lonbounds = [-15, 9.5]", "clim[0], clim[1])) # Set Figure title f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight) #", "# Scatter opts marker_size = 3 # Marker size cmap", "errors from a profile object with no z_dim (vertical dimension).", "numpy as np import sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast import pandas", "= a.flatten() # Dicretize colormap maybe if discrete_cmap: cmap =", "data[count_var < min_points_in_average] = np.nan # Scatter and set title", "# Color limits for normal points discrete_cmap = True #", "subtitles # PLOT SEASONS. Make sure n_r = 2 and", "2 # Number of subplot rows n_c = 2 #", "SEASONS. Make sure n_r = 2 and n_c = 2", "axis of the plot fn_list = [ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ]", "subplot panel. plot_seasons = True season_suffixes = [\"DJF\", \"MAM\", \"JJA\",", "# Subplot axes settings n_r = 2 # Number of", "= \"SST Errors\" # Whole figure title title_fontsize = 13", "] # Filename for the output fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%%", "= 3 # Marker size cmap = \"bwr\" # Colormap", "min_points_in_average = 5 name_of_count_variable = \"grid_N\" # Subplot axes settings", "Figure padding (left, top, right, bottom) # Leave some space", "on each subplot. The season_suffixes will be added to var_name", "ds_list[ii] var_ii = var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var = name_of_count_variable", "in extend_cbar and \"min\" in extend_cbar: extend = \"both\" elif", "to right and top to bottom. A colorbar will be", "N_var = \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05, 1.02, season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\") else:", "= \"min\" else: extend = \"neither\" cbar_ax = f.add_axes([(1 -", "= [ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ] # Filename for the output", "be added to var_name # for each subplot panel. plot_seasons", "= [\"DJF\", \"MAM\", \"JJA\", \"SON\"] #%% Read and plotdata #", "# Determine if we will extend the colormap or not", "#%% Read and plotdata # Read all datasets into list", "= False # Masking out grid cells that don't contain", "fontsize=title_fontsize, fontweight=title_fontweight) # Set tight figure layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]),", "subtitle_fontweight = \"normal\" # Fontweight for dataset subtitles # PLOT", "# Leave some space on right for colorbar # Scatter", "for dataset subtitles subtitle_fontweight = \"normal\" # Fontweight for dataset", "Read all datasets into list ds_list = [xr.open_dataset(dd) for dd", "= f.add_axes([(1 - fig_pad[2] + fig_pad[2] * 0.15), 0.15, 0.025,", "right of the figure. \"\"\" import xarray as xr import", "\"JJA\", \"SON\"] #%% Read and plotdata # Read all datasets", "fontweight=title_fontweight) # Set tight figure layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]),", "0.7]) f.colorbar(pc, cax=cbar_ax, extend=extend) # Save plot maybe if save_plot:", "option is true, only the first dataset will be plotted,", "to use for title dataset_names = [\"CO9p0\", \"CO9p0\", \"CO9p0\"] #", "of subplot columns figsize = (10, 5) # Figure size", "= n_r * n_c # Create plot and flatten axis", "colormap maybe if discrete_cmap: cmap = plt.cm.get_cmap(cmap, cmap_levels) # Determine", "each subplot panel. plot_seasons = True season_suffixes = [\"DJF\", \"MAM\",", "of vertical and horizontal padding between plots fig_pad = (0.075,", "transform=a_flat[ii].transAxes, fontweight=\"bold\") else: ds = ds_list[ii] var_ii = var_name a_flat[ii].set_title(dataset_names[ii],", "# Number of subplot columns figsize = (10, 5) #", "tight figure layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1 - fig_pad[2]),", "= True # Discretize colormap cmap_levels = 14 # Labels", "f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight) # Set tight figure layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding)", "provided list of netcdf datasets from left to right and", "Select season if required if plot_seasons: ds = ds_list[0] var_ii", "size cmap = \"bwr\" # Colormap for normal points clim", "# Will we extend the colorbar for this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data,", "Scatter opts marker_size = 3 # Marker size cmap =", "matplotlib.pyplot as plt import numpy as np import sys sys.path.append(\"/Users/dbyrne/code/COAsT\")", "# If you used var modified to make gridded data", "in analysis file to plot # If you used var", "# Fontweight to use for title dataset_names = [\"CO9p0\", \"CO9p0\",", "min_points_in_average] = np.nan # Scatter and set title pc =", "[ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ] # Filename for the output fn_out", "PLOT SEASONS. Make sure n_r = 2 and n_c =", "[\"DJF\", \"MAM\", \"JJA\", \"SON\"] #%% Read and plotdata # Read", "If this option is true, only the first dataset will", "import sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast import pandas as pd #%%", "(-1, 1) # Color limits for normal points discrete_cmap =", "ds = ds_list[ii] var_ii = var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var", "padding between plots fig_pad = (0.075, 0.075, 0.1, 0.1) #", "dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1])) # Set Figure title f.suptitle(fig_title, fontsize=title_fontsize,", "columns the plot will have. This script will plot the", "true, only the first dataset will be plotted, with seasonal", "extend = \"neither\" cbar_ax = f.add_axes([(1 - fig_pad[2] + fig_pad[2]", "n_c = 2 # If this option is true, only", "season_suffixes = [\"DJF\", \"MAM\", \"JJA\", \"SON\"] #%% Read and plotdata", "in range(n_ax): ur_index = np.unravel_index(ii, (n_r, n_c)) # Select season", "it? if \"both\" in extend_cbar: extend = \"both\" elif \"max\"", "will be placed right of the figure. \"\"\" import xarray", "pc = a_flat[ii].pcolormesh( ds.longitude, ds.latitude, data, cmap=cmap, vmin=clim[0], vmax=clim[1], )", "Subplot axes settings n_r = 2 # Number of subplot", "[xr.open_dataset(dd) for dd in fn_list] n_ds = len(ds_list) n_ax =", "0.15), 0.15, 0.025, 0.7]) f.colorbar(pc, cax=cbar_ax, extend=extend) # Save plot", "= 2 and n_c = 2 # If this option", "right, bottom) # Leave some space on right for colorbar", "\"abs_diff_temperature\" # Variable name in analysis file to plot #", "(left, top, right, bottom) # Leave some space on right", "var_ii = var_name + \"_{0}\".format(season_suffixes[ii]) N_var = \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05,", "= [xr.open_dataset(dd) for dd in fn_list] n_ds = len(ds_list) n_ax", "* n_c # Create plot and flatten axis array f,", "as pd #%% File settings run_name = \"test\" # List", "# Scatter and set title pc = a_flat[ii].pcolormesh( ds.longitude, ds.latitude,", "panel. plot_seasons = True season_suffixes = [\"DJF\", \"MAM\", \"JJA\", \"SON\"]", "if discrete_cmap: cmap = plt.cm.get_cmap(cmap, cmap_levels) # Determine if we", "# Figure padding (left, top, right, bottom) # Leave some", "ur_index = np.unravel_index(ii, (n_r, n_c)) # Select season if required", "of analysis output files. Profiles from each will be plotted", "a = coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r, n_c, figsize=figsize) a_flat = a.flatten()", "= [\"CO9p0\", \"CO9p0\", \"CO9p0\"] # Names to use for labelling", "fn_list] n_ds = len(ds_list) n_ax = n_r * n_c #", "fig_pad[3])) # Handle colorbar -- will we extend it? if", "as plt import numpy as np import sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import", "this is where to select season etc. save_plot = False", "Titles fig_title = \"SST Errors\" # Whole figure title title_fontsize", "in extend_cbar: extend = \"min\" else: extend = \"neither\" cbar_ax", "lonbounds = [-15, 9.5] # Longitude bounds latbounds = [45,", "Handle colorbar -- will we extend it? if \"both\" in", "Whole figure title title_fontsize = 13 # Fontsize of title", "dataset_names = [\"CO9p0\", \"CO9p0\", \"CO9p0\"] # Names to use for", "maybe if discrete_cmap: cmap = plt.cm.get_cmap(cmap, cmap_levels) # Determine if", "14 # Labels and Titles fig_title = \"SST Errors\" #", "xr import matplotlib.pyplot as plt import numpy as np import", "= \"grid_N\" # Subplot axes settings n_r = 2 #", "surface or bottom (or any fixed level) errors from a", "\"grid_N\" # Subplot axes settings n_r = 2 # Number", "cmap = \"bwr\" # Colormap for normal points clim =", "then this is where to select season etc. save_plot =", "subplot. The season_suffixes will be added to var_name # for", "n_c, figsize=figsize) a_flat = a.flatten() # Dicretize colormap maybe if", "run_name = \"test\" # List of analysis output files. Profiles", "= a_flat[ii].pcolormesh( ds.longitude, ds.latitude, data, cmap=cmap, vmin=clim[0], vmax=clim[1], ) #", "fixed level) errors from a profile object with no z_dim", "the figure. \"\"\" import xarray as xr import matplotlib.pyplot as", "Number of subplot columns figsize = (10, 5) # Figure", "# variables on each subplot. The season_suffixes will be added", "= \"abs_diff_temperature\" # Variable name in analysis file to plot", "ds.longitude, ds.latitude, data, cmap=cmap, vmin=clim[0], vmax=clim[1], ) # Will we", "contain many points min_points_in_average = 5 name_of_count_variable = \"grid_N\" #", "plotdata # Read all datasets into list ds_list = [xr.open_dataset(dd)", "= \"max\" elif \"min\" in extend_cbar: extend = \"min\" else:", "rows n_c = 2 # Number of subplot columns figsize", "= ds[N_var] data[count_var < min_points_in_average] = np.nan # Scatter and", "level) errors from a profile object with no z_dim (vertical", "right for colorbar # Scatter opts marker_size = 3 #", "count_var = ds[N_var] data[count_var < min_points_in_average] = np.nan # Scatter", "Profiles from each will be plotted # on each axis", "extend = \"both\" elif \"max\" in extend_cbar: extend = \"max\"", "f, a = coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r, n_c, figsize=figsize) a_flat =", "coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r, n_c, figsize=figsize) a_flat = a.flatten() # Dicretize", "#%% General Plot Settings var_name = \"abs_diff_temperature\" # Variable name", "data = ds[var_ii].values count_var = ds[N_var] data[count_var < min_points_in_average] =", "make gridded data # then this is where to select", "\"\"\" Plot up surface or bottom (or any fixed level)", "like. You can define how many rows and columns the", "# Number of subplot rows n_c = 2 # Number", "n_r * n_c # Create plot and flatten axis array", "fig_pad = (0.075, 0.075, 0.1, 0.1) # Figure padding (left,", "be placed right of the figure. \"\"\" import xarray as", "marker_size = 3 # Marker size cmap = \"bwr\" #", "= \"bwr\" # Colormap for normal points clim = (-1,", "Create plot and flatten axis array f, a = coast.plot_util.create_geo_subplots(lonbounds,", "Determine if we will extend the colormap or not extend_cbar", "layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1 - fig_pad[2]), top=(1 -", "limits for normal points discrete_cmap = True # Discretize colormap", "= [] # Loop over dataset for ii in range(n_ax):", "name_of_count_variable = \"grid_N\" # Subplot axes settings n_r = 2", "cmap_levels = 14 # Labels and Titles fig_title = \"SST", "is true, only the first dataset will be plotted, with", "for this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1])) # Set Figure title", "bounds latbounds = [45, 64] # Latitude bounds subplot_padding =", "# Amount of vertical and horizontal padding between plots fig_pad", "0.5 # Amount of vertical and horizontal padding between plots", "plots subtitle_fontsize = 11 # Fontsize for dataset subtitles subtitle_fontweight", "# for each subplot panel. plot_seasons = True season_suffixes =", "= \"both\" elif \"max\" in extend_cbar and \"min\" in extend_cbar:", "for colorbar # Scatter opts marker_size = 3 # Marker", "in extend_cbar: extend = \"both\" elif \"max\" in extend_cbar and", "+ \"_{0}\".format(season_suffixes[ii]) N_var = \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05, 1.02, season_suffixes[ii], transform=a_flat[ii].transAxes,", "= \"test\" # List of analysis output files. Profiles from", "Fontsize for dataset subtitles subtitle_fontweight = \"normal\" # Fontweight for", "# PLOT SEASONS. Make sure n_r = 2 and n_c", "= coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r, n_c, figsize=figsize) a_flat = a.flatten() #", "\"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ] # Filename for the output fn_out =", "f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1 - fig_pad[2]), top=(1 - fig_pad[3])) # Handle", "we extend the colorbar for this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0], clim[1]))", "left to right and top to bottom. A colorbar will", "right=(1 - fig_pad[2]), top=(1 - fig_pad[3])) # Handle colorbar --", "# Discretize colormap cmap_levels = 14 # Labels and Titles", "and columns the plot will have. This script will plot", "plot # If you used var modified to make gridded", "latbounds, n_r, n_c, figsize=figsize) a_flat = a.flatten() # Dicretize colormap", "for the output fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General Plot Settings", "up surface or bottom (or any fixed level) errors from", "This script will plot the provided list of netcdf datasets", "coast import pandas as pd #%% File settings run_name =", "a_flat[ii].text(0.05, 1.02, season_suffixes[ii], transform=a_flat[ii].transAxes, fontweight=\"bold\") else: ds = ds_list[ii] var_ii", "File settings run_name = \"test\" # List of analysis output", "import numpy as np import sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast import", "range(n_ax): ur_index = np.unravel_index(ii, (n_r, n_c)) # Select season if", "= ds_list[0] var_ii = var_name + \"_{0}\".format(season_suffixes[ii]) N_var = \"{0}_{1}\".format(name_of_count_variable,", "ds = ds_list[0] var_ii = var_name + \"_{0}\".format(season_suffixes[ii]) N_var =", "title_fontsize = 13 # Fontsize of title title_fontweight = \"bold\"", "General Plot Settings var_name = \"abs_diff_temperature\" # Variable name in", "normal points clim = (-1, 1) # Color limits for", "len(ds_list) n_ax = n_r * n_c # Create plot and", "= np.unravel_index(ii, (n_r, n_c)) # Select season if required if", "var modified to make gridded data # then this is", "for each subplot panel. plot_seasons = True season_suffixes = [\"DJF\",", "ds_list[0] var_ii = var_name + \"_{0}\".format(season_suffixes[ii]) N_var = \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii])", "figure title title_fontsize = 13 # Fontsize of title title_fontweight", "= np.nan # Scatter and set title pc = a_flat[ii].pcolormesh(", "= var_name + \"_{0}\".format(season_suffixes[ii]) N_var = \"{0}_{1}\".format(name_of_count_variable, season_suffixes[ii]) a_flat[ii].text(0.05, 1.02,", "[\"CO9p0\", \"CO9p0\", \"CO9p0\"] # Names to use for labelling plots", "\"min\" in extend_cbar: extend = \"min\" else: extend = \"neither\"", "files. Profiles from each will be plotted # on each", "n_r = 2 and n_c = 2 # If this", "of the plot fn_list = [ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ] #", "\"bwr\" # Colormap for normal points clim = (-1, 1)", "flatten axis array f, a = coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r, n_c,", "a figure you like. You can define how many rows", "figure layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1 - fig_pad[2]), top=(1", "output files. Profiles from each will be plotted # on", "clim[1])) # Set Figure title f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight) # Set", "var_ii = var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var = name_of_count_variable data", "xarray as xr import matplotlib.pyplot as plt import numpy as", "title title_fontweight = \"bold\" # Fontweight to use for title", "import xarray as xr import matplotlib.pyplot as plt import numpy", "between plots fig_pad = (0.075, 0.075, 0.1, 0.1) # Figure", "Amount of vertical and horizontal padding between plots fig_pad =", "in extend_cbar: extend = \"both\" elif \"max\" in extend_cbar: extend", "title title_fontsize = 13 # Fontsize of title title_fontweight =", "\"bold\" # Fontweight to use for title dataset_names = [\"CO9p0\",", "Set tight figure layout f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1 -", "sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast import pandas as pd #%% File settings", "np.unravel_index(ii, (n_r, n_c)) # Select season if required if plot_seasons:", "colorbar will be placed right of the figure. \"\"\" import", "rows and columns the plot will have. This script will", "not extend_cbar = [] # Loop over dataset for ii", "= \"both\" elif \"max\" in extend_cbar: extend = \"max\" elif", "bottom. A colorbar will be placed right of the figure.", "0.1) # Figure padding (left, top, right, bottom) # Leave", "h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1 - fig_pad[2]), top=(1 - fig_pad[3])) #", "# Colormap for normal points clim = (-1, 1) #", "extend = \"min\" else: extend = \"neither\" cbar_ax = f.add_axes([(1", "# Whole figure title title_fontsize = 13 # Fontsize of", "Filename for the output fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General Plot", "and Titles fig_title = \"SST Errors\" # Whole figure title", "fontweight=\"bold\") else: ds = ds_list[ii] var_ii = var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize,", "# Marker size cmap = \"bwr\" # Colormap for normal", "0.025, 0.7]) f.colorbar(pc, cax=cbar_ax, extend=extend) # Save plot maybe if", "be plotted, with seasonal # variables on each subplot. The", "0.15, 0.025, 0.7]) f.colorbar(pc, cax=cbar_ax, extend=extend) # Save plot maybe", "ds.latitude, data, cmap=cmap, vmin=clim[0], vmax=clim[1], ) # Will we extend", "N_var = name_of_count_variable data = ds[var_ii].values count_var = ds[N_var] data[count_var", "of subplot rows n_c = 2 # Number of subplot", "False # Masking out grid cells that don't contain many", "to get a figure you like. You can define how", "colormap or not extend_cbar = [] # Loop over dataset", "\"normal\" # Fontweight for dataset subtitles # PLOT SEASONS. Make", "you used var modified to make gridded data # then", "use for labelling plots subtitle_fontsize = 11 # Fontsize for", "have. This script will plot the provided list of netcdf", ") # Will we extend the colorbar for this dataset?", "cmap_levels) # Determine if we will extend the colormap or", "= 2 # Number of subplot rows n_c = 2", "# Longitude bounds latbounds = [45, 64] # Latitude bounds", "z_dim (vertical dimension). Provide an array of netcdf files and", "np.nan # Scatter and set title pc = a_flat[ii].pcolormesh( ds.longitude,", "each axis of the plot fn_list = [ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\",", "a_flat[ii].pcolormesh( ds.longitude, ds.latitude, data, cmap=cmap, vmin=clim[0], vmax=clim[1], ) # Will", "sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast import pandas as pd #%% File", "axis array f, a = coast.plot_util.create_geo_subplots(lonbounds, latbounds, n_r, n_c, figsize=figsize)", "ds[var_ii].values count_var = ds[N_var] data[count_var < min_points_in_average] = np.nan #", "= name_of_count_variable data = ds[var_ii].values count_var = ds[N_var] data[count_var <", "var_name a_flat[ii].set_title(dataset_names[ii], fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var = name_of_count_variable data = ds[var_ii].values", "Set Figure title f.suptitle(fig_title, fontsize=title_fontsize, fontweight=title_fontweight) # Set tight figure", "= 13 # Fontsize of title title_fontweight = \"bold\" #", "\"min\" in extend_cbar: extend = \"both\" elif \"max\" in extend_cbar:", "title pc = a_flat[ii].pcolormesh( ds.longitude, ds.latitude, data, cmap=cmap, vmin=clim[0], vmax=clim[1],", "= (-1, 1) # Color limits for normal points discrete_cmap", "first dataset will be plotted, with seasonal # variables on", "n_ds = len(ds_list) n_ax = n_r * n_c # Create", "over dataset for ii in range(n_ax): ur_index = np.unravel_index(ii, (n_r,", "all datasets into list ds_list = [xr.open_dataset(dd) for dd in", "how many rows and columns the plot will have. This", "analysis output files. Profiles from each will be plotted #", "= [45, 64] # Latitude bounds subplot_padding = 0.5 #", "import matplotlib.pyplot as plt import numpy as np import sys", "5 name_of_count_variable = \"grid_N\" # Subplot axes settings n_r =", "# Variable name in analysis file to plot # If", "script will plot the provided list of netcdf datasets from", "season etc. save_plot = False # Masking out grid cells", "any fixed level) errors from a profile object with no", "# Labels and Titles fig_title = \"SST Errors\" # Whole", "the colormap or not extend_cbar = [] # Loop over", "if required if plot_seasons: ds = ds_list[0] var_ii = var_name", "a_flat = a.flatten() # Dicretize colormap maybe if discrete_cmap: cmap", "dataset for ii in range(n_ax): ur_index = np.unravel_index(ii, (n_r, n_c))", "title_fontweight = \"bold\" # Fontweight to use for title dataset_names", "# Loop over dataset for ii in range(n_ax): ur_index =", "gridded data # then this is where to select season", "\"min\" else: extend = \"neither\" cbar_ax = f.add_axes([(1 - fig_pad[2]", "You can define how many rows and columns the plot", "List of analysis output files. Profiles from each will be", "Names to use for labelling plots subtitle_fontsize = 11 #", "dataset subtitles subtitle_fontweight = \"normal\" # Fontweight for dataset subtitles", "extend_cbar: extend = \"both\" elif \"max\" in extend_cbar: extend =", "padding (left, top, right, bottom) # Leave some space on", "f.tight_layout(w_pad=subplot_padding, h_pad=subplot_padding) f.subplots_adjust(left=(fig_pad[0]), bottom=(fig_pad[1]), right=(1 - fig_pad[2]), top=(1 - fig_pad[3]))", "fontsize=subtitle_fontsize, fontweight=subtitle_fontweight) N_var = name_of_count_variable data = ds[var_ii].values count_var =", "# Dicretize colormap maybe if discrete_cmap: cmap = plt.cm.get_cmap(cmap, cmap_levels)", "fig_pad[2] * 0.15), 0.15, 0.025, 0.7]) f.colorbar(pc, cax=cbar_ax, extend=extend) #", "out grid cells that don't contain many points min_points_in_average =", "n_c # Create plot and flatten axis array f, a", "of netcdf datasets from left to right and top to", "= 11 # Fontsize for dataset subtitles subtitle_fontweight = \"normal\"", "bottom=(fig_pad[1]), right=(1 - fig_pad[2]), top=(1 - fig_pad[3])) # Handle colorbar", "extend_cbar and \"min\" in extend_cbar: extend = \"both\" elif \"max\"", "a profile object with no z_dim (vertical dimension). Provide an", "of the figure. \"\"\" import xarray as xr import matplotlib.pyplot", "to make gridded data # then this is where to", "many points min_points_in_average = 5 name_of_count_variable = \"grid_N\" # Subplot", "vertical and horizontal padding between plots fig_pad = (0.075, 0.075,", "Dicretize colormap maybe if discrete_cmap: cmap = plt.cm.get_cmap(cmap, cmap_levels) #", "no z_dim (vertical dimension). Provide an array of netcdf files", "extend_cbar: extend = \"both\" elif \"max\" in extend_cbar and \"min\"", "for dd in fn_list] n_ds = len(ds_list) n_ax = n_r", "figure you like. You can define how many rows and", "is where to select season etc. save_plot = False #", "cmap = plt.cm.get_cmap(cmap, cmap_levels) # Determine if we will extend", "# Latitude bounds subplot_padding = 0.5 # Amount of vertical", "Color limits for normal points discrete_cmap = True # Discretize", "and mess with the options to get a figure you", "import coast import pandas as pd #%% File settings run_name", "output fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General Plot Settings var_name =", "the plot fn_list = [ \"~/transfer/test_grid.nc\", \"~/transfer/test_grid.nc\", ] # Filename", "as xr import matplotlib.pyplot as plt import numpy as np", "Plot Settings var_name = \"abs_diff_temperature\" # Variable name in analysis", "n_c = 2 # Number of subplot columns figsize =", "np import sys sys.path.append(\"/Users/dbyrne/code/COAsT\") import coast import pandas as pd", "that don't contain many points min_points_in_average = 5 name_of_count_variable =", "fn_out = \"/Users/dbyrne/transfer/surface_gridded_errors_{0}.png\".format(run_name) #%% General Plot Settings var_name = \"abs_diff_temperature\"", "plotted, with seasonal # variables on each subplot. The season_suffixes", "elif \"max\" in extend_cbar and \"min\" in extend_cbar: extend =", "we will extend the colormap or not extend_cbar = []", "= 2 # Number of subplot columns figsize = (10,", "fig_title = \"SST Errors\" # Whole figure title title_fontsize =", "# then this is where to select season etc. save_plot", "netcdf files and mess with the options to get a", "(n_r, n_c)) # Select season if required if plot_seasons: ds", "Will we extend the colorbar for this dataset? extend_cbar.append(coast.plot_util.determine_colorbar_extension(data, clim[0],", "columns figsize = (10, 5) # Figure size lonbounds =", "13 # Fontsize of title title_fontweight = \"bold\" # Fontweight", "subplot rows n_c = 2 # Number of subplot columns", "# Read all datasets into list ds_list = [xr.open_dataset(dd) for", "fig_pad[2]), top=(1 - fig_pad[3])) # Handle colorbar -- will we", "else: extend = \"neither\" cbar_ax = f.add_axes([(1 - fig_pad[2] +", "#%% File settings run_name = \"test\" # List of analysis", "+ fig_pad[2] * 0.15), 0.15, 0.025, 0.7]) f.colorbar(pc, cax=cbar_ax, extend=extend)", "profile object with no z_dim (vertical dimension). Provide an array", "n_r, n_c, figsize=figsize) a_flat = a.flatten() # Dicretize colormap maybe", "the provided list of netcdf datasets from left to right", "plot_seasons: ds = ds_list[0] var_ii = var_name + \"_{0}\".format(season_suffixes[ii]) N_var", "settings n_r = 2 # Number of subplot rows n_c" ]
[ "= [ 'This is sample document.', 'another random document.', 'third", "is sample document.', 'another random document.', 'third sample document text'", "def compute_tf_idf(corpus): \"\"\"Computing term frequency (tf) - inverse document frequency", "(tf) - inverse document frequency (idf). :param corpus: List of", ":param corpus: List of documents. :returns: tf-idf of corpus. \"\"\"", "document.', 'another random document.', 'third sample document text' ] print(compute_tf_idf(sample_corpus))", "'__main__': sample_corpus = [ 'This is sample document.', 'another random", "if __name__ == '__main__': sample_corpus = [ 'This is sample", "return TfidfVectorizer().fit_transform(corpus) if __name__ == '__main__': sample_corpus = [ 'This", "__name__ == '__main__': sample_corpus = [ 'This is sample document.',", "term frequency (tf) - inverse document frequency (idf). :param corpus:", "TfidfVectorizer def compute_tf_idf(corpus): \"\"\"Computing term frequency (tf) - inverse document", "\"\"\"Computing term frequency (tf) - inverse document frequency (idf). :param", "compute_tf_idf(corpus): \"\"\"Computing term frequency (tf) - inverse document frequency (idf).", "\"\"\" return TfidfVectorizer().fit_transform(corpus) if __name__ == '__main__': sample_corpus = [", "documents. :returns: tf-idf of corpus. \"\"\" return TfidfVectorizer().fit_transform(corpus) if __name__", "- inverse document frequency (idf). :param corpus: List of documents.", "sklearn.feature_extraction.text import TfidfVectorizer def compute_tf_idf(corpus): \"\"\"Computing term frequency (tf) -", "corpus. \"\"\" return TfidfVectorizer().fit_transform(corpus) if __name__ == '__main__': sample_corpus =", "[ 'This is sample document.', 'another random document.', 'third sample", "from sklearn.feature_extraction.text import TfidfVectorizer def compute_tf_idf(corpus): \"\"\"Computing term frequency (tf)", "inverse document frequency (idf). :param corpus: List of documents. :returns:", "of documents. :returns: tf-idf of corpus. \"\"\" return TfidfVectorizer().fit_transform(corpus) if", "document frequency (idf). :param corpus: List of documents. :returns: tf-idf", "TfidfVectorizer().fit_transform(corpus) if __name__ == '__main__': sample_corpus = [ 'This is", "'This is sample document.', 'another random document.', 'third sample document", "== '__main__': sample_corpus = [ 'This is sample document.', 'another", "tf-idf of corpus. \"\"\" return TfidfVectorizer().fit_transform(corpus) if __name__ == '__main__':", "of corpus. \"\"\" return TfidfVectorizer().fit_transform(corpus) if __name__ == '__main__': sample_corpus", "sample_corpus = [ 'This is sample document.', 'another random document.',", "import TfidfVectorizer def compute_tf_idf(corpus): \"\"\"Computing term frequency (tf) - inverse", "List of documents. :returns: tf-idf of corpus. \"\"\" return TfidfVectorizer().fit_transform(corpus)", "frequency (idf). :param corpus: List of documents. :returns: tf-idf of", ":returns: tf-idf of corpus. \"\"\" return TfidfVectorizer().fit_transform(corpus) if __name__ ==", "sample document.', 'another random document.', 'third sample document text' ]", "(idf). :param corpus: List of documents. :returns: tf-idf of corpus.", "frequency (tf) - inverse document frequency (idf). :param corpus: List", "corpus: List of documents. :returns: tf-idf of corpus. \"\"\" return" ]
[ "message here.... # print \"Sending UDP msg to \", dest_elem", "for now are assumed to be separated by a newline.", "address # Read the data from the socket data =", "Later this will handle other things such as sequence files", "\"A5A5 \" or a \"List \" \"\"\" # Read the", "message to destination <name> is done as \"A5A5 <name> <data>\"", "self.recv(4) return header + header2 else: return def readData(self, header):", "comment makes the server display all registered clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address", "# Process and send the packet of the message here...", "is done by sending the string \"Register <name>\". Sending a", "SocketServer as socketserver import time import os import signal import", "\"\\n\") sys.stderr.write(indent + \" for help use --help\\n\") return 2", "print(\"Socket error \" + str(err.errno) + \" occurred on recv().\")", "clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address = True def handle(self): # on each", "of the message here... data = self.readData(header, packet) # Process", "0.1 __date__ = \"2015-04-03\" __updated__ = \"2016-04-07\" # Universal server", "A5A5 header\") class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\" TCP Socket server. Keep", "GUI_ids = [] def signal_handler(*_): print(\"Ctrl-C received, server shutting down.\")", "from partial or full socket input \"\"\" commands = inputString.split(end_of_command)", "all clients registered. \"\"\" def __init__(self, name, request): \"\"\" Constructor", "if not header: break elif header == b\"Quit\": LOCK.acquire() print(\"Quit", "OptionParser __version__ = 0.1 __date__ = \"2015-04-03\" __updated__ = \"2016-04-07\"", "the packet of the message here... self.processNewPkt(header, data) def recv(self,", "Read the header data from the socket either A5A5 or", "that sends a \"List\" comment makes the server display all", "dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Packet missing A5A5 header\") class", "Routines to process the command messages ################################################# def getNewMsg(self, packet):", "= commands[-1] self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1]) def processQueue(self): for cmd in", "the \"List\\n\" command. \"\"\" header = packet[:4] header2 = packet[4:9]", "Read the 9 byte header (e.g. \"A5A5 GUI \" or", "missing A5A5 header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived from original Stable", "size = struct.unpack(\">I\", sizeb)[0] data = desc + sizeb +", "\"List\\n\" command. \"\"\" header = self.recv(5) if len(header) == 0:", "# New Routines to process the command messages ################################################# def", "if header == b\"List\": print(\"List of registered clients: \") LOCK.acquire()", "%s...\\n\" % (head,dst) if data == \"\": print(\" Data is", "as err: print(\"Socket error \" + str(err.errno) + \" occurred", "header: return # Got the header data so read the", "= [] FSW_ids = [] GUI_ids = [] def signal_handler(*_):", "\"%s\" % __updated__ program_version_string = \"%%prog %s (%s)\" % (program_version,", "= len(reg_client_str) reg_client_str = struct.pack(\"i%ds\" % l, l, reg_client_str) self.request.send(reg_client_str)", "LOCK = server.lock_obj ip, port = server.server_address print(\"TCP Socket Server", "to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Packet missing A5A5", "+ self.name.decode(DATA_ENCODING)) ################################################# # New Routines to process the command", "\" occurred on recv().\") return msg def readHeader(self): \"\"\" Read", "the command messages ################################################# def getNewMsg(self): \"\"\" After registration wait", "\"\"\" After registration wait for an incoming message The first", "\", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Telemetry missing A5A5 header\")", "comment makes the server display all registered clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address", "type=\"int\", help=\"Set threaded tcp socket server port [default: %default]\", default=50007,", "= msg + chunk n = len(msg) except socket.timeout: if", "<name>\". Sending a message to destination <name> is done as", "as e: indent = len(program_name) * \" \" sys.stderr.write(program_name +", "A5A5 or List (header, packet) = self.readHeader(packet) # If the", "here. The command must always start with A5A5 except if", "self.name self.socket.send(msg) except socket.error as err: print(\"Socket error \" +", "each client. Registration is done by sending the string \"Register", "with the server -- that thread will then start one", "data) def readHeader(self, packet): \"\"\" Read the 9 byte header", "this will handle other things such as sequence files and", "return LOCK.acquire() del SERVER.dest_obj[self.name] if self.name in FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id)", "default=\"127.0.0.1\", ) # process options (opts, args) = parser.parse_args(argv) HOST", "None LOCK = None shutdown_event = threading.Event() FSW_clients = []", "demo during R&TD and adapted for use in new FSW", "= FSW_clients for dest_elem in dest_list: # print \"Locking TCP\"", "in GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release() print(\"Closed %s connection.\" % self.name.decode(DATA_ENCODING))", "Destination object for all clients registered. \"\"\" def __init__(self, name,", "data here... tlm_packet_size = packet[:4] size = struct.unpack(\">I\", tlm_packet_size)[0] data", "= server.server_address print(\"TCP Socket Server listening on host addr %s,", "(header, packet) = self.readHeader(packet) # If the received header is", "errno from fprime.constants import DATA_ENCODING from optparse import OptionParser __version__", "params[1] + b\"_\" + bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name] = DestObj(name,", "shutdown_event.set() time.sleep(1) print(\"Quit processed!\") SERVER.shutdown() SERVER.server_close() LOCK.release() break # Got", "LOCK.acquire() for d in list(SERVER.dest_obj.keys()): print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str =", "msg def readHeader(self): \"\"\" Read the 9 byte header (e.g.", "telemetry data. Later this will handle other things such as", "header.strip(b\" \").split(b\" \") if head == b\"A5A5\": # Packet Header", "class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\" UDP Socket server. \"\"\" class DestObj:", "== b\"Quit\": LOCK.acquire() print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set() time.sleep(1) print(\"Quit", "socketserver.StreamRequestHandler.allow_reuse_address = True socketserver.StreamRequestHandler.timeout = 1 def handle(self): # on", "the \"List\\n\" command. \"\"\" header = self.recv(5) if len(header) ==", "the message here... data = self.readData(header, packet) # Process and", "= sys.argv[1:] try: parser = OptionParser( version=program_version_string, epilog=program_longdesc, description=program_license, )", "def __init__(self, name, request): \"\"\" Constructor \"\"\" self.name = name", "tlm_packet_size)[0] data = tlm_packet_size + self.recv(size) else: raise RuntimeError(\"unrecognized client", "command from partial or full socket input \"\"\" commands =", "global SERVER = None LOCK = None shutdown_event = threading.Event()", "d in list(SERVER.dest_obj.keys()): print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str = b\"List \"", "to process the command messages ################################################# def getNewMsg(self, packet): \"\"\"", "here... data = self.readData(header, packet) # Process and send the", "return b\"List\" elif header == b\"Quit\\n\": return b\"Quit\" elif header[:-1]", "[] if header == b\"List\": print(\"List of registered clients: \")", "l, l, reg_client_str) self.request.send(reg_client_str) LOCK.release() return 0 # Process data", "# If the received header is an empty string, connection", "def readData(self, header, packet): \"\"\" Read the data part of", "For each packet, call processPkt. \"\"\" self.partial = b\"\" self.cmdQueue", "= len(msg) except socket.timeout: if shutdown_event.is_set(): print(\"socket timed out and", "commands of various lengths. \"\"\" data = \"\" dst =", "SERVER.server_close() udp_server.shutdown() udp_server.server_close() time.sleep(1) except Exception as e: indent =", "data == \"\": print(\" Data is empty, returning.\") if b\"GUI\"", "self.name = name self.id = process_id print(\"Registered client \" +", "empty, returning.\") if b\"GUI\" in dst: dest_list = GUI_clients else:", "is empty, returning.\") if b\"GUI\" in dst: dest_list = GUI_clients", "# Read variable length command data here... desc = self.recv(4)", "message here.... # print \"Sending TCP msg to \", dest_elem", "readHeader(self, packet): \"\"\" Read the 9 byte header (e.g. \"A5A5", "if self.registered: print(\"Registration complete waiting for message.\") self.getNewMsg() else: print(\"Unable", "PORT), ThreadedUDPRequestHandler) # Hopefully this will allow address reuse and", "time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived from original Stable demo during", "parser = OptionParser( version=program_version_string, epilog=program_longdesc, description=program_license, ) parser.add_option( \"-p\", \"--port\",", "= \"2015-04-03\" __updated__ = \"2016-04-07\" # Universal server id global", "If the received header is an empty string, connection closed,", "data = desc + sizeb + self.recv(size) elif dst ==", "packet): \"\"\" After registration wait for an incoming message The", "clients: \") LOCK.acquire() for d in list(SERVER.dest_obj.keys()): print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING))", "header2 = packet[4:9] packet = packet[9:] return (header + header2,", "Read variable length command data here... desc = self.recv(4) sizeb", "b\"\": print(\"read data from socket is empty!\") return b\"\" msg", "tlm_packet_size = packet[:4] size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size", "returning.\") if b\"GUI\" in dst: dest_list = GUI_clients elif b\"FSW\"", "if head == b\"A5A5\": # Packet Header # print \"Received", "server to restart immediately server.allow_reuse_address = True SERVER = server", "print(\"List of registered clients: \") LOCK.acquire() for d in list(SERVER.dest_obj.keys()):", "= threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler) server_thread.daemon = False server_thread.start() udp_server_thread.daemon =", "sequence files and parameters. Handle is instanced in own thread", "FSW_ids = [] GUI_ids = [] def signal_handler(*_): print(\"Ctrl-C received,", "LOCK.release() else: raise RuntimeError(\"Packet missing A5A5 header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\"", "sys.stderr.write(indent + \" for help use --help\\n\") return 2 if", "################################################# def getNewMsg(self): \"\"\" After registration wait for an incoming", "call processPkt. \"\"\" self.getNewMsg(self.request[0]) ################################################# # New Routines to process", "print \"Locking TCP\" LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): # Send", "\"%%prog %s (%s)\" % (program_version, program_build_date) program_longdesc = ( \"\"\"\"\"\"", "# Process data here... head, dst = header.strip(b\" \").split(b\" \")", "elif header == b\"Quit\": LOCK.acquire() print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set()", "def fileno(self): \"\"\" \"\"\" return self.socket def main(argv=None): global SERVER,", "start with A5A5 except if it is a List. Once", "b\"Quit\": LOCK.acquire() print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set() time.sleep(1) print(\"Quit processed!\")", "n: try: chunk = self.request.recv(l - n) if chunk ==", "socketserver.StreamRequestHandler.timeout = 1 def handle(self): # on each client connect", "while the connected client has packets to send/receive while not", "dst = header.strip(b\" \").split(b\" \") if head == b\"A5A5\": #", "object for all clients registered. \"\"\" def __init__(self, name, request):", "elif self.name in GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release() print(\"Closed %s connection.\"", "\" or a \"List \" \"\"\" # Loop while the", "self.registered = True self.name = name self.id = process_id print(\"Registered", "client %s\" % dst.decode(DATA_ENCODING)) return data def processNewPkt(self, header, data):", "command here header and data here. The command must always", "For each packet, call processPkt. \"\"\" self.getNewMsg(self.request[0]) ################################################# # New", "wrong report and shutdown server. \"\"\" dest_list = [] #", "import sys import struct import errno from fprime.constants import DATA_ENCODING", "reg_client_str = struct.pack(\"i%ds\" % l, l, reg_client_str) self.request.send(reg_client_str) LOCK.release() return", "newline. For each packet, call processPkt. \"\"\" self.getNewMsg(self.request[0]) ################################################# #", "print(\"Ctrl-C received, server shutting down.\") shutdown_event.set() def now(): return time.ctime(time.time())", "(head,dst) if data == \"\": print(\" Data is empty, returning.\")", "= threading.Thread(target=server.serve_forever) udp_server_thread = threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler) server_thread.daemon = False", "= ( \"\"\"\"\"\" # optional - give further explanation about", "b\"_\" + bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id) elif b\"GUI\" in name: if", "else: return def readData(self, header): \"\"\" Read the data part", "sizeb = self.recv(4) size = struct.unpack(\">I\", sizeb)[0] data = desc", "self.cmdQueue = [] def processRegistration(self, cmd): params = cmd.split() process_id", "\"), or just read the \"List\\n\" command. \"\"\" header =", "reg_client_str) self.request.send(reg_client_str) LOCK.release() return 0 # Process data here... head,", "Derived from original Stable demo during R&TD and adapted for", "+ SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str = b\"List \" + SERVER.dest_obj[d].name l =", "argv is None: argv = sys.argv[1:] try: parser = OptionParser(", "such as sequence files and parameters. Handle is instanced in", "os import signal import sys import struct import errno from", "self.id = process_id print(\"Registered client \" + self.name.decode(DATA_ENCODING)) ################################################# #", "user_name (California Institute of Technology) \\ ALL RIGHTS RESERVED. U.S.", "sending the string \"Register <name>\". Sending a message to destination", "# Connection was closed by the client if not data:", "################################################# def getNewMsg(self, packet): \"\"\" After registration wait for an", "not header: break elif header == b\"Quit\": LOCK.acquire() print(\"Quit received!\")", "\"List\\n\" command. \"\"\" header = packet[:4] header2 = packet[4:9] packet", "chunk n = len(msg) except socket.timeout: if shutdown_event.is_set(): print(\"socket timed", "FSW receives commands of various lengths. \"\"\" data = b\"\"", "dest_list = [] # Process data here... head, dst =", "SERVER.dest_obj[self.name] if self.name in FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif self.name in", "server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown from main thread\") SERVER.shutdown() SERVER.server_close() udp_server.shutdown() udp_server.server_close()", "% l, l, reg_client_str) self.request.send(reg_client_str) LOCK.release() return 0 # Process", "not header: return # Got the header data so read", "class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\" TCP Socket server. Keep a dictionary", "\").split(b\" \") if head == b\"A5A5\": # Packet Header #", "= tlm_packet_size + packet[4 : 4 + size] return data", "- n) if chunk == b\"\": print(\"read data from socket", "self.name in FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif self.name in GUI_clients: GUI_clients.remove(self.name)", "read the \"List\\n\" command. \"\"\" header = packet[:4] header2 =", "\")[1].strip(b\" \") # Read telemetry data here... tlm_packet_size = packet[:4]", "import struct import errno from fprime.constants import DATA_ENCODING from optparse", "packet of the message here... self.processNewPkt(header, data) def readHeader(self, packet):", "\"\"\" try: # print \"about to send data to \"", "data = self.readData(header, packet) # Process and send the packet", "self.cmdQueue: self.processRegistration(cmd) self.cmdQueue = [] def processRegistration(self, cmd): params =", "about what the program does ) if argv is None:", "adapted for use in new FSW gse.py applicaiton. TCP socket", "Process data here... head, dst = header.strip(b\" \").split(b\" \") if", "if shutdown_event.is_set(): print(\"socket timed out and shutdown is requested\") return", "data into the cmdQueue self.getCmds(data) # Process the cmdQueue self.processQueue()", "+ repr(e) + \"\\n\") sys.stderr.write(indent + \" for help use", "if b\"FSW\" in name: if FSW_clients: process_id = sorted(FSW_ids)[-1] +", "help=\"Set threaded tcp socket server port [default: %default]\", default=50007, )", "tstring is processed send it on queue. If something goes", "\"A5A5 <name> <data>\" Note only <data> is sent. Any client", "processed!\") SERVER.shutdown() SERVER.server_close() LOCK.release() break # Got the header data", "dest_list = GUI_clients elif b\"FSW\" in dst: dest_list = FSW_clients", "return b\"Quit\\n\" continue except socket.error as err: if err.errno ==", "packet) = self.readHeader(packet) # If the received header is an", "__updated__ program_version_string = \"%%prog %s (%s)\" % (program_version, program_build_date) program_longdesc", "error \" + str(err.errno) + \" occurred on recv().\") return", "socket \"\"\" try: # print \"about to send data to", "recv(self, l): \"\"\" Read l bytes from socket. \"\"\" chunk", "by the client if not data: print(\"Client exited.\") return else:", "goes wrong report and shutdown server. \"\"\" dest_list = []", "len(self.partial): commands[0] = self.partial + commands[0] self.partial = b\"\" if", "FSW receives commands of various lengths. \"\"\" data = \"\"", "recv().\" ) else: print(\"Socket error \" + str(err.errno) + \"", "if header == b\"List\\n\": return b\"List\" elif header == b\"Quit\\n\":", "commands, log events, and telemetry data. Later this will handle", "0 if params[0] == b\"Register\": LOCK.acquire() name = params[1] if", "b\"\" msg = b\"\" n = 0 while l >", "SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Telemetry missing A5A5 header\") class ThreadedTCPServer(socketserver.ThreadingMixIn,", "dst.decode(DATA_ENCODING)) for dest_elem in dest_list: LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()):", "FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif self.name in GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release()", "of various lengths. \"\"\" data = b\"\" if header ==", "entire header tstring is processed send it on queue. If", "each packet, call processPkt. \"\"\" self.getNewMsg(self.request[0]) ################################################# # New Routines", "here... self.processNewPkt(header, data) def readHeader(self, packet): \"\"\" Read the 9", "addr %s, port %s\" % (HOST, PORT)) # Start a", "\"\"\"\"\"\" # optional - give further explanation about what the", "= True def handle(self): # on each packet \"\"\" The", "description=program_license, ) parser.add_option( \"-p\", \"--port\", dest=\"port\", action=\"store\", type=\"int\", help=\"Set threaded", "\"\"\" Constructor \"\"\" self.name = name self.socket = request self.packet", "of various lengths. \"\"\" data = \"\" dst = header.split(b\"", "main(argv=None): global SERVER, LOCK program_name = os.path.basename(sys.argv[0]) program_license = \"Copyright", "[] # Process data here... head, dst = header.strip(b\" \").split(b\"", "RuntimeError(\"Telemetry missing A5A5 header\") class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\" TCP Socket", "\" + str(err.errno) + \" occurred on send().\") def fileno(self):", "server -- that thread will then start one # more", "start one # more thread for each request server_thread =", "has packets to send/receive while not shutdown_event.is_set(): # Read the", "b\"_\" + bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name] = DestObj(name, self.request) LOCK.release()", "Packet: %s %s...\\n\" % (head,dst) if data == b\"\": print(\"", "the message here... data = self.readData(header) # Process and send", "\"\"\" data = \"\" dst = header.split(b\" \")[1].strip(b\" \") #", "as sequence files and parameters. Handle is instanced in own", "0: print( \"Header information is empty, client \" + self.name.decode(DATA_ENCODING)", "data so read the data of the message here... data", "for writting to destinations. \"\"\" dest_obj = dict() lock_obj =", "packet of the message here... self.processNewPkt(header, data) def recv(self, l):", "raise RuntimeError(\"Packet missing A5A5 header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived from", "b\"A5A5\": header2 = self.recv(4) return header + header2 else: return", "= True socketserver.StreamRequestHandler.timeout = 1 def handle(self): # on each", "(HOST, PORT)) # Start a thread with the server --", "print_function import socket import threading try: import socketserver except ImportError:", "from main thread\") SERVER.shutdown() SERVER.server_close() udp_server.shutdown() udp_server.server_close() time.sleep(1) except Exception", "\"\"\" header = packet[:4] header2 = packet[4:9] packet = packet[9:]", "+ self.name.decode(DATA_ENCODING) + \" exiting.\" ) return header if header", "\"\"\" def __init__(self, name, request): \"\"\" Constructor \"\"\" self.name =", "return b\"\" dst = header.split(b\" \")[1].strip(b\" \") if dst ==", "# show this client's address # Read the data from", "print(\"socket timed out and shutdown is requested\") return b\"Quit\\n\" continue", "string, connection closed, exit loop if not header: return #", "socket server for commands, log events, and telemetry data. Later", "except ImportError: import SocketServer as socketserver import time import os", "return # Got the header data so read the data", "RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.\" program_version = \"v0.1\" program_build_date", "here.... # print \"Sending TCP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data)", "= \"2016-04-07\" # Universal server id global SERVER = None", "len(reg_client_str) reg_client_str = struct.pack(\"i%ds\" % l, l, reg_client_str) self.request.send(reg_client_str) LOCK.release()", "+ packet[4 : 4 + size] return data def processNewPkt(self,", "client's address # Read the data from the socket data", "time import os import signal import sys import struct import", "\" for help use --help\\n\") return 2 if __name__ ==", "+ \": \" + repr(e) + \"\\n\") sys.stderr.write(indent + \"", "%s...\\n\" % (head,dst) if data == b\"\": print(\" Data is", "class DestObj: \"\"\" Destination object for all clients registered. \"\"\"", "self.name in GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release() print(\"Closed %s connection.\" %", "SERVER.server_close() LOCK.release() break # Got the header data so read", "% (head,dst) if data == b\"\": print(\" Data is empty,", "for help use --help\\n\") return 2 if __name__ == \"__main__\":", "Start a thread with the server -- that thread will", "self.getCmds(data) # Process the cmdQueue self.processQueue() if self.registered: print(\"Registration complete", "= self.readData(header) # Process and send the packet of the", "\"\"\" # Read the header data from the socket either", "self.request.close() def getCmds(self, inputString, end_of_command=b\"\\n\"): \"\"\" Build a command from", "except if it is a List. Once the entire header", "socket. \"\"\" chunk = b\"\" msg = b\"\" n =", "sends a \"List\" comment makes the server display all registered", "tlm_packet_size)[0] data = tlm_packet_size + packet[4 : 4 + size]", "send().\") def fileno(self): \"\"\" \"\"\" return self.socket def main(argv=None): global", "Socket server. \"\"\" class DestObj: \"\"\" Destination object for all", "<name> <data>\" Note only <data> is sent. Any client that", "l = len(reg_client_str) reg_client_str = struct.pack(\"i%ds\" % l, l, reg_client_str)", "struct.unpack(\">I\", sizeb)[0] data = desc + sizeb + self.recv(size) elif", "on queue. If something goes wrong report and shutdown server.", "== b\"A5A5\": header2 = self.recv(4) return header + header2 else:", "that is invoked when a packet is received. This function", "if err.errno == errno.ECONNRESET: print( \"Socket error \" + str(err.errno)", "data to \" + self.name self.socket.send(msg) except socket.error as err:", "Header # print \"Received Packet: %s %s...\\n\" % (head,dst) if", "import OptionParser __version__ = 0.1 __date__ = \"2015-04-03\" __updated__ =", "print(\"Unable to register client.\") return LOCK.acquire() del SERVER.dest_obj[self.name] if self.name", "DestObj(name, self.request) LOCK.release() self.registered = True self.name = name self.id", "def getCmds(self, inputString, end_of_command=b\"\\n\"): \"\"\" Build a command from partial", "\" \"\"\" # Loop while the connected client has packets", "self.recv(13) # Connection was closed by the client if not", "the data from the socket data = self.recv(13) # Connection", "program_build_date = \"%s\" % __updated__ program_version_string = \"%%prog %s (%s)\"", "\"\"\" socketserver.StreamRequestHandler.allow_reuse_address = True socketserver.StreamRequestHandler.timeout = 1 def handle(self): #", "from the socket either A5A5 or List (header, packet) =", "= False server_thread.start() udp_server_thread.daemon = False udp_server_thread.start() while not shutdown_event.is_set():", "commands[0] = self.partial + commands[0] self.partial = b\"\" if len(commands[-1]):", "length command data here... desc = self.recv(4) sizeb = self.recv(4)", "dest=\"port\", action=\"store\", type=\"int\", help=\"Set threaded tcp socket server port [default:", "Note only <data> is sent. Any client that sends a", "%s (%s)\" % (program_version, program_build_date) program_longdesc = ( \"\"\"\"\"\" #", "for commands, log events, and telemetry data. Later this will", "thread for each request server_thread = threading.Thread(target=server.serve_forever) udp_server_thread = threading.Thread(target=udp_server.serve_forever)", "send/receive while not shutdown_event.is_set(): # Read the header data from", "except socket.timeout: if shutdown_event.is_set(): print(\"socket timed out and shutdown is", "print(\"Socket error \" + str(err.errno) + \" occurred on send().\")", "Packets for now are assumed to be separated by a", "= b\"\" self.id = 0 # print self.client_address, now() #", "\"\"\" The function that is invoked when a packet is", "or \"A5A5 FSW \"), or just read the \"List\\n\" command.", "action=\"store\", type=\"string\", help=\"Set threaded tcp socket server ip [default: %default]\",", "return msg def readHeader(self): \"\"\" Read the 9 byte header", "opts.port server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) udp_server = ThreadedUDPServer((HOST, PORT),", "by a newline. For each packet, call processPkt. \"\"\" self.getNewMsg(self.request[0])", "complete waiting for message.\") self.getNewMsg() else: print(\"Unable to register client.\")", "name = params[1] + b\"_\" + bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id) elif", "= self.recv(4) size = struct.unpack(\">I\", sizeb)[0] data = desc +", "False udp_server_thread.start() while not shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown from main", "header: break elif header == b\"Quit\": LOCK.acquire() print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\",", "\"\"\" return self.socket def main(argv=None): global SERVER, LOCK program_name =", "+ self.name self.socket.send(msg) except socket.error as err: print(\"Socket error \"", "data def processNewPkt(self, header, data): \"\"\" Process a single command", "and shutdown server. \"\"\" dest_list = [] if header ==", "header == b\"Quit\\n\": return b\"Quit\" elif header[:-1] == b\"A5A5\": header2", "options (opts, args) = parser.parse_args(argv) HOST = opts.host PORT =", "header[:-1] == b\"A5A5\": header2 = self.recv(4) return header + header2", "Technology) \\ ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.\" program_version", "Process the cmdQueue self.processQueue() if self.registered: print(\"Registration complete waiting for", "if argv is None: argv = sys.argv[1:] try: parser =", "in list(SERVER.dest_obj.keys()): # Send the message here.... # print \"Sending", "b\"List\": return b\"\" elif header == b\"Quit\": return b\"\" dst", "FSW \"), or just read the \"List\\n\" command. \"\"\" header", "thread for each client. Registration is done by sending the", "# print \"Sending UDP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release()", "\"Sending UDP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise", "for data on the socket. Packets for now are assumed", "client.\") return LOCK.acquire() del SERVER.dest_obj[self.name] if self.name in FSW_clients: FSW_clients.remove(self.name)", "n = len(msg) except socket.timeout: if shutdown_event.is_set(): print(\"socket timed out", "b\"FSW\": # Read variable length command data here... desc =", "\" exiting.\" ) return header if header == b\"List\\n\": return", "the program does ) if argv is None: argv =", "for an incoming message The first part must always be", "end_of_command=b\"\\n\"): \"\"\" Build a command from partial or full socket", "# on each client connect \"\"\" The function that is", "Registration is done by sending the string \"Register <name>\". Sending", "and shutdown server. \"\"\" dest_list = [] # Process data", "handle(self): # on each packet \"\"\" The function that is", "import signal import sys import struct import errno from fprime.constants", "+ str(err.errno) + \" occurred on recv().\") return msg def", "during R&TD and adapted for use in new FSW gse.py", "LOCK program_name = os.path.basename(sys.argv[0]) program_license = \"Copyright 2015 user_name (California", "global SERVER, LOCK program_name = os.path.basename(sys.argv[0]) program_license = \"Copyright 2015", "+ bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id) elif b\"GUI\" in name: if GUI_clients:", "head, dst = header.strip(b\" \").split(b\" \") if head == b\"A5A5\":", "the connected client has packets to send/receive while not shutdown_event.is_set():", "\"Header information is empty, client \" + self.name.decode(DATA_ENCODING) + \"", "\" + str(err.errno) + \" (Connection reset by peer) occurred", "else: print(\"Unable to register client.\") return LOCK.acquire() del SERVER.dest_obj[self.name] if", "\"\"\" dest_obj = dict() lock_obj = threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):", "parser.parse_args(argv) HOST = opts.host PORT = opts.port server = ThreadedTCPServer((HOST,", "down.\") shutdown_event.set() def now(): return time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived", "print \"Sending UDP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else:", "missing A5A5 header\") class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\" TCP Socket server.", "acknowledged.\" program_version = \"v0.1\" program_build_date = \"%s\" % __updated__ program_version_string", "is received. This function listens for data on the socket.", "socket is empty!\") return b\"\" msg = msg + chunk", "def main(argv=None): global SERVER, LOCK program_name = os.path.basename(sys.argv[0]) program_license =", "If something goes wrong report and shutdown server. \"\"\" dest_list", "shutdown_event.is_set(): print(\"socket timed out and shutdown is requested\") return b\"Quit\\n\"", "return b\"\" elif header == b\"Quit\": return b\"\" dst =", "destination <name> is done as \"A5A5 <name> <data>\" Note only", "List (header, packet) = self.readHeader(packet) # If the received header", "socketserver.TCPServer): \"\"\" TCP Socket server. Keep a dictionary of destination", "the data into the cmdQueue self.getCmds(data) # Process the cmdQueue", "ImportError: import SocketServer as socketserver import time import os import", "\"\"\" Read l bytes from socket. \"\"\" chunk = b\"\"", "handle(self): # on each client connect \"\"\" The function that", "ThreadedUDPRequestHandler) # Hopefully this will allow address reuse and server", "data): \"\"\" Process a single command here header and data", "self.processNewPkt(header, data) def recv(self, l): \"\"\" Read l bytes from", "received. This function listens for data on the socket. Packets", "+ header2, packet) def readData(self, header, packet): \"\"\" Read the", "print \"about to send data to \" + self.name self.socket.send(msg)", "\"\"\" # Loop while the connected client has packets to", "socket either A5A5 or List (header, packet) = self.readHeader(packet) #", "commands[-1] self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1]) def processQueue(self): for cmd in self.cmdQueue:", "sys import struct import errno from fprime.constants import DATA_ENCODING from", "gse.py applicaiton. TCP socket server for commands, log events, and", "\"\"\" dest_list = [] # Process data here... head, dst", "DestObj: \"\"\" Destination object for all clients registered. \"\"\" def", "in dest_list: LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): # Send the", "List. Once the entire header tstring is processed send it", "data == b\"\": print(\" Data is empty, returning.\") if b\"GUI\"", "tcp socket server port [default: %default]\", default=50007, ) parser.add_option( \"-i\",", "each packet \"\"\" The function that is invoked when a", "header): \"\"\" Read the data part of the message sent", "of the message here... self.processNewPkt(header, data) def recv(self, l): \"\"\"", "here.... # print \"Sending UDP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data)", "LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): # Send the message here....", "log events, and telemetry data. Later this will handle other", "= params[1] + b\"_\" + bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name] =", "import print_function import socket import threading try: import socketserver except", "data from socket is empty!\") return b\"\" msg = msg", "LOCK.release() return 0 # Process data here... head, dst =", "len(program_name) * \" \" sys.stderr.write(program_name + \": \" + repr(e)", "will allow address reuse and server to restart immediately server.allow_reuse_address", "or a \"List \" \"\"\" # Loop while the connected", "either GUI or FSW. GUI receives telemetry. FSW receives commands", "\"Copyright 2015 user_name (California Institute of Technology) \\ ALL RIGHTS", "self.recv(4) size = struct.unpack(\">I\", sizeb)[0] data = desc + sizeb", "now(): return time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived from original Stable", "fileno(self): \"\"\" \"\"\" return self.socket def main(argv=None): global SERVER, LOCK", "getCmds(self, inputString, end_of_command=b\"\\n\"): \"\"\" Build a command from partial or", "restart immediately server.allow_reuse_address = True SERVER = server LOCK =", "commands[0] self.partial = b\"\" if len(commands[-1]): self.partial = commands[-1] self.cmdQueue.extend(commands[:-1])", "Send the message here.... # print \"Sending TCP msg to", "shutdown server. \"\"\" dest_list = [] if header == b\"List\":", "elif header[:-1] == b\"A5A5\": header2 = self.recv(4) return header +", "= True self.name = name self.id = process_id print(\"Registered client", "= True SERVER = server LOCK = server.lock_obj ip, port", "+ b\"_\" + bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id) elif b\"GUI\" in name:", "data = self.readData(header) # Process and send the packet of", "queue. If something goes wrong report and shutdown server. \"\"\"", "empty!\") return b\"\" msg = msg + chunk n =", "\" or \"A5A5 FSW \"), or just read the \"List\\n\"", "is sent. Any client that sends a \"List\" comment makes", "data: print(\"Client exited.\") return else: # Process the data into", "FSW_clients: process_id = sorted(FSW_ids)[-1] + 1 name = params[1] +", "and server to restart immediately server.allow_reuse_address = True SERVER =", "= header.strip(b\" \").split(b\" \") if head == b\"A5A5\": # Packet", "host addr %s, port %s\" % (HOST, PORT)) # Start", "Read l bytes from socket. \"\"\" chunk = b\"\" msg", "new client. This function listens for data on the socket.", "bytes from socket. \"\"\" chunk = b\"\" msg = b\"\"", "= header.split(b\" \")[1].strip(b\" \") if dst == b\"FSW\": # Read", "msg = b\"\" n = 0 while l > n:", "== errno.ECONNRESET: print( \"Socket error \" + str(err.errno) + \"", "shutting down.\") shutdown_event.set() def now(): return time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\"", "name: if GUI_clients: process_id = sorted(GUI_ids)[-1] + 1 name =", "thread\") SERVER.shutdown() SERVER.server_close() udp_server.shutdown() udp_server.server_close() time.sleep(1) except Exception as e:", "Once the entire header tstring is processed send it on", "the socket either A5A5 or List header = self.readHeader() #", "optparse import OptionParser __version__ = 0.1 __date__ = \"2015-04-03\" __updated__", "= self.readHeader(packet) # If the received header is an empty", "server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) udp_server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler)", "program does ) if argv is None: argv = sys.argv[1:]", "received, server shutting down.\") shutdown_event.set() def now(): return time.ctime(time.time()) class", "\"-p\", \"--port\", dest=\"port\", action=\"store\", type=\"int\", help=\"Set threaded tcp socket server", "is requested\") return b\"Quit\\n\" continue except socket.error as err: if", "print \"Sending TCP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else:", "msg = msg + chunk n = len(msg) except socket.timeout:", "dest_elem in dest_list: LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): # Send", "function that is invoked when a packet is received. This", "= inputString.split(end_of_command) if len(self.partial): commands[0] = self.partial + commands[0] self.partial", "for each request server_thread = threading.Thread(target=server.serve_forever) udp_server_thread = threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT,", "shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown from main thread\") SERVER.shutdown() SERVER.server_close() udp_server.shutdown()", "done as \"A5A5 <name> <data>\" Note only <data> is sent.", "\", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Packet missing A5A5 header\")", "U.S. Government Sponsorship acknowledged.\" program_version = \"v0.1\" program_build_date = \"%s\"", "server display all registered clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address = True def", "self.client_address, now() # show this client's address # Read the", "= [] GUI_ids = [] def signal_handler(*_): print(\"Ctrl-C received, server", "################################################# # New Routines to process the command messages #################################################", "b\"Quit\\n\" continue except socket.error as err: if err.errno == errno.ECONNRESET:", "data here... desc = self.recv(4) sizeb = self.recv(4) size =", "msg): \"\"\" Write out the message to the destination socket", "return else: # Process the data into the cmdQueue self.getCmds(data)", "PORT), ThreadedTCPRequestHandler) udp_server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) # Hopefully this", "udp_server_thread.start() while not shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown from main thread\")", "of the message here... self.processNewPkt(header, data) def readHeader(self, packet): \"\"\"", "if header == b\"List\": return b\"\" elif header == b\"Quit\":", "socket server port [default: %default]\", default=50007, ) parser.add_option( \"-i\", \"--host\",", "FSW_clients = [] GUI_clients = [] FSW_ids = [] GUI_ids", "the string \"Register <name>\". Sending a message to destination <name>", "dst = header.split(b\" \")[1].strip(b\" \") if dst == b\"FSW\": #", "packet[:4] size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + packet[4", "send data to \" + self.name self.socket.send(msg) except socket.error as", "the socket data = self.recv(13) # Connection was closed by", "receives commands of various lengths. \"\"\" data = b\"\" if", "help=\"Set threaded tcp socket server ip [default: %default]\", default=\"127.0.0.1\", )", "exited.\") return else: # Process the data into the cmdQueue", "bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name] = DestObj(name, self.request) LOCK.release() self.registered =", "A5A5 except if it is a List. Once the entire", "makes the server display all registered clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address =", "b\"\" elif header == b\"Quit\": return b\"\" dst = header.split(b\"", "objects containing queues and socket id's for writting to destinations.", "of the message here... data = self.readData(header) # Process and", "+ \" occurred on recv().\") return msg def readHeader(self): \"\"\"", "break elif header == b\"Quit\": LOCK.acquire() print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5))", "% dst.decode(DATA_ENCODING)) for dest_elem in dest_list: LOCK.acquire() if dest_elem in", "# Hopefully this will allow address reuse and server to", "here header and data here. The command must always start", "when a packet is received. This function listens for data", "argv = sys.argv[1:] try: parser = OptionParser( version=program_version_string, epilog=program_longdesc, description=program_license,", "reuse and server to restart immediately server.allow_reuse_address = True SERVER", "so read the data of the message here... data =", "OptionParser( version=program_version_string, epilog=program_longdesc, description=program_license, ) parser.add_option( \"-p\", \"--port\", dest=\"port\", action=\"store\",", "packet) # Process and send the packet of the message", "== b\"\": print(\" Data is empty, returning.\") if b\"GUI\" in", "b\"GUI\" in dst: dest_list = GUI_clients elif b\"FSW\" in dst:", "program_build_date) program_longdesc = ( \"\"\"\"\"\" # optional - give further", "for dest_elem in dest_list: # print \"Locking TCP\" LOCK.acquire() if", "Institute of Technology) \\ ALL RIGHTS RESERVED. U.S. Government Sponsorship", "is invoked upon a new client. This function listens for", "registered clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address = True def handle(self): # on", "str(err.errno) + \" occurred on recv().\") return msg def readHeader(self):", "\"\"\" class DestObj: \"\"\" Destination object for all clients registered.", "if len(header) == 0: print( \"Header information is empty, client", "True self.name = name self.id = process_id print(\"Registered client \"", "if chunk == b\"\": print(\"read data from socket is empty!\")", "= 0 # print self.client_address, now() # show this client's", "the header data from the socket either A5A5 or List", "with A5A5 except if it is a List. Once the", "always start with A5A5 except if it is a List.", "dest_list: LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): # Send the message", "b\"Quit\" elif header[:-1] == b\"A5A5\": header2 = self.recv(4) return header", "SERVER.dest_obj[name] = DestObj(name, self.request) LOCK.release() self.registered = True self.name =", "was closed by the client if not data: print(\"Client exited.\")", "name = params[1] if b\"FSW\" in name: if FSW_clients: process_id", "SERVER.shutdown() SERVER.server_close() LOCK.release() break # Got the header data so", "original Stable demo during R&TD and adapted for use in", "FSW_clients.append(name) FSW_ids.append(process_id) elif b\"GUI\" in name: if GUI_clients: process_id =", "python3 from __future__ import print_function import socket import threading try:", "= server LOCK = server.lock_obj ip, port = server.server_address print(\"TCP", "threaded tcp socket server ip [default: %default]\", default=\"127.0.0.1\", ) #", "and socket id's for writting to destinations. \"\"\" dest_obj =", "socketserver import time import os import signal import sys import", "socket either A5A5 or List header = self.readHeader() # If", "thread with the server -- that thread will then start", "header2 = self.recv(4) return header + header2 else: return def", "closed, exit loop if not header: break elif header ==", "= sorted(FSW_ids)[-1] + 1 name = params[1] + b\"_\" +", "Constructor \"\"\" self.name = name self.socket = request self.packet =", "process options (opts, args) = parser.parse_args(argv) HOST = opts.host PORT", "port = server.server_address print(\"TCP Socket Server listening on host addr", "loop if not header: break elif header == b\"Quit\": LOCK.acquire()", "data from the socket either A5A5 or List (header, packet)", "use in new FSW gse.py applicaiton. TCP socket server for", "function that is invoked upon a new client. This function", "to process the command messages ################################################# def getNewMsg(self): \"\"\" After", "if FSW_clients: process_id = sorted(FSW_ids)[-1] + 1 name = params[1]", "shutdown_event = threading.Event() FSW_clients = [] GUI_clients = [] FSW_ids", "\"\"\" self.partial = b\"\" self.cmdQueue = [] self.registered = False", "request self.packet = b\"\" def put(self, msg): \"\"\" Write out", "is invoked when a packet is received. This function listens", "parameters. Handle is instanced in own thread for each client.", "dest_elem in dest_list: # print \"Locking TCP\" LOCK.acquire() if dest_elem", "or just read the \"List\\n\" command. \"\"\" header = packet[:4]", "Server listening on host addr %s, port %s\" % (HOST,", "+ str(err.errno) + \" (Connection reset by peer) occurred on", "packet, call processPkt. \"\"\" self.getNewMsg(self.request[0]) ################################################# # New Routines to", "Packet Header # print \"Received Packet: %s %s...\\n\" % (head,dst)", "\"\"\" socketserver.BaseRequestHandler.allow_reuse_address = True def handle(self): # on each packet", "[] def signal_handler(*_): print(\"Ctrl-C received, server shutting down.\") shutdown_event.set() def", "server. \"\"\" dest_list = [] if header == b\"List\": print(\"List", "server_thread.daemon = False server_thread.start() udp_server_thread.daemon = False udp_server_thread.start() while not", "will then start one # more thread for each request", "# Read telemetry data here... tlm_packet_size = packet[:4] size =", "import errno from fprime.constants import DATA_ENCODING from optparse import OptionParser", "\" \" sys.stderr.write(program_name + \": \" + repr(e) + \"\\n\")", "command. \"\"\" header = self.recv(5) if len(header) == 0: print(", "not shutdown_event.is_set(): # Read the header data from the socket", "UDP Socket server. \"\"\" class DestObj: \"\"\" Destination object for", "return self.socket def main(argv=None): global SERVER, LOCK program_name = os.path.basename(sys.argv[0])", "b\"\" self.id = 0 # print self.client_address, now() # show", "shutdown server. \"\"\" dest_list = [] # Process data here...", "def put(self, msg): \"\"\" Write out the message to the", "give further explanation about what the program does ) if", "be an \"A5A5 \" or a \"List \" \"\"\" #", "self.socket def main(argv=None): global SERVER, LOCK program_name = os.path.basename(sys.argv[0]) program_license", "data = self.recv(13) # Connection was closed by the client", "= b\"\" def put(self, msg): \"\"\" Write out the message", "dest=\"host\", action=\"store\", type=\"string\", help=\"Set threaded tcp socket server ip [default:", "signal_handler(*_): print(\"Ctrl-C received, server shutting down.\") shutdown_event.set() def now(): return", "in FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif self.name in GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id)", "HOST = opts.host PORT = opts.port server = ThreadedTCPServer((HOST, PORT),", "def readHeader(self): \"\"\" Read the 9 byte header (e.g. \"A5A5", "= process_id print(\"Registered client \" + self.name.decode(DATA_ENCODING)) ################################################# # New", "processRegistration(self, cmd): params = cmd.split() process_id = 0 if params[0]", "= ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) udp_server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) #", "just read the \"List\\n\" command. \"\"\" header = self.recv(5) if", "command messages ################################################# def getNewMsg(self): \"\"\" After registration wait for", "l > n: try: chunk = self.request.recv(l - n) if", "type=\"string\", help=\"Set threaded tcp socket server ip [default: %default]\", default=\"127.0.0.1\",", "def processRegistration(self, cmd): params = cmd.split() process_id = 0 if", "commands of various lengths. \"\"\" data = b\"\" if header", "> n: try: chunk = self.request.recv(l - n) if chunk", "while l > n: try: chunk = self.request.recv(l - n)", "data on the socket. Packets for now are assumed to", "connect \"\"\" The function that is invoked upon a new", "exit loop if not header: break elif header == b\"Quit\":", "Process and send the packet of the message here... self.processNewPkt(header,", "message.\") self.getNewMsg() else: print(\"Unable to register client.\") return LOCK.acquire() del", "command messages ################################################# def getNewMsg(self, packet): \"\"\" After registration wait", ") if argv is None: argv = sys.argv[1:] try: parser", "server port [default: %default]\", default=50007, ) parser.add_option( \"-i\", \"--host\", dest=\"host\",", "messages ################################################# def getNewMsg(self, packet): \"\"\" After registration wait for", "= struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + packet[4 : 4", "self.getNewMsg() else: print(\"Unable to register client.\") return LOCK.acquire() del SERVER.dest_obj[self.name]", ") parser.add_option( \"-i\", \"--host\", dest=\"host\", action=\"store\", type=\"string\", help=\"Set threaded tcp", "\": \" + repr(e) + \"\\n\") sys.stderr.write(indent + \" for", "self.cmdQueue = [] self.registered = False self.name = b\"\" self.id", "an incoming message The first part must always be an", "or List header = self.readHeader() # If the received header", "udp_server.server_close() time.sleep(1) except Exception as e: indent = len(program_name) *", "import socket import threading try: import socketserver except ImportError: import", "cmdQueue self.getCmds(data) # Process the cmdQueue self.processQueue() if self.registered: print(\"Registration", "telemetry data here... tlm_packet_size = packet[:4] size = struct.unpack(\">I\", tlm_packet_size)[0]", "= ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) # Hopefully this will allow address", "b\"List\\n\": return b\"List\" elif header == b\"Quit\\n\": return b\"Quit\" elif", "self.partial = b\"\" if len(commands[-1]): self.partial = commands[-1] self.cmdQueue.extend(commands[:-1]) else:", "params[0] == b\"Register\": LOCK.acquire() name = params[1] if b\"FSW\" in", "= 1 def handle(self): # on each client connect \"\"\"", "print(\"Client exited.\") return else: # Process the data into the", "= None shutdown_event = threading.Event() FSW_clients = [] GUI_clients =", "FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif self.name in GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release() print(\"Closed", "= b\"\" if len(commands[-1]): self.partial = commands[-1] self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1])", "in list(SERVER.dest_obj.keys()): print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str = b\"List \" +", "= self.recv(4) size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size +", "= tlm_packet_size + self.recv(size) else: raise RuntimeError(\"unrecognized client %s\" %", "<data>\" Note only <data> is sent. Any client that sends", "telemetry data here... tlm_packet_size = self.recv(4) size = struct.unpack(\">I\", tlm_packet_size)[0]", "if data == \"\": print(\" Data is empty, returning.\") if", "\" + self.name.decode(DATA_ENCODING) + \" exiting.\" ) return header if", "empty, client \" + self.name.decode(DATA_ENCODING) + \" exiting.\" ) return", "\"List \" \"\"\" # Read the header data from the", "\"\"\" Destination object for all clients registered. \"\"\" def __init__(self,", "or FSW. GUI receives telemetry. FSW receives commands of various", "return (header + header2, packet) def readData(self, header, packet): \"\"\"", "on each packet \"\"\" The function that is invoked when", "\"\"\" Read the data part of the message sent to", "header = self.recv(5) if len(header) == 0: print( \"Header information", "dest_list = GUI_clients else: print(\"dest? %s\" % dst.decode(DATA_ENCODING)) for dest_elem", "clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address = True socketserver.StreamRequestHandler.timeout = 1 def handle(self):", "server_thread.start() udp_server_thread.daemon = False udp_server_thread.start() while not shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0)", "2015 user_name (California Institute of Technology) \\ ALL RIGHTS RESERVED.", "program_longdesc = ( \"\"\"\"\"\" # optional - give further explanation", "closed by the client if not data: print(\"Client exited.\") return", "send the packet of the message here... self.processNewPkt(header, data) def", "self.socket = request self.packet = b\"\" def put(self, msg): \"\"\"", "header.split(b\" \")[1].strip(b\" \") if dst == b\"FSW\": # Read variable", "udp_server_thread.join(timeout=5.0) print(\"shutdown from main thread\") SERVER.shutdown() SERVER.server_close() udp_server.shutdown() udp_server.server_close() time.sleep(1)", "R&TD and adapted for use in new FSW gse.py applicaiton.", "that is invoked upon a new client. This function listens", "string \"Register <name>\". Sending a message to destination <name> is", "Government Sponsorship acknowledged.\" program_version = \"v0.1\" program_build_date = \"%s\" %", "now are assumed to be separated by a newline. For", "more thread for each request server_thread = threading.Thread(target=server.serve_forever) udp_server_thread =", "GUI_clients = [] FSW_ids = [] GUI_ids = [] def", "and adapted for use in new FSW gse.py applicaiton. TCP", "\"\"\" Process a single command here header and data here.", "readHeader(self): \"\"\" Read the 9 byte header (e.g. \"A5A5 GUI", "def signal_handler(*_): print(\"Ctrl-C received, server shutting down.\") shutdown_event.set() def now():", "continue except socket.error as err: if err.errno == errno.ECONNRESET: print(", "= threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\" UDP Socket server. \"\"\"", "and telemetry data. Later this will handle other things such", "not data: print(\"Client exited.\") return else: # Process the data", "incoming message The first part must always be an \"A5A5", "Read telemetry data here... tlm_packet_size = packet[:4] size = struct.unpack(\">I\",", "__date__ = \"2015-04-03\" __updated__ = \"2016-04-07\" # Universal server id", "+ str(err.errno) + \" occurred on send().\") def fileno(self): \"\"\"", "self.partial = commands[-1] self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1]) def processQueue(self): for cmd", "packets to send/receive while not shutdown_event.is_set(): # Read the header", "def readHeader(self, packet): \"\"\" Read the 9 byte header (e.g.", "dict() lock_obj = threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\" UDP Socket", "server shutting down.\") shutdown_event.set() def now(): return time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):", "message The first part must always be an \"A5A5 \"", "FSW_clients for dest_elem in dest_list: # print \"Locking TCP\" LOCK.acquire()", "= b\"List \" + SERVER.dest_obj[d].name l = len(reg_client_str) reg_client_str =", "listens for data on the socket. Packets for now are", "it on queue. If something goes wrong report and shutdown", "from socket. \"\"\" chunk = b\"\" msg = b\"\" n", "header = self.readHeader() # If the received header is an", "client \" + self.name.decode(DATA_ENCODING) + \" exiting.\" ) return header", "of Technology) \\ ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.\"", "data of the message here... data = self.readData(header, packet) #", "allow address reuse and server to restart immediately server.allow_reuse_address =", "process_id print(\"Registered client \" + self.name.decode(DATA_ENCODING)) ################################################# # New Routines", "list(SERVER.dest_obj.keys()): # Send the message here.... # print \"Sending TCP", "request server_thread = threading.Thread(target=server.serve_forever) udp_server_thread = threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler) server_thread.daemon", "1 name = params[1] + b\"_\" + bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id)", "+ self.recv(size) elif dst == b\"GUI\": # Read telemetry data", "readData(self, header, packet): \"\"\" Read the data part of the", "sent. Any client that sends a \"List\" comment makes the", "False self.request.close() def getCmds(self, inputString, end_of_command=b\"\\n\"): \"\"\" Build a command", "header tstring is processed send it on queue. If something", "<data> is sent. Any client that sends a \"List\" comment", "= struct.pack(\"i%ds\" % l, l, reg_client_str) self.request.send(reg_client_str) LOCK.release() return 0", "else: self.cmdQueue.extend(commands[:-1]) def processQueue(self): for cmd in self.cmdQueue: self.processRegistration(cmd) self.cmdQueue", "occurred on send().\") def fileno(self): \"\"\" \"\"\" return self.socket def", "n = 0 while l > n: try: chunk =", "print self.client_address, now() # show this client's address # Read", "\" + self.name self.socket.send(msg) except socket.error as err: print(\"Socket error", "on the socket. Packets for now are assumed to be", "server.lock_obj ip, port = server.server_address print(\"TCP Socket Server listening on", "= 0 if params[0] == b\"Register\": LOCK.acquire() name = params[1]", "= None LOCK = None shutdown_event = threading.Event() FSW_clients =", "to register client.\") return LOCK.acquire() del SERVER.dest_obj[self.name] if self.name in", "self.registered = False self.name = b\"\" self.id = 0 #", "if data == b\"\": print(\" Data is empty, returning.\") if", "header2, packet) def readData(self, header, packet): \"\"\" Read the data", "= params[1] + b\"_\" + bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id) elif b\"GUI\"", "returning.\") if b\"GUI\" in dst: dest_list = GUI_clients else: print(\"dest?", "the server -- that thread will then start one #", "process the command messages ################################################# def getNewMsg(self, packet): \"\"\" After", "optional - give further explanation about what the program does", "from optparse import OptionParser __version__ = 0.1 __date__ = \"2015-04-03\"", "%default]\", default=\"127.0.0.1\", ) # process options (opts, args) = parser.parse_args(argv)", "chunk = self.request.recv(l - n) if chunk == b\"\": print(\"read", "elif b\"FSW\" in dst: dest_list = FSW_clients for dest_elem in", "send it on queue. If something goes wrong report and", "port [default: %default]\", default=50007, ) parser.add_option( \"-i\", \"--host\", dest=\"host\", action=\"store\",", "id's for writting to destinations. \"\"\" dest_obj = dict() lock_obj", "the server display all registered clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address = True", "the socket either A5A5 or List (header, packet) = self.readHeader(packet)", "upon a new client. This function listens for data on", "own thread for each client. Registration is done by sending", "PORT)) # Start a thread with the server -- that", "break # Got the header data so read the data", "address reuse and server to restart immediately server.allow_reuse_address = True", "server ip [default: %default]\", default=\"127.0.0.1\", ) # process options (opts,", "self.readHeader(packet) # If the received header is an empty string,", "header (e.g. \"A5A5 GUI \" or \"A5A5 FSW \"), or", "immediately server.allow_reuse_address = True SERVER = server LOCK = server.lock_obj", "dest_list = [] if header == b\"List\": print(\"List of registered", "dest_elem in list(SERVER.dest_obj.keys()): # Send the message here.... # print", "b\"\" def put(self, msg): \"\"\" Write out the message to", "shutdown is requested\") return b\"Quit\\n\" continue except socket.error as err:", "here... tlm_packet_size = self.recv(4) size = struct.unpack(\">I\", tlm_packet_size)[0] data =", "+ self.recv(size) else: raise RuntimeError(\"unrecognized client %s\" % dst.decode(DATA_ENCODING)) return", "if params[0] == b\"Register\": LOCK.acquire() name = params[1] if b\"FSW\"", "0 # print self.client_address, now() # show this client's address", "\") # Read telemetry data here... tlm_packet_size = packet[:4] size", "= b\"\" msg = b\"\" n = 0 while l", "processPkt. \"\"\" self.partial = b\"\" self.cmdQueue = [] self.registered =", "Connection was closed by the client if not data: print(\"Client", "things such as sequence files and parameters. Handle is instanced", "List. Once the entire header string is processed send it", "\" + self.name.decode(DATA_ENCODING)) ################################################# # New Routines to process the", "by sending the string \"Register <name>\". Sending a message to", "a message to destination <name> is done as \"A5A5 <name>", "= sorted(GUI_ids)[-1] + 1 name = params[1] + b\"_\" +", "data. Later this will handle other things such as sequence", "packet, call processPkt. \"\"\" self.partial = b\"\" self.cmdQueue = []", "(%s)\" % (program_version, program_build_date) program_longdesc = ( \"\"\"\"\"\" # optional", "\"\"\" Write out the message to the destination socket \"\"\"", "self.getNewMsg(self.request[0]) ################################################# # New Routines to process the command messages", "cmd in self.cmdQueue: self.processRegistration(cmd) self.cmdQueue = [] def processRegistration(self, cmd):", "if GUI_clients: process_id = sorted(GUI_ids)[-1] + 1 name = params[1]", "= \"v0.1\" program_build_date = \"%s\" % __updated__ program_version_string = \"%%prog", "opts.host PORT = opts.port server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) udp_server", "\"\"\" self.getNewMsg(self.request[0]) ################################################# # New Routines to process the command", "self.name = b\"\" self.id = 0 # print self.client_address, now()", "wrong report and shutdown server. \"\"\" dest_list = [] if", "TCP socket server for commands, log events, and telemetry data.", "getNewMsg(self): \"\"\" After registration wait for an incoming message The", "string, connection closed, exit loop if not header: break elif", "into the cmdQueue self.getCmds(data) # Process the cmdQueue self.processQueue() if", "registration wait for an incoming message The first part must", ") # process options (opts, args) = parser.parse_args(argv) HOST =", "always be an \"A5A5 \" or a \"List \" \"\"\"", "Hopefully this will allow address reuse and server to restart", ": 4 + size] return data def processNewPkt(self, header, data):", "1 name = params[1] + b\"_\" + bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id)", "packet[:4] header2 = packet[4:9] packet = packet[9:] return (header +", "further explanation about what the program does ) if argv", "reset by peer) occurred on recv().\" ) else: print(\"Socket error", "= opts.host PORT = opts.port server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)", "signal import sys import struct import errno from fprime.constants import", "in new FSW gse.py applicaiton. TCP socket server for commands,", "try: chunk = self.request.recv(l - n) if chunk == b\"\":", "error \" + str(err.errno) + \" (Connection reset by peer)", "threading.Thread(target=server.serve_forever) udp_server_thread = threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler) server_thread.daemon = False server_thread.start()", "elif b\"GUI\" in name: if GUI_clients: process_id = sorted(GUI_ids)[-1] +", "a List. Once the entire header string is processed send", "if it is a List. Once the entire header tstring", "client. Registration is done by sending the string \"Register <name>\".", "= b\"\" n = 0 while l > n: try:", "+ header2 else: return def readData(self, header): \"\"\" Read the", "processed send it on queue. If something goes wrong report", "print \"Received Packet: %s %s...\\n\" % (head,dst) if data ==", "= [] # Process data here... head, dst = header.strip(b\"", "command must always start with A5A5 except if it is", "= threading.Event() FSW_clients = [] GUI_clients = [] FSW_ids =", "sorted(FSW_ids)[-1] + 1 name = params[1] + b\"_\" + bytes(process_id)", "[] GUI_ids = [] def signal_handler(*_): print(\"Ctrl-C received, server shutting", "on recv().\" ) else: print(\"Socket error \" + str(err.errno) +", "in dest_list: # print \"Locking TCP\" LOCK.acquire() if dest_elem in", "+ commands[0] self.partial = b\"\" if len(commands[-1]): self.partial = commands[-1]", "<gh_stars>0 #!/usr/bin/env python3 from __future__ import print_function import socket import", "part of the message sent to either GUI or FSW.", "# optional - give further explanation about what the program", "def handle(self): # on each client connect \"\"\" The function", "queues and socket id's for writting to destinations. \"\"\" dest_obj", "and send the packet of the message here... self.processNewPkt(header, data)", "dst: dest_list = GUI_clients elif b\"FSW\" in dst: dest_list =", "it is a List. Once the entire header tstring is", "# print \"Locking TCP\" LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): #", "+ 1 name = params[1] + b\"_\" + bytes(process_id) GUI_clients.append(name)", "= len(program_name) * \" \" sys.stderr.write(program_name + \": \" +", "\"\"\" Derived from original Stable demo during R&TD and adapted", "is processed send it on queue. If something goes wrong", "does ) if argv is None: argv = sys.argv[1:] try:", "return data def processNewPkt(self, header, data): \"\"\" Process a single", "def getNewMsg(self, packet): \"\"\" After registration wait for an incoming", "tlm_packet_size = self.recv(4) size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size", "\"\"\" dest_list = [] if header == b\"List\": print(\"List of", "connection closed, exit loop if not header: break elif header", "size] return data def processNewPkt(self, header, data): \"\"\" Process a", "\"Received Packet: %s %s...\\n\" % (head,dst) if data == \"\":", "on each client connect \"\"\" The function that is invoked", "shutdown_event.set() def now(): return time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived from", "= 0.1 __date__ = \"2015-04-03\" __updated__ = \"2016-04-07\" # Universal", "+ b\"_\" + bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name] = DestObj(name, self.request)", "process_id = sorted(FSW_ids)[-1] + 1 name = params[1] + b\"_\"", "main thread\") SERVER.shutdown() SERVER.server_close() udp_server.shutdown() udp_server.server_close() time.sleep(1) except Exception as", "information is empty, client \" + self.name.decode(DATA_ENCODING) + \" exiting.\"", "msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Packet missing", "( \"\"\"\"\"\" # optional - give further explanation about what", "= request self.packet = b\"\" def put(self, msg): \"\"\" Write", "= struct.unpack(\">I\", sizeb)[0] data = desc + sizeb + self.recv(size)", "socket import threading try: import socketserver except ImportError: import SocketServer", "A5A5 header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived from original Stable demo", "str(err.errno) + \" occurred on send().\") def fileno(self): \"\"\" \"\"\"", "recv().\") return msg def readHeader(self): \"\"\" Read the 9 byte", "= [] def signal_handler(*_): print(\"Ctrl-C received, server shutting down.\") shutdown_event.set()", "(header + header2, packet) def readData(self, header, packet): \"\"\" Read", "the message here... self.processNewPkt(header, data) def recv(self, l): \"\"\" Read", "print(\"dest? %s\" % dst.decode(DATA_ENCODING)) for dest_elem in dest_list: LOCK.acquire() if", "server. \"\"\" class DestObj: \"\"\" Destination object for all clients", "to \" + self.name self.socket.send(msg) except socket.error as err: print(\"Socket", "err: if err.errno == errno.ECONNRESET: print( \"Socket error \" +", "message here... self.processNewPkt(header, data) def readHeader(self, packet): \"\"\" Read the", "destination socket \"\"\" try: # print \"about to send data", "Got the header data so read the data of the", "FSW. GUI receives telemetry. FSW receives commands of various lengths.", "server display all registered clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address = True socketserver.StreamRequestHandler.timeout", "tcp socket server ip [default: %default]\", default=\"127.0.0.1\", ) # process", "invoked upon a new client. This function listens for data", "= [] self.registered = False self.name = b\"\" self.id =", "client \" + self.name.decode(DATA_ENCODING)) ################################################# # New Routines to process", "program_name = os.path.basename(sys.argv[0]) program_license = \"Copyright 2015 user_name (California Institute", "print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set() time.sleep(1) print(\"Quit processed!\") SERVER.shutdown() SERVER.server_close()", "in name: if FSW_clients: process_id = sorted(FSW_ids)[-1] + 1 name", "struct import errno from fprime.constants import DATA_ENCODING from optparse import", "data = tlm_packet_size + packet[4 : 4 + size] return", "Build a command from partial or full socket input \"\"\"", "# Send the message here.... # print \"Sending UDP msg", "socket data = self.recv(13) # Connection was closed by the", "New Routines to process the command messages ################################################# def getNewMsg(self,", "= packet[4:9] packet = packet[9:] return (header + header2, packet)", "here... self.processNewPkt(header, data) def recv(self, l): \"\"\" Read l bytes", "for use in new FSW gse.py applicaiton. TCP socket server", "= 0 while l > n: try: chunk = self.request.recv(l", "variable length command data here... desc = self.recv(4) sizeb =", "udp_server.shutdown() udp_server.server_close() time.sleep(1) except Exception as e: indent = len(program_name)", "\"\"\" data = b\"\" if header == b\"List\": return b\"\"", "b\"FSW\" in name: if FSW_clients: process_id = sorted(FSW_ids)[-1] + 1", "n) if chunk == b\"\": print(\"read data from socket is", "dst: dest_list = FSW_clients for dest_elem in dest_list: # print", "+ \" occurred on send().\") def fileno(self): \"\"\" \"\"\" return", "SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str = b\"List \" + SERVER.dest_obj[d].name l = len(reg_client_str)", "TCP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Packet", "tlm_packet_size + packet[4 : 4 + size] return data def", "that thread will then start one # more thread for", "# more thread for each request server_thread = threading.Thread(target=server.serve_forever) udp_server_thread", "the cmdQueue self.processQueue() if self.registered: print(\"Registration complete waiting for message.\")", "header == b\"Quit\": LOCK.acquire() print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set() time.sleep(1)", "# print \"Sending TCP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release()", "for message.\") self.getNewMsg() else: print(\"Unable to register client.\") return LOCK.acquire()", "self.recv(5) if len(header) == 0: print( \"Header information is empty,", "process_id = sorted(GUI_ids)[-1] + 1 name = params[1] + b\"_\"", "= dict() lock_obj = threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\" UDP", "\"2016-04-07\" # Universal server id global SERVER = None LOCK", "self.partial + commands[0] self.partial = b\"\" if len(commands[-1]): self.partial =", "dst: dest_list = GUI_clients else: print(\"dest? %s\" % dst.decode(DATA_ENCODING)) for", "\"Socket error \" + str(err.errno) + \" (Connection reset by", "and data here. The command must always start with A5A5", "+ size] return data def processNewPkt(self, header, data): \"\"\" Process", "(Connection reset by peer) occurred on recv().\" ) else: print(\"Socket", "applicaiton. TCP socket server for commands, log events, and telemetry", "commands = inputString.split(end_of_command) if len(self.partial): commands[0] = self.partial + commands[0]", "SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Packet missing A5A5 header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):", "\"\"\" UDP Socket server. \"\"\" class DestObj: \"\"\" Destination object", "sys.argv[1:] try: parser = OptionParser( version=program_version_string, epilog=program_longdesc, description=program_license, ) parser.add_option(", "self.readData(header) # Process and send the packet of the message", "chunk = b\"\" msg = b\"\" n = 0 while", "client. This function listens for data on the socket. Packets", "header == b\"List\\n\": return b\"List\" elif header == b\"Quit\\n\": return", "server. \"\"\" dest_list = [] # Process data here... head,", "Socket Server listening on host addr %s, port %s\" %", "desc = self.recv(4) sizeb = self.recv(4) size = struct.unpack(\">I\", sizeb)[0]", "= \"\" dst = header.split(b\" \")[1].strip(b\" \") # Read telemetry", "dst.decode(DATA_ENCODING)) return data def processNewPkt(self, header, data): \"\"\" Process a", "Universal server id global SERVER = None LOCK = None", "else: raise RuntimeError(\"unrecognized client %s\" % dst.decode(DATA_ENCODING)) return data def", "[] self.registered = False self.name = b\"\" self.id = 0", "return b\"Quit\" elif header[:-1] == b\"A5A5\": header2 = self.recv(4) return", "= os.path.basename(sys.argv[0]) program_license = \"Copyright 2015 user_name (California Institute of", "and shutdown is requested\") return b\"Quit\\n\" continue except socket.error as", "readData(self, header): \"\"\" Read the data part of the message", "b\"\" self.cmdQueue = [] self.registered = False self.name = b\"\"", "in dst: dest_list = FSW_clients for dest_elem in dest_list: #", "all registered clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address = True def handle(self): #", "import os import signal import sys import struct import errno", "== 0: print( \"Header information is empty, client \" +", "is a List. Once the entire header tstring is processed", "b\"Quit\": return b\"\" dst = header.split(b\" \")[1].strip(b\" \") if dst", "ip, port = server.server_address print(\"TCP Socket Server listening on host", "the message here.... # print \"Sending TCP msg to \",", "= cmd.split() process_id = 0 if params[0] == b\"Register\": LOCK.acquire()", "a packet is received. This function listens for data on", "= b\"\" self.cmdQueue = [] self.registered = False self.name =", "from original Stable demo during R&TD and adapted for use", "= \"%s\" % __updated__ program_version_string = \"%%prog %s (%s)\" %", "\" + repr(e) + \"\\n\") sys.stderr.write(indent + \" for help", "from the socket either A5A5 or List header = self.readHeader()", "dest_list = FSW_clients for dest_elem in dest_list: # print \"Locking", "entire header string is processed send it on queue. If", "self.request.send(reg_client_str) LOCK.release() return 0 # Process data here... head, dst", "thread will then start one # more thread for each", "report and shutdown server. \"\"\" dest_list = [] # Process", "this client's address # Read the data from the socket", "while not shutdown_event.is_set(): # Read the header data from the", "#!/usr/bin/env python3 from __future__ import print_function import socket import threading", "socket.error as err: print(\"Socket error \" + str(err.errno) + \"", "else: print(\"dest? %s\" % dst.decode(DATA_ENCODING)) for dest_elem in dest_list: LOCK.acquire()", "ip [default: %default]\", default=\"127.0.0.1\", ) # process options (opts, args)", "as socketserver import time import os import signal import sys", "= struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + self.recv(size) else: raise", "== b\"Quit\": return b\"\" dst = header.split(b\" \")[1].strip(b\" \") if", "parser.add_option( \"-p\", \"--port\", dest=\"port\", action=\"store\", type=\"int\", help=\"Set threaded tcp socket", "name: if FSW_clients: process_id = sorted(FSW_ids)[-1] + 1 name =", "True def handle(self): # on each packet \"\"\" The function", "SERVER.shutdown() SERVER.server_close() udp_server.shutdown() udp_server.server_close() time.sleep(1) except Exception as e: indent", "self.id = 0 # print self.client_address, now() # show this", "just read the \"List\\n\" command. \"\"\" header = packet[:4] header2", "%s\" % (HOST, PORT)) # Start a thread with the", "return time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived from original Stable demo", "b\"FSW\" in dst: dest_list = FSW_clients for dest_elem in dest_list:", "epilog=program_longdesc, description=program_license, ) parser.add_option( \"-p\", \"--port\", dest=\"port\", action=\"store\", type=\"int\", help=\"Set", "name, request): \"\"\" Constructor \"\"\" self.name = name self.socket =", "program_version_string = \"%%prog %s (%s)\" % (program_version, program_build_date) program_longdesc =", ") return header if header == b\"List\\n\": return b\"List\" elif", "GUI_ids.append(process_id) SERVER.dest_obj[name] = DestObj(name, self.request) LOCK.release() self.registered = True self.name", "print(\" Data is empty, returning.\") if b\"GUI\" in dst: dest_list", "data from the socket data = self.recv(13) # Connection was", "containing queues and socket id's for writting to destinations. \"\"\"", "the 9 byte header (e.g. \"A5A5 GUI \" or \"A5A5", "default=50007, ) parser.add_option( \"-i\", \"--host\", dest=\"host\", action=\"store\", type=\"string\", help=\"Set threaded", "display all registered clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address = True def handle(self):", "0 while l > n: try: chunk = self.request.recv(l -", "msg + chunk n = len(msg) except socket.timeout: if shutdown_event.is_set():", "packet[4:9] packet = packet[9:] return (header + header2, packet) def", "partial or full socket input \"\"\" commands = inputString.split(end_of_command) if", "RuntimeError(\"unrecognized client %s\" % dst.decode(DATA_ENCODING)) return data def processNewPkt(self, header,", "socket. Packets for now are assumed to be separated by", "def recv(self, l): \"\"\" Read l bytes from socket. \"\"\"", "self.request) LOCK.release() self.registered = True self.name = name self.id =", "= \"%%prog %s (%s)\" % (program_version, program_build_date) program_longdesc = (", "err.errno == errno.ECONNRESET: print( \"Socket error \" + str(err.errno) +", "udp_server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) # Hopefully this will allow", "else: print(\"Socket error \" + str(err.errno) + \" occurred on", "# Loop while the connected client has packets to send/receive", "= params[1] if b\"FSW\" in name: if FSW_clients: process_id =", "if not data: print(\"Client exited.\") return else: # Process the", "dest_obj = dict() lock_obj = threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\"", "== b\"Register\": LOCK.acquire() name = params[1] if b\"FSW\" in name:", "header.split(b\" \")[1].strip(b\" \") # Read telemetry data here... tlm_packet_size =", "# Read telemetry data here... tlm_packet_size = self.recv(4) size =", "message to the destination socket \"\"\" try: # print \"about", "None: argv = sys.argv[1:] try: parser = OptionParser( version=program_version_string, epilog=program_longdesc,", "client that sends a \"List\" comment makes the server display", "print(\"read data from socket is empty!\") return b\"\" msg =", "a \"List \" \"\"\" # Read the header data from", "- give further explanation about what the program does )", "New Routines to process the command messages ################################################# def getNewMsg(self):", "= self.recv(5) if len(header) == 0: print( \"Header information is", "\" or a \"List \" \"\"\" # Read the header", "shutdown_event.is_set(): # Read the header data from the socket either", "for d in list(SERVER.dest_obj.keys()): print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str = b\"List", "the destination socket \"\"\" try: # print \"about to send", "the message to the destination socket \"\"\" try: # print", "action=\"store\", type=\"int\", help=\"Set threaded tcp socket server port [default: %default]\",", "or List (header, packet) = self.readHeader(packet) # If the received", "here... tlm_packet_size = packet[:4] size = struct.unpack(\">I\", tlm_packet_size)[0] data =", "other things such as sequence files and parameters. Handle is", "PORT = opts.port server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) udp_server =", "\"\"\" commands = inputString.split(end_of_command) if len(self.partial): commands[0] = self.partial +", "fprime.constants import DATA_ENCODING from optparse import OptionParser __version__ = 0.1", "Keep a dictionary of destination objects containing queues and socket", "socketserver.BaseRequestHandler.allow_reuse_address = True def handle(self): # on each packet \"\"\"", "requested\") return b\"Quit\\n\" continue except socket.error as err: if err.errno", "for all clients registered. \"\"\" def __init__(self, name, request): \"\"\"", "b\"GUI\" in name: if GUI_clients: process_id = sorted(GUI_ids)[-1] + 1", "== b\"List\": print(\"List of registered clients: \") LOCK.acquire() for d", "b\"\" if header == b\"List\": return b\"\" elif header ==", "the data of the message here... data = self.readData(header, packet)", "socketserver.UDPServer): \"\"\" UDP Socket server. \"\"\" class DestObj: \"\"\" Destination", "except socket.error as err: print(\"Socket error \" + str(err.errno) +", "+ \" for help use --help\\n\") return 2 if __name__", "__future__ import print_function import socket import threading try: import socketserver", "wait for an incoming message The first part must always", "# process options (opts, args) = parser.parse_args(argv) HOST = opts.host", "not shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown from main thread\") SERVER.shutdown() SERVER.server_close()", "packet[9:] return (header + header2, packet) def readData(self, header, packet):", "else: # Process the data into the cmdQueue self.getCmds(data) #", "= header.split(b\" \")[1].strip(b\" \") # Read telemetry data here... tlm_packet_size", "params = cmd.split() process_id = 0 if params[0] == b\"Register\":", "the received header is an empty string, connection closed, exit", "header, packet): \"\"\" Read the data part of the message", "LOCK.acquire() print(\"Quit received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set() time.sleep(1) print(\"Quit processed!\") SERVER.shutdown()", "Any client that sends a \"List\" comment makes the server", "processNewPkt(self, header, data): \"\"\" Process a single command here header", "self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1]) def processQueue(self): for cmd in self.cmdQueue: self.processRegistration(cmd)", "= packet[9:] return (header + header2, packet) def readData(self, header,", "data of the message here... data = self.readData(header) # Process", "print(\"Quit processed!\") SERVER.shutdown() SERVER.server_close() LOCK.release() break # Got the header", "GUI or FSW. GUI receives telemetry. FSW receives commands of", "This function listens for data on the socket. Packets for", "else: raise RuntimeError(\"Telemetry missing A5A5 header\") class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\"", "for dest_elem in dest_list: LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): #", "UDP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Telemetry", "data part of the message sent to either GUI or", "\"\": print(\" Data is empty, returning.\") if b\"GUI\" in dst:", "if it is a List. Once the entire header string", "to restart immediately server.allow_reuse_address = True SERVER = server LOCK", "(California Institute of Technology) \\ ALL RIGHTS RESERVED. U.S. Government", "inputString.split(end_of_command) if len(self.partial): commands[0] = self.partial + commands[0] self.partial =", "print(\"Registered client \" + self.name.decode(DATA_ENCODING)) ################################################# # New Routines to", "elif dst == b\"GUI\": # Read telemetry data here... tlm_packet_size", "packet \"\"\" The function that is invoked when a packet", "or just read the \"List\\n\" command. \"\"\" header = self.recv(5)", "return header + header2 else: return def readData(self, header): \"\"\"", "= OptionParser( version=program_version_string, epilog=program_longdesc, description=program_license, ) parser.add_option( \"-p\", \"--port\", dest=\"port\",", "header + header2 else: return def readData(self, header): \"\"\" Read", "a new client. This function listens for data on the", "return header if header == b\"List\\n\": return b\"List\" elif header", "def getNewMsg(self): \"\"\" After registration wait for an incoming message", "in name: if GUI_clients: process_id = sorted(GUI_ids)[-1] + 1 name", "threading try: import socketserver except ImportError: import SocketServer as socketserver", "def readData(self, header): \"\"\" Read the data part of the", "server.allow_reuse_address = True SERVER = server LOCK = server.lock_obj ip,", "== \"\": print(\" Data is empty, returning.\") if b\"GUI\" in", "import SocketServer as socketserver import time import os import signal", "if dst == b\"FSW\": # Read variable length command data", "is None: argv = sys.argv[1:] try: parser = OptionParser( version=program_version_string,", "lengths. \"\"\" data = \"\" dst = header.split(b\" \")[1].strip(b\" \")", "def processQueue(self): for cmd in self.cmdQueue: self.processRegistration(cmd) self.cmdQueue = []", "packet = packet[9:] return (header + header2, packet) def readData(self,", "new FSW gse.py applicaiton. TCP socket server for commands, log", "destinations. \"\"\" dest_obj = dict() lock_obj = threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn,", "+ bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name] = DestObj(name, self.request) LOCK.release() self.registered", "# print \"about to send data to \" + self.name", "loop if not header: return # Got the header data", "the cmdQueue self.getCmds(data) # Process the cmdQueue self.processQueue() if self.registered:", "if len(commands[-1]): self.partial = commands[-1] self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1]) def processQueue(self):", "% (program_version, program_build_date) program_longdesc = ( \"\"\"\"\"\" # optional -", "\"A5A5 \" or a \"List \" \"\"\" # Loop while", "\") LOCK.acquire() for d in list(SERVER.dest_obj.keys()): print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str", "= self.recv(13) # Connection was closed by the client if", "= False self.name = b\"\" self.id = 0 # print", "call processPkt. \"\"\" self.partial = b\"\" self.cmdQueue = [] self.registered", "Packet: %s %s...\\n\" % (head,dst) if data == \"\": print(\"", "a dictionary of destination objects containing queues and socket id's", "data = tlm_packet_size + self.recv(size) else: raise RuntimeError(\"unrecognized client %s\"", "an \"A5A5 \" or a \"List \" \"\"\" # Loop", "ThreadedTCPRequestHandler) udp_server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) # Hopefully this will", "signal_handler) server_thread.daemon = False server_thread.start() udp_server_thread.daemon = False udp_server_thread.start() while", "FSW_ids.remove(self.id) elif self.name in GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release() print(\"Closed %s", "connection.\" % self.name.decode(DATA_ENCODING)) self.registered = False self.request.close() def getCmds(self, inputString,", "\\ ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.\" program_version =", "Data is empty, returning.\") if b\"GUI\" in dst: dest_list =", "udp_server_thread.daemon = False udp_server_thread.start() while not shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown", "destination objects containing queues and socket id's for writting to", "is a List. Once the entire header string is processed", "# Send the message here.... # print \"Sending TCP msg", "# Process the cmdQueue self.processQueue() if self.registered: print(\"Registration complete waiting", "% __updated__ program_version_string = \"%%prog %s (%s)\" % (program_version, program_build_date)", "GUI_clients: GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release() print(\"Closed %s connection.\" % self.name.decode(DATA_ENCODING)) self.registered", "on host addr %s, port %s\" % (HOST, PORT)) #", "len(commands[-1]): self.partial = commands[-1] self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1]) def processQueue(self): for", "occurred on recv().\") return msg def readHeader(self): \"\"\" Read the", "server_thread = threading.Thread(target=server.serve_forever) udp_server_thread = threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler) server_thread.daemon =", "try: import socketserver except ImportError: import SocketServer as socketserver import", "\" (Connection reset by peer) occurred on recv().\" ) else:", "socket.timeout: if shutdown_event.is_set(): print(\"socket timed out and shutdown is requested\")", "tlm_packet_size + self.recv(size) else: raise RuntimeError(\"unrecognized client %s\" % dst.decode(DATA_ENCODING))", "False self.name = b\"\" self.id = 0 # print self.client_address,", "all registered clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address = True socketserver.StreamRequestHandler.timeout = 1", "empty, returning.\") if b\"GUI\" in dst: dest_list = GUI_clients elif", "what the program does ) if argv is None: argv", "+ \"\\n\") sys.stderr.write(indent + \" for help use --help\\n\") return", "will handle other things such as sequence files and parameters.", "data) def recv(self, l): \"\"\" Read l bytes from socket.", "data here... tlm_packet_size = self.recv(4) size = struct.unpack(\">I\", tlm_packet_size)[0] data", "program_license = \"Copyright 2015 user_name (California Institute of Technology) \\", "header if header == b\"List\\n\": return b\"List\" elif header ==", "time.sleep(1) except Exception as e: indent = len(program_name) * \"", "return b\"\" msg = msg + chunk n = len(msg)", "a command from partial or full socket input \"\"\" commands", "connected client has packets to send/receive while not shutdown_event.is_set(): #", "The function that is invoked when a packet is received.", "= GUI_clients elif b\"FSW\" in dst: dest_list = FSW_clients for", "explanation about what the program does ) if argv is", "socket.error as err: if err.errno == errno.ECONNRESET: print( \"Socket error", "ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.\" program_version = \"v0.1\"", "an empty string, connection closed, exit loop if not header:", "try: parser = OptionParser( version=program_version_string, epilog=program_longdesc, description=program_license, ) parser.add_option( \"-p\",", "the message here... self.processNewPkt(header, data) def readHeader(self, packet): \"\"\" Read", "events, and telemetry data. Later this will handle other things", "class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived from original Stable demo during R&TD", ") parser.add_option( \"-p\", \"--port\", dest=\"port\", action=\"store\", type=\"int\", help=\"Set threaded tcp", "e: indent = len(program_name) * \" \" sys.stderr.write(program_name + \":", "registered clients: \") LOCK.acquire() for d in list(SERVER.dest_obj.keys()): print(\"\\t\" +", "%s, port %s\" % (HOST, PORT)) # Start a thread", "the data part of the message sent to either GUI", "of the message sent to either GUI or FSW. GUI", "self.recv(size) elif dst == b\"GUI\": # Read telemetry data here...", "either A5A5 or List header = self.readHeader() # If the", "== b\"A5A5\": # Packet Header # print \"Received Packet: %s", "print(\"shutdown from main thread\") SERVER.shutdown() SERVER.server_close() udp_server.shutdown() udp_server.server_close() time.sleep(1) except", "from the socket data = self.recv(13) # Connection was closed", "packet is received. This function listens for data on the", "dst == b\"GUI\": # Read telemetry data here... tlm_packet_size =", "sizeb)[0] data = desc + sizeb + self.recv(size) elif dst", "= packet[:4] size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size +", "the entire header string is processed send it on queue.", "ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived from original Stable demo during R&TD and", "self.partial = b\"\" self.cmdQueue = [] self.registered = False self.name", "bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id) elif b\"GUI\" in name: if GUI_clients: process_id", "the header data so read the data of the message", "%s %s...\\n\" % (head,dst) if data == b\"\": print(\" Data", "to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Telemetry missing A5A5", "b\"\": print(\" Data is empty, returning.\") if b\"GUI\" in dst:", "(e.g. \"A5A5 GUI \" or \"A5A5 FSW \"), or just", "\"Register <name>\". Sending a message to destination <name> is done", "%s %s...\\n\" % (head,dst) if data == \"\": print(\" Data", "the socket. Packets for now are assumed to be separated", "[] GUI_clients = [] FSW_ids = [] GUI_ids = []", "ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) # Hopefully this will allow address reuse", "header data from the socket either A5A5 or List header", "[] def processRegistration(self, cmd): params = cmd.split() process_id = 0", "to destination <name> is done as \"A5A5 <name> <data>\" Note", "os.path.basename(sys.argv[0]) program_license = \"Copyright 2015 user_name (California Institute of Technology)", "Process the data into the cmdQueue self.getCmds(data) # Process the", "packet) def readData(self, header, packet): \"\"\" Read the data part", "header data from the socket either A5A5 or List (header,", "Read telemetry data here... tlm_packet_size = self.recv(4) size = struct.unpack(\">I\",", "Loop while the connected client has packets to send/receive while", "one # more thread for each request server_thread = threading.Thread(target=server.serve_forever)", "listening on host addr %s, port %s\" % (HOST, PORT))", "== b\"List\": return b\"\" elif header == b\"Quit\": return b\"\"", "size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + packet[4 :", "header is an empty string, connection closed, exit loop if", "if b\"GUI\" in dst: dest_list = GUI_clients elif b\"FSW\" in", "1 def handle(self): # on each client connect \"\"\" The", "inputString, end_of_command=b\"\\n\"): \"\"\" Build a command from partial or full", "\"--host\", dest=\"host\", action=\"store\", type=\"string\", help=\"Set threaded tcp socket server ip", "clients registered. \"\"\" def __init__(self, name, request): \"\"\" Constructor \"\"\"", "self.recv(4) sizeb = self.recv(4) size = struct.unpack(\">I\", sizeb)[0] data =", "print(\"Registration complete waiting for message.\") self.getNewMsg() else: print(\"Unable to register", "header string is processed send it on queue. If something", "command data here... desc = self.recv(4) sizeb = self.recv(4) size", "Handle is instanced in own thread for each client. Registration", "The command must always start with A5A5 except if it", "(head,dst) if data == b\"\": print(\" Data is empty, returning.\")", "register client.\") return LOCK.acquire() del SERVER.dest_obj[self.name] if self.name in FSW_clients:", "self.request.recv(l - n) if chunk == b\"\": print(\"read data from", "= self.recv(4) return header + header2 else: return def readData(self,", "= self.recv(4) sizeb = self.recv(4) size = struct.unpack(\">I\", sizeb)[0] data", "= opts.port server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) udp_server = ThreadedUDPServer((HOST,", "here... desc = self.recv(4) sizeb = self.recv(4) size = struct.unpack(\">I\",", "b\"GUI\" in dst: dest_list = GUI_clients else: print(\"dest? %s\" %", "\"\"\" self.name = name self.socket = request self.packet = b\"\"", "reg_client_str = b\"List \" + SERVER.dest_obj[d].name l = len(reg_client_str) reg_client_str", "getNewMsg(self, packet): \"\"\" After registration wait for an incoming message", "received!\") SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set() time.sleep(1) print(\"Quit processed!\") SERVER.shutdown() SERVER.server_close() LOCK.release()", "\"\"\" \"\"\" return self.socket def main(argv=None): global SERVER, LOCK program_name", "while not shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown from main thread\") SERVER.shutdown()", "# on each packet \"\"\" The function that is invoked", "empty string, connection closed, exit loop if not header: return", "read the data of the message here... data = self.readData(header,", "cmd): params = cmd.split() process_id = 0 if params[0] ==", "b\"List\" elif header == b\"Quit\\n\": return b\"Quit\" elif header[:-1] ==", "full socket input \"\"\" commands = inputString.split(end_of_command) if len(self.partial): commands[0]", "b\"List\": print(\"List of registered clients: \") LOCK.acquire() for d in", "\" occurred on send().\") def fileno(self): \"\"\" \"\"\" return self.socket", "== b\"Quit\\n\": return b\"Quit\" elif header[:-1] == b\"A5A5\": header2 =", "server.server_address print(\"TCP Socket Server listening on host addr %s, port", "and parameters. Handle is instanced in own thread for each", "SERVER, LOCK program_name = os.path.basename(sys.argv[0]) program_license = \"Copyright 2015 user_name", "in dst: dest_list = GUI_clients elif b\"FSW\" in dst: dest_list", "port %s\" % (HOST, PORT)) # Start a thread with", "peer) occurred on recv().\" ) else: print(\"Socket error \" +", "help use --help\\n\") return 2 if __name__ == \"__main__\": sys.exit(main())", "+ sizeb + self.recv(size) elif dst == b\"GUI\": # Read", "data from the socket either A5A5 or List header =", "LOCK.release() print(\"Closed %s connection.\" % self.name.decode(DATA_ENCODING)) self.registered = False self.request.close()", "= False udp_server_thread.start() while not shutdown_event.is_set(): server_thread.join(timeout=5.0) udp_server_thread.join(timeout=5.0) print(\"shutdown from", "FSW_ids.append(process_id) elif b\"GUI\" in name: if GUI_clients: process_id = sorted(GUI_ids)[-1]", "\") if dst == b\"FSW\": # Read variable length command", "LOCK = None shutdown_event = threading.Event() FSW_clients = [] GUI_clients", "it is a List. Once the entire header string is", "self.recv(4) size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + self.recv(size)", "from fprime.constants import DATA_ENCODING from optparse import OptionParser __version__ =", "out and shutdown is requested\") return b\"Quit\\n\" continue except socket.error", "= self.request.recv(l - n) if chunk == b\"\": print(\"read data", "print( \"Header information is empty, client \" + self.name.decode(DATA_ENCODING) +", "name self.socket = request self.packet = b\"\" def put(self, msg):", "connection closed, exit loop if not header: return # Got", "0 # Process data here... head, dst = header.strip(b\" \").split(b\"", "to either GUI or FSW. GUI receives telemetry. FSW receives", "= parser.parse_args(argv) HOST = opts.host PORT = opts.port server =", "each packet, call processPkt. \"\"\" self.partial = b\"\" self.cmdQueue =", "version=program_version_string, epilog=program_longdesc, description=program_license, ) parser.add_option( \"-p\", \"--port\", dest=\"port\", action=\"store\", type=\"int\",", "len(header) == 0: print( \"Header information is empty, client \"", "# Packet Header # print \"Received Packet: %s %s...\\n\" %", "<name> is done as \"A5A5 <name> <data>\" Note only <data>", "as \"A5A5 <name> <data>\" Note only <data> is sent. Any", "Socket server. Keep a dictionary of destination objects containing queues", "%s\" % dst.decode(DATA_ENCODING)) for dest_elem in dest_list: LOCK.acquire() if dest_elem", "ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\" TCP Socket server. Keep a dictionary of", "string is processed send it on queue. If something goes", "to be separated by a newline. For each packet, call", "raise RuntimeError(\"unrecognized client %s\" % dst.decode(DATA_ENCODING)) return data def processNewPkt(self,", "threaded tcp socket server port [default: %default]\", default=50007, ) parser.add_option(", "single command here header and data here. The command must", "b\"A5A5\": # Packet Header # print \"Received Packet: %s %s...\\n\"", "params[1] + b\"_\" + bytes(process_id) FSW_clients.append(name) FSW_ids.append(process_id) elif b\"GUI\" in", "self.readHeader() # If the received header is an empty string,", "b\"\" msg = msg + chunk n = len(msg) except", "header\") class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\" TCP Socket server. Keep a", "def handle(self): # on each packet \"\"\" The function that", "self.name.decode(DATA_ENCODING) + \" exiting.\" ) return header if header ==", "class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived from original Stable demo during R&TD", "b\"List \" + SERVER.dest_obj[d].name l = len(reg_client_str) reg_client_str = struct.pack(\"i%ds\"", "command. \"\"\" header = packet[:4] header2 = packet[4:9] packet =", "DATA_ENCODING from optparse import OptionParser __version__ = 0.1 __date__ =", "% dst.decode(DATA_ENCODING)) return data def processNewPkt(self, header, data): \"\"\" Process", "list(SERVER.dest_obj.keys()): print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str = b\"List \" + SERVER.dest_obj[d].name", "is instanced in own thread for each client. Registration is", "parser.add_option( \"-i\", \"--host\", dest=\"host\", action=\"store\", type=\"string\", help=\"Set threaded tcp socket", "various lengths. \"\"\" data = b\"\" if header == b\"List\":", "closed, exit loop if not header: return # Got the", "exiting.\" ) return header if header == b\"List\\n\": return b\"List\"", "socket server ip [default: %default]\", default=\"127.0.0.1\", ) # process options", "messages ################################################# def getNewMsg(self): \"\"\" After registration wait for an", "something goes wrong report and shutdown server. \"\"\" dest_list =", "(program_version, program_build_date) program_longdesc = ( \"\"\"\"\"\" # optional - give", "FSW gse.py applicaiton. TCP socket server for commands, log events,", "processPkt. \"\"\" self.getNewMsg(self.request[0]) ################################################# # New Routines to process the", "List header = self.readHeader() # If the received header is", "\"Locking TCP\" LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): # Send the", "elif header == b\"Quit\\n\": return b\"Quit\" elif header[:-1] == b\"A5A5\":", "must always start with A5A5 except if it is a", "\"--port\", dest=\"port\", action=\"store\", type=\"int\", help=\"Set threaded tcp socket server port", "makes the server display all registered clients. \"\"\" socketserver.BaseRequestHandler.allow_reuse_address =", "if b\"GUI\" in dst: dest_list = GUI_clients else: print(\"dest? %s\"", "report and shutdown server. \"\"\" dest_list = [] if header", "is an empty string, connection closed, exit loop if not", "empty string, connection closed, exit loop if not header: break", "data = \"\" dst = header.split(b\" \")[1].strip(b\" \") # Read", "either A5A5 or List (header, packet) = self.readHeader(packet) # If", "sys.stderr.write(program_name + \": \" + repr(e) + \"\\n\") sys.stderr.write(indent +", "or full socket input \"\"\" commands = inputString.split(end_of_command) if len(self.partial):", "socketserver except ImportError: import SocketServer as socketserver import time import", "by peer) occurred on recv().\" ) else: print(\"Socket error \"", "udp_server_thread = threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler) server_thread.daemon = False server_thread.start() udp_server_thread.daemon", "indent = len(program_name) * \" \" sys.stderr.write(program_name + \": \"", "packet): \"\"\" Read the 9 byte header (e.g. \"A5A5 GUI", "False server_thread.start() udp_server_thread.daemon = False udp_server_thread.start() while not shutdown_event.is_set(): server_thread.join(timeout=5.0)", "here... head, dst = header.strip(b\" \").split(b\" \") if head ==", "__version__ = 0.1 __date__ = \"2015-04-03\" __updated__ = \"2016-04-07\" #", "dictionary of destination objects containing queues and socket id's for", "[default: %default]\", default=\"127.0.0.1\", ) # process options (opts, args) =", "header == b\"Quit\": return b\"\" dst = header.split(b\" \")[1].strip(b\" \")", "or a \"List \" \"\"\" # Read the header data", "= packet[:4] header2 = packet[4:9] packet = packet[9:] return (header", "TCP Socket server. Keep a dictionary of destination objects containing", "b\"Quit\\n\": return b\"Quit\" elif header[:-1] == b\"A5A5\": header2 = self.recv(4)", "timed out and shutdown is requested\") return b\"Quit\\n\" continue except", "here... data = self.readData(header) # Process and send the packet", "client has packets to send/receive while not shutdown_event.is_set(): # Read", "exit loop if not header: return # Got the header", "try: # print \"about to send data to \" +", "process_id = 0 if params[0] == b\"Register\": LOCK.acquire() name =", "# Read the data from the socket data = self.recv(13)", "in own thread for each client. Registration is done by", "% (HOST, PORT)) # Start a thread with the server", "None shutdown_event = threading.Event() FSW_clients = [] GUI_clients = []", "# Read the header data from the socket either A5A5", "\"Received Packet: %s %s...\\n\" % (head,dst) if data == b\"\":", "[default: %default]\", default=50007, ) parser.add_option( \"-i\", \"--host\", dest=\"host\", action=\"store\", type=\"string\",", "header2 else: return def readData(self, header): \"\"\" Read the data", "print(\"TCP Socket Server listening on host addr %s, port %s\"", "== b\"List\\n\": return b\"List\" elif header == b\"Quit\\n\": return b\"Quit\"", "GUI_clients elif b\"FSW\" in dst: dest_list = FSW_clients for dest_elem", "must always be an \"A5A5 \" or a \"List \"", "on recv().\") return msg def readHeader(self): \"\"\" Read the 9", "head == b\"A5A5\": # Packet Header # print \"Received Packet:", "__init__(self, name, request): \"\"\" Constructor \"\"\" self.name = name self.socket", "the server display all registered clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address = True", "import DATA_ENCODING from optparse import OptionParser __version__ = 0.1 __date__", "self.recv(size) else: raise RuntimeError(\"unrecognized client %s\" % dst.decode(DATA_ENCODING)) return data", "if dest_elem in list(SERVER.dest_obj.keys()): # Send the message here.... #", "GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name] = DestObj(name, self.request) LOCK.release() self.registered = True", "The function that is invoked upon a new client. This", "registered clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address = True socketserver.StreamRequestHandler.timeout = 1 def", "l, reg_client_str) self.request.send(reg_client_str) LOCK.release() return 0 # Process data here...", "sent to either GUI or FSW. GUI receives telemetry. FSW", "print(\"\\t\" + SERVER.dest_obj[d].name.decode(DATA_ENCODING)) reg_client_str = b\"List \" + SERVER.dest_obj[d].name l", "\") if head == b\"A5A5\": # Packet Header # print", "+ \" exiting.\" ) return header if header == b\"List\\n\":", ") else: print(\"Socket error \" + str(err.errno) + \" occurred", "\"\"\" Build a command from partial or full socket input", "# Got the header data so read the data of", "show this client's address # Read the data from the", "of destination objects containing queues and socket id's for writting", "in self.cmdQueue: self.processRegistration(cmd) self.cmdQueue = [] def processRegistration(self, cmd): params", "GUI_clients.remove(self.name) GUI_ids.remove(self.id) LOCK.release() print(\"Closed %s connection.\" % self.name.decode(DATA_ENCODING)) self.registered =", "put(self, msg): \"\"\" Write out the message to the destination", "# Universal server id global SERVER = None LOCK =", "receives commands of various lengths. \"\"\" data = \"\" dst", "__updated__ = \"2016-04-07\" # Universal server id global SERVER =", "return 0 # Process data here... head, dst = header.strip(b\"", "len(msg) except socket.timeout: if shutdown_event.is_set(): print(\"socket timed out and shutdown", "self.processNewPkt(header, data) def readHeader(self, packet): \"\"\" Read the 9 byte", "str(err.errno) + \" (Connection reset by peer) occurred on recv().\"", "+ \" (Connection reset by peer) occurred on recv().\" )", "b\"\" dst = header.split(b\" \")[1].strip(b\" \") if dst == b\"FSW\":", "%s\" % dst.decode(DATA_ENCODING)) return data def processNewPkt(self, header, data): \"\"\"", "lock_obj = threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\" UDP Socket server.", "TCP\" LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()): # Send the message", "A5A5 or List header = self.readHeader() # If the received", "to send data to \" + self.name self.socket.send(msg) except socket.error", "on send().\") def fileno(self): \"\"\" \"\"\" return self.socket def main(argv=None):", "= name self.id = process_id print(\"Registered client \" + self.name.decode(DATA_ENCODING))", "\"-i\", \"--host\", dest=\"host\", action=\"store\", type=\"string\", help=\"Set threaded tcp socket server", "an \"A5A5 \" or a \"List \" \"\"\" # Read", "dest_list: # print \"Locking TCP\" LOCK.acquire() if dest_elem in list(SERVER.dest_obj.keys()):", "the client if not data: print(\"Client exited.\") return else: #", "various lengths. \"\"\" data = \"\" dst = header.split(b\" \")[1].strip(b\"", "\"2015-04-03\" __updated__ = \"2016-04-07\" # Universal server id global SERVER", "\"\"\" The function that is invoked upon a new client.", "\"about to send data to \" + self.name self.socket.send(msg) except", "the data of the message here... data = self.readData(header) #", "args) = parser.parse_args(argv) HOST = opts.host PORT = opts.port server", "Write out the message to the destination socket \"\"\" try:", "self.registered = False self.request.close() def getCmds(self, inputString, end_of_command=b\"\\n\"): \"\"\" Build", "= self.readData(header, packet) # Process and send the packet of", "%default]\", default=50007, ) parser.add_option( \"-i\", \"--host\", dest=\"host\", action=\"store\", type=\"string\", help=\"Set", "\" \"\"\" # Read the header data from the socket", "packet): \"\"\" Read the data part of the message sent", "in dst: dest_list = GUI_clients else: print(\"dest? %s\" % dst.decode(DATA_ENCODING))", "Sponsorship acknowledged.\" program_version = \"v0.1\" program_build_date = \"%s\" % __updated__", "LOCK.acquire() name = params[1] if b\"FSW\" in name: if FSW_clients:", "time.sleep(1) print(\"Quit processed!\") SERVER.shutdown() SERVER.server_close() LOCK.release() break # Got the", "GUI_clients else: print(\"dest? %s\" % dst.decode(DATA_ENCODING)) for dest_elem in dest_list:", "packet[4 : 4 + size] return data def processNewPkt(self, header,", "LOCK.release() else: raise RuntimeError(\"Telemetry missing A5A5 header\") class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):", "l): \"\"\" Read l bytes from socket. \"\"\" chunk =", "b\"\" n = 0 while l > n: try: chunk", "handle other things such as sequence files and parameters. Handle", "# print self.client_address, now() # show this client's address #", "dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Telemetry missing A5A5 header\") class", "a single command here header and data here. The command", "LOCK.release() self.registered = True self.name = name self.id = process_id", "to send/receive while not shutdown_event.is_set(): # Read the header data", "+ chunk n = len(msg) except socket.timeout: if shutdown_event.is_set(): print(\"socket", "SERVER.dest_obj[d].name l = len(reg_client_str) reg_client_str = struct.pack(\"i%ds\" % l, l,", "if len(self.partial): commands[0] = self.partial + commands[0] self.partial = b\"\"", "self.readData(header, packet) # Process and send the packet of the", "chunk == b\"\": print(\"read data from socket is empty!\") return", "(opts, args) = parser.parse_args(argv) HOST = opts.host PORT = opts.port", "be separated by a newline. For each packet, call processPkt.", "= name self.socket = request self.packet = b\"\" def put(self,", "\"List\" comment makes the server display all registered clients. \"\"\"", "program_version = \"v0.1\" program_build_date = \"%s\" % __updated__ program_version_string =", "header == b\"List\": print(\"List of registered clients: \") LOCK.acquire() for", "by a newline. For each packet, call processPkt. \"\"\" self.partial", "from __future__ import print_function import socket import threading try: import", "SERVER = server LOCK = server.lock_obj ip, port = server.server_address", "errno.ECONNRESET: print( \"Socket error \" + str(err.errno) + \" (Connection", "each client connect \"\"\" The function that is invoked upon", "only <data> is sent. Any client that sends a \"List\"", "header and data here. The command must always start with", "a \"List \" \"\"\" # Loop while the connected client", "Send the message here.... # print \"Sending UDP msg to", "After registration wait for an incoming message The first part", "from socket is empty!\") return b\"\" msg = msg +", "err: print(\"Socket error \" + str(err.errno) + \" occurred on", "struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + self.recv(size) else: raise RuntimeError(\"unrecognized", "data here. The command must always start with A5A5 except", "self.registered: print(\"Registration complete waiting for message.\") self.getNewMsg() else: print(\"Unable to", "dst == b\"FSW\": # Read variable length command data here...", "self.name.decode(DATA_ENCODING)) self.registered = False self.request.close() def getCmds(self, inputString, end_of_command=b\"\\n\"): \"\"\"", "first part must always be an \"A5A5 \" or a", "%s connection.\" % self.name.decode(DATA_ENCODING)) self.registered = False self.request.close() def getCmds(self,", "print(\"Closed %s connection.\" % self.name.decode(DATA_ENCODING)) self.registered = False self.request.close() def", "name = params[1] + b\"_\" + bytes(process_id) GUI_clients.append(name) GUI_ids.append(process_id) SERVER.dest_obj[name]", "server LOCK = server.lock_obj ip, port = server.server_address print(\"TCP Socket", "assumed to be separated by a newline. For each packet,", "out the message to the destination socket \"\"\" try: #", "self.processQueue() if self.registered: print(\"Registration complete waiting for message.\") self.getNewMsg() else:", "header, data): \"\"\" Process a single command here header and", "sizeb + self.recv(size) elif dst == b\"GUI\": # Read telemetry", "[] FSW_ids = [] GUI_ids = [] def signal_handler(*_): print(\"Ctrl-C", "= b\"\" if header == b\"List\": return b\"\" elif header", "request): \"\"\" Constructor \"\"\" self.name = name self.socket = request", "# print \"Received Packet: %s %s...\\n\" % (head,dst) if data", "SERVER.dest_obj[self.name].put(struct.pack(\">I\", 0xA5A5A5A5)) shutdown_event.set() time.sleep(1) print(\"Quit processed!\") SERVER.shutdown() SERVER.server_close() LOCK.release() break", "server for commands, log events, and telemetry data. Later this", "read the data of the message here... data = self.readData(header)", "input \"\"\" commands = inputString.split(end_of_command) if len(self.partial): commands[0] = self.partial", "LOCK.release() break # Got the header data so read the", "-- that thread will then start one # more thread", "\"\"\" header = self.recv(5) if len(header) == 0: print( \"Header", "client connect \"\"\" The function that is invoked upon a", "== b\"\": print(\"read data from socket is empty!\") return b\"\"", "cmdQueue self.processQueue() if self.registered: print(\"Registration complete waiting for message.\") self.getNewMsg()", "are assumed to be separated by a newline. For each", "+ 1 name = params[1] + b\"_\" + bytes(process_id) FSW_clients.append(name)", "header = packet[:4] header2 = packet[4:9] packet = packet[9:] return", "\"Sending TCP msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise", "files and parameters. Handle is instanced in own thread for", "Routines to process the command messages ################################################# def getNewMsg(self): \"\"\"", "receives telemetry. FSW receives commands of various lengths. \"\"\" data", "* \" \" sys.stderr.write(program_name + \": \" + repr(e) +", "% self.name.decode(DATA_ENCODING)) self.registered = False self.request.close() def getCmds(self, inputString, end_of_command=b\"\\n\"):", "\" sys.stderr.write(program_name + \": \" + repr(e) + \"\\n\") sys.stderr.write(indent", "\"A5A5 FSW \"), or just read the \"List\\n\" command. \"\"\"", "Read the data from the socket data = self.recv(13) #", "GUI_ids.remove(self.id) LOCK.release() print(\"Closed %s connection.\" % self.name.decode(DATA_ENCODING)) self.registered = False", "else: raise RuntimeError(\"Packet missing A5A5 header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived", "id global SERVER = None LOCK = None shutdown_event =", "# Start a thread with the server -- that thread", "ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\" UDP Socket server. \"\"\" class DestObj: \"\"\"", "the command messages ################################################# def getNewMsg(self, packet): \"\"\" After registration", "a List. Once the entire header tstring is processed send", "a thread with the server -- that thread will then", "LOCK.acquire() del SERVER.dest_obj[self.name] if self.name in FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif", "to destinations. \"\"\" dest_obj = dict() lock_obj = threading.Lock() class", "error \" + str(err.errno) + \" occurred on send().\") def", "= [] def processRegistration(self, cmd): params = cmd.split() process_id =", "= desc + sizeb + self.recv(size) elif dst == b\"GUI\":", "params[1] if b\"FSW\" in name: if FSW_clients: process_id = sorted(FSW_ids)[-1]", "\")[1].strip(b\" \") if dst == b\"FSW\": # Read variable length", "now() # show this client's address # Read the data", "the packet of the message here... self.processNewPkt(header, data) def readHeader(self,", "def now(): return time.ctime(time.time()) class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): \"\"\" Derived from original", "threading.Lock() class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): \"\"\" UDP Socket server. \"\"\" class", "\"v0.1\" program_build_date = \"%s\" % __updated__ program_version_string = \"%%prog %s", "is empty!\") return b\"\" msg = msg + chunk n", "name self.id = process_id print(\"Registered client \" + self.name.decode(DATA_ENCODING)) #################################################", "to the destination socket \"\"\" try: # print \"about to", "Process a single command here header and data here. The", "import socketserver except ImportError: import SocketServer as socketserver import time", "separated by a newline. For each packet, call processPkt. \"\"\"", "if self.name in FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif self.name in GUI_clients:", "waiting for message.\") self.getNewMsg() else: print(\"Unable to register client.\") return", "+ SERVER.dest_obj[d].name l = len(reg_client_str) reg_client_str = struct.pack(\"i%ds\" % l,", "ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) udp_server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) # Hopefully", "a \"List\" comment makes the server display all registered clients.", "lengths. \"\"\" data = b\"\" if header == b\"List\": return", "data = b\"\" if header == b\"List\": return b\"\" elif", "each request server_thread = threading.Thread(target=server.serve_forever) udp_server_thread = threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler)", "\"\" dst = header.split(b\" \")[1].strip(b\" \") # Read telemetry data", "socket id's for writting to destinations. \"\"\" dest_obj = dict()", "l bytes from socket. \"\"\" chunk = b\"\" msg =", "Once the entire header string is processed send it on", "the entire header tstring is processed send it on queue.", "telemetry. FSW receives commands of various lengths. \"\"\" data =", "data here... head, dst = header.strip(b\" \").split(b\" \") if head", "= GUI_clients else: print(\"dest? %s\" % dst.decode(DATA_ENCODING)) for dest_elem in", "b\"GUI\": # Read telemetry data here... tlm_packet_size = self.recv(4) size", "instanced in own thread for each client. Registration is done", "message here... data = self.readData(header, packet) # Process and send", "\" + str(err.errno) + \" occurred on recv().\") return msg", "header == b\"List\": return b\"\" elif header == b\"Quit\": return", "True socketserver.StreamRequestHandler.timeout = 1 def handle(self): # on each client", "del SERVER.dest_obj[self.name] if self.name in FSW_clients: FSW_clients.remove(self.name) FSW_ids.remove(self.id) elif self.name", "except socket.error as err: if err.errno == errno.ECONNRESET: print( \"Socket", "message here... self.processNewPkt(header, data) def recv(self, l): \"\"\" Read l", "message here... data = self.readData(header) # Process and send the", "server. Keep a dictionary of destination objects containing queues and", "display all registered clients. \"\"\" socketserver.StreamRequestHandler.allow_reuse_address = True socketserver.StreamRequestHandler.timeout =", "repr(e) + \"\\n\") sys.stderr.write(indent + \" for help use --help\\n\")", "RESERVED. U.S. Government Sponsorship acknowledged.\" program_version = \"v0.1\" program_build_date =", "function listens for data on the socket. Packets for now", "for each client. Registration is done by sending the string", "b\"\" if len(commands[-1]): self.partial = commands[-1] self.cmdQueue.extend(commands[:-1]) else: self.cmdQueue.extend(commands[:-1]) def", "except Exception as e: indent = len(program_name) * \" \"", "threading.Event() FSW_clients = [] GUI_clients = [] FSW_ids = []", "RuntimeError(\"Packet missing A5A5 header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived from original", "header\") class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived from original Stable demo during", "print( \"Socket error \" + str(err.errno) + \" (Connection reset", "\"A5A5 GUI \" or \"A5A5 FSW \"), or just read", "registered. \"\"\" def __init__(self, name, request): \"\"\" Constructor \"\"\" self.name", "msg to \", dest_elem SERVER.dest_obj[dest_elem].put(data) LOCK.release() else: raise RuntimeError(\"Telemetry missing", "self.name.decode(DATA_ENCODING)) ################################################# # New Routines to process the command messages", "4 + size] return data def processNewPkt(self, header, data): \"\"\"", "Read the data part of the message sent to either", "import time import os import signal import sys import struct", "header data so read the data of the message here...", "elif header == b\"Quit\": return b\"\" dst = header.split(b\" \")[1].strip(b\"", "signal.signal(signal.SIGINT, signal_handler) server_thread.daemon = False server_thread.start() udp_server_thread.daemon = False udp_server_thread.start()", "== b\"GUI\": # Read telemetry data here... tlm_packet_size = self.recv(4)", "a newline. For each packet, call processPkt. \"\"\" self.getNewMsg(self.request[0]) #################################################", "threading.Thread(target=udp_server.serve_forever) signal.signal(signal.SIGINT, signal_handler) server_thread.daemon = False server_thread.start() udp_server_thread.daemon = False", "if not header: return # Got the header data so", "for cmd in self.cmdQueue: self.processRegistration(cmd) self.cmdQueue = [] def processRegistration(self,", "= self.partial + commands[0] self.partial = b\"\" if len(commands[-1]): self.partial", "byte header (e.g. \"A5A5 GUI \" or \"A5A5 FSW \"),", "= False self.request.close() def getCmds(self, inputString, end_of_command=b\"\\n\"): \"\"\" Build a", "struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + packet[4 : 4 +", "process the command messages ################################################# def getNewMsg(self): \"\"\" After registration", "= DestObj(name, self.request) LOCK.release() self.registered = True self.name = name", "client if not data: print(\"Client exited.\") return else: # Process", "as err: if err.errno == errno.ECONNRESET: print( \"Socket error \"", "the message here.... # print \"Sending UDP msg to \",", "newline. For each packet, call processPkt. \"\"\" self.partial = b\"\"", "GUI \" or \"A5A5 FSW \"), or just read the", "is done as \"A5A5 <name> <data>\" Note only <data> is", "0xA5A5A5A5)) shutdown_event.set() time.sleep(1) print(\"Quit processed!\") SERVER.shutdown() SERVER.server_close() LOCK.release() break #", "\"\"\" chunk = b\"\" msg = b\"\" n = 0", "= [] GUI_clients = [] FSW_ids = [] GUI_ids =", "self.packet = b\"\" def put(self, msg): \"\"\" Write out the", "list(SERVER.dest_obj.keys()): # Send the message here.... # print \"Sending UDP", "\" + SERVER.dest_obj[d].name l = len(reg_client_str) reg_client_str = struct.pack(\"i%ds\" %", "then start one # more thread for each request server_thread", "Exception as e: indent = len(program_name) * \" \" sys.stderr.write(program_name", "the message sent to either GUI or FSW. GUI receives", "occurred on recv().\" ) else: print(\"Socket error \" + str(err.errno)", "9 byte header (e.g. \"A5A5 GUI \" or \"A5A5 FSW", "server id global SERVER = None LOCK = None shutdown_event", "of registered clients: \") LOCK.acquire() for d in list(SERVER.dest_obj.keys()): print(\"\\t\"", "= \"Copyright 2015 user_name (California Institute of Technology) \\ ALL", "self.cmdQueue.extend(commands[:-1]) def processQueue(self): for cmd in self.cmdQueue: self.processRegistration(cmd) self.cmdQueue =", "self.socket.send(msg) except socket.error as err: print(\"Socket error \" + str(err.errno)", "return def readData(self, header): \"\"\" Read the data part of", "\"\"\" Read the 9 byte header (e.g. \"A5A5 GUI \"", "= [] if header == b\"List\": print(\"List of registered clients:", "self.name = name self.socket = request self.packet = b\"\" def", "sorted(GUI_ids)[-1] + 1 name = params[1] + b\"_\" + bytes(process_id)", "invoked when a packet is received. This function listens for", "% (head,dst) if data == \"\": print(\" Data is empty,", "\"List \" \"\"\" # Loop while the connected client has", "SERVER = None LOCK = None shutdown_event = threading.Event() FSW_clients", "desc + sizeb + self.recv(size) elif dst == b\"GUI\": #", "socket input \"\"\" commands = inputString.split(end_of_command) if len(self.partial): commands[0] =", "GUI_clients: process_id = sorted(GUI_ids)[-1] + 1 name = params[1] +", "part must always be an \"A5A5 \" or a \"List", "def processNewPkt(self, header, data): \"\"\" Process a single command here", "is empty, client \" + self.name.decode(DATA_ENCODING) + \" exiting.\" )", "processQueue(self): for cmd in self.cmdQueue: self.processRegistration(cmd) self.cmdQueue = [] def", "read the \"List\\n\" command. \"\"\" header = self.recv(5) if len(header)", "== b\"FSW\": # Read variable length command data here... desc", "# Process the data into the cmdQueue self.getCmds(data) # Process", "message sent to either GUI or FSW. GUI receives telemetry.", "b\"Register\": LOCK.acquire() name = params[1] if b\"FSW\" in name: if", "\"\"\" TCP Socket server. Keep a dictionary of destination objects", "GUI receives telemetry. FSW receives commands of various lengths. \"\"\"", "Sending a message to destination <name> is done as \"A5A5", "received header is an empty string, connection closed, exit loop", "this will allow address reuse and server to restart immediately", "import threading try: import socketserver except ImportError: import SocketServer as", "writting to destinations. \"\"\" dest_obj = dict() lock_obj = threading.Lock()", "Stable demo during R&TD and adapted for use in new", "raise RuntimeError(\"Telemetry missing A5A5 header\") class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): \"\"\" TCP", "True SERVER = server LOCK = server.lock_obj ip, port =", "= self.readHeader() # If the received header is an empty", "done by sending the string \"Register <name>\". Sending a message", "struct.pack(\"i%ds\" % l, l, reg_client_str) self.request.send(reg_client_str) LOCK.release() return 0 #", "size = struct.unpack(\">I\", tlm_packet_size)[0] data = tlm_packet_size + self.recv(size) else:", "= server.lock_obj ip, port = server.server_address print(\"TCP Socket Server listening", "a newline. For each packet, call processPkt. \"\"\" self.partial =", "ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): \"\"\" Derived from original Stable demo during R&TD and", "cmd.split() process_id = 0 if params[0] == b\"Register\": LOCK.acquire() name", "dst = header.split(b\" \")[1].strip(b\" \") # Read telemetry data here...", "The first part must always be an \"A5A5 \" or", "self.processRegistration(cmd) self.cmdQueue = [] def processRegistration(self, cmd): params = cmd.split()" ]
[ "= range(8) BOUGHT, BUYING, SOLD, SELLING = range(4) logging.basicConfig( format=\"%(asctime)s", "UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, ) = range(8) BOUGHT, BUYING, SOLD, SELLING", "- %(levelname)s - %(message)s\", level=logging.INFO ) logger = logging.getLogger(\"btb_manager_telegram_logger\") scheduler", "= range(4) logging.basicConfig( format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",", "time ( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT,", "format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO ) logger", "CUSTOM_SCRIPT, ) = range(8) BOUGHT, BUYING, SOLD, SELLING = range(4)", "BOUGHT, BUYING, SOLD, SELLING = range(4) logging.basicConfig( format=\"%(asctime)s - %(name)s", "%(levelname)s - %(message)s\", level=logging.INFO ) logger = logging.getLogger(\"btb_manager_telegram_logger\") scheduler =", "logging.basicConfig( format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO )", "- %(name)s - %(levelname)s - %(message)s\", level=logging.INFO ) logger =", "%(name)s - %(levelname)s - %(message)s\", level=logging.INFO ) logger = logging.getLogger(\"btb_manager_telegram_logger\")", "sched import time ( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB,", "UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, ) = range(8) BOUGHT, BUYING, SOLD,", "import time ( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON,", "PANIC_BUTTON, CUSTOM_SCRIPT, ) = range(8) BOUGHT, BUYING, SOLD, SELLING =", "range(8) BOUGHT, BUYING, SOLD, SELLING = range(4) logging.basicConfig( format=\"%(asctime)s -", "- %(message)s\", level=logging.INFO ) logger = logging.getLogger(\"btb_manager_telegram_logger\") scheduler = sched.scheduler(time.time,", "logging import sched import time ( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB,", "( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, )", "EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, ) = range(8)", "import sched import time ( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG,", "%(message)s\", level=logging.INFO ) logger = logging.getLogger(\"btb_manager_telegram_logger\") scheduler = sched.scheduler(time.time, time.sleep)", "EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, ) = range(8) BOUGHT,", ") = range(8) BOUGHT, BUYING, SOLD, SELLING = range(4) logging.basicConfig(", "range(4) logging.basicConfig( format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO", "MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, ) =", "BUYING, SOLD, SELLING = range(4) logging.basicConfig( format=\"%(asctime)s - %(name)s -", "SOLD, SELLING = range(4) logging.basicConfig( format=\"%(asctime)s - %(name)s - %(levelname)s", "SELLING = range(4) logging.basicConfig( format=\"%(asctime)s - %(name)s - %(levelname)s -", "DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, ) = range(8) BOUGHT, BUYING,", "import logging import sched import time ( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG," ]