repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
twidi/django-extended-choices
extended_choices/helpers.py
create_choice_attribute
def create_choice_attribute(creator_type, value, choice_entry): """Create an instance of a subclass of ChoiceAttributeMixin for the given value. Parameters ---------- creator_type : type ``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value`` class-method. value : ? The value for which we want to create an instance of a new subclass of ``creator_type``. choice_entry: ChoiceEntry The ``ChoiceEntry`` instance that hold the current value, used to access its constant, value and display name. Returns ------- ChoiceAttributeMixin An instance of a subclass of ``creator_type`` for the given value """ klass = creator_type.get_class_for_value(value) return klass(value, choice_entry)
python
def create_choice_attribute(creator_type, value, choice_entry): """Create an instance of a subclass of ChoiceAttributeMixin for the given value. Parameters ---------- creator_type : type ``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value`` class-method. value : ? The value for which we want to create an instance of a new subclass of ``creator_type``. choice_entry: ChoiceEntry The ``ChoiceEntry`` instance that hold the current value, used to access its constant, value and display name. Returns ------- ChoiceAttributeMixin An instance of a subclass of ``creator_type`` for the given value """ klass = creator_type.get_class_for_value(value) return klass(value, choice_entry)
Create an instance of a subclass of ChoiceAttributeMixin for the given value. Parameters ---------- creator_type : type ``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value`` class-method. value : ? The value for which we want to create an instance of a new subclass of ``creator_type``. choice_entry: ChoiceEntry The ``ChoiceEntry`` instance that hold the current value, used to access its constant, value and display name. Returns ------- ChoiceAttributeMixin An instance of a subclass of ``creator_type`` for the given value
https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/helpers.py#L200-L222
twidi/django-extended-choices
extended_choices/helpers.py
ChoiceAttributeMixin.get_class_for_value
def get_class_for_value(cls, value): """Class method to construct a class based on this mixin and the type of the given value. Parameters ---------- value: ? The value from which to extract the type to create the new class. Notes ----- The create classes are cached (in ``cls.__classes_by_type``) to avoid recreating already created classes. """ type_ = value.__class__ # Check if the type is already a ``ChoiceAttribute`` if issubclass(type_, ChoiceAttributeMixin): # In this case we can return this type return type_ # Create a new class only if it wasn't already created for this type. if type_ not in cls._classes_by_type: # Compute the name of the class with the name of the type. class_name = str('%sChoiceAttribute' % type_.__name__.capitalize()) # Create a new class and save it in the cache. cls._classes_by_type[type_] = type(class_name, (cls, type_), { 'creator_type': cls, }) # Return the class from the cache based on the type. return cls._classes_by_type[type_]
python
def get_class_for_value(cls, value): """Class method to construct a class based on this mixin and the type of the given value. Parameters ---------- value: ? The value from which to extract the type to create the new class. Notes ----- The create classes are cached (in ``cls.__classes_by_type``) to avoid recreating already created classes. """ type_ = value.__class__ # Check if the type is already a ``ChoiceAttribute`` if issubclass(type_, ChoiceAttributeMixin): # In this case we can return this type return type_ # Create a new class only if it wasn't already created for this type. if type_ not in cls._classes_by_type: # Compute the name of the class with the name of the type. class_name = str('%sChoiceAttribute' % type_.__name__.capitalize()) # Create a new class and save it in the cache. cls._classes_by_type[type_] = type(class_name, (cls, type_), { 'creator_type': cls, }) # Return the class from the cache based on the type. return cls._classes_by_type[type_]
Class method to construct a class based on this mixin and the type of the given value. Parameters ---------- value: ? The value from which to extract the type to create the new class. Notes ----- The create classes are cached (in ``cls.__classes_by_type``) to avoid recreating already created classes.
https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/helpers.py#L136-L166
twidi/django-extended-choices
extended_choices/helpers.py
ChoiceEntry._get_choice_attribute
def _get_choice_attribute(self, value): """Get a choice attribute for the given value. Parameters ---------- value: ? The value for which we want a choice attribute. Returns ------- An instance of a class based on ``ChoiceAttributeMixin`` for the given value. Raises ------ ValueError If the value is None, as we cannot really subclass NoneType. """ if value is None: raise ValueError('Using `None` in a `Choices` object is not supported. You may ' 'use an empty string.') return create_choice_attribute(self.ChoiceAttributeMixin, value, self)
python
def _get_choice_attribute(self, value): """Get a choice attribute for the given value. Parameters ---------- value: ? The value for which we want a choice attribute. Returns ------- An instance of a class based on ``ChoiceAttributeMixin`` for the given value. Raises ------ ValueError If the value is None, as we cannot really subclass NoneType. """ if value is None: raise ValueError('Using `None` in a `Choices` object is not supported. You may ' 'use an empty string.') return create_choice_attribute(self.ChoiceAttributeMixin, value, self)
Get a choice attribute for the given value. Parameters ---------- value: ? The value for which we want a choice attribute. Returns ------- An instance of a class based on ``ChoiceAttributeMixin`` for the given value. Raises ------ ValueError If the value is None, as we cannot really subclass NoneType.
https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/helpers.py#L306-L329
grundic/yagocd
yagocd/session.py
Session.urljoin
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. """ return "/".join(map(lambda x: str(x).rstrip('/'), args)).rstrip('/')
python
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. """ return "/".join(map(lambda x: str(x).rstrip('/'), args)).rstrip('/')
Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/session.py#L52-L57
grundic/yagocd
yagocd/session.py
Session.server_version
def server_version(self): """ Special method for getting server version. Because of different behaviour on different versions of server, we have to pass different headers to the endpoints. This method requests the version from server and caches it in internal variable, so other resources could use it. :return: server version parsed from `about` page. """ if self.__server_version is None: from yagocd.resources.info import InfoManager self.__server_version = InfoManager(self).version return self.__server_version
python
def server_version(self): """ Special method for getting server version. Because of different behaviour on different versions of server, we have to pass different headers to the endpoints. This method requests the version from server and caches it in internal variable, so other resources could use it. :return: server version parsed from `about` page. """ if self.__server_version is None: from yagocd.resources.info import InfoManager self.__server_version = InfoManager(self).version return self.__server_version
Special method for getting server version. Because of different behaviour on different versions of server, we have to pass different headers to the endpoints. This method requests the version from server and caches it in internal variable, so other resources could use it. :return: server version parsed from `about` page.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/session.py#L69-L84
grundic/yagocd
yagocd/resources/job.py
JobInstance.pipeline_name
def pipeline_name(self): """ Get pipeline name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name. """ if 'pipeline_name' in self.data and self.data.pipeline_name: return self.data.get('pipeline_name') elif self.stage.pipeline is not None: return self.stage.pipeline.data.name else: return self.stage.data.pipeline_name
python
def pipeline_name(self): """ Get pipeline name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name. """ if 'pipeline_name' in self.data and self.data.pipeline_name: return self.data.get('pipeline_name') elif self.stage.pipeline is not None: return self.stage.pipeline.data.name else: return self.stage.data.pipeline_name
Get pipeline name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/job.py#L134-L148
grundic/yagocd
yagocd/resources/job.py
JobInstance.pipeline_counter
def pipeline_counter(self): """ Get pipeline counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter. """ if 'pipeline_counter' in self.data and self.data.pipeline_counter: return self.data.get('pipeline_counter') elif self.stage.pipeline is not None: return self.stage.pipeline.data.counter else: return self.stage.data.pipeline_counter
python
def pipeline_counter(self): """ Get pipeline counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter. """ if 'pipeline_counter' in self.data and self.data.pipeline_counter: return self.data.get('pipeline_counter') elif self.stage.pipeline is not None: return self.stage.pipeline.data.counter else: return self.stage.data.pipeline_counter
Get pipeline counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/job.py#L151-L165
grundic/yagocd
yagocd/resources/job.py
JobInstance.stage_name
def stage_name(self): """ Get stage name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the stage. :return: stage name. """ if 'stage_name' in self.data and self.data.stage_name: return self.data.get('stage_name') else: return self.stage.data.name
python
def stage_name(self): """ Get stage name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the stage. :return: stage name. """ if 'stage_name' in self.data and self.data.stage_name: return self.data.get('stage_name') else: return self.stage.data.name
Get stage name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the stage. :return: stage name.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/job.py#L168-L180
grundic/yagocd
yagocd/resources/job.py
JobInstance.stage_counter
def stage_counter(self): """ Get stage counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the stage. :return: stage counter. """ if 'stage_counter' in self.data and self.data.stage_counter: return self.data.get('stage_counter') else: return self.stage.data.counter
python
def stage_counter(self): """ Get stage counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the stage. :return: stage counter. """ if 'stage_counter' in self.data and self.data.stage_counter: return self.data.get('stage_counter') else: return self.stage.data.counter
Get stage counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the stage. :return: stage counter.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/job.py#L183-L195
grundic/yagocd
yagocd/resources/job.py
JobInstance.artifacts
def artifacts(self): """ Property for accessing artifact manager of the current job. :return: instance of :class:`yagocd.resources.artifact.ArtifactManager` :rtype: yagocd.resources.artifact.ArtifactManager """ return ArtifactManager( session=self._session, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.stage_name, stage_counter=self.stage_counter, job_name=self.data.name )
python
def artifacts(self): """ Property for accessing artifact manager of the current job. :return: instance of :class:`yagocd.resources.artifact.ArtifactManager` :rtype: yagocd.resources.artifact.ArtifactManager """ return ArtifactManager( session=self._session, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.stage_name, stage_counter=self.stage_counter, job_name=self.data.name )
Property for accessing artifact manager of the current job. :return: instance of :class:`yagocd.resources.artifact.ArtifactManager` :rtype: yagocd.resources.artifact.ArtifactManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/job.py#L218-L232
grundic/yagocd
yagocd/resources/job.py
JobInstance.properties
def properties(self): """ Property for accessing property (doh!) manager of the current job. :return: instance of :class:`yagocd.resources.property.PropertyManager` :rtype: yagocd.resources.property.PropertyManager """ return PropertyManager( session=self._session, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.stage_name, stage_counter=self.stage_counter, job_name=self.data.name )
python
def properties(self): """ Property for accessing property (doh!) manager of the current job. :return: instance of :class:`yagocd.resources.property.PropertyManager` :rtype: yagocd.resources.property.PropertyManager """ return PropertyManager( session=self._session, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.stage_name, stage_counter=self.stage_counter, job_name=self.data.name )
Property for accessing property (doh!) manager of the current job. :return: instance of :class:`yagocd.resources.property.PropertyManager` :rtype: yagocd.resources.property.PropertyManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/job.py#L235-L249
grundic/yagocd
yagocd/resources/stage.py
StageInstance.url
def url(self): """ Returns url for accessing stage instance. """ return "{server_url}/go/pipelines/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}".format( server_url=self._session.server_url, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.data.name, stage_counter=self.data.counter, )
python
def url(self): """ Returns url for accessing stage instance. """ return "{server_url}/go/pipelines/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}".format( server_url=self._session.server_url, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.data.name, stage_counter=self.data.counter, )
Returns url for accessing stage instance.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/stage.py#L247-L257
grundic/yagocd
yagocd/resources/stage.py
StageInstance.pipeline_name
def pipeline_name(self): """ Get pipeline name of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name. """ if 'pipeline_name' in self.data: return self.data.get('pipeline_name') elif self.pipeline is not None: return self.pipeline.data.name
python
def pipeline_name(self): """ Get pipeline name of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name. """ if 'pipeline_name' in self.data: return self.data.get('pipeline_name') elif self.pipeline is not None: return self.pipeline.data.name
Get pipeline name of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/stage.py#L260-L272
grundic/yagocd
yagocd/resources/stage.py
StageInstance.pipeline_counter
def pipeline_counter(self): """ Get pipeline counter of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter. """ if 'pipeline_counter' in self.data: return self.data.get('pipeline_counter') elif self.pipeline is not None: return self.pipeline.data.counter
python
def pipeline_counter(self): """ Get pipeline counter of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter. """ if 'pipeline_counter' in self.data: return self.data.get('pipeline_counter') elif self.pipeline is not None: return self.pipeline.data.counter
Get pipeline counter of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/stage.py#L275-L287
grundic/yagocd
yagocd/resources/stage.py
StageInstance.cancel
def cancel(self): """ Cancel an active stage of a specified stage. :return: a text confirmation. """ return self._manager.cancel(pipeline_name=self.pipeline_name, stage_name=self.stage_name)
python
def cancel(self): """ Cancel an active stage of a specified stage. :return: a text confirmation. """ return self._manager.cancel(pipeline_name=self.pipeline_name, stage_name=self.stage_name)
Cancel an active stage of a specified stage. :return: a text confirmation.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/stage.py#L317-L323
grundic/yagocd
yagocd/resources/stage.py
StageInstance.jobs
def jobs(self): """ Method for getting jobs from stage instance. :return: arrays of jobs. :rtype: list of yagocd.resources.job.JobInstance """ jobs = list() for data in self.data.jobs: jobs.append(JobInstance(session=self._session, data=data, stage=self)) return jobs
python
def jobs(self): """ Method for getting jobs from stage instance. :return: arrays of jobs. :rtype: list of yagocd.resources.job.JobInstance """ jobs = list() for data in self.data.jobs: jobs.append(JobInstance(session=self._session, data=data, stage=self)) return jobs
Method for getting jobs from stage instance. :return: arrays of jobs. :rtype: list of yagocd.resources.job.JobInstance
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/stage.py#L325-L336
grundic/yagocd
yagocd/resources/stage.py
StageInstance.job
def job(self, name): """ Method for searching specific job by it's name. :param name: name of the job to search. :return: found job or None. :rtype: yagocd.resources.job.JobInstance """ for job in self.jobs(): if job.data.name == name: return job
python
def job(self, name): """ Method for searching specific job by it's name. :param name: name of the job to search. :return: found job or None. :rtype: yagocd.resources.job.JobInstance """ for job in self.jobs(): if job.data.name == name: return job
Method for searching specific job by it's name. :param name: name of the job to search. :return: found job or None. :rtype: yagocd.resources.job.JobInstance
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/stage.py#L338-L348
grundic/yagocd
yagocd/client.py
Yagocd.agents
def agents(self): """ Property for accessing :class:`AgentManager` instance, which is used to manage agents. :rtype: yagocd.resources.agent.AgentManager """ if self._agent_manager is None: self._agent_manager = AgentManager(session=self._session) return self._agent_manager
python
def agents(self): """ Property for accessing :class:`AgentManager` instance, which is used to manage agents. :rtype: yagocd.resources.agent.AgentManager """ if self._agent_manager is None: self._agent_manager = AgentManager(session=self._session) return self._agent_manager
Property for accessing :class:`AgentManager` instance, which is used to manage agents. :rtype: yagocd.resources.agent.AgentManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L131-L139
grundic/yagocd
yagocd/client.py
Yagocd.artifacts
def artifacts(self): """ Property for accessing :class:`ArtifactManager` instance, which is used to manage artifacts. :rtype: yagocd.resources.artifact.ArtifactManager """ if self._artifact_manager is None: self._artifact_manager = ArtifactManager(session=self._session) return self._artifact_manager
python
def artifacts(self): """ Property for accessing :class:`ArtifactManager` instance, which is used to manage artifacts. :rtype: yagocd.resources.artifact.ArtifactManager """ if self._artifact_manager is None: self._artifact_manager = ArtifactManager(session=self._session) return self._artifact_manager
Property for accessing :class:`ArtifactManager` instance, which is used to manage artifacts. :rtype: yagocd.resources.artifact.ArtifactManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L142-L150
grundic/yagocd
yagocd/client.py
Yagocd.configurations
def configurations(self): """ Property for accessing :class:`ConfigurationManager` instance, which is used to manage configurations. :rtype: yagocd.resources.configuration.ConfigurationManager """ if self._configuration_manager is None: self._configuration_manager = ConfigurationManager(session=self._session) return self._configuration_manager
python
def configurations(self): """ Property for accessing :class:`ConfigurationManager` instance, which is used to manage configurations. :rtype: yagocd.resources.configuration.ConfigurationManager """ if self._configuration_manager is None: self._configuration_manager = ConfigurationManager(session=self._session) return self._configuration_manager
Property for accessing :class:`ConfigurationManager` instance, which is used to manage configurations. :rtype: yagocd.resources.configuration.ConfigurationManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L153-L161
grundic/yagocd
yagocd/client.py
Yagocd.encryption
def encryption(self): """ Property for accessing :class:`EncryptionManager` instance, which is used to manage encryption. :rtype: yagocd.resources.encryption.EncryptionManager """ if self._encryption_manager is None: self._encryption_manager = EncryptionManager(session=self._session) return self._encryption_manager
python
def encryption(self): """ Property for accessing :class:`EncryptionManager` instance, which is used to manage encryption. :rtype: yagocd.resources.encryption.EncryptionManager """ if self._encryption_manager is None: self._encryption_manager = EncryptionManager(session=self._session) return self._encryption_manager
Property for accessing :class:`EncryptionManager` instance, which is used to manage encryption. :rtype: yagocd.resources.encryption.EncryptionManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L164-L173
grundic/yagocd
yagocd/client.py
Yagocd.elastic_profiles
def elastic_profiles(self): """ Property for accessing :class:`ElasticAgentProfileManager` instance, which is used to manage elastic agent profiles. :rtype: yagocd.resources.elastic_profile.ElasticAgentProfileManager """ if self._elastic_agent_profile_manager is None: self._elastic_agent_profile_manager = ElasticAgentProfileManager(session=self._session) return self._elastic_agent_profile_manager
python
def elastic_profiles(self): """ Property for accessing :class:`ElasticAgentProfileManager` instance, which is used to manage elastic agent profiles. :rtype: yagocd.resources.elastic_profile.ElasticAgentProfileManager """ if self._elastic_agent_profile_manager is None: self._elastic_agent_profile_manager = ElasticAgentProfileManager(session=self._session) return self._elastic_agent_profile_manager
Property for accessing :class:`ElasticAgentProfileManager` instance, which is used to manage elastic agent profiles. :rtype: yagocd.resources.elastic_profile.ElasticAgentProfileManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L176-L185
grundic/yagocd
yagocd/client.py
Yagocd.environments
def environments(self): """ Property for accessing :class:`EnvironmentManager` instance, which is used to manage environments. :rtype: yagocd.resources.environment.EnvironmentManager """ if self._environment_manager is None: self._environment_manager = EnvironmentManager(session=self._session) return self._environment_manager
python
def environments(self): """ Property for accessing :class:`EnvironmentManager` instance, which is used to manage environments. :rtype: yagocd.resources.environment.EnvironmentManager """ if self._environment_manager is None: self._environment_manager = EnvironmentManager(session=self._session) return self._environment_manager
Property for accessing :class:`EnvironmentManager` instance, which is used to manage environments. :rtype: yagocd.resources.environment.EnvironmentManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L188-L196
grundic/yagocd
yagocd/client.py
Yagocd.feeds
def feeds(self): """ Property for accessing :class:`FeedManager` instance, which is used to manage feeds. :rtype: yagocd.resources.feed.FeedManager """ if self._feed_manager is None: self._feed_manager = FeedManager(session=self._session) return self._feed_manager
python
def feeds(self): """ Property for accessing :class:`FeedManager` instance, which is used to manage feeds. :rtype: yagocd.resources.feed.FeedManager """ if self._feed_manager is None: self._feed_manager = FeedManager(session=self._session) return self._feed_manager
Property for accessing :class:`FeedManager` instance, which is used to manage feeds. :rtype: yagocd.resources.feed.FeedManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L199-L207
grundic/yagocd
yagocd/client.py
Yagocd.jobs
def jobs(self): """ Property for accessing :class:`JobManager` instance, which is used to manage feeds. :rtype: yagocd.resources.job.JobManager """ if self._job_manager is None: self._job_manager = JobManager(session=self._session) return self._job_manager
python
def jobs(self): """ Property for accessing :class:`JobManager` instance, which is used to manage feeds. :rtype: yagocd.resources.job.JobManager """ if self._job_manager is None: self._job_manager = JobManager(session=self._session) return self._job_manager
Property for accessing :class:`JobManager` instance, which is used to manage feeds. :rtype: yagocd.resources.job.JobManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L210-L218
grundic/yagocd
yagocd/client.py
Yagocd.info
def info(self): """ Property for accessing :class:`InfoManager` instance, which is used to general server info. :rtype: yagocd.resources.info.InfoManager """ if self._info_manager is None: self._info_manager = InfoManager(session=self._session) return self._info_manager
python
def info(self): """ Property for accessing :class:`InfoManager` instance, which is used to general server info. :rtype: yagocd.resources.info.InfoManager """ if self._info_manager is None: self._info_manager = InfoManager(session=self._session) return self._info_manager
Property for accessing :class:`InfoManager` instance, which is used to general server info. :rtype: yagocd.resources.info.InfoManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L221-L229
grundic/yagocd
yagocd/client.py
Yagocd.notification_filters
def notification_filters(self): """ Property for accessing :class:`NotificationFilterManager` instance, which is used to manage notification filters. :rtype: yagocd.resources.notification_filter.NotificationFilterManager """ if self._notification_filter_manager is None: self._notification_filter_manager = NotificationFilterManager(session=self._session) return self._notification_filter_manager
python
def notification_filters(self): """ Property for accessing :class:`NotificationFilterManager` instance, which is used to manage notification filters. :rtype: yagocd.resources.notification_filter.NotificationFilterManager """ if self._notification_filter_manager is None: self._notification_filter_manager = NotificationFilterManager(session=self._session) return self._notification_filter_manager
Property for accessing :class:`NotificationFilterManager` instance, which is used to manage notification filters. :rtype: yagocd.resources.notification_filter.NotificationFilterManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L232-L241
grundic/yagocd
yagocd/client.py
Yagocd.materials
def materials(self): """ Property for accessing :class:`MaterialManager` instance, which is used to manage materials. :rtype: yagocd.resources.material.MaterialManager """ if self._material_manager is None: self._material_manager = MaterialManager(session=self._session) return self._material_manager
python
def materials(self): """ Property for accessing :class:`MaterialManager` instance, which is used to manage materials. :rtype: yagocd.resources.material.MaterialManager """ if self._material_manager is None: self._material_manager = MaterialManager(session=self._session) return self._material_manager
Property for accessing :class:`MaterialManager` instance, which is used to manage materials. :rtype: yagocd.resources.material.MaterialManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L244-L252
grundic/yagocd
yagocd/client.py
Yagocd.packages
def packages(self): """ Property for accessing :class:`PackageManager` instance, which is used to manage packages. :rtype: yagocd.resources.package.PackageManager """ if self._package_manager is None: self._package_manager = PackageManager(session=self._session) return self._package_manager
python
def packages(self): """ Property for accessing :class:`PackageManager` instance, which is used to manage packages. :rtype: yagocd.resources.package.PackageManager """ if self._package_manager is None: self._package_manager = PackageManager(session=self._session) return self._package_manager
Property for accessing :class:`PackageManager` instance, which is used to manage packages. :rtype: yagocd.resources.package.PackageManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L255-L263
grundic/yagocd
yagocd/client.py
Yagocd.package_repositories
def package_repositories(self): """ Property for accessing :class:`PackageRepositoryManager` instance, which is used to manage package repos. :rtype: yagocd.resources.package_repository.PackageRepositoryManager """ if self._package_repository_manager is None: self._package_repository_manager = PackageRepositoryManager(session=self._session) return self._package_repository_manager
python
def package_repositories(self): """ Property for accessing :class:`PackageRepositoryManager` instance, which is used to manage package repos. :rtype: yagocd.resources.package_repository.PackageRepositoryManager """ if self._package_repository_manager is None: self._package_repository_manager = PackageRepositoryManager(session=self._session) return self._package_repository_manager
Property for accessing :class:`PackageRepositoryManager` instance, which is used to manage package repos. :rtype: yagocd.resources.package_repository.PackageRepositoryManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L266-L274
grundic/yagocd
yagocd/client.py
Yagocd.pipelines
def pipelines(self): """ Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines. :rtype: yagocd.resources.pipeline.PipelineManager """ if self._pipeline_manager is None: self._pipeline_manager = PipelineManager(session=self._session) return self._pipeline_manager
python
def pipelines(self): """ Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines. :rtype: yagocd.resources.pipeline.PipelineManager """ if self._pipeline_manager is None: self._pipeline_manager = PipelineManager(session=self._session) return self._pipeline_manager
Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines. :rtype: yagocd.resources.pipeline.PipelineManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L277-L285
grundic/yagocd
yagocd/client.py
Yagocd.pipeline_configs
def pipeline_configs(self): """ Property for accessing :class:`PipelineConfigManager` instance, which is used to manage pipeline configurations. :rtype: yagocd.resources.pipeline_config.PipelineConfigManager """ if self._pipeline_config_manager is None: self._pipeline_config_manager = PipelineConfigManager(session=self._session) return self._pipeline_config_manager
python
def pipeline_configs(self): """ Property for accessing :class:`PipelineConfigManager` instance, which is used to manage pipeline configurations. :rtype: yagocd.resources.pipeline_config.PipelineConfigManager """ if self._pipeline_config_manager is None: self._pipeline_config_manager = PipelineConfigManager(session=self._session) return self._pipeline_config_manager
Property for accessing :class:`PipelineConfigManager` instance, which is used to manage pipeline configurations. :rtype: yagocd.resources.pipeline_config.PipelineConfigManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L288-L296
grundic/yagocd
yagocd/client.py
Yagocd.plugin_info
def plugin_info(self): """ Property for accessing :class:`PluginInfoManager` instance, which is used to manage pipeline configurations. :rtype: yagocd.resources.plugin_info.PluginInfoManager """ if self._plugin_info_manager is None: self._plugin_info_manager = PluginInfoManager(session=self._session) return self._plugin_info_manager
python
def plugin_info(self): """ Property for accessing :class:`PluginInfoManager` instance, which is used to manage pipeline configurations. :rtype: yagocd.resources.plugin_info.PluginInfoManager """ if self._plugin_info_manager is None: self._plugin_info_manager = PluginInfoManager(session=self._session) return self._plugin_info_manager
Property for accessing :class:`PluginInfoManager` instance, which is used to manage pipeline configurations. :rtype: yagocd.resources.plugin_info.PluginInfoManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L299-L307
grundic/yagocd
yagocd/client.py
Yagocd.properties
def properties(self): """ Property for accessing :class:`PropertyManager` instance, which is used to manage properties of the jobs. :rtype: yagocd.resources.property.PropertyManager """ if self._property_manager is None: self._property_manager = PropertyManager(session=self._session) return self._property_manager
python
def properties(self): """ Property for accessing :class:`PropertyManager` instance, which is used to manage properties of the jobs. :rtype: yagocd.resources.property.PropertyManager """ if self._property_manager is None: self._property_manager = PropertyManager(session=self._session) return self._property_manager
Property for accessing :class:`PropertyManager` instance, which is used to manage properties of the jobs. :rtype: yagocd.resources.property.PropertyManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L310-L318
grundic/yagocd
yagocd/client.py
Yagocd.scms
def scms(self): """ Property for accessing :class:`SCMManager` instance, which is used to manage pluggable SCM materials. :rtype: yagocd.resources.scm.SCMManager """ if self._scm_manager is None: self._scm_manager = SCMManager(session=self._session) return self._scm_manager
python
def scms(self): """ Property for accessing :class:`SCMManager` instance, which is used to manage pluggable SCM materials. :rtype: yagocd.resources.scm.SCMManager """ if self._scm_manager is None: self._scm_manager = SCMManager(session=self._session) return self._scm_manager
Property for accessing :class:`SCMManager` instance, which is used to manage pluggable SCM materials. :rtype: yagocd.resources.scm.SCMManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L321-L329
grundic/yagocd
yagocd/client.py
Yagocd.stages
def stages(self): """ Property for accessing :class:`StageManager` instance, which is used to manage stages. :rtype: yagocd.resources.stage.StageManager """ if self._stage_manager is None: self._stage_manager = StageManager(session=self._session) return self._stage_manager
python
def stages(self): """ Property for accessing :class:`StageManager` instance, which is used to manage stages. :rtype: yagocd.resources.stage.StageManager """ if self._stage_manager is None: self._stage_manager = StageManager(session=self._session) return self._stage_manager
Property for accessing :class:`StageManager` instance, which is used to manage stages. :rtype: yagocd.resources.stage.StageManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L332-L340
grundic/yagocd
yagocd/client.py
Yagocd.templates
def templates(self): """ Property for accessing :class:`TemplateManager` instance, which is used to manage templates. :rtype: yagocd.resources.template.TemplateManager """ if self._template_manager is None: self._template_manager = TemplateManager(session=self._session) return self._template_manager
python
def templates(self): """ Property for accessing :class:`TemplateManager` instance, which is used to manage templates. :rtype: yagocd.resources.template.TemplateManager """ if self._template_manager is None: self._template_manager = TemplateManager(session=self._session) return self._template_manager
Property for accessing :class:`TemplateManager` instance, which is used to manage templates. :rtype: yagocd.resources.template.TemplateManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L343-L351
grundic/yagocd
yagocd/client.py
Yagocd.users
def users(self): """ Property for accessing :class:`UserManager` instance, which is used to manage users. :rtype: yagocd.resources.user.UserManager """ if self._user_manager is None: self._user_manager = UserManager(session=self._session) return self._user_manager
python
def users(self): """ Property for accessing :class:`UserManager` instance, which is used to manage users. :rtype: yagocd.resources.user.UserManager """ if self._user_manager is None: self._user_manager = UserManager(session=self._session) return self._user_manager
Property for accessing :class:`UserManager` instance, which is used to manage users. :rtype: yagocd.resources.user.UserManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L354-L362
grundic/yagocd
yagocd/client.py
Yagocd.versions
def versions(self): """ Property for accessing :class:`VersionManager` instance, which is used to get server info. :rtype: yagocd.resources.version.VersionManager """ if self._version_manager is None: self._version_manager = VersionManager(session=self._session) return self._version_manager
python
def versions(self): """ Property for accessing :class:`VersionManager` instance, which is used to get server info. :rtype: yagocd.resources.version.VersionManager """ if self._version_manager is None: self._version_manager = VersionManager(session=self._session) return self._version_manager
Property for accessing :class:`VersionManager` instance, which is used to get server info. :rtype: yagocd.resources.version.VersionManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L365-L373
grundic/yagocd
yagocd/resources/pipeline.py
PipelineEntity.url
def url(self): """ Returns url for accessing pipeline entity. """ return self.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)
python
def url(self): """ Returns url for accessing pipeline entity. """ return self.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)
Returns url for accessing pipeline entity.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L459-L463
grundic/yagocd
yagocd/resources/pipeline.py
PipelineEntity.config
def config(self): """ Property for accessing pipeline configuration. :rtype: yagocd.resources.pipeline_config.PipelineConfigManager """ return PipelineConfigManager(session=self._session, pipeline_name=self.data.name)
python
def config(self): """ Property for accessing pipeline configuration. :rtype: yagocd.resources.pipeline_config.PipelineConfigManager """ return PipelineConfigManager(session=self._session, pipeline_name=self.data.name)
Property for accessing pipeline configuration. :rtype: yagocd.resources.pipeline_config.PipelineConfigManager
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L466-L472
grundic/yagocd
yagocd/resources/pipeline.py
PipelineEntity.history
def history(self, offset=0): """ The pipeline history allows users to list pipeline instances. :param offset: number of pipeline instances to be skipped. :return: an array of pipeline instances :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: list of yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.history(name=self.data.name, offset=offset)
python
def history(self, offset=0): """ The pipeline history allows users to list pipeline instances. :param offset: number of pipeline instances to be skipped. :return: an array of pipeline instances :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: list of yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.history(name=self.data.name, offset=offset)
The pipeline history allows users to list pipeline instances. :param offset: number of pipeline instances to be skipped. :return: an array of pipeline instances :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: list of yagocd.resources.pipeline.PipelineInstance
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L474-L482
grundic/yagocd
yagocd/resources/pipeline.py
PipelineEntity.get
def get(self, counter): """ Gets pipeline instance object. :param counter pipeline counter: :return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.get(name=self.data.name, counter=counter)
python
def get(self, counter): """ Gets pipeline instance object. :param counter pipeline counter: :return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.get(name=self.data.name, counter=counter)
Gets pipeline instance object. :param counter pipeline counter: :return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: yagocd.resources.pipeline.PipelineInstance
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L502-L510
grundic/yagocd
yagocd/resources/pipeline.py
PipelineEntity.pause
def pause(self, cause): """ Pause the current pipeline. :param cause: reason for pausing the pipeline. """ self._pipeline.pause(name=self.data.name, cause=cause)
python
def pause(self, cause): """ Pause the current pipeline. :param cause: reason for pausing the pipeline. """ self._pipeline.pause(name=self.data.name, cause=cause)
Pause the current pipeline. :param cause: reason for pausing the pipeline.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L520-L526
grundic/yagocd
yagocd/resources/pipeline.py
PipelineEntity.schedule
def schedule(self, materials=None, variables=None, secure_variables=None): """ Scheduling allows user to trigger a specific pipeline. :param materials: material revisions to use. :param variables: environment variables to set. :param secure_variables: secure environment variables to set. :return: a text confirmation. """ return self._pipeline.schedule( name=self.data.name, materials=materials, variables=variables, secure_variables=secure_variables )
python
def schedule(self, materials=None, variables=None, secure_variables=None): """ Scheduling allows user to trigger a specific pipeline. :param materials: material revisions to use. :param variables: environment variables to set. :param secure_variables: secure environment variables to set. :return: a text confirmation. """ return self._pipeline.schedule( name=self.data.name, materials=materials, variables=variables, secure_variables=secure_variables )
Scheduling allows user to trigger a specific pipeline. :param materials: material revisions to use. :param variables: environment variables to set. :param secure_variables: secure environment variables to set. :return: a text confirmation.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L543-L557
grundic/yagocd
yagocd/resources/pipeline.py
PipelineEntity.schedule_with_instance
def schedule_with_instance( self, materials=None, variables=None, secure_variables=None, backoff=0.5, max_tries=20 ): """ Schedule pipeline and return instance. Credits of implementation comes to `gaqzi`: https://github.com/gaqzi/py-gocd/blob/master/gocd/api/pipeline.py#L122 :warning: Replace this with whatever is the official way as soon as gocd#990 is fixed. \ https://github.com/gocd/gocd/issues/990 :param materials: material revisions to use. :param variables: environment variables to set. :param secure_variables: secure environment variables to set. :param backoff: time to wait before checking for new instance. :param max_tries: maximum tries to do. :return: possible triggered instance of pipeline. :rtype: yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.schedule_with_instance( name=self.data.name, materials=materials, variables=variables, secure_variables=secure_variables, backoff=backoff, max_tries=max_tries )
python
def schedule_with_instance( self, materials=None, variables=None, secure_variables=None, backoff=0.5, max_tries=20 ): """ Schedule pipeline and return instance. Credits of implementation comes to `gaqzi`: https://github.com/gaqzi/py-gocd/blob/master/gocd/api/pipeline.py#L122 :warning: Replace this with whatever is the official way as soon as gocd#990 is fixed. \ https://github.com/gocd/gocd/issues/990 :param materials: material revisions to use. :param variables: environment variables to set. :param secure_variables: secure environment variables to set. :param backoff: time to wait before checking for new instance. :param max_tries: maximum tries to do. :return: possible triggered instance of pipeline. :rtype: yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.schedule_with_instance( name=self.data.name, materials=materials, variables=variables, secure_variables=secure_variables, backoff=backoff, max_tries=max_tries )
Schedule pipeline and return instance. Credits of implementation comes to `gaqzi`: https://github.com/gaqzi/py-gocd/blob/master/gocd/api/pipeline.py#L122 :warning: Replace this with whatever is the official way as soon as gocd#990 is fixed. \ https://github.com/gocd/gocd/issues/990 :param materials: material revisions to use. :param variables: environment variables to set. :param secure_variables: secure environment variables to set. :param backoff: time to wait before checking for new instance. :param max_tries: maximum tries to do. :return: possible triggered instance of pipeline. :rtype: yagocd.resources.pipeline.PipelineInstance
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L559-L590
grundic/yagocd
yagocd/resources/pipeline.py
PipelineInstance.pipeline_url
def pipeline_url(self): """ Returns url for accessing pipeline entity. """ return PipelineEntity.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)
python
def pipeline_url(self): """ Returns url for accessing pipeline entity. """ return PipelineEntity.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)
Returns url for accessing pipeline entity.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L636-L640
grundic/yagocd
yagocd/resources/pipeline.py
PipelineInstance.stages
def stages(self): """ Method for getting stages from pipeline instance. :return: arrays of stages :rtype: list of yagocd.resources.stage.StageInstance """ stages = list() for data in self.data.stages: stages.append(StageInstance(session=self._session, data=data, pipeline=self)) return stages
python
def stages(self): """ Method for getting stages from pipeline instance. :return: arrays of stages :rtype: list of yagocd.resources.stage.StageInstance """ stages = list() for data in self.data.stages: stages.append(StageInstance(session=self._session, data=data, pipeline=self)) return stages
Method for getting stages from pipeline instance. :return: arrays of stages :rtype: list of yagocd.resources.stage.StageInstance
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L642-L653
grundic/yagocd
yagocd/resources/pipeline.py
PipelineInstance.stage
def stage(self, name): """ Method for searching specific stage by it's name. :param name: name of the stage to search. :return: found stage or None. :rtype: yagocd.resources.stage.StageInstance """ for stage in self.stages(): if stage.data.name == name: return stage
python
def stage(self, name): """ Method for searching specific stage by it's name. :param name: name of the stage to search. :return: found stage or None. :rtype: yagocd.resources.stage.StageInstance """ for stage in self.stages(): if stage.data.name == name: return stage
Method for searching specific stage by it's name. :param name: name of the stage to search. :return: found stage or None. :rtype: yagocd.resources.stage.StageInstance
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L655-L665
grundic/yagocd
yagocd/util.py
RequireParamMixin._require_param
def _require_param(self, name, values): """ Method for finding the value for the given parameter name. The value for the parameter could be extracted from two places: * `values` dictionary * `self._<name>` attribute The use case for this method is that some resources are nested and managers could have dependencies on parent data, for example :class:`ArtifactManager` should know about pipeline, stage and job in order to get data for specific instance of artifact. In case we obtain this information from pipeline and going down to the artifact, it will be provided in constructor for that manager. But in case we would like to use functionality of specific manager without getting parents -- directly from :class:`Yagocd`, then we have to be able to execute method with given parameters for parents. Current method - `_require_param` - is used to find out which parameters should one use: either provided at construction time and stored as `self._<name>` or provided as function arguments. :param name: name of the parameter, which value to extract. :param values: dictionary, which could contain the value for our parameter. :return: founded value or raises `ValueError`. """ values = [values[name]] instance_name = '_{}'.format(name) values.append(getattr(self, instance_name, None)) try: return next(item for item in values if item is not None) except StopIteration: raise ValueError("The value for parameter '{}' is required!".format(name))
python
def _require_param(self, name, values): """ Method for finding the value for the given parameter name. The value for the parameter could be extracted from two places: * `values` dictionary * `self._<name>` attribute The use case for this method is that some resources are nested and managers could have dependencies on parent data, for example :class:`ArtifactManager` should know about pipeline, stage and job in order to get data for specific instance of artifact. In case we obtain this information from pipeline and going down to the artifact, it will be provided in constructor for that manager. But in case we would like to use functionality of specific manager without getting parents -- directly from :class:`Yagocd`, then we have to be able to execute method with given parameters for parents. Current method - `_require_param` - is used to find out which parameters should one use: either provided at construction time and stored as `self._<name>` or provided as function arguments. :param name: name of the parameter, which value to extract. :param values: dictionary, which could contain the value for our parameter. :return: founded value or raises `ValueError`. """ values = [values[name]] instance_name = '_{}'.format(name) values.append(getattr(self, instance_name, None)) try: return next(item for item in values if item is not None) except StopIteration: raise ValueError("The value for parameter '{}' is required!".format(name))
Method for finding the value for the given parameter name. The value for the parameter could be extracted from two places: * `values` dictionary * `self._<name>` attribute The use case for this method is that some resources are nested and managers could have dependencies on parent data, for example :class:`ArtifactManager` should know about pipeline, stage and job in order to get data for specific instance of artifact. In case we obtain this information from pipeline and going down to the artifact, it will be provided in constructor for that manager. But in case we would like to use functionality of specific manager without getting parents -- directly from :class:`Yagocd`, then we have to be able to execute method with given parameters for parents. Current method - `_require_param` - is used to find out which parameters should one use: either provided at construction time and stored as `self._<name>` or provided as function arguments. :param name: name of the parameter, which value to extract. :param values: dictionary, which could contain the value for our parameter. :return: founded value or raises `ValueError`.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/util.py#L121-L155
grundic/yagocd
yagocd/resources/__init__.py
BaseManager._accept_header
def _accept_header(self): """ Method for determining correct `Accept` header. Different resources and different GoCD version servers prefer a diverse headers. In order to manage all of them, this method tries to help: if `VERSION_TO_ACCEPT_HEADER` is not provided, if would simply return default `ACCEPT_HEADER`. Though if some manager specifies `VERSION_TO_ACCEPT_HEADER` class variable, then it should be a dictionary: keys should be a versions and values should be desired accept headers. Choosing is pessimistic: if version of a server is less or equal to one of the dictionary, the value of that key would be used. :return: accept header to use in request. """ if not self.VERSION_TO_ACCEPT_HEADER: return self.ACCEPT_HEADER return YagocdUtil.choose_option( version_to_options=self.VERSION_TO_ACCEPT_HEADER, default=self.ACCEPT_HEADER, server_version=self._session.server_version )
python
def _accept_header(self): """ Method for determining correct `Accept` header. Different resources and different GoCD version servers prefer a diverse headers. In order to manage all of them, this method tries to help: if `VERSION_TO_ACCEPT_HEADER` is not provided, if would simply return default `ACCEPT_HEADER`. Though if some manager specifies `VERSION_TO_ACCEPT_HEADER` class variable, then it should be a dictionary: keys should be a versions and values should be desired accept headers. Choosing is pessimistic: if version of a server is less or equal to one of the dictionary, the value of that key would be used. :return: accept header to use in request. """ if not self.VERSION_TO_ACCEPT_HEADER: return self.ACCEPT_HEADER return YagocdUtil.choose_option( version_to_options=self.VERSION_TO_ACCEPT_HEADER, default=self.ACCEPT_HEADER, server_version=self._session.server_version )
Method for determining correct `Accept` header. Different resources and different GoCD version servers prefer a diverse headers. In order to manage all of them, this method tries to help: if `VERSION_TO_ACCEPT_HEADER` is not provided, if would simply return default `ACCEPT_HEADER`. Though if some manager specifies `VERSION_TO_ACCEPT_HEADER` class variable, then it should be a dictionary: keys should be a versions and values should be desired accept headers. Choosing is pessimistic: if version of a server is less or equal to one of the dictionary, the value of that key would be used. :return: accept header to use in request.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/__init__.py#L57-L81
grundic/yagocd
yagocd/resources/__init__.py
BaseNode.get_predecessors
def get_predecessors(self, transitive=False): """ Property for getting predecessors (parents) of current pipeline. This property automatically populates from API call :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.PipelineEntity """ result = self._predecessors if transitive: return YagocdUtil.graph_depth_walk(result, lambda v: v.predecessors) return result
python
def get_predecessors(self, transitive=False): """ Property for getting predecessors (parents) of current pipeline. This property automatically populates from API call :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.PipelineEntity """ result = self._predecessors if transitive: return YagocdUtil.graph_depth_walk(result, lambda v: v.predecessors) return result
Property for getting predecessors (parents) of current pipeline. This property automatically populates from API call :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.PipelineEntity
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/__init__.py#L114-L125
grundic/yagocd
yagocd/resources/__init__.py
BaseNode.get_descendants
def get_descendants(self, transitive=False): """ Property for getting descendants (children) of current pipeline. It's calculated by :meth:`yagocd.resources.pipeline.PipelineManager#tie_descendants` method during listing of all pipelines. :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.PipelineEntity """ result = self._descendants if transitive: return YagocdUtil.graph_depth_walk(result, lambda v: v.descendants) return result
python
def get_descendants(self, transitive=False): """ Property for getting descendants (children) of current pipeline. It's calculated by :meth:`yagocd.resources.pipeline.PipelineManager#tie_descendants` method during listing of all pipelines. :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.PipelineEntity """ result = self._descendants if transitive: return YagocdUtil.graph_depth_walk(result, lambda v: v.descendants) return result
Property for getting descendants (children) of current pipeline. It's calculated by :meth:`yagocd.resources.pipeline.PipelineManager#tie_descendants` method during listing of all pipelines. :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.PipelineEntity
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/__init__.py#L132-L144
grundic/yagocd
yagocd/resources/artifact.py
Artifact.walk
def walk(self, topdown=True): """ Artifact tree generator - analogue of `os.walk`. :param topdown: if is True or not specified, directories are scanned from top-down. If topdown is set to False, directories are scanned from bottom-up. :rtype: collections.Iterator[ (str, list[yagocd.resources.artifact.Artifact], list[yagocd.resources.artifact.Artifact]) ] """ return self._manager.walk(top=self._path, topdown=topdown)
python
def walk(self, topdown=True): """ Artifact tree generator - analogue of `os.walk`. :param topdown: if is True or not specified, directories are scanned from top-down. If topdown is set to False, directories are scanned from bottom-up. :rtype: collections.Iterator[ (str, list[yagocd.resources.artifact.Artifact], list[yagocd.resources.artifact.Artifact]) ] """ return self._manager.walk(top=self._path, topdown=topdown)
Artifact tree generator - analogue of `os.walk`. :param topdown: if is True or not specified, directories are scanned from top-down. If topdown is set to False, directories are scanned from bottom-up. :rtype: collections.Iterator[ (str, list[yagocd.resources.artifact.Artifact], list[yagocd.resources.artifact.Artifact]) ]
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/artifact.py#L515-L526
grundic/yagocd
yagocd/resources/artifact.py
Artifact.fetch
def fetch(self): """ Method for getting artifact's content. Could only be applicable for file type. :return: content of the artifact. """ if self.data.type == self._manager.FOLDER_TYPE: raise YagocdException("Can't fetch folder <{}>, only file!".format(self._path)) response = self._session.get(self.data.url) return response.content
python
def fetch(self): """ Method for getting artifact's content. Could only be applicable for file type. :return: content of the artifact. """ if self.data.type == self._manager.FOLDER_TYPE: raise YagocdException("Can't fetch folder <{}>, only file!".format(self._path)) response = self._session.get(self.data.url) return response.content
Method for getting artifact's content. Could only be applicable for file type. :return: content of the artifact.
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/artifact.py#L528-L539
jupyterhub/ltiauthenticator
ltiauthenticator/__init__.py
LTILaunchValidator.validate_launch_request
def validate_launch_request( self, launch_url, headers, args ): """ Validate a given launch request launch_url: Full URL that the launch request was POSTed to headers: k/v pair of HTTP headers coming in with the POST args: dictionary of body arguments passed to the launch_url Must have the following keys to be valid: oauth_consumer_key, oauth_timestamp, oauth_nonce, oauth_signature """ # Validate args! if 'oauth_consumer_key' not in args: raise web.HTTPError(401, "oauth_consumer_key missing") if args['oauth_consumer_key'] not in self.consumers: raise web.HTTPError(401, "oauth_consumer_key not known") if 'oauth_signature' not in args: raise web.HTTPError(401, "oauth_signature missing") if 'oauth_timestamp' not in args: raise web.HTTPError(401, 'oauth_timestamp missing') # Allow 30s clock skew between LTI Consumer and Provider # Also don't accept timestamps from before our process started, since that could be # a replay attack - we won't have nonce lists from back then. This would allow users # who can control / know when our process restarts to trivially do replay attacks. oauth_timestamp = int(float(args['oauth_timestamp'])) if ( int(time.time()) - oauth_timestamp > 30 or oauth_timestamp < LTILaunchValidator.PROCESS_START_TIME ): raise web.HTTPError(401, "oauth_timestamp too old") if 'oauth_nonce' not in args: raise web.HTTPError(401, 'oauth_nonce missing') if ( oauth_timestamp in LTILaunchValidator.nonces and args['oauth_nonce'] in LTILaunchValidator.nonces[oauth_timestamp] ): raise web.HTTPError(401, "oauth_nonce + oauth_timestamp already used") LTILaunchValidator.nonces.setdefault(oauth_timestamp, set()).add(args['oauth_nonce']) args_list = [] for key, values in args.items(): if type(values) is list: args_list += [(key, value) for value in values] else: args_list.append((key, values)) base_string = signature.construct_base_string( 'POST', signature.normalize_base_string_uri(launch_url), signature.normalize_parameters( signature.collect_parameters(body=args_list, headers=headers) ) ) consumer_secret = self.consumers[args['oauth_consumer_key']] sign = signature.sign_hmac_sha1(base_string, consumer_secret, None) is_valid = signature.safe_string_equals(sign, args['oauth_signature']) if not is_valid: raise web.HTTPError(401, "Invalid oauth_signature") return True
python
def validate_launch_request( self, launch_url, headers, args ): """ Validate a given launch request launch_url: Full URL that the launch request was POSTed to headers: k/v pair of HTTP headers coming in with the POST args: dictionary of body arguments passed to the launch_url Must have the following keys to be valid: oauth_consumer_key, oauth_timestamp, oauth_nonce, oauth_signature """ # Validate args! if 'oauth_consumer_key' not in args: raise web.HTTPError(401, "oauth_consumer_key missing") if args['oauth_consumer_key'] not in self.consumers: raise web.HTTPError(401, "oauth_consumer_key not known") if 'oauth_signature' not in args: raise web.HTTPError(401, "oauth_signature missing") if 'oauth_timestamp' not in args: raise web.HTTPError(401, 'oauth_timestamp missing') # Allow 30s clock skew between LTI Consumer and Provider # Also don't accept timestamps from before our process started, since that could be # a replay attack - we won't have nonce lists from back then. This would allow users # who can control / know when our process restarts to trivially do replay attacks. oauth_timestamp = int(float(args['oauth_timestamp'])) if ( int(time.time()) - oauth_timestamp > 30 or oauth_timestamp < LTILaunchValidator.PROCESS_START_TIME ): raise web.HTTPError(401, "oauth_timestamp too old") if 'oauth_nonce' not in args: raise web.HTTPError(401, 'oauth_nonce missing') if ( oauth_timestamp in LTILaunchValidator.nonces and args['oauth_nonce'] in LTILaunchValidator.nonces[oauth_timestamp] ): raise web.HTTPError(401, "oauth_nonce + oauth_timestamp already used") LTILaunchValidator.nonces.setdefault(oauth_timestamp, set()).add(args['oauth_nonce']) args_list = [] for key, values in args.items(): if type(values) is list: args_list += [(key, value) for value in values] else: args_list.append((key, values)) base_string = signature.construct_base_string( 'POST', signature.normalize_base_string_uri(launch_url), signature.normalize_parameters( signature.collect_parameters(body=args_list, headers=headers) ) ) consumer_secret = self.consumers[args['oauth_consumer_key']] sign = signature.sign_hmac_sha1(base_string, consumer_secret, None) is_valid = signature.safe_string_equals(sign, args['oauth_signature']) if not is_valid: raise web.HTTPError(401, "Invalid oauth_signature") return True
Validate a given launch request launch_url: Full URL that the launch request was POSTed to headers: k/v pair of HTTP headers coming in with the POST args: dictionary of body arguments passed to the launch_url Must have the following keys to be valid: oauth_consumer_key, oauth_timestamp, oauth_nonce, oauth_signature
https://github.com/jupyterhub/ltiauthenticator/blob/ae4d95959116c5a2c5d3cbefa6a3ee1be574cc4e/ltiauthenticator/__init__.py#L25-L97
lightning-viz/lightning-python
lightning/main.py
Lightning.enable_ipython
def enable_ipython(self, **kwargs): """ Enable plotting in the iPython notebook. Once enabled, all lightning plots will be automatically produced within the iPython notebook. They will also be available on your lightning server within the current session. """ # inspired by code powering similar functionality in mpld3 # https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L357 from IPython.core.getipython import get_ipython from IPython.display import display, Javascript, HTML self.ipython_enabled = True self.set_size('medium') ip = get_ipython() formatter = ip.display_formatter.formatters['text/html'] if self.local_enabled: from lightning.visualization import VisualizationLocal js = VisualizationLocal.load_embed() display(HTML("<script>" + js + "</script>")) if not self.quiet: print('Running local mode, some functionality limited.\n') formatter.for_type(VisualizationLocal, lambda viz, kwds=kwargs: viz.get_html()) else: formatter.for_type(Visualization, lambda viz, kwds=kwargs: viz.get_html()) r = requests.get(self.get_ipython_markup_link(), auth=self.auth) display(Javascript(r.text))
python
def enable_ipython(self, **kwargs): """ Enable plotting in the iPython notebook. Once enabled, all lightning plots will be automatically produced within the iPython notebook. They will also be available on your lightning server within the current session. """ # inspired by code powering similar functionality in mpld3 # https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L357 from IPython.core.getipython import get_ipython from IPython.display import display, Javascript, HTML self.ipython_enabled = True self.set_size('medium') ip = get_ipython() formatter = ip.display_formatter.formatters['text/html'] if self.local_enabled: from lightning.visualization import VisualizationLocal js = VisualizationLocal.load_embed() display(HTML("<script>" + js + "</script>")) if not self.quiet: print('Running local mode, some functionality limited.\n') formatter.for_type(VisualizationLocal, lambda viz, kwds=kwargs: viz.get_html()) else: formatter.for_type(Visualization, lambda viz, kwds=kwargs: viz.get_html()) r = requests.get(self.get_ipython_markup_link(), auth=self.auth) display(Javascript(r.text))
Enable plotting in the iPython notebook. Once enabled, all lightning plots will be automatically produced within the iPython notebook. They will also be available on your lightning server within the current session.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L52-L83
lightning-viz/lightning-python
lightning/main.py
Lightning.disable_ipython
def disable_ipython(self): """ Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook. """ from IPython.core.getipython import get_ipython self.ipython_enabled = False ip = get_ipython() formatter = ip.display_formatter.formatters['text/html'] formatter.type_printers.pop(Visualization, None) formatter.type_printers.pop(VisualizationLocal, None)
python
def disable_ipython(self): """ Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook. """ from IPython.core.getipython import get_ipython self.ipython_enabled = False ip = get_ipython() formatter = ip.display_formatter.formatters['text/html'] formatter.type_printers.pop(Visualization, None) formatter.type_printers.pop(VisualizationLocal, None)
Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L85-L98
lightning-viz/lightning-python
lightning/main.py
Lightning.create_session
def create_session(self, name=None): """ Create a lightning session. Can create a session with the provided name, otherwise session name will be "Session No." with the number automatically generated. """ self.session = Session.create(self, name=name) return self.session
python
def create_session(self, name=None): """ Create a lightning session. Can create a session with the provided name, otherwise session name will be "Session No." with the number automatically generated. """ self.session = Session.create(self, name=name) return self.session
Create a lightning session. Can create a session with the provided name, otherwise session name will be "Session No." with the number automatically generated.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L100-L108
lightning-viz/lightning-python
lightning/main.py
Lightning.use_session
def use_session(self, session_id): """ Use the specified lightning session. Specify a lightning session by id number. Check the number of an existing session in the attribute lightning.session.id. """ self.session = Session(lgn=self, id=session_id) return self.session
python
def use_session(self, session_id): """ Use the specified lightning session. Specify a lightning session by id number. Check the number of an existing session in the attribute lightning.session.id. """ self.session = Session(lgn=self, id=session_id) return self.session
Use the specified lightning session. Specify a lightning session by id number. Check the number of an existing session in the attribute lightning.session.id.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L110-L118
lightning-viz/lightning-python
lightning/main.py
Lightning.set_basic_auth
def set_basic_auth(self, username, password): """ Set authenatication. """ from requests.auth import HTTPBasicAuth self.auth = HTTPBasicAuth(username, password) return self
python
def set_basic_auth(self, username, password): """ Set authenatication. """ from requests.auth import HTTPBasicAuth self.auth = HTTPBasicAuth(username, password) return self
Set authenatication.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L136-L142
lightning-viz/lightning-python
lightning/main.py
Lightning.set_host
def set_host(self, host): """ Set the host for a lightning server. Host can be local (e.g. http://localhost:3000), a heroku instance (e.g. http://lightning-test.herokuapp.com), or a independently hosted lightning server. """ if host[-1] == '/': host = host[:-1] self.host = host return self
python
def set_host(self, host): """ Set the host for a lightning server. Host can be local (e.g. http://localhost:3000), a heroku instance (e.g. http://lightning-test.herokuapp.com), or a independently hosted lightning server. """ if host[-1] == '/': host = host[:-1] self.host = host return self
Set the host for a lightning server. Host can be local (e.g. http://localhost:3000), a heroku instance (e.g. http://lightning-test.herokuapp.com), or a independently hosted lightning server.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L144-L156
lightning-viz/lightning-python
lightning/main.py
Lightning.check_status
def check_status(self): """ Check the server for status """ try: r = requests.get(self.host + '/status', auth=self.auth, timeout=(10.0, 10.0)) if not r.status_code == requests.codes.ok: print("Problem connecting to server at %s" % self.host) print("status code: %s" % r.status_code) return False else: print("Connected to server at %s" % self.host) return True except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema) as e: print("Problem connecting to server at %s" % self.host) print("error: %s" % e) return False
python
def check_status(self): """ Check the server for status """ try: r = requests.get(self.host + '/status', auth=self.auth, timeout=(10.0, 10.0)) if not r.status_code == requests.codes.ok: print("Problem connecting to server at %s" % self.host) print("status code: %s" % r.status_code) return False else: print("Connected to server at %s" % self.host) return True except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema) as e: print("Problem connecting to server at %s" % self.host) print("error: %s" % e) return False
Check the server for status
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L169-L188
lightning-viz/lightning-python
lightning/types/base.py
Base._clean_data
def _clean_data(cls, *args, **kwargs): """ Convert raw data into a dictionary with plot-type specific methods. The result of the cleaning operation should be a dictionary. If the dictionary contains a 'data' field it will be passed directly (ensuring appropriate formatting). Otherwise, it should be a dictionary of data-type specific array data (e.g. 'points', 'timeseries'), which will be labeled appropriately (see _check_unkeyed_arrays). """ datadict = cls.clean(*args, **kwargs) if 'data' in datadict: data = datadict['data'] data = cls._ensure_dict_or_list(data) else: data = {} for key in datadict: if key == 'images': data[key] = datadict[key] else: d = cls._ensure_dict_or_list(datadict[key]) data[key] = cls._check_unkeyed_arrays(key, d) return data
python
def _clean_data(cls, *args, **kwargs): """ Convert raw data into a dictionary with plot-type specific methods. The result of the cleaning operation should be a dictionary. If the dictionary contains a 'data' field it will be passed directly (ensuring appropriate formatting). Otherwise, it should be a dictionary of data-type specific array data (e.g. 'points', 'timeseries'), which will be labeled appropriately (see _check_unkeyed_arrays). """ datadict = cls.clean(*args, **kwargs) if 'data' in datadict: data = datadict['data'] data = cls._ensure_dict_or_list(data) else: data = {} for key in datadict: if key == 'images': data[key] = datadict[key] else: d = cls._ensure_dict_or_list(datadict[key]) data[key] = cls._check_unkeyed_arrays(key, d) return data
Convert raw data into a dictionary with plot-type specific methods. The result of the cleaning operation should be a dictionary. If the dictionary contains a 'data' field it will be passed directly (ensuring appropriate formatting). Otherwise, it should be a dictionary of data-type specific array data (e.g. 'points', 'timeseries'), which will be labeled appropriately (see _check_unkeyed_arrays).
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L80-L106
lightning-viz/lightning-python
lightning/types/base.py
Base._baseplot
def _baseplot(cls, session, type, *args, **kwargs): """ Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all plot-type specific positional and keyword arguments, which will be handled by the clean method of the given plot type. If the dictionary contains only images, or only non-image data, they will be passed on their own. If the dictionary contains both images and non-image data, the images will be appended to the visualization. """ if not type: raise Exception("Must provide a plot type") options, description = cls._clean_options(**kwargs) data = cls._clean_data(*args) if 'images' in data and len(data) > 1: images = data['images'] del data['images'] viz = cls._create(session, data=data, type=type, options=options, description=description) first_image, remaining_images = images[0], images[1:] viz._append_image(first_image) for image in remaining_images: viz._append_image(image) elif 'images' in data: images = data['images'] viz = cls._create(session, images=images, type=type, options=options, description=description) else: viz = cls._create(session, data=data, type=type, options=options, description=description) return viz
python
def _baseplot(cls, session, type, *args, **kwargs): """ Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all plot-type specific positional and keyword arguments, which will be handled by the clean method of the given plot type. If the dictionary contains only images, or only non-image data, they will be passed on their own. If the dictionary contains both images and non-image data, the images will be appended to the visualization. """ if not type: raise Exception("Must provide a plot type") options, description = cls._clean_options(**kwargs) data = cls._clean_data(*args) if 'images' in data and len(data) > 1: images = data['images'] del data['images'] viz = cls._create(session, data=data, type=type, options=options, description=description) first_image, remaining_images = images[0], images[1:] viz._append_image(first_image) for image in remaining_images: viz._append_image(image) elif 'images' in data: images = data['images'] viz = cls._create(session, images=images, type=type, options=options, description=description) else: viz = cls._create(session, data=data, type=type, options=options, description=description) return viz
Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all plot-type specific positional and keyword arguments, which will be handled by the clean method of the given plot type. If the dictionary contains only images, or only non-image data, they will be passed on their own. If the dictionary contains both images and non-image data, the images will be appended to the visualization.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L141-L179
lightning-viz/lightning-python
lightning/types/base.py
Base.update
def update(self, *args, **kwargs): """ Base method for updating data. Applies a plot-type specific cleaning operation, then updates the data in the visualization. """ data = self._clean_data(*args, **kwargs) if 'images' in data: images = data['images'] for img in images: self._update_image(img) else: self._update_data(data=data)
python
def update(self, *args, **kwargs): """ Base method for updating data. Applies a plot-type specific cleaning operation, then updates the data in the visualization. """ data = self._clean_data(*args, **kwargs) if 'images' in data: images = data['images'] for img in images: self._update_image(img) else: self._update_data(data=data)
Base method for updating data. Applies a plot-type specific cleaning operation, then updates the data in the visualization.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L181-L195
lightning-viz/lightning-python
lightning/types/base.py
Base.append
def append(self, *args, **kwargs): """ Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization. """ data = self._clean_data(*args, **kwargs) if 'images' in data: images = data['images'] for img in images: self._append_image(img) else: self._append_data(data=data)
python
def append(self, *args, **kwargs): """ Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization. """ data = self._clean_data(*args, **kwargs) if 'images' in data: images = data['images'] for img in images: self._append_image(img) else: self._append_data(data=data)
Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L197-L211
lightning-viz/lightning-python
lightning/types/base.py
Base._get_user_data
def _get_user_data(self): """ Base method for retrieving user data from a viz. """ url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/settings/' r = requests.get(url) if r.status_code == 200: content = r.json() else: raise Exception('Error retrieving user data from server') return content
python
def _get_user_data(self): """ Base method for retrieving user data from a viz. """ url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/settings/' r = requests.get(url) if r.status_code == 200: content = r.json() else: raise Exception('Error retrieving user data from server') return content
Base method for retrieving user data from a viz.
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L213-L225
lightning-viz/lightning-python
lightning/types/utils.py
check_property
def check_property(prop, name, **kwargs): """ Check and parse a property with either a specific checking function or a generic parser """ checkers = { 'color': check_color, 'alpha': check_alpha, 'size': check_size, 'thickness': check_thickness, 'index': check_index, 'coordinates': check_coordinates, 'colormap': check_colormap, 'bins': check_bins, 'spec': check_spec } if name in checkers: return checkers[name](prop, **kwargs) elif isinstance(prop, list) or isinstance(prop, ndarray) or isscalar(prop): return check_1d(prop, name) else: return prop
python
def check_property(prop, name, **kwargs): """ Check and parse a property with either a specific checking function or a generic parser """ checkers = { 'color': check_color, 'alpha': check_alpha, 'size': check_size, 'thickness': check_thickness, 'index': check_index, 'coordinates': check_coordinates, 'colormap': check_colormap, 'bins': check_bins, 'spec': check_spec } if name in checkers: return checkers[name](prop, **kwargs) elif isinstance(prop, list) or isinstance(prop, ndarray) or isscalar(prop): return check_1d(prop, name) else: return prop
Check and parse a property with either a specific checking function or a generic parser
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L16-L39
lightning-viz/lightning-python
lightning/types/utils.py
check_coordinates
def check_coordinates(co, xy=None): """ Check and parse coordinates as either a single coordinate list [[r,c],[r,c]] or a list of coordinates for multiple regions [[[r0,c0],[r0,c0]], [[r1,c1],[r1,c1]]] """ if isinstance(co, ndarray): co = co.tolist() if not (isinstance(co[0][0], list) or isinstance(co[0][0], tuple)): co = [co] if xy is not True: co = map(lambda p: asarray(p)[:, ::-1].tolist(), co) return co
python
def check_coordinates(co, xy=None): """ Check and parse coordinates as either a single coordinate list [[r,c],[r,c]] or a list of coordinates for multiple regions [[[r0,c0],[r0,c0]], [[r1,c1],[r1,c1]]] """ if isinstance(co, ndarray): co = co.tolist() if not (isinstance(co[0][0], list) or isinstance(co[0][0], tuple)): co = [co] if xy is not True: co = map(lambda p: asarray(p)[:, ::-1].tolist(), co) return co
Check and parse coordinates as either a single coordinate list [[r,c],[r,c]] or a list of coordinates for multiple regions [[[r0,c0],[r0,c0]], [[r1,c1],[r1,c1]]]
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L42-L53
lightning-viz/lightning-python
lightning/types/utils.py
check_color
def check_color(c): """ Check and parse color specs as either a single [r,g,b] or a list of [[r,g,b],[r,g,b]...] """ c = asarray(c) if c.ndim == 1: c = c.flatten() c = c[newaxis, :] if c.shape[1] != 3: raise Exception("Color must have three values per point") elif c.ndim == 2: if c.shape[1] != 3: raise Exception("Color array must have three values per point") return c
python
def check_color(c): """ Check and parse color specs as either a single [r,g,b] or a list of [[r,g,b],[r,g,b]...] """ c = asarray(c) if c.ndim == 1: c = c.flatten() c = c[newaxis, :] if c.shape[1] != 3: raise Exception("Color must have three values per point") elif c.ndim == 2: if c.shape[1] != 3: raise Exception("Color array must have three values per point") return c
Check and parse color specs as either a single [r,g,b] or a list of [[r,g,b],[r,g,b]...]
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L59-L74
lightning-viz/lightning-python
lightning/types/utils.py
check_colormap
def check_colormap(cmap): """ Check if cmap is one of the colorbrewer maps """ names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Lightning']) if cmap not in names: raise Exception("Invalid cmap '%s', must be one of %s" % (cmap, names)) else: return cmap
python
def check_colormap(cmap): """ Check if cmap is one of the colorbrewer maps """ names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Lightning']) if cmap not in names: raise Exception("Invalid cmap '%s', must be one of %s" % (cmap, names)) else: return cmap
Check if cmap is one of the colorbrewer maps
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L77-L88
lightning-viz/lightning-python
lightning/types/utils.py
check_size
def check_size(s): """ Check and parse size specs as either a single [s] or a list of [s,s,s,...] """ s = check_1d(s, "size") if any(map(lambda d: d <= 0, s)): raise Exception('Size cannot be 0 or negative') return s
python
def check_size(s): """ Check and parse size specs as either a single [s] or a list of [s,s,s,...] """ s = check_1d(s, "size") if any(map(lambda d: d <= 0, s)): raise Exception('Size cannot be 0 or negative') return s
Check and parse size specs as either a single [s] or a list of [s,s,s,...]
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L91-L100
lightning-viz/lightning-python
lightning/types/utils.py
check_thickness
def check_thickness(s): """ Check and parse thickness specs as either a single [s] or a list of [s,s,s,...] """ s = check_1d(s, "thickness") if any(map(lambda d: d <= 0, s)): raise Exception('Thickness cannot be 0 or negative') return s
python
def check_thickness(s): """ Check and parse thickness specs as either a single [s] or a list of [s,s,s,...] """ s = check_1d(s, "thickness") if any(map(lambda d: d <= 0, s)): raise Exception('Thickness cannot be 0 or negative') return s
Check and parse thickness specs as either a single [s] or a list of [s,s,s,...]
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L102-L111
lightning-viz/lightning-python
lightning/types/utils.py
check_index
def check_index(i): """ Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...] """ i = asarray(i) if (i.ndim > 1) or (size(i) < 1): raise Exception("Index must be one-dimensional and non-singleton") return i
python
def check_index(i): """ Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...] """ i = asarray(i) if (i.ndim > 1) or (size(i) < 1): raise Exception("Index must be one-dimensional and non-singleton") return i
Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...]
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L113-L122
lightning-viz/lightning-python
lightning/types/utils.py
check_alpha
def check_alpha(a): """ Check and parse alpha specs as either a single [a] or a list of [a,a,a,...] """ a = check_1d(a, "alpha") if any(map(lambda d: d <= 0, a)): raise Exception('Alpha cannot be 0 or negative') return a
python
def check_alpha(a): """ Check and parse alpha specs as either a single [a] or a list of [a,a,a,...] """ a = check_1d(a, "alpha") if any(map(lambda d: d <= 0, a)): raise Exception('Alpha cannot be 0 or negative') return a
Check and parse alpha specs as either a single [a] or a list of [a,a,a,...]
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L125-L134
lightning-viz/lightning-python
lightning/types/utils.py
check_1d
def check_1d(x, name): """ Check and parse a one-dimensional spec as either a single [x] or a list of [x,x,x...] """ x = asarray(x) if size(x) == 1: x = asarray([x]) if x.ndim == 2: raise Exception("Property: %s must be one-dimensional" % name) x = x.flatten() return x
python
def check_1d(x, name): """ Check and parse a one-dimensional spec as either a single [x] or a list of [x,x,x...] """ x = asarray(x) if size(x) == 1: x = asarray([x]) if x.ndim == 2: raise Exception("Property: %s must be one-dimensional" % name) x = x.flatten() return x
Check and parse a one-dimensional spec as either a single [x] or a list of [x,x,x...]
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L137-L149
lightning-viz/lightning-python
lightning/types/utils.py
polygon_to_mask
def polygon_to_mask(coords, dims, z=None): """ Given a list of pairs of points which define a polygon, return a binary mask covering the interior of the polygon with dimensions dim """ bounds = array(coords).astype('int') path = Path(bounds) grid = meshgrid(range(dims[1]), range(dims[0])) grid_flat = zip(grid[0].ravel(), grid[1].ravel()) mask = path.contains_points(grid_flat).reshape(dims[0:2]).astype('int') if z is not None: if len(dims) < 3: raise Exception('Dims must have three-dimensions for embedding z-index') if z >= dims[2]: raise Exception('Z-index %g exceeds third dimension %g' % (z, dims[2])) tmp = zeros(dims) tmp[:, :, z] = mask mask = tmp return mask
python
def polygon_to_mask(coords, dims, z=None): """ Given a list of pairs of points which define a polygon, return a binary mask covering the interior of the polygon with dimensions dim """ bounds = array(coords).astype('int') path = Path(bounds) grid = meshgrid(range(dims[1]), range(dims[0])) grid_flat = zip(grid[0].ravel(), grid[1].ravel()) mask = path.contains_points(grid_flat).reshape(dims[0:2]).astype('int') if z is not None: if len(dims) < 3: raise Exception('Dims must have three-dimensions for embedding z-index') if z >= dims[2]: raise Exception('Z-index %g exceeds third dimension %g' % (z, dims[2])) tmp = zeros(dims) tmp[:, :, z] = mask mask = tmp return mask
Given a list of pairs of points which define a polygon, return a binary mask covering the interior of the polygon with dimensions dim
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L295-L318
lightning-viz/lightning-python
lightning/types/utils.py
polygon_to_points
def polygon_to_points(coords, z=None): """ Given a list of pairs of points which define a polygon, return a list of points interior to the polygon """ bounds = array(coords).astype('int') bmax = bounds.max(0) bmin = bounds.min(0) path = Path(bounds) grid = meshgrid(range(bmin[0], bmax[0]+1), range(bmin[1], bmax[1]+1)) grid_flat = zip(grid[0].ravel(), grid[1].ravel()) points = path.contains_points(grid_flat).reshape(grid[0].shape).astype('int') points = where(points) points = (vstack([points[0], points[1]]).T + bmin[-1::-1]).tolist() if z is not None: points = map(lambda p: [p[0], p[1], z], points) return points
python
def polygon_to_points(coords, z=None): """ Given a list of pairs of points which define a polygon, return a list of points interior to the polygon """ bounds = array(coords).astype('int') bmax = bounds.max(0) bmin = bounds.min(0) path = Path(bounds) grid = meshgrid(range(bmin[0], bmax[0]+1), range(bmin[1], bmax[1]+1)) grid_flat = zip(grid[0].ravel(), grid[1].ravel()) points = path.contains_points(grid_flat).reshape(grid[0].shape).astype('int') points = where(points) points = (vstack([points[0], points[1]]).T + bmin[-1::-1]).tolist() if z is not None: points = map(lambda p: [p[0], p[1], z], points) return points
Given a list of pairs of points which define a polygon, return a list of points interior to the polygon
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L321-L344
lightning-viz/lightning-python
lightning/visualization.py
VisualizationLocal.save_html
def save_html(self, filename=None, overwrite=False): """ Save self-contained html to a file. Parameters ---------- filename : str The filename to save to """ if filename is None: raise ValueError('Please provide a filename, e.g. viz.save_html(filename="viz.html").') import os base = self._html js = self.load_embed() if os.path.exists(filename): if overwrite is False: raise ValueError("File '%s' exists. To ovewrite call save_html with overwrite=True." % os.path.abspath(filename)) else: os.remove(filename) with open(filename, "wb") as f: f.write(base.encode('utf-8')) f.write('<script>' + js.encode('utf-8') + '</script>')
python
def save_html(self, filename=None, overwrite=False): """ Save self-contained html to a file. Parameters ---------- filename : str The filename to save to """ if filename is None: raise ValueError('Please provide a filename, e.g. viz.save_html(filename="viz.html").') import os base = self._html js = self.load_embed() if os.path.exists(filename): if overwrite is False: raise ValueError("File '%s' exists. To ovewrite call save_html with overwrite=True." % os.path.abspath(filename)) else: os.remove(filename) with open(filename, "wb") as f: f.write(base.encode('utf-8')) f.write('<script>' + js.encode('utf-8') + '</script>')
Save self-contained html to a file. Parameters ---------- filename : str The filename to save to
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/visualization.py#L173-L197
shanx/django-maintenancemode
maintenancemode/views.py
temporary_unavailable
def temporary_unavailable(request, template_name='503.html'): """ Default 503 handler, which looks for the requested URL in the redirects table, redirects if found, and displays 404 page if not redirected. Templates: ``503.html`` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ context = { 'request_path': request.path, } return http.HttpResponseTemporaryUnavailable( render_to_string(template_name, context))
python
def temporary_unavailable(request, template_name='503.html'): """ Default 503 handler, which looks for the requested URL in the redirects table, redirects if found, and displays 404 page if not redirected. Templates: ``503.html`` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ context = { 'request_path': request.path, } return http.HttpResponseTemporaryUnavailable( render_to_string(template_name, context))
Default 503 handler, which looks for the requested URL in the redirects table, redirects if found, and displays 404 page if not redirected. Templates: ``503.html`` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/')
https://github.com/shanx/django-maintenancemode/blob/16e256172dc289122643ec6f4882abbe02dc2b3c/maintenancemode/views.py#L19-L35
jimporter/bfg9000
bfg9000/versioning.py
simplify_specifiers
def simplify_specifiers(spec): """Try to simplify a SpecifierSet by combining redundant specifiers.""" def key(s): return (s.version, 1 if s.operator in ['>=', '<'] else 2) def in_bounds(v, lo, hi): if lo and v not in lo: return False if hi and v not in hi: return False return True def err(reason='inconsistent'): return ValueError('{} specifier set {}'.format(reason, spec)) gt = None lt = None eq = None ne = [] for i in spec: if i.operator == '==': if eq is None: eq = i elif eq != i: # pragma: no branch raise err() elif i.operator == '!=': ne.append(i) elif i.operator in ['>', '>=']: gt = i if gt is None else max(gt, i, key=key) elif i.operator in ['<', '<=']: lt = i if lt is None else min(lt, i, key=key) else: raise err('invalid') ne = [i for i in ne if in_bounds(i.version, gt, lt)] if eq: if ( any(i.version in eq for i in ne) or not in_bounds(eq.version, gt, lt)): raise err() return SpecifierSet(str(eq)) if lt and gt: if lt.version not in gt or gt.version not in lt: raise err() if ( gt.version == lt.version and gt.operator == '>=' and lt.operator == '<='): return SpecifierSet('=={}'.format(gt.version)) return SpecifierSet( ','.join(str(i) for i in chain(iterate(gt), iterate(lt), ne)) )
python
def simplify_specifiers(spec): """Try to simplify a SpecifierSet by combining redundant specifiers.""" def key(s): return (s.version, 1 if s.operator in ['>=', '<'] else 2) def in_bounds(v, lo, hi): if lo and v not in lo: return False if hi and v not in hi: return False return True def err(reason='inconsistent'): return ValueError('{} specifier set {}'.format(reason, spec)) gt = None lt = None eq = None ne = [] for i in spec: if i.operator == '==': if eq is None: eq = i elif eq != i: # pragma: no branch raise err() elif i.operator == '!=': ne.append(i) elif i.operator in ['>', '>=']: gt = i if gt is None else max(gt, i, key=key) elif i.operator in ['<', '<=']: lt = i if lt is None else min(lt, i, key=key) else: raise err('invalid') ne = [i for i in ne if in_bounds(i.version, gt, lt)] if eq: if ( any(i.version in eq for i in ne) or not in_bounds(eq.version, gt, lt)): raise err() return SpecifierSet(str(eq)) if lt and gt: if lt.version not in gt or gt.version not in lt: raise err() if ( gt.version == lt.version and gt.operator == '>=' and lt.operator == '<='): return SpecifierSet('=={}'.format(gt.version)) return SpecifierSet( ','.join(str(i) for i in chain(iterate(gt), iterate(lt), ne)) )
Try to simplify a SpecifierSet by combining redundant specifiers.
https://github.com/jimporter/bfg9000/blob/33615fc67573f0d416297ee9a98dd1ec8b1aa960/bfg9000/versioning.py#L37-L88
boriel/zxbasic
symbols/function.py
SymbolFUNCTION.reset
def reset(self, lineno=None, offset=None, type_=None): """ This is called when we need to reinitialize the instance state """ self.lineno = self.lineno if lineno is None else lineno self.type_ = self.type_ if type_ is None else type_ self.offset = self.offset if offset is None else offset self.callable = True self.params = SymbolPARAMLIST() self.body = SymbolBLOCK() self.__kind = KIND.unknown self.local_symbol_table = None
python
def reset(self, lineno=None, offset=None, type_=None): """ This is called when we need to reinitialize the instance state """ self.lineno = self.lineno if lineno is None else lineno self.type_ = self.type_ if type_ is None else type_ self.offset = self.offset if offset is None else offset self.callable = True self.params = SymbolPARAMLIST() self.body = SymbolBLOCK() self.__kind = KIND.unknown self.local_symbol_table = None
This is called when we need to reinitialize the instance state
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/function.py#L28-L39
boriel/zxbasic
symbols/funcdecl.py
SymbolFUNCDECL.make_node
def make_node(cls, func_name, lineno, type_=None): """ This will return a node with the symbol as a function. """ entry = global_.SYMBOL_TABLE.declare_func(func_name, lineno, type_=type_) if entry is None: return None entry.declared = True return cls(entry, lineno)
python
def make_node(cls, func_name, lineno, type_=None): """ This will return a node with the symbol as a function. """ entry = global_.SYMBOL_TABLE.declare_func(func_name, lineno, type_=type_) if entry is None: return None entry.declared = True return cls(entry, lineno)
This will return a node with the symbol as a function.
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/funcdecl.py#L73-L81
boriel/zxbasic
api/decorator.py
check_type
def check_type(*args, **kwargs): ''' Checks the function types ''' args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args) kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs} def decorate(func): types = args kwtypes = kwargs gi = "Got <{}> instead" errmsg1 = "to be of type <{}>. " + gi errmsg2 = "to be one of type ({}). " + gi errar = "{}:{} expected '{}' " errkw = "{}:{} expected {} " def check(*ar, **kw): line = inspect.getouterframes(inspect.currentframe())[1][2] fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1]) for arg, type_ in zip(ar, types): if type(arg) not in type_: if len(type_) == 1: raise TypeError((errar + errmsg1).format(fname, line, arg, type_[0].__name__, type(arg).__name__)) else: raise TypeError((errar + errmsg2).format(fname, line, arg, ', '.join('<%s>' % x.__name__ for x in type_), type(arg).__name__)) for kwarg in kw: if kwtypes.get(kwarg, None) is None: continue if type(kw[kwarg]) not in kwtypes[kwarg]: if len(kwtypes[kwarg]) == 1: raise TypeError((errkw + errmsg1).format(fname, line, kwarg, kwtypes[kwarg][0].__name__, type(kw[kwarg]).__name__)) else: raise TypeError((errkw + errmsg2).format( fname, line, kwarg, ', '.join('<%s>' % x.__name__ for x in kwtypes[kwarg]), type(kw[kwarg]).__name__) ) return func(*ar, **kw) return check return decorate
python
def check_type(*args, **kwargs): ''' Checks the function types ''' args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args) kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs} def decorate(func): types = args kwtypes = kwargs gi = "Got <{}> instead" errmsg1 = "to be of type <{}>. " + gi errmsg2 = "to be one of type ({}). " + gi errar = "{}:{} expected '{}' " errkw = "{}:{} expected {} " def check(*ar, **kw): line = inspect.getouterframes(inspect.currentframe())[1][2] fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1]) for arg, type_ in zip(ar, types): if type(arg) not in type_: if len(type_) == 1: raise TypeError((errar + errmsg1).format(fname, line, arg, type_[0].__name__, type(arg).__name__)) else: raise TypeError((errar + errmsg2).format(fname, line, arg, ', '.join('<%s>' % x.__name__ for x in type_), type(arg).__name__)) for kwarg in kw: if kwtypes.get(kwarg, None) is None: continue if type(kw[kwarg]) not in kwtypes[kwarg]: if len(kwtypes[kwarg]) == 1: raise TypeError((errkw + errmsg1).format(fname, line, kwarg, kwtypes[kwarg][0].__name__, type(kw[kwarg]).__name__)) else: raise TypeError((errkw + errmsg2).format( fname, line, kwarg, ', '.join('<%s>' % x.__name__ for x in kwtypes[kwarg]), type(kw[kwarg]).__name__) ) return func(*ar, **kw) return check return decorate
Checks the function types
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/decorator.py#L21-L69
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.add_string_label
def add_string_label(self, str_): """ Maps ("folds") the given string, returning an unique label ID. This allows several constant labels to be initialized to the same address thus saving memory space. :param str_: the string to map :return: the unique label ID """ if self.STRING_LABELS.get(str_, None) is None: self.STRING_LABELS[str_] = backend.tmp_label() return self.STRING_LABELS[str_]
python
def add_string_label(self, str_): """ Maps ("folds") the given string, returning an unique label ID. This allows several constant labels to be initialized to the same address thus saving memory space. :param str_: the string to map :return: the unique label ID """ if self.STRING_LABELS.get(str_, None) is None: self.STRING_LABELS[str_] = backend.tmp_label() return self.STRING_LABELS[str_]
Maps ("folds") the given string, returning an unique label ID. This allows several constant labels to be initialized to the same address thus saving memory space. :param str_: the string to map :return: the unique label ID
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L89-L99
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.TYPE
def TYPE(type_): """ Converts a backend type (from api.constants) to a SymbolTYPE object (taken from the SYMBOL_TABLE). If type_ is already a SymbolTYPE object, nothing is done. """ if isinstance(type_, symbols.TYPE): return type_ assert TYPE.is_valid(type_) return gl.SYMBOL_TABLE.basic_types[type_]
python
def TYPE(type_): """ Converts a backend type (from api.constants) to a SymbolTYPE object (taken from the SYMBOL_TABLE). If type_ is already a SymbolTYPE object, nothing is done. """ if isinstance(type_, symbols.TYPE): return type_ assert TYPE.is_valid(type_) return gl.SYMBOL_TABLE.basic_types[type_]
Converts a backend type (from api.constants) to a SymbolTYPE object (taken from the SYMBOL_TABLE). If type_ is already a SymbolTYPE object, nothing is done.
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L106-L116
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.emit
def emit(*args): """ Convert the given args to a Quad (3 address code) instruction """ quad = Quad(*args) __DEBUG__('EMIT ' + str(quad)) MEMORY.append(quad)
python
def emit(*args): """ Convert the given args to a Quad (3 address code) instruction """ quad = Quad(*args) __DEBUG__('EMIT ' + str(quad)) MEMORY.append(quad)
Convert the given args to a Quad (3 address code) instruction
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L139-L144
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.norm_attr
def norm_attr(self): """ Normalize attr state """ if not self.HAS_ATTR: return self.HAS_ATTR = False self.emit('call', 'COPY_ATTR', 0) backend.REQUIRES.add('copy_attr.asm')
python
def norm_attr(self): """ Normalize attr state """ if not self.HAS_ATTR: return self.HAS_ATTR = False self.emit('call', 'COPY_ATTR', 0) backend.REQUIRES.add('copy_attr.asm')
Normalize attr state
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L217-L225
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.traverse_const
def traverse_const(node): """ Traverses a constant and returns an string with the arithmetic expression """ if node.token == 'NUMBER': return node.t if node.token == 'UNARY': mid = node.operator if mid == 'MINUS': result = ' -' + Translator.traverse_const(node.operand) elif mid == 'ADDRESS': if node.operand.scope == SCOPE.global_ or node.operand.token in ('LABEL', 'FUNCTION'): result = Translator.traverse_const(node.operand) else: syntax_error_not_constant(node.operand.lineno) return else: raise InvalidOperatorError(mid) return result if node.token == 'BINARY': mid = node.operator if mid == 'PLUS': mid = '+' elif mid == 'MINUS': mid = '-' elif mid == 'MUL': mid = '*' elif mid == 'DIV': mid = '/' elif mid == 'MOD': mid = '%' elif mid == 'POW': mid = '^' elif mid == 'SHL': mid = '>>' elif mid == 'SHR': mid = '<<' else: raise InvalidOperatorError(mid) return '(%s) %s (%s)' % (Translator.traverse_const(node.left), mid, Translator.traverse_const(node.right)) if node.token == 'TYPECAST': if node.type_ in (Type.byte_, Type.ubyte): return '(' + Translator.traverse_const(node.operand) + ') & 0xFF' if node.type_ in (Type.integer, Type.uinteger): return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFF' if node.type_ in (Type.long_, Type.ulong): return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFFFFFF' if node.type_ == Type.fixed: return '((' + Translator.traverse_const(node.operand) + ') & 0xFFFF) << 16' syntax_error_cant_convert_to_type(node.lineno, str(node.operand), node.type_) return if node.token in ('VAR', 'VARARRAY', 'LABEL', 'FUNCTION'): # TODO: Check what happens with local vars and params return node.t if node.token == 'CONST': return Translator.traverse_const(node.expr) if node.token == 'ARRAYACCESS': return '({} + {})'.format(node.entry.mangled, node.offset) raise InvalidCONSTexpr(node)
python
def traverse_const(node): """ Traverses a constant and returns an string with the arithmetic expression """ if node.token == 'NUMBER': return node.t if node.token == 'UNARY': mid = node.operator if mid == 'MINUS': result = ' -' + Translator.traverse_const(node.operand) elif mid == 'ADDRESS': if node.operand.scope == SCOPE.global_ or node.operand.token in ('LABEL', 'FUNCTION'): result = Translator.traverse_const(node.operand) else: syntax_error_not_constant(node.operand.lineno) return else: raise InvalidOperatorError(mid) return result if node.token == 'BINARY': mid = node.operator if mid == 'PLUS': mid = '+' elif mid == 'MINUS': mid = '-' elif mid == 'MUL': mid = '*' elif mid == 'DIV': mid = '/' elif mid == 'MOD': mid = '%' elif mid == 'POW': mid = '^' elif mid == 'SHL': mid = '>>' elif mid == 'SHR': mid = '<<' else: raise InvalidOperatorError(mid) return '(%s) %s (%s)' % (Translator.traverse_const(node.left), mid, Translator.traverse_const(node.right)) if node.token == 'TYPECAST': if node.type_ in (Type.byte_, Type.ubyte): return '(' + Translator.traverse_const(node.operand) + ') & 0xFF' if node.type_ in (Type.integer, Type.uinteger): return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFF' if node.type_ in (Type.long_, Type.ulong): return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFFFFFF' if node.type_ == Type.fixed: return '((' + Translator.traverse_const(node.operand) + ') & 0xFFFF) << 16' syntax_error_cant_convert_to_type(node.lineno, str(node.operand), node.type_) return if node.token in ('VAR', 'VARARRAY', 'LABEL', 'FUNCTION'): # TODO: Check what happens with local vars and params return node.t if node.token == 'CONST': return Translator.traverse_const(node.expr) if node.token == 'ARRAYACCESS': return '({} + {})'.format(node.entry.mangled, node.offset) raise InvalidCONSTexpr(node)
Traverses a constant and returns an string with the arithmetic expression
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L228-L294
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.check_attr
def check_attr(node, n): """ Check if ATTR has to be normalized after this instruction has been translated to intermediate code. """ if len(node.children) > n: return node.children[n]
python
def check_attr(node, n): """ Check if ATTR has to be normalized after this instruction has been translated to intermediate code. """ if len(node.children) > n: return node.children[n]
Check if ATTR has to be normalized after this instruction has been translated to intermediate code.
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L297-L303
boriel/zxbasic
arch/zx48k/translator.py
Translator.emit_var_assign
def emit_var_assign(self, var, t): """ Emits code for storing a value into a variable :param var: variable (node) to be updated :param t: the value to emmit (e.g. a _label, a const, a tN...) """ p = '*' if var.byref else '' # Indirection prefix if self.O_LEVEL > 1 and not var.accessed: return if not var.type_.is_basic: raise NotImplementedError() if var.scope == SCOPE.global_: self.emit('store' + self.TSUFFIX(var.type_), var.mangled, t) elif var.scope == SCOPE.parameter: self.emit('pstore' + self.TSUFFIX(var.type_), p + str(var.offset), t) elif var.scope == SCOPE.local: if var.alias is not None and var.alias.class_ == CLASS.array: var.offset -= 1 + 2 * var.alias.count self.emit('pstore' + self.TSUFFIX(var.type_), p + str(-var.offset), t)
python
def emit_var_assign(self, var, t): """ Emits code for storing a value into a variable :param var: variable (node) to be updated :param t: the value to emmit (e.g. a _label, a const, a tN...) """ p = '*' if var.byref else '' # Indirection prefix if self.O_LEVEL > 1 and not var.accessed: return if not var.type_.is_basic: raise NotImplementedError() if var.scope == SCOPE.global_: self.emit('store' + self.TSUFFIX(var.type_), var.mangled, t) elif var.scope == SCOPE.parameter: self.emit('pstore' + self.TSUFFIX(var.type_), p + str(var.offset), t) elif var.scope == SCOPE.local: if var.alias is not None and var.alias.class_ == CLASS.array: var.offset -= 1 + 2 * var.alias.count self.emit('pstore' + self.TSUFFIX(var.type_), p + str(-var.offset), t)
Emits code for storing a value into a variable :param var: variable (node) to be updated :param t: the value to emmit (e.g. a _label, a const, a tN...)
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1159-L1178
boriel/zxbasic
arch/zx48k/translator.py
Translator.loop_exit_label
def loop_exit_label(self, loop_type): """ Returns the label for the given loop type which exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' """ for i in range(len(self.LOOPS) - 1, -1, -1): if loop_type == self.LOOPS[i][0]: return self.LOOPS[i][1] raise InvalidLoopError(loop_type)
python
def loop_exit_label(self, loop_type): """ Returns the label for the given loop type which exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' """ for i in range(len(self.LOOPS) - 1, -1, -1): if loop_type == self.LOOPS[i][0]: return self.LOOPS[i][1] raise InvalidLoopError(loop_type)
Returns the label for the given loop type which exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1195-L1203
boriel/zxbasic
arch/zx48k/translator.py
Translator.loop_cont_label
def loop_cont_label(self, loop_type): """ Returns the label for the given loop type which continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' """ for i in range(len(self.LOOPS) - 1, -1, -1): if loop_type == self.LOOPS[i][0]: return self.LOOPS[i][2] raise InvalidLoopError(loop_type)
python
def loop_cont_label(self, loop_type): """ Returns the label for the given loop type which continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' """ for i in range(len(self.LOOPS) - 1, -1, -1): if loop_type == self.LOOPS[i][0]: return self.LOOPS[i][2] raise InvalidLoopError(loop_type)
Returns the label for the given loop type which continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1205-L1213
boriel/zxbasic
arch/zx48k/translator.py
Translator.default_value
def default_value(cls, type_, expr): # TODO: This function must be moved to api.xx """ Returns a list of bytes (as hexadecimal 2 char string) """ assert isinstance(type_, symbols.TYPE) assert type_.is_basic assert check.is_static(expr) if isinstance(expr, (symbols.CONST, symbols.VAR)): # a constant expression like @label + 1 if type_ in (cls.TYPE(TYPE.float_), cls.TYPE(TYPE.string)): syntax_error(expr.lineno, "Can't convert non-numeric value to {0} at compile time".format(type_.name)) return ['<ERROR>'] val = Translator.traverse_const(expr) if type_.size == 1: # U/byte if expr.type_.size != 1: return ['#({0}) & 0xFF'.format(val)] else: return ['#{0}'.format(val)] if type_.size == 2: # U/integer if expr.type_.size != 2: return ['##({0}) & 0xFFFF'.format(val)] else: return ['##{0}'.format(val)] if type_ == cls.TYPE(TYPE.fixed): return ['0000', '##({0}) & 0xFFFF'.format(val)] # U/Long return ['##({0}) & 0xFFFF'.format(val), '##(({0}) >> 16) & 0xFFFF'.format(val)] if type_ == cls.TYPE(TYPE.float_): C, DE, HL = _float(expr.value) C = C[:-1] # Remove 'h' suffix if len(C) > 2: C = C[-2:] DE = DE[:-1] # Remove 'h' suffix if len(DE) > 4: DE = DE[-4:] elif len(DE) < 3: DE = '00' + DE HL = HL[:-1] # Remove 'h' suffix if len(HL) > 4: HL = HL[-4:] elif len(HL) < 3: HL = '00' + HL return [C, DE[-2:], DE[:-2], HL[-2:], HL[:-2]] if type_ == cls.TYPE(TYPE.fixed): value = 0xFFFFFFFF & int(expr.value * 2 ** 16) else: value = int(expr.value) result = [value, value >> 8, value >> 16, value >> 24] result = ['%02X' % (v & 0xFF) for v in result] return result[:type_.size]
python
def default_value(cls, type_, expr): # TODO: This function must be moved to api.xx """ Returns a list of bytes (as hexadecimal 2 char string) """ assert isinstance(type_, symbols.TYPE) assert type_.is_basic assert check.is_static(expr) if isinstance(expr, (symbols.CONST, symbols.VAR)): # a constant expression like @label + 1 if type_ in (cls.TYPE(TYPE.float_), cls.TYPE(TYPE.string)): syntax_error(expr.lineno, "Can't convert non-numeric value to {0} at compile time".format(type_.name)) return ['<ERROR>'] val = Translator.traverse_const(expr) if type_.size == 1: # U/byte if expr.type_.size != 1: return ['#({0}) & 0xFF'.format(val)] else: return ['#{0}'.format(val)] if type_.size == 2: # U/integer if expr.type_.size != 2: return ['##({0}) & 0xFFFF'.format(val)] else: return ['##{0}'.format(val)] if type_ == cls.TYPE(TYPE.fixed): return ['0000', '##({0}) & 0xFFFF'.format(val)] # U/Long return ['##({0}) & 0xFFFF'.format(val), '##(({0}) >> 16) & 0xFFFF'.format(val)] if type_ == cls.TYPE(TYPE.float_): C, DE, HL = _float(expr.value) C = C[:-1] # Remove 'h' suffix if len(C) > 2: C = C[-2:] DE = DE[:-1] # Remove 'h' suffix if len(DE) > 4: DE = DE[-4:] elif len(DE) < 3: DE = '00' + DE HL = HL[:-1] # Remove 'h' suffix if len(HL) > 4: HL = HL[-4:] elif len(HL) < 3: HL = '00' + HL return [C, DE[-2:], DE[:-2], HL[-2:], HL[:-2]] if type_ == cls.TYPE(TYPE.fixed): value = 0xFFFFFFFF & int(expr.value * 2 ** 16) else: value = int(expr.value) result = [value, value >> 8, value >> 16, value >> 24] result = ['%02X' % (v & 0xFF) for v in result] return result[:type_.size]
Returns a list of bytes (as hexadecimal 2 char string)
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1216-L1274
boriel/zxbasic
arch/zx48k/translator.py
Translator.array_default_value
def array_default_value(type_, values): """ Returns a list of bytes (as hexadecimal 2 char string) which represents the array initial value. """ if not isinstance(values, list): return Translator.default_value(type_, values) l = [] for row in values: l.extend(Translator.array_default_value(type_, row)) return l
python
def array_default_value(type_, values): """ Returns a list of bytes (as hexadecimal 2 char string) which represents the array initial value. """ if not isinstance(values, list): return Translator.default_value(type_, values) l = [] for row in values: l.extend(Translator.array_default_value(type_, row)) return l
Returns a list of bytes (as hexadecimal 2 char string) which represents the array initial value.
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1277-L1288
boriel/zxbasic
arch/zx48k/translator.py
Translator.has_control_chars
def has_control_chars(i): """ Returns true if the passed token is an unknown string or a constant string having control chars (inverse, etc """ if not hasattr(i, 'type_'): return False if i.type_ != Type.string: return False if i.token in ('VAR', 'PARAMDECL'): return True # We don't know what an alphanumeric variable will hold if i.token == 'STRING': for c in i.value: if 15 < ord(c) < 22: # is it an attr char? return True return False for j in i.children: if Translator.has_control_chars(j): return True return False
python
def has_control_chars(i): """ Returns true if the passed token is an unknown string or a constant string having control chars (inverse, etc """ if not hasattr(i, 'type_'): return False if i.type_ != Type.string: return False if i.token in ('VAR', 'PARAMDECL'): return True # We don't know what an alphanumeric variable will hold if i.token == 'STRING': for c in i.value: if 15 < ord(c) < 22: # is it an attr char? return True return False for j in i.children: if Translator.has_control_chars(j): return True return False
Returns true if the passed token is an unknown string or a constant string having control chars (inverse, etc
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1291-L1314
boriel/zxbasic
arch/zx48k/translator.py
BuiltinTranslator.visit_USR
def visit_USR(self, node): """ Machine code call from basic """ self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t) self.emit('call', 'USR', node.type_.size) backend.REQUIRES.add('usr.asm')
python
def visit_USR(self, node): """ Machine code call from basic """ self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t) self.emit('call', 'USR', node.type_.size) backend.REQUIRES.add('usr.asm')
Machine code call from basic
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1559-L1564
boriel/zxbasic
symbols/symbol_.py
Symbol.copy_attr
def copy_attr(self, other): """ Copies all other attributes (not methods) from the other object to this instance. """ if not isinstance(other, Symbol): return # Nothing done if not a Symbol object tmp = re.compile('__.*__') for attr in (x for x in dir(other) if not tmp.match(x)): if ( hasattr(self.__class__, attr) and str(type(getattr(self.__class__, attr)) in ('property', 'function', 'instancemethod')) ): continue val = getattr(other, attr) if isinstance(val, str) or str(val)[0] != '<': # Not a value setattr(self, attr, val)
python
def copy_attr(self, other): """ Copies all other attributes (not methods) from the other object to this instance. """ if not isinstance(other, Symbol): return # Nothing done if not a Symbol object tmp = re.compile('__.*__') for attr in (x for x in dir(other) if not tmp.match(x)): if ( hasattr(self.__class__, attr) and str(type(getattr(self.__class__, attr)) in ('property', 'function', 'instancemethod')) ): continue val = getattr(other, attr) if isinstance(val, str) or str(val)[0] != '<': # Not a value setattr(self, attr, val)
Copies all other attributes (not methods) from the other object to this instance.
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/symbol_.py#L47-L65
boriel/zxbasic
prepro/definestable.py
DefinesTable.define
def define(self, id_, lineno, value='', fname=None, args=None): """ Defines the value of a macro. Issues a warning if the macro is already defined. """ if fname is None: if CURRENT_FILE: fname = CURRENT_FILE[-1] else: # If no files opened yet, use owns program fname fname = sys.argv[0] if self.defined(id_): i = self.table[id_] warning(lineno, '"%s" redefined (previous definition at %s:%i)' % (i.name, i.fname, i.lineno)) self.set(id_, lineno, value, fname, args)
python
def define(self, id_, lineno, value='', fname=None, args=None): """ Defines the value of a macro. Issues a warning if the macro is already defined. """ if fname is None: if CURRENT_FILE: fname = CURRENT_FILE[-1] else: # If no files opened yet, use owns program fname fname = sys.argv[0] if self.defined(id_): i = self.table[id_] warning(lineno, '"%s" redefined (previous definition at %s:%i)' % (i.name, i.fname, i.lineno)) self.set(id_, lineno, value, fname, args)
Defines the value of a macro. Issues a warning if the macro is already defined.
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/prepro/definestable.py#L31-L45