Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • alexander.pace/server
  • geoffrey.mo/gracedb-server
  • deep.chatterjee/gracedb-server
  • cody.messick/server
  • sushant.sharma-chaudhary/server
  • michael-coughlin/server
  • daniel.wysocki/gracedb-server
  • roberto.depietri/gracedb
  • philippe.grassia/gracedb
  • tri.nguyen/gracedb
  • jonah-kanner/gracedb
  • brandon.piotrzkowski/gracedb
  • joseph-areeda/gracedb
  • duncanmmacleod/gracedb
  • thomas.downes/gracedb
  • tanner.prestegard/gracedb
  • leo-singer/gracedb
  • computing/gracedb/server
18 results
Show changes
Commits on Source (2202)
Showing
with 2778 additions and 4116 deletions
{
"directory" : "../bower_components"
}
.git
*.swo
*.swp
*~
*.pyc
django-*.wsgi
static-collected
static/admin/
static/rest_framework/
config/settings/secret.py
config/settings/local.py
docs/user_docs/build/*
docs/admin_docs/build/*
static_root/*
.pytest_cache
junit.xml
.coverage
---
image: docker:latest
variables:
APT_CACHE_DIR: "${CI_PROJECT_DIR}/.cache/apt"
DOCKER_DRIVER: overlay
DOCKER_BRANCH: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME
DOCKER_LATEST: $CI_REGISTRY_IMAGE:latest
PIP_CACHE_DIR: "${CI_PROJECT_DIR}/.cache/pip"
stages:
- test
- branch
- latest
before_script:
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
include:
# Container scanning
- component: $CI_SERVER_FQDN/computing/gitlab/components/container-scanning/container-scanning@~latest
inputs:
job_name: branch_scan
# Software scanning
- component: $CI_SERVER_FQDN/computing/gitlab/components/sast/sast@~latest
inputs:
run_advanced_sast: true
- component: $CI_SERVER_FQDN/computing/gitlab/components/secret-detection/secret-detection@~latest
- component: $CI_SERVER_FQDN/computing/gitlab/components/python/dependency-scanning@~latest
# -- software scanning
# overwrite some settings for the scanning jobs
dependency_scanning:
stage: test
needs: []
variables:
DEBIAN_FRONTEND: "noninteractive"
before_script:
# install some underlying utilities using `apt` so that the dependency
# scanner can use pip to install everything else
- apt-get update -yqq
- apt-get install -yqq
libkrb5-dev
libldap-dev
libsasl2-dev
.sast-analyzer:
stage: test
needs: []
before_script: []
secret_detection:
stage: test
needs: []
before_script: []
# -- testing
.test: &test
image: igwn/base:bookworm
services:
- postgres:15.6
- memcached
variables:
AWS_SES_ACCESS_KEY_ID: "fake_aws_id"
AWS_SES_SECRET_ACCESS_KEY: "fake_aws_key"
DJANGO_ALERT_EMAIL_FROM: "fake_email"
DJANGO_DB_HOST: "postgres"
DJANGO_DB_PORT: "5432"
DJANGO_DB_NAME: "fake_name"
DJANGO_DB_USER: "runner"
DJANGO_DB_PASSWORD: ""
DJANGO_PRIMARY_FQDN: "fake_fqdn"
DJANGO_SECRET_KEY: "fake_key"
DJANGO_SETTINGS_MODULE: "config.settings.container.dev"
DJANGO_TWILIO_ACCOUNT_SID: "fake_sid"
DJANGO_TWILIO_AUTH_TOKEN: "fake_token"
DJANGO_DOCKER_MEMCACHED_ADDR: "memcached:11211"
EGAD_URL: "fake_url"
EGAD_API_KEY: "fake_key"
ENABLE_LVALERT_OVERSEER: "false"
ENABLE_IGWN_OVERSEER: "false"
LVALERT_OVERSEER_PORT: "2"
LVALERT_SERVER: "fake_server"
LVALERT_USER: "fake_user"
LVALERT_PASSWORD: "fake_password"
ENABLE_IGWN_OVERSEER: "false"
IGWN_ALERT_OVERSEER_PORT: "2"
IGWN_ALERT_SERVER: "fake_server"
IGWN_ALERT_USER: "fake_user"
IGWN_ALERT_PASSWORD: "fake_password"
POSTGRES_DB: "${DJANGO_DB_NAME}"
POSTGRES_USER: "${DJANGO_DB_USER}"
POSTGRES_PASSWORD: "${DJANGO_DB_PASSWORD}"
POSTGRES_HOST_AUTH_METHOD: trust
before_script:
# create apt cache directory
- mkdir -pv ${APT_CACHE_DIR}
# set python version
- PYTHON_VERSION="${CI_JOB_NAME##*:}"
- PYTHON_MAJOR="${PYTHON_VERSION:0:1}"
- PYTHON="python3"
# install build requirements
- apt-get -y install gnupg
- sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
- wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
- apt-get -yqq update
- apt-get -o dir::cache::archives="${APT_CACHE_DIR}" install -yqq
git
gnupg
libldap2-dev
libsasl2-dev
libssl-dev
libxml2-dev
krb5-user
libkrb5-dev
libsasl2-modules-gssapi-mit
swig
pkg-config
libpng-dev
libfreetype6-dev
libxslt-dev
${PYTHON}-pip
postgresql-15
postgresql-client-15
libpq-dev
# upgrade pip (requirement for lalsuite)
- ${PYTHON} -m pip install --upgrade pip --break-system-packages
# install everything else from pip
- ${PYTHON} -m pip install -r requirements.txt --break-system-packages
# create logs path required for tests
- mkdir -pv ../logs/
# list packages
- ${PYTHON} -m pip list installed
script:
- PYTHONPATH=${PYTHONPATH}:${PWD}/gracedb ${PYTHON} -m pytest --cov-report term-missing --cov ./gracedb --junitxml=${CI_PROJECT_DIR}/junit.xml
after_script:
- rm -fvr ${PIP_CACHE_DIR}/log
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
artifacts:
reports:
junit: junit.xml
cache:
key: "${CI_JOB_NAME}"
paths:
- .cache/pip
- .cache/apt
coverage: '/^TOTAL\s+.*\s+(\d+\.?\d*)%/'
tags:
- executor-docker
test:3.11:
<<: *test
# -- docker
branch_image:
stage: branch
script:
- docker build --pull -t $DOCKER_BRANCH .
- docker push $DOCKER_BRANCH
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
tags:
- executor-docker
branch_scan:
stage: branch
needs: [branch_image]
# default rules spawn a merge request pipeline, we don't want that
rules:
- if: $CI_COMMIT_BRANCH
variables:
GIT_STRATEGY: fetch
# image to scan
CS_IMAGE: "$DOCKER_BRANCH"
# image to compare to
CS_DEFAULT_BRANCH_IMAGE: "$CI_REGISTRY/computing/gitlab/server:latest"
# path to Dockerfile for remediation
CS_DOCKERFILE_PATH: "Dockerfile"
before_script: []
latest_image:
stage: latest
dependencies:
- branch_image
script:
- docker pull $DOCKER_BRANCH
- docker tag $DOCKER_BRANCH $DOCKER_LATEST
- docker push $DOCKER_LATEST
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
tags:
- executor-docker
## Description of problem
<!--
Describe in detail what you are trying to do and what the result is.
Exact timestamps, error tracebacks, and screenshots (if applicable) are very helpful.
-->
## Expected behavior
<!-- What do you expect to happen instead? -->
## Steps to reproduce
<!-- Step-by-step procedure for reproducing the issue -->
## Context/environment
<!--
Describe the environment you are working in:
* If using the ligo-gracedb client package, which version?
* Your operating system
* Your browser (web interface issues only)
* If you are experiencing this problem while working on a LIGO or Virgo computing cluster, which cluster are you using?
-->
## Suggested solutions
<!-- Any ideas for how to resolve this problem? -->
## Description of feature request
<!--
Describe your feature request!
Is it a web interface change? Some underlying feature? An API resource?
The more detail you can provide, the better.
-->
## Use cases
<!-- List some specific cases where this feature will be useful -->
## Benefits
<!-- Describe the benefits of adding this feature -->
## Drawbacks
<!--
Are there any drawbacks to adding this feature?
Can you think of any ways in which this will negatively affect the service for any set of users?
-->
## Suggested solutions
<!-- Do you have any ideas for how to implement this feature? -->
# Changelog
All notable changes to this project will be documented in this file.
## 2017-07-05 (gracedb-1.0.10) <tanner.prestegard@ligo.org>
### Added
- global setting for turning off LVAlerts (SEND_XMPP_ALERTS)
- instructions to the web page for creating notifications
### Fixed
- logging and display of performance information
- failover to lvalert_send when lvalert_overseer is not working
## 2017-05-30 (gracedb-1.0.9) <tanner.prestegard@ligo.org>
### Added
- list of labels for an event is now included in all LVAlert messages
- available labels now exposed via the REST API
- ability to create events with labels attached
- 'offline' parameter
### Fixed
- cleanup of label and event creation code, use of proper HTTP response codes
- LVAlert messages now sent when a label is removed and when a log entry is added via the web interface
## 2017-05-08 (gracedb-1.0.8) <tanner.prestegard@ligo.org>
### Added
- case-insensitive search queries
### Changed
- removed gracedb/pyparsing.py in favor of the pip-installed version
- overall reorganization and cleanup of Django settings
## 2017-04-25 (gracedb-1.0.7) <tanner.prestegard@ligo.org>
### Added
- V1OPS label and access to signoff pages from Virgo control room
- EM_SENT label
- new save method for EventLog, EMBBEventLog, EMObservation, EMFootprint to generate log number and save in a single SQL query
### Fixed
- typo in an MOU group's name (CTA)
## 2017-03-21 (gracedb-1.0.6) <tanner.prestegard@ligo.org>
### Changed
- modify handling of Fermi GCNs so as to not overwrite trigger durations
- change settings so gracedb servers use 'test' settings by default
## 2017-03-07 (gracedb-1.0.5) <tanner.prestegard@ligo.org>
### Added
- extraction of single IFO times from CWB event files, saving them in the database, and exposing them to MOU partners
### Changed
- increased size of 'debug' Django logs
## 2017-02-28 (gracedb-1.0.4) <tanner.prestegard@ligo.org>
### Changed
- added new LIB robot certificate
### Fixed
- issue where non-LVC members could remove the lv-em tag on log messages
## 2017-01-24 (gracedb-1.0.3) <tanner.prestegard@ligo.org>
### Added
- several MOU groups
- human-readable FAR to event pages
- leap second from 31 Dec 2016
- test button for contacts
### Changed
- separated phone alerts into voice and text options
## 2017-01-10 (gracedb-1.0.2) <tanner.prestegard@ligo.org>
### Changed
- increased Django logging verbosity and clarity
- modernized Django template structure to Django 1.8 standard
- reorganized settings
## 2016-12-20 (gracedb-1.0.1) <tanner.prestegard@ligo.org>
### Added
- capability for removing labels via gracedb-client
### Changed
- expose singleInspiral times and IFOs for EM partners
## 2016-11-22 <tanner.prestegard@ligo.org>
### Added
- capability for sending phone/SMS alerts via Twilio
### Changed
- updated admin documentation
## 2016-11-11 <tanner.prestegard@ligo.org>
### Added
- AllSkyLong search and updated LVAlert nodes
### Changed
- event file structure for LIB events
## 2016-10-20 <tanner.prestegard@ligo.org>
### Added
- README.md file
### Changed
- Repository moved from versions.ligo.org to git.ligo.org
## 2016-01-07
### Added
- 'less than' sign in event display when FAR is an upper limit (#3105)
- deprecation warning header for old client url endpoints (#2420)
- event subclass for oLIB events (#3093)
### Changed
- now including WhereWhen section in retraction VOEvents (#3092)
### Fixed
- only add SkymapViewer button for json files corresponding to skymaps (#3004)
## 2015-11-17
### Added
- support for tagnames with spaces in REST URL patterns (#2730)
- documentation about requesting changes to EM Observation entries (#2591)
- support for more complex label queries for searches and email
notifications (#2672, #2569)
- support for file uploads through the web interface (#2543, #1367)
### Changed
- create LigoLdapUser object (instead of django User) for unknown
Shib users with a valid session (#2629)
- time conversion functions handle None and empty string input (#2664)
### Fixed
- internal_user_required decorator no longer assumes HTTP request as
first arg (#2524)
- removed spurious factor of 1000 from fluence calculation (#2625)
## 2015-10-06
### Added
- banner warning if the user is looking at an lvem_view page (#2600)
- this changelog file (#2599)
- added event page link to labelling email alerts (#2575)
- add value from coinc_event.likelihood column to "Coinc Tables" for gstlal
events (#2513)
### Changed
- interpretation of values for cWB events (see #2484)
- list of labels for query now generated by DB query instead of static list
(#2523)
- allow more than one EMObservation subrow to be expanded at one time (#2605)
- Changed name of "Duration" field in EMObservation form to "On source
exposure" (#2603)
- Removed customized wait method from throttles so that we can send an
x-throttle-wait-seconds header to the user (#2457)
- Allow the internal parameter of VOEvents to be controlled by the requestor.
This is now taken from post data and defaults to 1 (internal only #2608).
### Fixed
- remove user from groups that are not present in IdP shibboleth assertion
(#2600)
- description of the 'internal' parameter in buildVOEvent.py (#2600)
FROM debian:bookworm
LABEL name="LIGO GraceDB Django application" \
maintainer="alexander.pace@ligo.org" \
date="20240306"
ARG SETTINGS_MODULE="config.settings.container.dev"
COPY docker/SWITCHaai-swdistrib.gpg /etc/apt/trusted.gpg.d
COPY docker/backports.pref /etc/apt/preferences.d
RUN apt-get update && \
apt-get -y install gnupg curl
RUN echo 'deb http://deb.debian.org/debian bookworm-backports main' > /etc/apt/sources.list.d/backports.list
RUN echo 'deb http://apt.postgresql.org/pub/repos/apt bookworm-pgdg main' > /etc/apt/sources.list.d/pgdg.list
RUN curl https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
RUN apt-get update && \
apt-get --assume-yes upgrade && \
apt-get install --install-recommends --assume-yes \
apache2 \
emacs-nox \
gcc \
git \
krb5-user \
libkrb5-dev \
libapache2-mod-shib \
libapache2-mod-xsendfile \
libldap2-dev \
libldap-2.5-0 \
libsasl2-dev \
libsasl2-modules-gssapi-mit \
libxml2-dev \
pkg-config \
libpng-dev \
libpq-dev \
libfreetype6-dev \
libxslt-dev \
libsqlite3-dev \
php \
php8.2-pgsql \
php8.2-mbstring \
postgresql-client-15 \
python3 \
python3-dev \
python3-libxml2 \
python3-pip \
procps \
redis \
shibboleth-sp-common \
shibboleth-sp-utils \
libssl-dev \
swig \
htop \
telnet \
vim && \
apt-get clean && \
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
apt-get update && apt-get install --assume-yes yarn
# Install AWS X-ray daemon
RUN curl -O https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray-daemon-3.x.deb
RUN dpkg -i aws-xray-daemon-3.x.deb
RUN rm aws-xray-daemon-3.x.deb
# Install osg-ca-certs:
RUN curl -O https://hypatia.aei.mpg.de/lsc-amd64-bookworm/osg-ca-certs_1.132NEW-1+deb12u0_all.deb
RUN dpkg -i osg-ca-certs_1.132NEW-1+deb12u0_all.deb
RUN rm osg-ca-certs_1.132NEW-1+deb12u0_all.deb
# Install ligo-ca-certs:
RUN curl -O https://hypatia.aei.mpg.de/lsc-amd64-bookworm/ligo-ca-certs_1.0.2-0+deb12u0_all.deb
RUN dpkg -i ligo-ca-certs_1.0.2-0+deb12u0_all.deb
RUN rm ligo-ca-certs_1.0.2-0+deb12u0_all.deb
# Docker scripts:
COPY docker/entrypoint /usr/local/bin/entrypoint
COPY docker/cleanup /usr/local/bin/cleanup
# Supervisord configs:
COPY docker/supervisord.conf /etc/supervisor/supervisord.conf
COPY docker/supervisord-apache2.conf /etc/supervisor/conf.d/apache2.conf
COPY docker/supervisord-igwn-alert-overseer.conf /etc/supervisor/conf.d/igwn-overseer.conf
COPY docker/supervisord-shibd.conf /etc/supervisor/conf.d/shibd.conf
COPY docker/supervisord-aws-xray.conf /etc/supervisor/conf.d/aws-xray.conf
COPY docker/supervisord-qcluster.conf /etc/supervisor/conf.d/qcluster.conf
# Apache configs:
COPY docker/apache-config /etc/apache2/sites-available/gracedb.conf
COPY docker/mpm_prefork.conf /etc/apache2/mods-enabled/mpm_prefork.conf
# Enable mpm_event module:
RUN rm /etc/apache2/mods-enabled/mpm_prefork.*
RUN rm /etc/apache2/mods-enabled/php8.2.*
RUN cp /etc/apache2/mods-available/mpm_event.* /etc/apache2/mods-enabled/
# Shibboleth configs and certs:
COPY docker/shibboleth-ds /etc/shibboleth-ds
COPY docker/login.ligo.org.cert.LIGOCA.pem /etc/shibboleth/login.ligo.org.cert.LIGOCA.pem
COPY docker/inc-md-cert.pem /etc/shibboleth/inc-md-cert.pem
COPY docker/check_shibboleth_status /usr/local/bin/check_shibboleth_status
RUN a2dissite 000-default.conf && \
a2ensite gracedb.conf && \
a2enmod headers proxy proxy_http rewrite xsendfile
# this line is unfortunate because "." updates for nearly any change to the
# repository and therefore docker build rarely caches the steps below
ADD . /app/gracedb_project
# install gracedb application itself
WORKDIR /app/gracedb_project
RUN pip3 install --upgrade pip --break-system-packages
RUN pip3 install -r requirements.txt --break-system-packages
# install supervisor from pip
RUN pip3 install supervisor --break-system-packages
# Give pip-installed packages priority over distribution packages
ENV PYTHONPATH /usr/local/lib/python3.11/dist-packages:$PYTHONPATH
ENV ENABLE_SHIBD false
ENV ENABLE_OVERSEER true
ENV VIRTUAL_ENV /dummy/
# Expose port and run Gunicorn
EXPOSE 8000
# Generate documentation
WORKDIR /app/gracedb_project/docs/user_docs
RUN sphinx-build -b html source build
WORKDIR /app/gracedb_project/docs/admin_docs
RUN sphinx-build -b html source build
RUN mkdir /app/logs /app/project_data
WORKDIR /app/gracedb_project
RUN DJANGO_SETTINGS_MODULE=${SETTINGS_MODULE} \
DJANGO_DB_NAME=fake_name \
DJANGO_DB_USER=fake_user \
DJANGO_DB_PASSWORD=fake_password \
DJANGO_SECRET_KEY=fake_key \
DJANGO_PRIMARY_FQDN=fake_fqdn \
DJANGO_ALERT_EMAIL_FROM=fake_email \
EGAD_URL=fake_url \
EGAD_API_KEY=fake_key \
LVALERT_USER=fake_user \
LVALERT_PASSWORD=fake_password \
LVALERT_SERVER=fake_server \
LVALERT_OVERSEER_PORT=2 \
IGWN_ALERT_USER=fake_user \
IGWN_ALERT_PASSWORD=fake_password \
IGWN_ALERT_SERVER=fake_server \
IGWN_ALERT_OVERSEER_PORT=2 \
IGWN_ALERT_GROUP=fake_group \
DJANGO_TWILIO_ACCOUNT_SID=fake_sid \
DJANGO_TWILIO_AUTH_TOKEN=fake_token \
DJANGO_AWS_ELASTICACHE_ADDR=fake_address:11211 \
AWS_SES_ACCESS_KEY_ID=fake_aws_id \
AWS_SES_SECRET_ACCESS_KEY=fake_aws_key \
python3 manage.py collectstatic --noinput
RUN rm -rf /app/logs/* /app/project_data/*
RUN useradd -M -u 50001 -g www-data -s /bin/false gracedb
#RUN groupadd -r xray
#RUN useradd -M -u 50002 -g xray -s /bin/false xray
# set secure file/directory permissions. In particular, ADD command at
# beginning of recipe inherits umask of user running the build
RUN chmod 0755 /usr/local/bin/entrypoint && \
chmod 0755 /usr/local/bin/cleanup && \
chown gracedb:www-data /app/logs /app/project_data && \
chmod 0750 /app/logs /app/project_data && \
find /app/gracedb_project -type d -exec chmod 0755 {} + && \
find /app/gracedb_project -type f -exec chmod 0644 {} +
# create and set scitoken key cache directory
RUN mkdir /app/scitokens_cache && \
chown gracedb:www-data /app/scitokens_cache && \
chmod 0750 /app/scitokens_cache
ENV XDG_CACHE_HOME /app/scitokens_cache
# patch voeventparse for python3.10+:
RUN sed -i 's/collections.Iterable/collections.abc.Iterable/g' /usr/local/lib/python3.11/dist-packages/voeventparse/voevent.py
# Remove packages that expose security vulnerabilities and close out.
# Edit: zlib1g* can't be removed because of a PrePend error
RUN apt-get --assume-yes --purge autoremove wget libaom3 node-ip
RUN apt-get clean
ENTRYPOINT [ "/usr/local/bin/entrypoint" ]
CMD ["/usr/local/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
\ No newline at end of file
# GraceDB server code
Server code for the GRAvitational-wave Candidate Event Database.
You will need to fork this repository and submit a merge request
in order to make changes to the code.
\ No newline at end of file
#!/usr/bin/env python
#
# Generated Fri Mar 4 13:10:52 2011 by generateDS.py version 2.1a.
#
import sys
import getopt
from string import lower as str_lower
import re as re_
etree_ = None
Verbose_import_ = False
( XMLParser_import_none, XMLParser_import_lxml,
XMLParser_import_elementtree
) = range(3)
XMLParser_import_library = None
try:
# lxml
from lxml import etree as etree_
XMLParser_import_library = XMLParser_import_lxml
if Verbose_import_:
print("running with lxml.etree")
except ImportError:
try:
# cElementTree from Python 2.5+
import xml.etree.cElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# ElementTree from Python 2.5+
import xml.etree.ElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with ElementTree")
except ImportError:
raise ImportError("Failed to import ElementTree from any known place")
def parsexml_(*args, **kwargs):
if (XMLParser_import_library == XMLParser_import_lxml and
'parser' not in kwargs):
# Use the lxml ElementTree compatible parser so that, e.g.,
# we ignore comments.
kwargs['parser'] = etree_.ETCompatXMLParser()
doc = etree_.parse(*args, **kwargs)
return doc
#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these methods by re-implementing the following class
# in a module named generatedssuper.py.
try:
from generatedssuper import GeneratedsSuper
except ImportError, exp:
class GeneratedsSuper(object):
def format_string(self, input_data, input_name=''):
return input_data
def format_integer(self, input_data, input_name=''):
return '%d' % input_data
def format_float(self, input_data, input_name=''):
return '%f' % input_data
def format_double(self, input_data, input_name=''):
return '%e' % input_data
def format_boolean(self, input_data, input_name=''):
return '%s' % input_data
#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')
#
# Globals
#
ExternalEncoding = 'ascii'
Tag_pattern_ = re_.compile(r'({.*})?(.*)')
#
# Support/utility functions.
#
def showIndent(outfile, level):
for idx in range(level):
outfile.write(' ')
def quote_xml(inStr):
s1 = (isinstance(inStr, basestring) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&amp;')
s1 = s1.replace('<', '&lt;')
s1 = s1.replace('>', '&gt;')
return s1
def quote_attrib(inStr):
s1 = (isinstance(inStr, basestring) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&amp;')
s1 = s1.replace('<', '&lt;')
s1 = s1.replace('>', '&gt;')
if '"' in s1:
if "'" in s1:
s1 = '"%s"' % s1.replace('"', "&quot;")
else:
s1 = "'%s'" % s1
else:
s1 = '"%s"' % s1
return s1
def quote_python(inStr):
s1 = inStr
if s1.find("'") == -1:
if s1.find('\n') == -1:
return "'%s'" % s1
else:
return "'''%s'''" % s1
else:
if s1.find('"') != -1:
s1 = s1.replace('"', '\\"')
if s1.find('\n') == -1:
return '"%s"' % s1
else:
return '"""%s"""' % s1
def get_all_text_(node):
if node.text is not None:
text = node.text
else:
text = ''
for child in node:
if child.tail is not None:
text += child.tail
return text
class GDSParseError(Exception):
pass
def raise_parse_error(node, msg):
if XMLParser_import_library == XMLParser_import_lxml:
msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, )
else:
msg = '%s (element %s)' % (msg, node.tag, )
raise GDSParseError(msg)
class MixedContainer:
# Constants for category:
CategoryNone = 0
CategoryText = 1
CategorySimple = 2
CategoryComplex = 3
# Constants for content_type:
TypeNone = 0
TypeText = 1
TypeString = 2
TypeInteger = 3
TypeFloat = 4
TypeDecimal = 5
TypeDouble = 6
TypeBoolean = 7
def __init__(self, category, content_type, name, value):
self.category = category
self.content_type = content_type
self.name = name
self.value = value
def getCategory(self):
return self.category
def getContenttype(self, content_type):
return self.content_type
def getValue(self):
return self.value
def getName(self):
return self.name
def export(self, outfile, level, name, namespace):
if self.category == MixedContainer.CategoryText:
outfile.write(self.value)
elif self.category == MixedContainer.CategorySimple:
self.exportSimple(outfile, level, name)
else: # category == MixedContainer.CategoryComplex
self.value.export(outfile, level, namespace,name)
def exportSimple(self, outfile, level, name):
if self.content_type == MixedContainer.TypeString:
outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeInteger or \
self.content_type == MixedContainer.TypeBoolean:
outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeFloat or \
self.content_type == MixedContainer.TypeDecimal:
outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeDouble:
outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name))
def exportLiteral(self, outfile, level, name):
if self.category == MixedContainer.CategoryText:
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \
(self.category, self.content_type, self.name, self.value))
elif self.category == MixedContainer.CategorySimple:
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \
(self.category, self.content_type, self.name, self.value))
else: # category == MixedContainer.CategoryComplex
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
(self.category, self.content_type, self.name,))
self.value.exportLiteral(outfile, level + 1)
showIndent(outfile, level)
outfile.write(')\n')
class MemberSpec_(object):
def __init__(self, name='', data_type='', container=0):
self.name = name
self.data_type = data_type
self.container = container
def set_name(self, name): self.name = name
def get_name(self): return self.name
def set_data_type(self, data_type): self.data_type = data_type
def get_data_type_chain(self): return self.data_type
def get_data_type(self):
if isinstance(self.data_type, list):
if len(self.data_type) > 0:
return self.data_type[-1]
else:
return 'xs:string'
else:
return self.data_type
def set_container(self, container): self.container = container
def get_container(self): return self.container
def _cast(typ, value):
if typ is None or value is None:
return value
return typ(value)
#
# Data representation classes.
#
class VOEvent(GeneratedsSuper):
"""VOEvent is the root element for describing observations of immediate
astronomical events. For more information, see
http://www.ivoa.net/twiki/bin/view/IVOA/IvoaVOEvent. The event
consists of at most one of each of: Who, What, WhereWhen, How,
Why, Citations, Description, and Reference."""
subclass = None
superclass = None
def __init__(self, version=None, role='observation', ivorn=None, Who=None, What=None, WhereWhen=None, How=None, Why=None, Citations=None, Description=None, Reference=None):
self.version = _cast(None, version)
self.role = _cast(None, role)
self.ivorn = _cast(None, ivorn)
self.Who = Who
self.What = What
self.WhereWhen = WhereWhen
self.How = How
self.Why = Why
self.Citations = Citations
self.Description = Description
self.Reference = Reference
def factory(*args_, **kwargs_):
if VOEvent.subclass:
return VOEvent.subclass(*args_, **kwargs_)
else:
return VOEvent(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Who(self): return self.Who
def set_Who(self, Who): self.Who = Who
def get_What(self): return self.What
def set_What(self, What): self.What = What
def get_WhereWhen(self): return self.WhereWhen
def set_WhereWhen(self, WhereWhen): self.WhereWhen = WhereWhen
def get_How(self): return self.How
def set_How(self, How): self.How = How
def get_Why(self): return self.Why
def set_Why(self, Why): self.Why = Why
def get_Citations(self): return self.Citations
def set_Citations(self, Citations): self.Citations = Citations
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def get_version(self): return self.version
def set_version(self, version): self.version = version
def get_role(self): return self.role
def set_role(self, role): self.role = role
def validate_roleValues(self, value):
# Validate type roleValues, a restriction on xs:string.
pass
def get_ivorn(self): return self.ivorn
def set_ivorn(self, ivorn): self.ivorn = ivorn
def export(self, outfile, level, namespace_='', name_='VOEvent', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='VOEvent')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='VOEvent'):
outfile.write(' version=%s' % (self.format_string(quote_attrib(self.version).encode(ExternalEncoding), input_name='version'), ))
if self.role is not None:
outfile.write(' role=%s' % (quote_attrib(self.role), ))
outfile.write(' ivorn=%s' % (self.format_string(quote_attrib(self.ivorn).encode(ExternalEncoding), input_name='ivorn'), ))
def exportChildren(self, outfile, level, namespace_='', name_='VOEvent'):
if self.Who:
self.Who.export(outfile, level, namespace_, name_='Who')
if self.What:
self.What.export(outfile, level, namespace_, name_='What')
if self.WhereWhen:
self.WhereWhen.export(outfile, level, namespace_, name_='WhereWhen')
if self.How:
self.How.export(outfile, level, namespace_, name_='How')
if self.Why:
self.Why.export(outfile, level, namespace_, name_='Why')
if self.Citations:
self.Citations.export(outfile, level, namespace_, name_='Citations')
if self.Description is not None:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), namespace_))
if self.Reference:
self.Reference.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.Who is not None or
self.What is not None or
self.WhereWhen is not None or
self.How is not None or
self.Why is not None or
self.Citations is not None or
self.Description is not None or
self.Reference is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='VOEvent'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.version is not None:
showIndent(outfile, level)
outfile.write('version = "%s",\n' % (self.version,))
if self.role is not None:
showIndent(outfile, level)
outfile.write('role = "%s",\n' % (self.role,))
if self.ivorn is not None:
showIndent(outfile, level)
outfile.write('ivorn = "%s",\n' % (self.ivorn,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Who is not None:
showIndent(outfile, level)
outfile.write('Who=model_.Who(\n')
self.Who.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.What is not None:
showIndent(outfile, level)
outfile.write('What=model_.What(\n')
self.What.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.WhereWhen is not None:
showIndent(outfile, level)
outfile.write('WhereWhen=model_.WhereWhen(\n')
self.WhereWhen.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.How is not None:
showIndent(outfile, level)
outfile.write('How=model_.How(\n')
self.How.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Why is not None:
showIndent(outfile, level)
outfile.write('Why=model_.Why(\n')
self.Why.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Citations is not None:
showIndent(outfile, level)
outfile.write('Citations=model_.Citations(\n')
self.Citations.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
if self.Reference is not None:
showIndent(outfile, level)
outfile.write('Reference=model_.Reference(\n')
self.Reference.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('version')
if value is not None:
self.version = value
self.version = ' '.join(self.version.split())
value = attrs.get('role')
if value is not None:
self.role = value
self.validate_roleValues(self.role) # validate type roleValues
value = attrs.get('ivorn')
if value is not None:
self.ivorn = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Who':
obj_ = Who.factory()
obj_.build(child_)
self.set_Who(obj_)
elif nodeName_ == 'What':
obj_ = What.factory()
obj_.build(child_)
self.set_What(obj_)
elif nodeName_ == 'WhereWhen':
obj_ = WhereWhen.factory()
obj_.build(child_)
self.set_WhereWhen(obj_)
elif nodeName_ == 'How':
obj_ = How.factory()
obj_.build(child_)
self.set_How(obj_)
elif nodeName_ == 'Why':
obj_ = Why.factory()
obj_.build(child_)
self.set_Why(obj_)
elif nodeName_ == 'Citations':
obj_ = Citations.factory()
obj_.build(child_)
self.set_Citations(obj_)
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description = Description_
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.set_Reference(obj_)
# end class VOEvent
class Who(GeneratedsSuper):
"""Who: Curation Metadata"""
subclass = None
superclass = None
def __init__(self, AuthorIVORN=None, Date=None, Description=None, Reference=None, Author=None):
self.AuthorIVORN = AuthorIVORN
self.Date = Date
self.Description = Description
self.Reference = Reference
self.Author = Author
def factory(*args_, **kwargs_):
if Who.subclass:
return Who.subclass(*args_, **kwargs_)
else:
return Who(*args_, **kwargs_)
factory = staticmethod(factory)
def get_AuthorIVORN(self): return self.AuthorIVORN
def set_AuthorIVORN(self, AuthorIVORN): self.AuthorIVORN = AuthorIVORN
def get_Date(self): return self.Date
def set_Date(self, Date): self.Date = Date
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def get_Author(self): return self.Author
def set_Author(self, Author): self.Author = Author
def export(self, outfile, level, namespace_='', name_='Who', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Who')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Who'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='Who'):
if self.AuthorIVORN is not None:
showIndent(outfile, level)
outfile.write('<%sAuthorIVORN>%s</%sAuthorIVORN>\n' % (namespace_, self.format_string(quote_xml(self.AuthorIVORN).encode(ExternalEncoding), input_name='AuthorIVORN'), namespace_))
if self.Date is not None:
showIndent(outfile, level)
outfile.write('<%sDate>%s</%sDate>\n' % (namespace_, self.format_string(quote_xml(self.Date).encode(ExternalEncoding), input_name='Date'), namespace_))
if self.Description is not None:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), namespace_))
if self.Reference:
self.Reference.export(outfile, level, namespace_, name_='Reference')
if self.Author:
self.Author.export(outfile, level, namespace_, name_='Author')
def hasContent_(self):
if (
self.AuthorIVORN is not None or
self.Date is not None or
self.Description is not None or
self.Reference is not None or
self.Author is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Who'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.AuthorIVORN is not None:
showIndent(outfile, level)
outfile.write('AuthorIVORN=%s,\n' % quote_python(self.AuthorIVORN).encode(ExternalEncoding))
if self.Date is not None:
showIndent(outfile, level)
outfile.write('Date=%s,\n' % quote_python(self.Date).encode(ExternalEncoding))
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
if self.Reference is not None:
showIndent(outfile, level)
outfile.write('Reference=model_.Reference(\n')
self.Reference.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Author is not None:
showIndent(outfile, level)
outfile.write('Author=model_.Author(\n')
self.Author.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'AuthorIVORN':
AuthorIVORN_ = child_.text
self.AuthorIVORN = AuthorIVORN_
elif nodeName_ == 'Date':
Date_ = child_.text
self.Date = Date_
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description = Description_
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.set_Reference(obj_)
elif nodeName_ == 'Author':
obj_ = Author.factory()
obj_.build(child_)
self.set_Author(obj_)
# end class Who
class Author(GeneratedsSuper):
"""Author information follows the IVOA curation information schema: the
organization responsible for the packet can have a title, short
name or acronym, and a logo. A contact person has a name, email,
and phone number. Other contributors can also be noted."""
subclass = None
superclass = None
def __init__(self, title=None, shortName=None, logoURL=None, contactName=None, contactEmail=None, contactPhone=None, contributor=None):
if title is None:
self.title = []
else:
self.title = title
if shortName is None:
self.shortName = []
else:
self.shortName = shortName
if logoURL is None:
self.logoURL = []
else:
self.logoURL = logoURL
if contactName is None:
self.contactName = []
else:
self.contactName = contactName
if contactEmail is None:
self.contactEmail = []
else:
self.contactEmail = contactEmail
if contactPhone is None:
self.contactPhone = []
else:
self.contactPhone = contactPhone
if contributor is None:
self.contributor = []
else:
self.contributor = contributor
def factory(*args_, **kwargs_):
if Author.subclass:
return Author.subclass(*args_, **kwargs_)
else:
return Author(*args_, **kwargs_)
factory = staticmethod(factory)
def get_title(self): return self.title
def set_title(self, title): self.title = title
def add_title(self, value): self.title.append(value)
def insert_title(self, index, value): self.title[index] = value
def get_shortName(self): return self.shortName
def set_shortName(self, shortName): self.shortName = shortName
def add_shortName(self, value): self.shortName.append(value)
def insert_shortName(self, index, value): self.shortName[index] = value
def get_logoURL(self): return self.logoURL
def set_logoURL(self, logoURL): self.logoURL = logoURL
def add_logoURL(self, value): self.logoURL.append(value)
def insert_logoURL(self, index, value): self.logoURL[index] = value
def get_contactName(self): return self.contactName
def set_contactName(self, contactName): self.contactName = contactName
def add_contactName(self, value): self.contactName.append(value)
def insert_contactName(self, index, value): self.contactName[index] = value
def get_contactEmail(self): return self.contactEmail
def set_contactEmail(self, contactEmail): self.contactEmail = contactEmail
def add_contactEmail(self, value): self.contactEmail.append(value)
def insert_contactEmail(self, index, value): self.contactEmail[index] = value
def get_contactPhone(self): return self.contactPhone
def set_contactPhone(self, contactPhone): self.contactPhone = contactPhone
def add_contactPhone(self, value): self.contactPhone.append(value)
def insert_contactPhone(self, index, value): self.contactPhone[index] = value
def get_contributor(self): return self.contributor
def set_contributor(self, contributor): self.contributor = contributor
def add_contributor(self, value): self.contributor.append(value)
def insert_contributor(self, index, value): self.contributor[index] = value
def export(self, outfile, level, namespace_='', name_='Author', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Author')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Author'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='Author'):
for title_ in self.title:
showIndent(outfile, level)
outfile.write('<%stitle>%s</%stitle>\n' % (namespace_, self.format_string(quote_xml(title_).encode(ExternalEncoding), input_name='title'), namespace_))
for shortName_ in self.shortName:
showIndent(outfile, level)
outfile.write('<%sshortName>%s</%sshortName>\n' % (namespace_, self.format_string(quote_xml(shortName_).encode(ExternalEncoding), input_name='shortName'), namespace_))
for logoURL_ in self.logoURL:
showIndent(outfile, level)
outfile.write('<%slogoURL>%s</%slogoURL>\n' % (namespace_, self.format_string(quote_xml(logoURL_).encode(ExternalEncoding), input_name='logoURL'), namespace_))
for contactName_ in self.contactName:
showIndent(outfile, level)
outfile.write('<%scontactName>%s</%scontactName>\n' % (namespace_, self.format_string(quote_xml(contactName_).encode(ExternalEncoding), input_name='contactName'), namespace_))
for contactEmail_ in self.contactEmail:
showIndent(outfile, level)
outfile.write('<%scontactEmail>%s</%scontactEmail>\n' % (namespace_, self.format_string(quote_xml(contactEmail_).encode(ExternalEncoding), input_name='contactEmail'), namespace_))
for contactPhone_ in self.contactPhone:
showIndent(outfile, level)
outfile.write('<%scontactPhone>%s</%scontactPhone>\n' % (namespace_, self.format_string(quote_xml(contactPhone_).encode(ExternalEncoding), input_name='contactPhone'), namespace_))
for contributor_ in self.contributor:
showIndent(outfile, level)
outfile.write('<%scontributor>%s</%scontributor>\n' % (namespace_, self.format_string(quote_xml(contributor_).encode(ExternalEncoding), input_name='contributor'), namespace_))
def hasContent_(self):
if (
self.title or
self.shortName or
self.logoURL or
self.contactName or
self.contactEmail or
self.contactPhone or
self.contributor
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Author'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('title=[\n')
level += 1
for title_ in self.title:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(title_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('shortName=[\n')
level += 1
for shortName_ in self.shortName:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(shortName_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('logoURL=[\n')
level += 1
for logoURL_ in self.logoURL:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(logoURL_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('contactName=[\n')
level += 1
for contactName_ in self.contactName:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(contactName_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('contactEmail=[\n')
level += 1
for contactEmail_ in self.contactEmail:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(contactEmail_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('contactPhone=[\n')
level += 1
for contactPhone_ in self.contactPhone:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(contactPhone_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('contributor=[\n')
level += 1
for contributor_ in self.contributor:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(contributor_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'title':
title_ = child_.text
self.title.append(title_)
elif nodeName_ == 'shortName':
shortName_ = child_.text
self.shortName.append(shortName_)
elif nodeName_ == 'logoURL':
logoURL_ = child_.text
self.logoURL.append(logoURL_)
elif nodeName_ == 'contactName':
contactName_ = child_.text
self.contactName.append(contactName_)
elif nodeName_ == 'contactEmail':
contactEmail_ = child_.text
self.contactEmail.append(contactEmail_)
elif nodeName_ == 'contactPhone':
contactPhone_ = child_.text
self.contactPhone.append(contactPhone_)
elif nodeName_ == 'contributor':
contributor_ = child_.text
self.contributor.append(contributor_)
# end class Author
class What(GeneratedsSuper):
"""What: Event Characterization. This is the part of the data model
that is chosen by the Authoer of the event rather than the IVOA.
There can be Params, that may be in Groups, and Tables, and
simpleTimeSeries. There can also be Description and Reference as
with most VOEvent elements."""
subclass = None
superclass = None
def __init__(self, Param=None, Group=None, Table=None, Description=None, Reference=None):
if Param is None:
self.Param = []
else:
self.Param = Param
if Group is None:
self.Group = []
else:
self.Group = Group
if Table is None:
self.Table = []
else:
self.Table = Table
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
def factory(*args_, **kwargs_):
if What.subclass:
return What.subclass(*args_, **kwargs_)
else:
return What(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Param(self): return self.Param
def set_Param(self, Param): self.Param = Param
def add_Param(self, value): self.Param.append(value)
def insert_Param(self, index, value): self.Param[index] = value
def get_Group(self): return self.Group
def set_Group(self, Group): self.Group = Group
def add_Group(self, value): self.Group.append(value)
def insert_Group(self, index, value): self.Group[index] = value
def get_Table(self): return self.Table
def set_Table(self, Table): self.Table = Table
def add_Table(self, value): self.Table.append(value)
def insert_Table(self, index, value): self.Table[index] = value
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def export(self, outfile, level, namespace_='', name_='What', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='What')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='What'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='What'):
for Param_ in self.Param:
Param_.export(outfile, level, namespace_, name_='Param')
for Group_ in self.Group:
Group_.export(outfile, level, namespace_, name_='Group')
for Table_ in self.Table:
Table_.export(outfile, level, namespace_, name_='Table')
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.Param or
self.Group or
self.Table or
self.Description or
self.Reference
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='What'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Param=[\n')
level += 1
for Param_ in self.Param:
showIndent(outfile, level)
outfile.write('model_.Param(\n')
Param_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Group=[\n')
level += 1
for Group_ in self.Group:
showIndent(outfile, level)
outfile.write('model_.Group(\n')
Group_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Table=[\n')
level += 1
for Table_ in self.Table:
showIndent(outfile, level)
outfile.write('model_.Table(\n')
Table_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Param':
obj_ = Param.factory()
obj_.build(child_)
self.Param.append(obj_)
elif nodeName_ == 'Group':
obj_ = Group.factory()
obj_.build(child_)
self.Group.append(obj_)
elif nodeName_ == 'Table':
obj_ = Table.factory()
obj_.build(child_)
self.Table.append(obj_)
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
# end class What
class Param(GeneratedsSuper):
"""What/Param definition. A Param has name, value, ucd, unit, dataType;
and may have Description and Reference."""
subclass = None
superclass = None
def __init__(self, name=None, dataType='string', value=None, utype=None, ucd=None, unit=None, Description=None, Reference=None, Value=None):
self.name = _cast(None, name)
self.dataType = _cast(None, dataType)
self.value = _cast(None, value)
self.utype = _cast(None, utype)
self.ucd = _cast(None, ucd)
self.unit = _cast(None, unit)
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
self.Value = Value
def factory(*args_, **kwargs_):
if Param.subclass:
return Param.subclass(*args_, **kwargs_)
else:
return Param(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def get_Value(self): return self.Value
def set_Value(self, Value): self.Value = Value
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_dataType(self): return self.dataType
def set_dataType(self, dataType): self.dataType = dataType
def validate_dataType(self, value):
# Validate type dataType, a restriction on xs:string.
pass
def get_value(self): return self.value
def set_value(self, value): self.value = value
def get_utype(self): return self.utype
def set_utype(self, utype): self.utype = utype
def get_ucd(self): return self.ucd
def set_ucd(self, ucd): self.ucd = ucd
def get_unit(self): return self.unit
def set_unit(self, unit): self.unit = unit
def export(self, outfile, level, namespace_='', name_='Param', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Param')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Param'):
if self.name is not None:
outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
if self.dataType is not None:
outfile.write(' dataType=%s' % (quote_attrib(self.dataType), ))
if self.value is not None:
outfile.write(' value=%s' % (self.format_string(quote_attrib(self.value).encode(ExternalEncoding), input_name='value'), ))
if self.utype is not None:
outfile.write(' utype=%s' % (self.format_string(quote_attrib(self.utype).encode(ExternalEncoding), input_name='utype'), ))
if self.ucd is not None:
outfile.write(' ucd=%s' % (self.format_string(quote_attrib(self.ucd).encode(ExternalEncoding), input_name='ucd'), ))
if self.unit is not None:
outfile.write(' unit=%s' % (self.format_string(quote_attrib(self.unit).encode(ExternalEncoding), input_name='unit'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Param'):
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
if self.Value is not None:
showIndent(outfile, level)
outfile.write('<%sValue>%s</%sValue>\n' % (namespace_, self.format_string(quote_xml(self.Value).encode(ExternalEncoding), input_name='Value'), namespace_))
def hasContent_(self):
if (
self.Description or
self.Reference or
self.Value is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Param'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.name is not None:
showIndent(outfile, level)
outfile.write('name = "%s",\n' % (self.name,))
if self.dataType is not None:
showIndent(outfile, level)
outfile.write('dataType = "%s",\n' % (self.dataType,))
if self.value is not None:
showIndent(outfile, level)
outfile.write('value = "%s",\n' % (self.value,))
if self.utype is not None:
showIndent(outfile, level)
outfile.write('utype = "%s",\n' % (self.utype,))
if self.ucd is not None:
showIndent(outfile, level)
outfile.write('ucd = "%s",\n' % (self.ucd,))
if self.unit is not None:
showIndent(outfile, level)
outfile.write('unit = "%s",\n' % (self.unit,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.Value is not None:
showIndent(outfile, level)
outfile.write('Value=%s,\n' % quote_python(self.Value).encode(ExternalEncoding))
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('name')
if value is not None:
self.name = value
value = attrs.get('dataType')
if value is not None:
self.dataType = value
self.validate_dataType(self.dataType) # validate type dataType
value = attrs.get('value')
if value is not None:
self.value = value
value = attrs.get('utype')
if value is not None:
self.utype = value
value = attrs.get('ucd')
if value is not None:
self.ucd = value
value = attrs.get('unit')
if value is not None:
self.unit = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
elif nodeName_ == 'Value':
Value_ = child_.text
self.Value = Value_
# end class Param
class Group(GeneratedsSuper):
"""What/Group definition: A group is a collection of Params, with name
and type attributes."""
subclass = None
superclass = None
def __init__(self, type_=None, name=None, Param=None, Description=None, Reference=None):
self.type_ = _cast(None, type_)
self.name = _cast(None, name)
if Param is None:
self.Param = []
else:
self.Param = Param
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
def factory(*args_, **kwargs_):
if Group.subclass:
return Group.subclass(*args_, **kwargs_)
else:
return Group(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Param(self): return self.Param
def set_Param(self, Param): self.Param = Param
def add_Param(self, value): self.Param.append(value)
def insert_Param(self, index, value): self.Param[index] = value
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_name(self): return self.name
def set_name(self, name): self.name = name
def export(self, outfile, level, namespace_='', name_='Group', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Group')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Group'):
if self.type_ is not None:
outfile.write(' type=%s' % (self.format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), ))
if self.name is not None:
outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Group'):
for Param_ in self.Param:
Param_.export(outfile, level, namespace_, name_='Param')
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.Param or
self.Description or
self.Reference
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Group'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.type_ is not None:
showIndent(outfile, level)
outfile.write('type_ = "%s",\n' % (self.type_,))
if self.name is not None:
showIndent(outfile, level)
outfile.write('name = "%s",\n' % (self.name,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Param=[\n')
level += 1
for Param_ in self.Param:
showIndent(outfile, level)
outfile.write('model_.Param(\n')
Param_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('type')
if value is not None:
self.type_ = value
value = attrs.get('name')
if value is not None:
self.name = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Param':
obj_ = Param.factory()
obj_.build(child_)
self.Param.append(obj_)
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
# end class Group
class Table(GeneratedsSuper):
"""What/Table definition. This small Table has Fields for the column
definitions, and Data to hold the table data, with TR for row
and TD for value of a table cell."""
subclass = None
superclass = None
def __init__(self, type_=None, name=None, Description=None, Reference=None, Param=None, Field=None, Data=None):
self.type_ = _cast(None, type_)
self.name = _cast(None, name)
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
if Param is None:
self.Param = []
else:
self.Param = Param
if Field is None:
self.Field = []
else:
self.Field = Field
self.Data = Data
def factory(*args_, **kwargs_):
if Table.subclass:
return Table.subclass(*args_, **kwargs_)
else:
return Table(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def get_Param(self): return self.Param
def set_Param(self, Param): self.Param = Param
def add_Param(self, value): self.Param.append(value)
def insert_Param(self, index, value): self.Param[index] = value
def get_Field(self): return self.Field
def set_Field(self, Field): self.Field = Field
def add_Field(self, value): self.Field.append(value)
def insert_Field(self, index, value): self.Field[index] = value
def get_Data(self): return self.Data
def set_Data(self, Data): self.Data = Data
def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_name(self): return self.name
def set_name(self, name): self.name = name
def export(self, outfile, level, namespace_='', name_='Table', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Table')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Table'):
if self.type_ is not None:
outfile.write(' type=%s' % (self.format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), ))
if self.name is not None:
outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Table'):
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
for Param_ in self.Param:
Param_.export(outfile, level, namespace_, name_='Param')
for Field_ in self.Field:
Field_.export(outfile, level, namespace_, name_='Field')
if self.Data:
self.Data.export(outfile, level, namespace_, name_='Data', )
def hasContent_(self):
if (
self.Description or
self.Reference or
self.Param or
self.Field or
self.Data is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Table'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.type_ is not None:
showIndent(outfile, level)
outfile.write('type_ = "%s",\n' % (self.type_,))
if self.name is not None:
showIndent(outfile, level)
outfile.write('name = "%s",\n' % (self.name,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Param=[\n')
level += 1
for Param_ in self.Param:
showIndent(outfile, level)
outfile.write('model_.Param(\n')
Param_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Field=[\n')
level += 1
for Field_ in self.Field:
showIndent(outfile, level)
outfile.write('model_.Field(\n')
Field_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.Data is not None:
showIndent(outfile, level)
outfile.write('Data=model_.Data(\n')
self.Data.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('type')
if value is not None:
self.type_ = value
value = attrs.get('name')
if value is not None:
self.name = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
elif nodeName_ == 'Param':
obj_ = Param.factory()
obj_.build(child_)
self.Param.append(obj_)
elif nodeName_ == 'Field':
obj_ = Field.factory()
obj_.build(child_)
self.Field.append(obj_)
elif nodeName_ == 'Data':
obj_ = Data.factory()
obj_.build(child_)
self.set_Data(obj_)
# end class Table
class Field(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, dataType='string', utype=None, ucd=None, name=None, unit=None, Description=None, Reference=None):
self.dataType = _cast(None, dataType)
self.utype = _cast(None, utype)
self.ucd = _cast(None, ucd)
self.name = _cast(None, name)
self.unit = _cast(None, unit)
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
def factory(*args_, **kwargs_):
if Field.subclass:
return Field.subclass(*args_, **kwargs_)
else:
return Field(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def get_dataType(self): return self.dataType
def set_dataType(self, dataType): self.dataType = dataType
def validate_dataType(self, value):
# Validate type dataType, a restriction on xs:string.
pass
def get_utype(self): return self.utype
def set_utype(self, utype): self.utype = utype
def get_ucd(self): return self.ucd
def set_ucd(self, ucd): self.ucd = ucd
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_unit(self): return self.unit
def set_unit(self, unit): self.unit = unit
def export(self, outfile, level, namespace_='', name_='Field', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Field')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Field'):
if self.dataType is not None:
outfile.write(' dataType=%s' % (quote_attrib(self.dataType), ))
if self.utype is not None:
outfile.write(' utype=%s' % (self.format_string(quote_attrib(self.utype).encode(ExternalEncoding), input_name='utype'), ))
if self.ucd is not None:
outfile.write(' ucd=%s' % (self.format_string(quote_attrib(self.ucd).encode(ExternalEncoding), input_name='ucd'), ))
if self.name is not None:
outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
if self.unit is not None:
outfile.write(' unit=%s' % (self.format_string(quote_attrib(self.unit).encode(ExternalEncoding), input_name='unit'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Field'):
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.Description or
self.Reference
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Field'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.dataType is not None:
showIndent(outfile, level)
outfile.write('dataType = "%s",\n' % (self.dataType,))
if self.utype is not None:
showIndent(outfile, level)
outfile.write('utype = "%s",\n' % (self.utype,))
if self.ucd is not None:
showIndent(outfile, level)
outfile.write('ucd = "%s",\n' % (self.ucd,))
if self.name is not None:
showIndent(outfile, level)
outfile.write('name = "%s",\n' % (self.name,))
if self.unit is not None:
showIndent(outfile, level)
outfile.write('unit = "%s",\n' % (self.unit,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('dataType')
if value is not None:
self.dataType = value
self.validate_dataType(self.dataType) # validate type dataType
value = attrs.get('utype')
if value is not None:
self.utype = value
value = attrs.get('ucd')
if value is not None:
self.ucd = value
value = attrs.get('name')
if value is not None:
self.name = value
value = attrs.get('unit')
if value is not None:
self.unit = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
# end class Field
class Data(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, TR=None):
if TR is None:
self.TR = []
else:
self.TR = TR
def factory(*args_, **kwargs_):
if Data.subclass:
return Data.subclass(*args_, **kwargs_)
else:
return Data(*args_, **kwargs_)
factory = staticmethod(factory)
def get_TR(self): return self.TR
def set_TR(self, TR): self.TR = TR
def add_TR(self, value): self.TR.append(value)
def insert_TR(self, index, value): self.TR[index] = value
def export(self, outfile, level, namespace_='', name_='Data', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Data')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Data'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='Data'):
for TR_ in self.TR:
TR_.export(outfile, level, namespace_, name_='TR')
def hasContent_(self):
if (
self.TR
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Data'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('TR=[\n')
level += 1
for TR_ in self.TR:
showIndent(outfile, level)
outfile.write('model_.TR(\n')
TR_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'TR':
obj_ = TR.factory()
obj_.build(child_)
self.TR.append(obj_)
# end class Data
class TR(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, TD=None):
if TD is None:
self.TD = []
else:
self.TD = TD
def factory(*args_, **kwargs_):
if TR.subclass:
return TR.subclass(*args_, **kwargs_)
else:
return TR(*args_, **kwargs_)
factory = staticmethod(factory)
def get_TD(self): return self.TD
def set_TD(self, TD): self.TD = TD
def add_TD(self, value): self.TD.append(value)
def insert_TD(self, index, value): self.TD[index] = value
def export(self, outfile, level, namespace_='', name_='TR', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='TR')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='TR'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='TR'):
for TD_ in self.TD:
showIndent(outfile, level)
outfile.write('<%sTD>%s</%sTD>\n' % (namespace_, self.format_string(quote_xml(TD_).encode(ExternalEncoding), input_name='TD'), namespace_))
def hasContent_(self):
if (
self.TD
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='TR'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('TD=[\n')
level += 1
for TD_ in self.TD:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(TD_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'TD':
TD_ = child_.text
self.TD.append(TD_)
# end class TR
class WhereWhen(GeneratedsSuper):
"""WhereWhen: Space-Time Coordinates. Lots and lots of elements here,
but the import is that each event has these: observatory,
coord_system, time, timeError, longitude, latitude, posError."""
subclass = None
superclass = None
def __init__(self, id=None, ObsDataLocation=None, Description=None, Reference=None):
self.id = _cast(None, id)
self.ObsDataLocation = ObsDataLocation
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
def factory(*args_, **kwargs_):
if WhereWhen.subclass:
return WhereWhen.subclass(*args_, **kwargs_)
else:
return WhereWhen(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ObsDataLocation(self): return self.ObsDataLocation
def set_ObsDataLocation(self, ObsDataLocation): self.ObsDataLocation = ObsDataLocation
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='', name_='WhereWhen', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='WhereWhen')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='WhereWhen'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='WhereWhen'):
if self.ObsDataLocation:
self.ObsDataLocation.export(outfile, level, namespace_, name_='ObsDataLocation', )
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.ObsDataLocation is not None or
self.Description or
self.Reference
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='WhereWhen'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.id is not None:
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
def exportLiteralChildren(self, outfile, level, name_):
if self.ObsDataLocation is not None:
showIndent(outfile, level)
outfile.write('ObsDataLocation=model_.ObsDataLocation(\n')
self.ObsDataLocation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('id')
if value is not None:
self.id = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'ObsDataLocation':
obj_ = ObsDataLocation.factory()
obj_.build(child_)
self.set_ObsDataLocation(obj_)
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
# end class WhereWhen
class ObsDataLocation(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, ObservatoryLocation=None, ObservationLocation=None):
self.ObservatoryLocation = ObservatoryLocation
self.ObservationLocation = ObservationLocation
def factory(*args_, **kwargs_):
if ObsDataLocation.subclass:
return ObsDataLocation.subclass(*args_, **kwargs_)
else:
return ObsDataLocation(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ObservatoryLocation(self): return self.ObservatoryLocation
def set_ObservatoryLocation(self, ObservatoryLocation): self.ObservatoryLocation = ObservatoryLocation
def get_ObservationLocation(self): return self.ObservationLocation
def set_ObservationLocation(self, ObservationLocation): self.ObservationLocation = ObservationLocation
def export(self, outfile, level, namespace_='', name_='ObsDataLocation', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='ObsDataLocation')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='ObsDataLocation'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='ObsDataLocation'):
if self.ObservatoryLocation:
self.ObservatoryLocation.export(outfile, level, namespace_, name_='ObservatoryLocation', )
if self.ObservationLocation:
self.ObservationLocation.export(outfile, level, namespace_, name_='ObservationLocation', )
def hasContent_(self):
if (
self.ObservatoryLocation is not None or
self.ObservationLocation is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='ObsDataLocation'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.ObservatoryLocation is not None:
showIndent(outfile, level)
outfile.write('ObservatoryLocation=model_.ObservatoryLocation(\n')
self.ObservatoryLocation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ObservationLocation is not None:
showIndent(outfile, level)
outfile.write('ObservationLocation=model_.ObservationLocation(\n')
self.ObservationLocation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'ObservatoryLocation':
obj_ = ObservatoryLocation.factory()
obj_.build(child_)
self.set_ObservatoryLocation(obj_)
elif nodeName_ == 'ObservationLocation':
obj_ = ObservationLocation.factory()
obj_.build(child_)
self.set_ObservationLocation(obj_)
# end class ObsDataLocation
class ObservationLocation(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, AstroCoordSystem=None, AstroCoords=None):
self.AstroCoordSystem = AstroCoordSystem
self.AstroCoords = AstroCoords
def factory(*args_, **kwargs_):
if ObservationLocation.subclass:
return ObservationLocation.subclass(*args_, **kwargs_)
else:
return ObservationLocation(*args_, **kwargs_)
factory = staticmethod(factory)
def get_AstroCoordSystem(self): return self.AstroCoordSystem
def set_AstroCoordSystem(self, AstroCoordSystem): self.AstroCoordSystem = AstroCoordSystem
def get_AstroCoords(self): return self.AstroCoords
def set_AstroCoords(self, AstroCoords): self.AstroCoords = AstroCoords
def export(self, outfile, level, namespace_='', name_='ObservationLocation', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='ObservationLocation')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='ObservationLocation'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='ObservationLocation'):
if self.AstroCoordSystem:
self.AstroCoordSystem.export(outfile, level, namespace_, name_='AstroCoordSystem', )
if self.AstroCoords:
self.AstroCoords.export(outfile, level, namespace_, name_='AstroCoords', )
def hasContent_(self):
if (
self.AstroCoordSystem is not None or
self.AstroCoords is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='ObservationLocation'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.AstroCoordSystem is not None:
showIndent(outfile, level)
outfile.write('AstroCoordSystem=model_.AstroCoordSystem(\n')
self.AstroCoordSystem.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.AstroCoords is not None:
showIndent(outfile, level)
outfile.write('AstroCoords=model_.AstroCoords(\n')
self.AstroCoords.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'AstroCoordSystem':
obj_ = AstroCoordSystem.factory()
obj_.build(child_)
self.set_AstroCoordSystem(obj_)
elif nodeName_ == 'AstroCoords':
obj_ = AstroCoords.factory()
obj_.build(child_)
self.set_AstroCoords(obj_)
# end class ObservationLocation
class AstroCoordSystem(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, id=None, valueOf_=None):
self.id = _cast(None, id)
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if AstroCoordSystem.subclass:
return AstroCoordSystem.subclass(*args_, **kwargs_)
else:
return AstroCoordSystem(*args_, **kwargs_)
factory = staticmethod(factory)
def get_id(self): return self.id
def set_id(self, id): self.id = id
def validate_idValues(self, value):
# Validate type idValues, a restriction on xs:string.
pass
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='AstroCoordSystem', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='AstroCoordSystem')
if self.hasContent_():
outfile.write('>')
outfile.write(self.valueOf_)
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='AstroCoordSystem'):
if self.id is not None:
outfile.write(' id=%s' % (quote_attrib(self.id), ))
def exportChildren(self, outfile, level, namespace_='', name_='AstroCoordSystem'):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='AstroCoordSystem'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.id is not None:
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def build(self, node):
self.buildAttributes(node, node.attrib)
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('id')
if value is not None:
self.id = value
self.validate_idValues(self.id) # validate type idValues
def buildChildren(self, child_, nodeName_):
pass
# end class AstroCoordSystem
class AstroCoords(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, coord_system_id=None, Time=None, Position2D=None, Position3D=None):
self.coord_system_id = _cast(None, coord_system_id)
self.Time = Time
self.Position2D = Position2D
self.Position3D = Position3D
def factory(*args_, **kwargs_):
if AstroCoords.subclass:
return AstroCoords.subclass(*args_, **kwargs_)
else:
return AstroCoords(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Time(self): return self.Time
def set_Time(self, Time): self.Time = Time
def get_Position2D(self): return self.Position2D
def set_Position2D(self, Position2D): self.Position2D = Position2D
def get_Position3D(self): return self.Position3D
def set_Position3D(self, Position3D): self.Position3D = Position3D
def get_coord_system_id(self): return self.coord_system_id
def set_coord_system_id(self, coord_system_id): self.coord_system_id = coord_system_id
def validate_idValues(self, value):
# Validate type idValues, a restriction on xs:string.
pass
def export(self, outfile, level, namespace_='', name_='AstroCoords', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='AstroCoords')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='AstroCoords'):
if self.coord_system_id is not None:
outfile.write(' coord_system_id=%s' % (quote_attrib(self.coord_system_id), ))
def exportChildren(self, outfile, level, namespace_='', name_='AstroCoords'):
if self.Time:
self.Time.export(outfile, level, namespace_, name_='Time')
if self.Position2D:
self.Position2D.export(outfile, level, namespace_, name_='Position2D')
if self.Position3D:
self.Position3D.export(outfile, level, namespace_, name_='Position3D')
def hasContent_(self):
if (
self.Time is not None or
self.Position2D is not None or
self.Position3D is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='AstroCoords'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.coord_system_id is not None:
showIndent(outfile, level)
outfile.write('coord_system_id = "%s",\n' % (self.coord_system_id,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Time is not None:
showIndent(outfile, level)
outfile.write('Time=model_.Time(\n')
self.Time.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Position2D is not None:
showIndent(outfile, level)
outfile.write('Position2D=model_.Position2D(\n')
self.Position2D.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Position3D is not None:
showIndent(outfile, level)
outfile.write('Position3D=model_.Position3D(\n')
self.Position3D.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('coord_system_id')
if value is not None:
self.coord_system_id = value
self.validate_idValues(self.coord_system_id) # validate type idValues
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Time':
obj_ = Time.factory()
obj_.build(child_)
self.set_Time(obj_)
elif nodeName_ == 'Position2D':
obj_ = Position2D.factory()
obj_.build(child_)
self.set_Position2D(obj_)
elif nodeName_ == 'Position3D':
obj_ = Position3D.factory()
obj_.build(child_)
self.set_Position3D(obj_)
# end class AstroCoords
class Time(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, unit=None, TimeInstant=None, Error=None):
self.unit = _cast(None, unit)
self.TimeInstant = TimeInstant
self.Error = Error
def factory(*args_, **kwargs_):
if Time.subclass:
return Time.subclass(*args_, **kwargs_)
else:
return Time(*args_, **kwargs_)
factory = staticmethod(factory)
def get_TimeInstant(self): return self.TimeInstant
def set_TimeInstant(self, TimeInstant): self.TimeInstant = TimeInstant
def get_Error(self): return self.Error
def set_Error(self, Error): self.Error = Error
def get_unit(self): return self.unit
def set_unit(self, unit): self.unit = unit
def export(self, outfile, level, namespace_='', name_='Time', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Time')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Time'):
if self.unit is not None:
outfile.write(' unit=%s' % (self.format_string(quote_attrib(self.unit).encode(ExternalEncoding), input_name='unit'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Time'):
if self.TimeInstant:
self.TimeInstant.export(outfile, level, namespace_, name_='TimeInstant', )
if self.Error is not None:
showIndent(outfile, level)
outfile.write('<%sError>%s</%sError>\n' % (namespace_, self.format_float(self.Error, input_name='Error'), namespace_))
def hasContent_(self):
if (
self.TimeInstant is not None or
self.Error is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Time'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.unit is not None:
showIndent(outfile, level)
outfile.write('unit = "%s",\n' % (self.unit,))
def exportLiteralChildren(self, outfile, level, name_):
if self.TimeInstant is not None:
showIndent(outfile, level)
outfile.write('TimeInstant=model_.TimeInstant(\n')
self.TimeInstant.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Error is not None:
showIndent(outfile, level)
outfile.write('Error=%f,\n' % self.Error)
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('unit')
if value is not None:
self.unit = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'TimeInstant':
obj_ = TimeInstant.factory()
obj_.build(child_)
self.set_TimeInstant(obj_)
elif nodeName_ == 'Error':
sval_ = child_.text
try:
fval_ = float(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
self.Error = fval_
# end class Time
class TimeInstant(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, ISOTime=None):
self.ISOTime = ISOTime
def factory(*args_, **kwargs_):
if TimeInstant.subclass:
return TimeInstant.subclass(*args_, **kwargs_)
else:
return TimeInstant(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ISOTime(self): return self.ISOTime
def set_ISOTime(self, ISOTime): self.ISOTime = ISOTime
def export(self, outfile, level, namespace_='', name_='TimeInstant', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='TimeInstant')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='TimeInstant'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='TimeInstant'):
if self.ISOTime is not None:
showIndent(outfile, level)
outfile.write('<%sISOTime>%s</%sISOTime>\n' % (namespace_, self.format_string(quote_xml(self.ISOTime).encode(ExternalEncoding), input_name='ISOTime'), namespace_))
def hasContent_(self):
if (
self.ISOTime is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='TimeInstant'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.ISOTime is not None:
showIndent(outfile, level)
outfile.write('ISOTime=%s,\n' % quote_python(self.ISOTime).encode(ExternalEncoding))
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'ISOTime':
ISOTime_ = child_.text
self.ISOTime = ISOTime_
# end class TimeInstant
class Position2D(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, unit=None, Name1=None, Name2=None, Value2=None, Error2Radius=None):
self.unit = _cast(None, unit)
self.Name1 = Name1
self.Name2 = Name2
self.Value2 = Value2
self.Error2Radius = Error2Radius
def factory(*args_, **kwargs_):
if Position2D.subclass:
return Position2D.subclass(*args_, **kwargs_)
else:
return Position2D(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Name1(self): return self.Name1
def set_Name1(self, Name1): self.Name1 = Name1
def get_Name2(self): return self.Name2
def set_Name2(self, Name2): self.Name2 = Name2
def get_Value2(self): return self.Value2
def set_Value2(self, Value2): self.Value2 = Value2
def get_Error2Radius(self): return self.Error2Radius
def set_Error2Radius(self, Error2Radius): self.Error2Radius = Error2Radius
def get_unit(self): return self.unit
def set_unit(self, unit): self.unit = unit
def export(self, outfile, level, namespace_='', name_='Position2D', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Position2D')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Position2D'):
if self.unit is not None:
outfile.write(' unit=%s' % (self.format_string(quote_attrib(self.unit).encode(ExternalEncoding), input_name='unit'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Position2D'):
if self.Name1 is not None:
showIndent(outfile, level)
outfile.write('<%sName1>%s</%sName1>\n' % (namespace_, self.format_string(quote_xml(self.Name1).encode(ExternalEncoding), input_name='Name1'), namespace_))
if self.Name2 is not None:
showIndent(outfile, level)
outfile.write('<%sName2>%s</%sName2>\n' % (namespace_, self.format_string(quote_xml(self.Name2).encode(ExternalEncoding), input_name='Name2'), namespace_))
if self.Value2:
self.Value2.export(outfile, level, namespace_, name_='Value2', )
if self.Error2Radius is not None:
showIndent(outfile, level)
outfile.write('<%sError2Radius>%s</%sError2Radius>\n' % (namespace_, self.format_float(self.Error2Radius, input_name='Error2Radius'), namespace_))
def hasContent_(self):
if (
self.Name1 is not None or
self.Name2 is not None or
self.Value2 is not None or
self.Error2Radius is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Position2D'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.unit is not None:
showIndent(outfile, level)
outfile.write('unit = "%s",\n' % (self.unit,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Name1 is not None:
showIndent(outfile, level)
outfile.write('Name1=%s,\n' % quote_python(self.Name1).encode(ExternalEncoding))
if self.Name2 is not None:
showIndent(outfile, level)
outfile.write('Name2=%s,\n' % quote_python(self.Name2).encode(ExternalEncoding))
if self.Value2 is not None:
showIndent(outfile, level)
outfile.write('Value2=model_.Value2(\n')
self.Value2.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Error2Radius is not None:
showIndent(outfile, level)
outfile.write('Error2Radius=%f,\n' % self.Error2Radius)
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('unit')
if value is not None:
self.unit = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Name1':
Name1_ = child_.text
self.Name1 = Name1_
elif nodeName_ == 'Name2':
Name2_ = child_.text
self.Name2 = Name2_
elif nodeName_ == 'Value2':
obj_ = Value2.factory()
obj_.build(child_)
self.set_Value2(obj_)
elif nodeName_ == 'Error2Radius':
sval_ = child_.text
try:
fval_ = float(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
self.Error2Radius = fval_
# end class Position2D
class Position3D(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, unit=None, Name1=None, Name2=None, Name3=None, Value3=None):
self.unit = _cast(None, unit)
self.Name1 = Name1
self.Name2 = Name2
self.Name3 = Name3
self.Value3 = Value3
def factory(*args_, **kwargs_):
if Position3D.subclass:
return Position3D.subclass(*args_, **kwargs_)
else:
return Position3D(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Name1(self): return self.Name1
def set_Name1(self, Name1): self.Name1 = Name1
def get_Name2(self): return self.Name2
def set_Name2(self, Name2): self.Name2 = Name2
def get_Name3(self): return self.Name3
def set_Name3(self, Name3): self.Name3 = Name3
def get_Value3(self): return self.Value3
def set_Value3(self, Value3): self.Value3 = Value3
def get_unit(self): return self.unit
def set_unit(self, unit): self.unit = unit
def export(self, outfile, level, namespace_='', name_='Position3D', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Position3D')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Position3D'):
if self.unit is not None:
outfile.write(' unit=%s' % (self.format_string(quote_attrib(self.unit).encode(ExternalEncoding), input_name='unit'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Position3D'):
if self.Name1 is not None:
showIndent(outfile, level)
outfile.write('<%sName1>%s</%sName1>\n' % (namespace_, self.format_string(quote_xml(self.Name1).encode(ExternalEncoding), input_name='Name1'), namespace_))
if self.Name2 is not None:
showIndent(outfile, level)
outfile.write('<%sName2>%s</%sName2>\n' % (namespace_, self.format_string(quote_xml(self.Name2).encode(ExternalEncoding), input_name='Name2'), namespace_))
if self.Name3 is not None:
showIndent(outfile, level)
outfile.write('<%sName3>%s</%sName3>\n' % (namespace_, self.format_string(quote_xml(self.Name3).encode(ExternalEncoding), input_name='Name3'), namespace_))
if self.Value3:
self.Value3.export(outfile, level, namespace_, name_='Value3', )
def hasContent_(self):
if (
self.Name1 is not None or
self.Name2 is not None or
self.Name3 is not None or
self.Value3 is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Position3D'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.unit is not None:
showIndent(outfile, level)
outfile.write('unit = "%s",\n' % (self.unit,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Name1 is not None:
showIndent(outfile, level)
outfile.write('Name1=%s,\n' % quote_python(self.Name1).encode(ExternalEncoding))
if self.Name2 is not None:
showIndent(outfile, level)
outfile.write('Name2=%s,\n' % quote_python(self.Name2).encode(ExternalEncoding))
if self.Name3 is not None:
showIndent(outfile, level)
outfile.write('Name3=%s,\n' % quote_python(self.Name3).encode(ExternalEncoding))
if self.Value3 is not None:
showIndent(outfile, level)
outfile.write('Value3=model_.Value3(\n')
self.Value3.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('unit')
if value is not None:
self.unit = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Name1':
Name1_ = child_.text
self.Name1 = Name1_
elif nodeName_ == 'Name2':
Name2_ = child_.text
self.Name2 = Name2_
elif nodeName_ == 'Name3':
Name3_ = child_.text
self.Name3 = Name3_
elif nodeName_ == 'Value3':
obj_ = Value3.factory()
obj_.build(child_)
self.set_Value3(obj_)
# end class Position3D
class Value2(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, C1=None, C2=None):
self.C1 = C1
self.C2 = C2
def factory(*args_, **kwargs_):
if Value2.subclass:
return Value2.subclass(*args_, **kwargs_)
else:
return Value2(*args_, **kwargs_)
factory = staticmethod(factory)
def get_C1(self): return self.C1
def set_C1(self, C1): self.C1 = C1
def get_C2(self): return self.C2
def set_C2(self, C2): self.C2 = C2
def export(self, outfile, level, namespace_='', name_='Value2', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Value2')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Value2'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='Value2'):
if self.C1 is not None:
showIndent(outfile, level)
outfile.write('<%sC1>%s</%sC1>\n' % (namespace_, self.format_float(self.C1, input_name='C1'), namespace_))
if self.C2 is not None:
showIndent(outfile, level)
outfile.write('<%sC2>%s</%sC2>\n' % (namespace_, self.format_float(self.C2, input_name='C2'), namespace_))
def hasContent_(self):
if (
self.C1 is not None or
self.C2 is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Value2'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.C1 is not None:
showIndent(outfile, level)
outfile.write('C1=%f,\n' % self.C1)
if self.C2 is not None:
showIndent(outfile, level)
outfile.write('C2=%f,\n' % self.C2)
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'C1':
sval_ = child_.text
try:
fval_ = float(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
self.C1 = fval_
elif nodeName_ == 'C2':
sval_ = child_.text
try:
fval_ = float(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
self.C2 = fval_
# end class Value2
class Value3(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, C1=None, C2=None, C3=None):
self.C1 = C1
self.C2 = C2
self.C3 = C3
def factory(*args_, **kwargs_):
if Value3.subclass:
return Value3.subclass(*args_, **kwargs_)
else:
return Value3(*args_, **kwargs_)
factory = staticmethod(factory)
def get_C1(self): return self.C1
def set_C1(self, C1): self.C1 = C1
def get_C2(self): return self.C2
def set_C2(self, C2): self.C2 = C2
def get_C3(self): return self.C3
def set_C3(self, C3): self.C3 = C3
def export(self, outfile, level, namespace_='', name_='Value3', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Value3')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Value3'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='Value3'):
if self.C1 is not None:
showIndent(outfile, level)
outfile.write('<%sC1>%s</%sC1>\n' % (namespace_, self.format_float(self.C1, input_name='C1'), namespace_))
if self.C2 is not None:
showIndent(outfile, level)
outfile.write('<%sC2>%s</%sC2>\n' % (namespace_, self.format_float(self.C2, input_name='C2'), namespace_))
if self.C3 is not None:
showIndent(outfile, level)
outfile.write('<%sC3>%s</%sC3>\n' % (namespace_, self.format_float(self.C3, input_name='C3'), namespace_))
def hasContent_(self):
if (
self.C1 is not None or
self.C2 is not None or
self.C3 is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Value3'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.C1 is not None:
showIndent(outfile, level)
outfile.write('C1=%f,\n' % self.C1)
if self.C2 is not None:
showIndent(outfile, level)
outfile.write('C2=%f,\n' % self.C2)
if self.C3 is not None:
showIndent(outfile, level)
outfile.write('C3=%f,\n' % self.C3)
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'C1':
sval_ = child_.text
try:
fval_ = float(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
self.C1 = fval_
elif nodeName_ == 'C2':
sval_ = child_.text
try:
fval_ = float(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
self.C2 = fval_
elif nodeName_ == 'C3':
sval_ = child_.text
try:
fval_ = float(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
self.C3 = fval_
# end class Value3
class ObservatoryLocation(GeneratedsSuper):
"""Part of WhereWhen"""
subclass = None
superclass = None
def __init__(self, id=None, AstroCoordSystem=None, AstroCoords=None):
self.id = _cast(None, id)
self.AstroCoordSystem = AstroCoordSystem
self.AstroCoords = AstroCoords
def factory(*args_, **kwargs_):
if ObservatoryLocation.subclass:
return ObservatoryLocation.subclass(*args_, **kwargs_)
else:
return ObservatoryLocation(*args_, **kwargs_)
factory = staticmethod(factory)
def get_AstroCoordSystem(self): return self.AstroCoordSystem
def set_AstroCoordSystem(self, AstroCoordSystem): self.AstroCoordSystem = AstroCoordSystem
def get_AstroCoords(self): return self.AstroCoords
def set_AstroCoords(self, AstroCoords): self.AstroCoords = AstroCoords
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='', name_='ObservatoryLocation', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='ObservatoryLocation')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='ObservatoryLocation'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='ObservatoryLocation'):
if self.AstroCoordSystem:
self.AstroCoordSystem.export(outfile, level, namespace_, name_='AstroCoordSystem')
if self.AstroCoords:
self.AstroCoords.export(outfile, level, namespace_, name_='AstroCoords')
def hasContent_(self):
if (
self.AstroCoordSystem is not None or
self.AstroCoords is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='ObservatoryLocation'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.id is not None:
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
def exportLiteralChildren(self, outfile, level, name_):
if self.AstroCoordSystem is not None:
showIndent(outfile, level)
outfile.write('AstroCoordSystem=model_.AstroCoordSystem(\n')
self.AstroCoordSystem.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.AstroCoords is not None:
showIndent(outfile, level)
outfile.write('AstroCoords=model_.AstroCoords(\n')
self.AstroCoords.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('id')
if value is not None:
self.id = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'AstroCoordSystem':
obj_ = AstroCoordSystem.factory()
obj_.build(child_)
self.set_AstroCoordSystem(obj_)
elif nodeName_ == 'AstroCoords':
obj_ = AstroCoords.factory()
obj_.build(child_)
self.set_AstroCoords(obj_)
# end class ObservatoryLocation
class How(GeneratedsSuper):
"""How: Instrument Configuration. Built with some Description and
Reference elements."""
subclass = None
superclass = None
def __init__(self, Description=None, Reference=None):
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
def factory(*args_, **kwargs_):
if How.subclass:
return How.subclass(*args_, **kwargs_)
else:
return How(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def export(self, outfile, level, namespace_='', name_='How', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='How')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='How'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='How'):
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.Description or
self.Reference
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='How'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
# end class How
class Why(GeneratedsSuper):
"""Why: Initial Scientific Assessment. Can make simple
Concept/Name/Desc/Ref for the inference or use multiple
Inference containers for more semantic sophistication."""
subclass = None
superclass = None
def __init__(self, importance=None, expires=None, Name=None, Concept=None, Inference=None, Description=None, Reference=None):
self.importance = _cast(float, importance)
self.expires = _cast(None, expires)
if Name is None:
self.Name = []
else:
self.Name = Name
if Concept is None:
self.Concept = []
else:
self.Concept = Concept
if Inference is None:
self.Inference = []
else:
self.Inference = Inference
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
def factory(*args_, **kwargs_):
if Why.subclass:
return Why.subclass(*args_, **kwargs_)
else:
return Why(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Name(self): return self.Name
def set_Name(self, Name): self.Name = Name
def add_Name(self, value): self.Name.append(value)
def insert_Name(self, index, value): self.Name[index] = value
def get_Concept(self): return self.Concept
def set_Concept(self, Concept): self.Concept = Concept
def add_Concept(self, value): self.Concept.append(value)
def insert_Concept(self, index, value): self.Concept[index] = value
def get_Inference(self): return self.Inference
def set_Inference(self, Inference): self.Inference = Inference
def add_Inference(self, value): self.Inference.append(value)
def insert_Inference(self, index, value): self.Inference[index] = value
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def get_importance(self): return self.importance
def set_importance(self, importance): self.importance = importance
def get_expires(self): return self.expires
def set_expires(self, expires): self.expires = expires
def export(self, outfile, level, namespace_='', name_='Why', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Why')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Why'):
if self.importance is not None:
outfile.write(' importance="%s"' % self.format_float(self.importance, input_name='importance'))
if self.expires is not None:
outfile.write(' expires=%s' % (self.format_string(quote_attrib(self.expires).encode(ExternalEncoding), input_name='expires'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Why'):
for Name_ in self.Name:
showIndent(outfile, level)
outfile.write('<%sName>%s</%sName>\n' % (namespace_, self.format_string(quote_xml(Name_).encode(ExternalEncoding), input_name='Name'), namespace_))
for Concept_ in self.Concept:
showIndent(outfile, level)
outfile.write('<%sConcept>%s</%sConcept>\n' % (namespace_, self.format_string(quote_xml(Concept_).encode(ExternalEncoding), input_name='Concept'), namespace_))
for Inference_ in self.Inference:
Inference_.export(outfile, level, namespace_, name_='Inference')
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.Name or
self.Concept or
self.Inference or
self.Description or
self.Reference
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Why'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.importance is not None:
showIndent(outfile, level)
outfile.write('importance = %f,\n' % (self.importance,))
if self.expires is not None:
showIndent(outfile, level)
outfile.write('expires = "%s",\n' % (self.expires,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Name=[\n')
level += 1
for Name_ in self.Name:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Name_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Concept=[\n')
level += 1
for Concept_ in self.Concept:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Concept_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Inference=[\n')
level += 1
for Inference_ in self.Inference:
showIndent(outfile, level)
outfile.write('model_.Inference(\n')
Inference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('importance')
if value is not None:
try:
self.importance = float(value)
except ValueError, exp:
raise ValueError('Bad float/double attribute (importance): %s' % exp)
value = attrs.get('expires')
if value is not None:
self.expires = value
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Name':
Name_ = child_.text
self.Name.append(Name_)
elif nodeName_ == 'Concept':
Concept_ = child_.text
self.Concept.append(Concept_)
elif nodeName_ == 'Inference':
obj_ = Inference.factory()
obj_.build(child_)
self.Inference.append(obj_)
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
# end class Why
class Inference(GeneratedsSuper):
"""Why/Inference: A container for a more nuanced expression, including
relationships and probability."""
subclass = None
superclass = None
def __init__(self, relation=None, probability=None, Name=None, Concept=None, Description=None, Reference=None):
self.relation = _cast(None, relation)
self.probability = _cast(None, probability)
if Name is None:
self.Name = []
else:
self.Name = Name
if Concept is None:
self.Concept = []
else:
self.Concept = Concept
if Description is None:
self.Description = []
else:
self.Description = Description
if Reference is None:
self.Reference = []
else:
self.Reference = Reference
def factory(*args_, **kwargs_):
if Inference.subclass:
return Inference.subclass(*args_, **kwargs_)
else:
return Inference(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Name(self): return self.Name
def set_Name(self, Name): self.Name = Name
def add_Name(self, value): self.Name.append(value)
def insert_Name(self, index, value): self.Name[index] = value
def get_Concept(self): return self.Concept
def set_Concept(self, Concept): self.Concept = Concept
def add_Concept(self, value): self.Concept.append(value)
def insert_Concept(self, index, value): self.Concept[index] = value
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def add_Description(self, value): self.Description.append(value)
def insert_Description(self, index, value): self.Description[index] = value
def get_Reference(self): return self.Reference
def set_Reference(self, Reference): self.Reference = Reference
def add_Reference(self, value): self.Reference.append(value)
def insert_Reference(self, index, value): self.Reference[index] = value
def get_relation(self): return self.relation
def set_relation(self, relation): self.relation = relation
def get_probability(self): return self.probability
def set_probability(self, probability): self.probability = probability
def validate_smallFloat(self, value):
# Validate type smallFloat, a restriction on xs:float.
pass
def export(self, outfile, level, namespace_='', name_='Inference', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Inference')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Inference'):
if self.relation is not None:
outfile.write(' relation=%s' % (self.format_string(quote_attrib(self.relation).encode(ExternalEncoding), input_name='relation'), ))
if self.probability is not None:
outfile.write(' probability=%s' % (quote_attrib(self.probability), ))
def exportChildren(self, outfile, level, namespace_='', name_='Inference'):
for Name_ in self.Name:
showIndent(outfile, level)
outfile.write('<%sName>%s</%sName>\n' % (namespace_, self.format_string(quote_xml(Name_).encode(ExternalEncoding), input_name='Name'), namespace_))
for Concept_ in self.Concept:
showIndent(outfile, level)
outfile.write('<%sConcept>%s</%sConcept>\n' % (namespace_, self.format_string(quote_xml(Concept_).encode(ExternalEncoding), input_name='Concept'), namespace_))
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(Description_).encode(ExternalEncoding), input_name='Description'), namespace_))
for Reference_ in self.Reference:
Reference_.export(outfile, level, namespace_, name_='Reference')
def hasContent_(self):
if (
self.Name or
self.Concept or
self.Description or
self.Reference
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Inference'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.relation is not None:
showIndent(outfile, level)
outfile.write('relation = "%s",\n' % (self.relation,))
if self.probability is not None:
showIndent(outfile, level)
outfile.write('probability = %f,\n' % (self.probability,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Name=[\n')
level += 1
for Name_ in self.Name:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Name_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Concept=[\n')
level += 1
for Concept_ in self.Concept:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Concept_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Description=[\n')
level += 1
for Description_ in self.Description:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(Description_).encode(ExternalEncoding))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Reference=[\n')
level += 1
for Reference_ in self.Reference:
showIndent(outfile, level)
outfile.write('model_.Reference(\n')
Reference_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('relation')
if value is not None:
self.relation = value
value = attrs.get('probability')
if value is not None:
self.probability = value
self.validate_smallFloat(self.probability) # validate type smallFloat
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'Name':
Name_ = child_.text
self.Name.append(Name_)
elif nodeName_ == 'Concept':
Concept_ = child_.text
self.Concept.append(Concept_)
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description.append(Description_)
elif nodeName_ == 'Reference':
obj_ = Reference.factory()
obj_.build(child_)
self.Reference.append(obj_)
# end class Inference
class Citations(GeneratedsSuper):
"""Citations: Follow-up Observations. This section is a sequence of
EventIVORN elements, each of which has the IVORN of a cited
event."""
subclass = None
superclass = None
def __init__(self, EventIVORN=None, Description=None):
if EventIVORN is None:
self.EventIVORN = []
else:
self.EventIVORN = EventIVORN
self.Description = Description
def factory(*args_, **kwargs_):
if Citations.subclass:
return Citations.subclass(*args_, **kwargs_)
else:
return Citations(*args_, **kwargs_)
factory = staticmethod(factory)
def get_EventIVORN(self): return self.EventIVORN
def set_EventIVORN(self, EventIVORN): self.EventIVORN = EventIVORN
def add_EventIVORN(self, value): self.EventIVORN.append(value)
def insert_EventIVORN(self, index, value): self.EventIVORN[index] = value
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def export(self, outfile, level, namespace_='', name_='Citations', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Citations')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Citations'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='Citations'):
for EventIVORN_ in self.EventIVORN:
EventIVORN_.export(outfile, level, namespace_, name_='EventIVORN')
if self.Description is not None:
showIndent(outfile, level)
outfile.write('<%sDescription>%s</%sDescription>\n' % (namespace_, self.format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), namespace_))
def hasContent_(self):
if (
self.EventIVORN or
self.Description is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Citations'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('EventIVORN=[\n')
level += 1
for EventIVORN_ in self.EventIVORN:
showIndent(outfile, level)
outfile.write('model_.EventIVORN(\n')
EventIVORN_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
def build(self, node):
self.buildAttributes(node, node.attrib)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
pass
def buildChildren(self, child_, nodeName_):
if nodeName_ == 'EventIVORN':
obj_ = EventIVORN.factory()
obj_.build(child_)
self.EventIVORN.append(obj_)
elif nodeName_ == 'Description':
Description_ = child_.text
self.Description = Description_
# end class Citations
class EventIVORN(GeneratedsSuper):
"""Citations/EventIVORN. The value is the IVORN of the cited event, the
'cite' attribute is the nature of that relationship, choosing
from 'followup', 'supersedes', or 'retraction'."""
subclass = None
superclass = None
def __init__(self, cite=None, valueOf_=None):
self.cite = _cast(None, cite)
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if EventIVORN.subclass:
return EventIVORN.subclass(*args_, **kwargs_)
else:
return EventIVORN(*args_, **kwargs_)
factory = staticmethod(factory)
def get_cite(self): return self.cite
def set_cite(self, cite): self.cite = cite
def validate_citeValues(self, value):
# Validate type citeValues, a restriction on xs:string.
pass
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='EventIVORN', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='EventIVORN')
if self.hasContent_():
outfile.write('>')
outfile.write(self.valueOf_)
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='EventIVORN'):
if self.cite is not None:
outfile.write(' cite=%s' % (quote_attrib(self.cite), ))
def exportChildren(self, outfile, level, namespace_='', name_='EventIVORN'):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='EventIVORN'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.cite is not None:
showIndent(outfile, level)
outfile.write('cite = "%s",\n' % (self.cite,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def build(self, node):
self.buildAttributes(node, node.attrib)
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('cite')
if value is not None:
self.cite = value
self.validate_citeValues(self.cite) # validate type citeValues
def buildChildren(self, child_, nodeName_):
pass
# end class EventIVORN
class Reference(GeneratedsSuper):
"""Reference: External Content. The payload is the uri, and the 'type'
describes the nature of the data under that uri. The Reference
can also be named."""
subclass = None
superclass = None
def __init__(self, type_='url', uri=None, name=None, valueOf_=None):
self.type_ = _cast(None, type_)
self.uri = _cast(None, uri)
self.name = _cast(None, name)
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if Reference.subclass:
return Reference.subclass(*args_, **kwargs_)
else:
return Reference(*args_, **kwargs_)
factory = staticmethod(factory)
def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_uri(self): return self.uri
def set_uri(self, uri): self.uri = uri
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='Reference', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
self.exportAttributes(outfile, level, namespace_, name_='Reference')
if self.hasContent_():
outfile.write('>')
outfile.write(self.valueOf_)
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, namespace_='', name_='Reference'):
if self.type_ is not None:
outfile.write(' type=%s' % (self.format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), ))
outfile.write(' uri=%s' % (self.format_string(quote_attrib(self.uri).encode(ExternalEncoding), input_name='uri'), ))
if self.name is not None:
outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
def exportChildren(self, outfile, level, namespace_='', name_='Reference'):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Reference'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
if self.type_ is not None:
showIndent(outfile, level)
outfile.write('type_ = "%s",\n' % (self.type_,))
if self.uri is not None:
showIndent(outfile, level)
outfile.write('uri = "%s",\n' % (self.uri,))
if self.name is not None:
showIndent(outfile, level)
outfile.write('name = "%s",\n' % (self.name,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def build(self, node):
self.buildAttributes(node, node.attrib)
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, nodeName_)
def buildAttributes(self, node, attrs):
value = attrs.get('type')
if value is not None:
self.type_ = value
value = attrs.get('uri')
if value is not None:
self.uri = value
value = attrs.get('name')
if value is not None:
self.name = value
def buildChildren(self, child_, nodeName_):
pass
# end class Reference
USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
"""
def usage():
print USAGE_TEXT
sys.exit(1)
def get_root_tag(node):
tag = Tag_pattern_.match(node.tag).groups()[-1]
rootClass = globals().get(tag)
return tag, rootClass
def parse(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0, name_=rootTag,
namespacedef_='')
return rootObj
def parseString(inString):
from StringIO import StringIO
doc = parsexml_(StringIO(inString))
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0, name_="VOEvent",
namespacedef_='')
return rootObj
def parseLiteral(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('#from VOEvent import *\n\n')
sys.stdout.write('import VOEvent as model_\n\n')
sys.stdout.write('rootObj = model_.rootTag(\n')
rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
sys.stdout.write(')\n')
return rootObj
def main():
args = sys.argv[1:]
if len(args) == 1:
parse(args[0])
else:
usage()
if __name__ == '__main__':
#import pdb; pdb.set_trace()
main()
import sys
import VOEvent
class VOEventExportClass(VOEvent.VOEvent):
def __init__(self, event, schemaURL):
self.event = event
self.schemaURL = schemaURL
def export(self, outfile, level, namespace_='', name_='VOEvent', namespacedef_=''):
VOEvent.showIndent(outfile, level)
added_stuff = 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n'
added_stuff += 'xmlns:voe="http://www.ivoa.net/xml/VOEvent/v2.0"\n'
added_stuff += 'xsi:schemaLocation="http://www.ivoa.net/xml/VOEvent/v2.0 %s"\n' % self.schemaURL
outfile.write('<%s%s%s %s' % (namespace_, name_,
namespacedef_ and ' ' + namespacedef_ or '',
added_stuff,
))
# self.event.exportAttributes(outfile, level, [], namespace_)
self.event.exportAttributes(outfile, level, [])
if self.event.hasContent_():
outfile.write('>\n')
# self.event.exportChildren(outfile, level + 1, namespace_='', name_)
self.event.exportChildren(outfile, level + 1, '', name_)
VOEvent.showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def stringVOEvent(event, schemaURL = "http://www.ivoa.net/xml/VOEvent/VOEvent-v2.0.xsd"):
'''
Converts a VOEvent to a string suitable for output
'''
v = VOEventExportClass(event, schemaURL)
out = StringIO()
out.write('<?xml version="1.0" ?>\n')
v.export(out, 0, namespace_='voe:')
out.write('\n')
return out.getvalue()
def paramValue(p):
s1 = p.get_value()
s2 = p.get_Value()
if not s2: return s1
if not s1: return s2
if len(s1) > len(s2): return s1
else: return s2
def htmlList(list):
'''
Converts a list of strings to an HTML <ul><li> structure.
'''
s = '<ul>'
for x in list:
s += '<li>' + str(x) + '</li>'
s += '</ul>'
return s
def htmlParam(g, p):
'''
Builds an HTML table row from a Param and its enclosing Group (or None)
'''
s = ''
if g == None:
s += '<td/>'
else:
s += '<td>' + g.get_name() + '</td>'
s += '<td>' + str(p.get_name()) + '</td>'
s += '<td>'
for d in p.get_Description(): s += str(d)
s += '</td>'
s += '<td><b>' + str(paramValue(p)) + '</b></td>'
s += '<td>' + str(p.get_ucd()) + '</td>'
s += '<td>' + str(p.get_unit()) + '</td>'
s += '<td>' + str(p.get_dataType()) + '</td>'
return s
def parse(file):
'''
Parses a file and builds the VOEvent DOM.
'''
doc = VOEvent.parsexml_(file)
rootNode = doc.getroot()
rootTag, rootClass = VOEvent.get_root_tag(rootNode)
v = rootClass.factory()
v.build(rootNode)
return v
def parseString(inString):
'''
Parses a string and builds the VOEvent DOM.
'''
from StringIO import StringIO
doc = VOEvent.parsexml_(StringIO(inString))
rootNode = doc.getroot()
rootTag, rootClass = VOEvent.get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
return rootObj
def getWhereWhen(v):
'''
Builds a dictionary of the information in the WhereWhen section:
observatory: location of observatory (string);
coord_system: coordinate system ID, for example UTC-FK5-GEO;
time: ISO8601 representation of time, for example 1918-11-11T11:11:11;
timeError: in seconds;
longitude: in degrees, usually right ascension;
latitiude: in degrees, usually declination;
positionalError: positional error in degrees.
'''
wwd = {}
ww = v.get_WhereWhen()
if not ww:
return wwd
w = ww.get_ObsDataLocation()
if not w:
return wwd
ol = w.get_ObservatoryLocation()
if ol:
wwd['observatory'] = ol.get_id()
ol = w.get_ObservationLocation()
if not ol:
return wwd
observation = ol.get_AstroCoords()
if not observation:
return wwd
wwd['coord_system'] = observation.get_coord_system_id()
time = observation.get_Time()
wwd['time'] = time.get_TimeInstant().get_ISOTime()
wwd['timeError'] = time.get_Error()
pos = observation.get_Position2D()
if not pos:
return wwd
wwd['positionalError'] = pos.get_Error2Radius()
v2 = pos.get_Value2()
if not v2:
return wwd
wwd['longitude'] = v2.get_C1()
wwd['latitude'] = v2.get_C2()
return wwd
def makeWhereWhen(wwd):
'''
Expects a dictionary of the information in the WhereWhen section, and makes a
VOEvent.WhereWhen object suitable for set_WhereWhen().
observatory: location of observatory (string);
coord_system: coordinate system ID, for example UTC-FK5-GEO;
time: ISO8601 representation of time, for example 1918-11-11T11:11:11;
timeError: in seconds;
longitude: in degrees, usually right ascension;
latitiude: in degrees, usually declination;
positionalError: positional error in degrees.
'''
if not wwd.has_key('observatory'): wwd['observatory'] = 'unknown'
if not wwd.has_key('coord_system'): wwd['coord_system'] = 'UTC-FK5-GEO'
if not wwd.has_key('timeError'): wwd['timeError'] = 0.0
if not wwd.has_key('positionalError'): wwd['positionalError'] = 0.0
if not wwd.has_key('time'):
print "Cannot make WhereWhen without time"
return None
if not wwd.has_key('longitude'):
print "Cannot make WhereWhen without longitude"
return None
if not wwd.has_key('latitude'):
print "Cannot make WhereWhen without latitude"
return None
ac = VOEvent.AstroCoords(coord_system_id=wwd['coord_system'])
ac.set_Time(
VOEvent.Time(
TimeInstant = VOEvent.TimeInstant(wwd['time'])))
ac.set_Position2D(
VOEvent.Position2D(
Value2 = VOEvent.Value2(wwd['longitude'], wwd['latitude']),
Error2Radius = wwd['positionalError']))
acs = VOEvent.AstroCoordSystem(id=wwd['coord_system'])
onl = VOEvent.ObservationLocation(acs, ac)
oyl = VOEvent.ObservatoryLocation(id=wwd['observatory'])
odl = VOEvent.ObsDataLocation(oyl, onl)
ww = VOEvent.WhereWhen()
ww.set_ObsDataLocation(odl)
return ww
def getParamNames(v):
'''
Takes a VOEvent and produces a list of pairs of group name and param name.
For a bare param, the group name is the empty string.
'''
list = []
w = v.get_What()
if not w: return list
for p in v.get_What().get_Param():
list.append(('', p.get_name()))
for g in v.get_What().get_Group():
for p in v.get_What().get_Param():
list.append((g.get_Name(), p.get_Name()))
return list
def findParam(event, groupName, paramName):
'''
Finds a Param in a given VOEvent that has the specified groupName
and paramName. If it is a bare param, the group name is the empty string.
'''
w = event.get_What()
if not w:
print "No <What> section in the event!"
return None
if groupName == '':
for p in event.get_What().get_Param():
if p.get_name() == paramName:
return p
else:
for g in event.get_What().get_Group():
if g.get_Name == groupName:
for p in event.get_What().get_Param():
if p.get_name() == paramName:
return p
print 'Cannot find param named %s/%s' % (groupName, paramName)
return None
######## utilityTable ########################
class utilityTable(VOEvent.Table):
'''
Class to represent a simple Table from VOEvent
'''
def __init__(self, table):
self.table = table
self.colNames = []
self.default = []
col = 0
for f in table.get_Field():
if f.get_name():
self.colNames.append(f.get_name())
type = f.get_dataType()
if type == 'float': self.default.append(0.0)
elif type == 'int': self.default.append(0)
else: self.default.append('')
def getTable(self):
return self.table
def blankTable(self, nrows):
'''
From a table template, replaces the Data section with nrows of empty TR and TD
'''
data = VOEvent.Data()
ncol = len(self.colNames)
for i in range(nrows):
tr = VOEvent.TR()
for col in range(ncol):
tr.add_TD(self.default[col])
data.add_TR(tr)
self.table.set_Data(data)
def getByCols(self):
'''
Returns a dictionary of column vectors that represent the table.
The key for the dict is the Field name for that column.
'''
d = self.table.get_Data()
nrow = len(d.get_TR())
ncol = len(self.colNames)
# we will build a matrix nrow*ncol and fill in the values as they
# come in, with col varying fastest. The return is a dictionary,
# arranged by column name, each with a vector of
# properly typed values.
data = []
for col in range(ncol):
data.append([self.default[col]]*nrow)
row = 0
for tr in d.get_TR():
col = 0
for td in tr.get_TD():
data[col][row] = td
col += 1
row += 1
dict = {}
col = 0
for colName in self.colNames:
dict[colName] = data[col]
col += 1
return dict
def setValue(self, name, irow, value, out=sys.stdout):
'''
Copies a single value into a cell of the table.
The column is identified by its name, and the row by an index 0,1,2...
'''
if name in self.colNames:
icol = self.colNames.index(name)
else:
print>>out, "setTable: Unknown column name %s. Known list is %s" % (name, str(self.colNames))
return False
d = self.table.get_Data()
ncols = len(self.colNames)
nrows = len(d.get_TR())
if nrows <= irow:
print>>out, "setTable: not enough rows -- you want %d, table has %d. Use blankTable to allocate the table." % (irow+1, nrows)
return False
tr = d.get_TR()[irow]
row = tr.get_TD()
row[icol] = value
tr.set_TD(row)
def toString(self):
'''
Makes a crude string representation of a utilityTable
'''
s = ' '
for name in self.colNames:
s += '%9s|' % name[:9]
s += '\n\n'
d = self.table.get_Data()
for tr in d.get_TR():
for td in tr.get_TD():
s += '%10s' % str(td)[:10]
s += '\n'
return s
{
"name": "gracedb",
"dependencies": {
"dijit": "1.10.4",
"dojox": "1.10.4"
}
}
File moved
# To run this manually (not via systemd):
# gunicorn --config config/gunicorn_config.py config.wsgi:application
# (assuming that you are in the base directory of the GraceDB server code repo)
import os
from os.path import abspath, dirname, join
import sys
import multiprocessing
# Useful function for getting environment variables
def get_from_env(envvar, default_value=None, fail_if_not_found=True):
value = os.environ.get(envvar, default_value)
if (value == default_value and fail_if_not_found):
raise ImproperlyConfigured(
'Could not get environment variable {0}'.format(envvar))
return value
# Parameters
GUNICORN_PORT = 8080
LOG_DIR = abspath(join(dirname(__file__), "..", "..", "logs"))
# Gunicorn configuration ------------------------------------------------------
# Bind to localhost on specified port
bind = "127.0.0.1:{port}".format(port=GUNICORN_PORT)
# Number of workers -----------------------------------------------------------
# 2*CPU + 1 (recommendation from Gunicorn documentation)
# bumped to 4*CPU + 1 after testing. Maybe increase this number in the cloud
# deployment?
workers = int(get_from_env('GUNICORN_WORKERS',
default_value=multiprocessing.cpu_count()*3 + 1,
fail_if_not_found=False))
# NOTE: it was found in extensive testing that threads > 1 are prone
# to connection lockups. Leave this at 1 for safety until there are
# fixes in gunicorn.
# Why not sync? The sync worker is prone to timeout for long requests,
# like big queries. But gthread sends a heartbeat back to the main worker
# to keep it alive. We could just set the timeout to a really large number
# which would keep the long requests stable, but if there is a stuck worker,
# then they would be subject to that really long timeout. It's a tradeoff.
# All this goes away with async workers, but as of 3.2, django's ORM does support
# async, and testing failed pretty catastrophically and unreliably.
threads = int(get_from_env('GUNICORN_THREADS',
default_value=1,
fail_if_not_found=False))
# Worker connections. Limit the number of connections between apache<-->gunicorn
worker_connections = workers * threads
# Worker class ----------------------------------------------------------------
# sync by default, generally safe and low-resource:
# https://docs.gunicorn.org/en/stable/design.html#sync-workers
worker_class = get_from_env('GUNICORN_WORKER_CLASS',
default_value='gthread',
fail_if_not_found=False)
# Timeout ---------------------------------------------------------------------
# If not specified, the timeout default is 30 seconds:
# https://gunicorn-docs.readthedocs.io/en/stable/settings.html#worker-processes
timeout = get_from_env('GUNICORN_TIMEOUT',
default_value=30,
fail_if_not_found=False)
graceful_timeout = timeout
# max_requests settings -------------------------------------------------------
# The maximum number of requests a worker will process before restarting.
# May be useful if we have memory leak problems.
# The jitter is drawn from a uniform distribution:
# randint(0, max_requests_jitter)
max_requests = get_from_env('GUNICORN_MAX_REQUESTS',
default_value=5000,
fail_if_not_found=False)
max_requests_jitter = get_from_env('GUNICORN_MAX_REQUESTS_JITTER',
default_value=250,
fail_if_not_found=False)
# keepalive -------------------------------------------------------------------
# The number of seconds to wait for requests on a Keep-Alive connection.
# Generally set in the 1-5 seconds range for servers with direct connection
# to the client (e.g. when you don’t have separate load balancer).
# When Gunicorn is deployed behind a load balancer, it often makes sense to set
# this to a higher value.
# NOTE: force gunicorn to close its connection to apache after each request.
# This has been the source of so many 502's. Basically in periods of high activity,
# gunicorn would hold on to open sockets with apache, and just deadlock itself:
# https://github.com/benoitc/gunicorn/issues/2917
keepalive = get_from_env('GUNICORN_KEEPALIVE',
default_value=0,
fail_if_not_found=False)
# preload_app -----------------------------------------------------------------
# Load application code before the worker processes are forked.
# By preloading an application you can save some RAM resources as well as speed
# up server boot times. Although, if you defer application loading to each
# worker process, you can reload your application code easily by restarting
# workers.
# If you aren't going to make use of on-the-fly reloading, consider preloading
# your application code to reduce its memory footprint. So, turn this on in
# production. This is default set to False for development, but
# **TURN THIS TO TRUE FOR AWS DEPLOYMENT **
preload_app = get_from_env('GUNICORN_PRELOAD_APP',
default_value=True,
fail_if_not_found=False)
# Logging ---------------------------------------------------------------------
# Access log
accesslog = join(LOG_DIR, "gunicorn_access.log")
access_log_format = ('GUNICORN | %(h)s %(l)s %(u)s %(t)s '
'"%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"')
# Error log
errorlog = join(LOG_DIR, "gunicorn_error.log")
# debug logging doesn't provide actual information. And this will
# eliminate the "Connection closed." messages while still giving info
# about worker restarts.
loglevel = 'info'
capture_output = True
# using /dev/shm/ instead of /tmp for the temporary worker directory. See:
# https://pythonspeed.com/articles/gunicorn-in-docker/
# “in AWS an EBS root instance volume may sometimes hang for half a minute
# and during this time Gunicorn workers may completely block.”
worker_tmp_dir='/dev/shm'
# Override logger class to modify error format
from gunicorn.glogging import Logger
class CustomLogger(Logger):
error_fmt = 'GUNICORN | ' + Logger.error_fmt
logger_class = CustomLogger
def post_fork(server, worker):
server.log.info("Worker spawned (pid: %s)", worker.pid)
def pre_fork(server, worker):
pass
def pre_exec(server):
server.log.info("Forked child, re-executing.")
def when_ready(server):
server.log.info("Server is ready. Spawning workers")
def worker_int(worker):
worker.log.info("worker received INT or QUIT signal")
def worker_abort(worker):
worker.log.info("worker received SIGABRT signal")
"""
Django settings for gracedb project.
Environment variable DJANGO_SETTINGS_MODULE should be set for a
given instance to determine the settings to run.
Description of settings:
BASE SETTINGS - not to be used as a full settings configuration
---------------------------------------------------------------
base.py - contains the basic settings for running a GraceDB
server.
secret.py - generated by Puppet, contains secret settings like the
database password, API keys, etc. For use with VM-based
deployments. DO NOT EDIT.
Virtual machine deployments
---------------------------
vm/production.py - settings for a VM-based production instance deployed
with Puppet.
vm/dev.py - settings for Va M-based production instance deployed
with Puppet.
Container-based deployments
---------------------------
NOTE: many settings are imported from environment variables for
this deployment type!
container/production.py - settings for a container-based deployment
of a production instance.
container/dev.py - settings for a container-based deployment of a
development instance.
"""
from concurrent_log_handler import ConcurrentRotatingFileHandler
from datetime import datetime, timedelta
import os, time, logging, multiprocessing
from os.path import abspath, dirname, join
import socket
from django.core.exceptions import ImproperlyConfigured
from aws_xray_sdk.core.exceptions.exceptions import SegmentNotFoundException
# Set up path to root of project
BASE_DIR = abspath(join(dirname(__file__), "..", ".."))
CONFIG_ROOT = join(BASE_DIR, "config")
PROJECT_ROOT = join(BASE_DIR, "gracedb")
# Other useful paths
PROJECT_DATA_DIR = join(BASE_DIR, "..", "project_data")
# Useful function for getting environment variables
def get_from_env(envvar, default_value=None, fail_if_not_found=True):
value = os.environ.get(envvar, default_value)
if (value == default_value and fail_if_not_found):
raise ImproperlyConfigured(
'Could not get environment variable {0}'.format(envvar))
return value
def parse_envvar_bool(x):
return x.lower() in ['t', 'true', '1']
# a sentry before_send function that filters aws SegmentNotFoundException's.
# these exceptions are harmless and occur when performing management tasks
# outside of the core gracedb app. but sentry picks it up and reports it as
# an error which is ANNOYING.
def before_send(event, hint):
if "exc_info" in hint:
exc_type, exc_value, tb = hint["exc_info"]
if isinstance(exc_value, (SegmentNotFoundException,)):
return None
return event
# Maintenance mode
MAINTENANCE_MODE = False
MAINTENANCE_MODE_MESSAGE = None
# Enable/Disable Information Banner:
INFO_BANNER_ENABLED = False
INFO_BANNER_MESSAGE = "TEST MESSAGE"
# Beta reports page:
BETA_REPORTS_LINK = False
# Version ---------------------------------------------------------------------
PROJECT_VERSION = '2.31.0'
# Unauthenticated access ------------------------------------------------------
# This variable should eventually control whether unauthenticated access is
# allowed *ANYWHERE* on this service, except the home page, which is always
# public. For now, it just controls the API and the public alerts page.
# Update: make this updatable from the environment:
UNAUTHENTICATED_ACCESS = parse_envvar_bool(
get_from_env('ENABLE_UNAUTHENTICATED_ACCESS',
fail_if_not_found=False, default_value="true")
)
# Miscellaneous settings ------------------------------------------------------
# Debug mode is off by default
DEBUG = False
# When debug mode is enabled, use custom reporter
DEFAULT_EXCEPTION_REPORTER = 'core.utils.CustomExceptionReporter'
# Number of results to show on latest page
LATEST_RESULTS_NUMBER = 25
# Maximum number of log messages to display before throwing
# a warning. NOTE: There should be a better way of doing this,
# but just put in the hard cutoff for right now
# Set to cover this:
# https://gracedb.ligo.org/events/G184098
TOO_MANY_LOG_ENTRIES = int(get_from_env('DJANGO_TOO_MANY_LOG_ENTRIES',
fail_if_not_found=False, default_value=2000))
# Path to root URLconf
ROOT_URLCONF = '{module}.urls'.format(module=os.path.basename(CONFIG_ROOT))
# Used for running unit tests
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
# ADMINS defines who gets code error notifications.
# MANAGERS defines who gets broken link notifications when
# BrokenLinkEmailsMiddleware is enabled
ADMINS = [
("Alexander Pace", "alexander.pace@ligo.org"),
("Duncan Meacher", "duncan.meacher@ligo.org"),
("Daniel Wysocki", "daniel.wysocki@ligo.org"),
]
MANAGERS = ADMINS
# Client versions allowed - pip-like specifier strings,
# can be multiple (comma-separated)
ALLOWED_CLIENT_VERSIONS = '>=2.0.0'
# Allow requests to API without user-agent header specified
# Temporary fix while we transition
ALLOW_BLANK_USER_AGENT_TO_API = False
# Use forwarded host header for Apache -> Gunicorn reverse proxy configuration
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Base URL for TwiML bins (for Twilio phone/text alerts)
TWIML_BASE_URL = 'https://handler.twilio.com/twiml/'
# TwiML bin SIDs (for Twilio)
TWIML_BIN = {
'event': {
'new': 'EH761b6a35102737e3d21830a484a98a08',
'update': 'EH95d69491c166fbe8888a3b83b8aff4af',
'label_added': 'EHb596a53b9c92a41950ce1a47335fd834',
'label_removed': 'EH071c034f27f714bb7a832e85e6f82119',
},
'superevent': {
'new': 'EH5d4d61f5aee9f8687c5bc7d9d42acab9',
'update': 'EH35356707718e1b9a887c50359c3ab064',
'label_added': 'EH244c07ceeb152c6a374e4ffbd853e7a4',
'label_removed': 'EH9d796ce6a80e282a5c96e757e5c39406',
},
'test': 'EH6c0a168b0c6b011047afa1caeb49b241',
'verify': 'EHfaea274d4d87f6ff152ac39fea3a87d4',
}
# Use timezone-aware datetimes internally
USE_TZ = True
# Allow this site to be served on localhost, the FQDN of this server, and
# hostname.ligo.org. Security measure for preventing cache poisoning and
# stopping requests submitted with a fake HTTP Host header.
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
# Internal hostname and IP address
INTERNAL_HOSTNAME = socket.gethostname()
INTERNAL_IP_ADDRESS = socket.gethostbyname(INTERNAL_HOSTNAME)
# Sessions settings -----------------------------------------------------------
SESSION_COOKIE_AGE = 3600*23
SESSION_COOKIE_SECURE = True
SESSION_ENGINE = 'user_sessions.backends.db'
# Login/logout settings -------------------------------------------------------
# Login pages
# URL of Shibboleth login page
LOGIN_URL = 'login'
SHIB_LOGIN_URL = '/Shibboleth.sso/Login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
# LVAlert and LVAlert Overseer settings ---------------------------------------
# Switches which control whether alerts are sent out
SEND_XMPP_ALERTS = False
SEND_PHONE_ALERTS = False
SEND_EMAIL_ALERTS = False
SEND_MATTERMOST_ALERTS = False
# igwn-alert group settings. the default development group is 'lvalert-dev'
# for the container deployments, the variable will be overwriten by the
# IGWN_ALERT_GROUP environment variable.
DEFAULT_IGWN_ALERT_GROUP = 'lvalert-dev'
# enable/disable sending alerts to topics that have the search tag
# for g/e-events. default to false, so only send to {group}_{pipeline}
SEND_TO_SEARCH_TOPICS = parse_envvar_bool(
get_from_env('IGWN_ALERT_SEARCH_TOPICS',
fail_if_not_found=False, default_value="false")
)
# overseer timeout:
OVERSEER_TIMEOUT = float(get_from_env('IGWN_ALERT_OVERSEER_TIMEOUT',
fail_if_not_found=False, default_value=0.1))
# Use LVAlert Overseer?
USE_LVALERT_OVERSEER = True
# For each LVAlert server, a separate instance of LVAlert Overseer
# must be running and listening on a distinct port.
# lvalert_server: LVAlert server which overseer sends messages to
# listen_port: port which that instance of overseer is listening on
LVALERT_OVERSEER_INSTANCES = [
{
"lvalert_server": "kafka://kafka.scimma.org/",
"listen_port": 8002,
"igwn_alert_group": DEFAULT_IGWN_ALERT_GROUP,
},
]
# Access and authorization ----------------------------------------------------
# Some proper names related to authorization
LVC_GROUP = 'internal_users'
LVEM_GROUP = 'lvem_users'
LVEM_OBSERVERS_GROUP = 'lvem_observers'
PUBLIC_GROUP = 'public_users'
PRIORITY_USERS_GROUP = 'priority_users'
# Group names
# Executives group name
EXEC_GROUP = 'executives'
# Access managers - will replace executives eventually. For now,
# membership will be the same.
ACCESS_MANAGERS_GROUP = 'access_managers'
# EM Advocate group name
EM_ADVOCATE_GROUP = 'em_advocates'
# Superevent managers
SUPEREVENT_MANAGERS_GROUP = 'superevent_managers'
# RRT group name:
RRT_MEMBERS_GROUP = 'rrt_members'
# Analysis groups
# Analysis group name for non-GW events
EXTERNAL_ANALYSIS_GROUP = 'External'
# Tag to apply to log messages to allow EM partners to view
EXTERNAL_ACCESS_TAGNAME = 'lvem'
PUBLIC_ACCESS_TAGNAME = 'public'
# FAR floor for outgoing VOEvents intended for GCN
VOEVENT_FAR_FLOOR = 0 # Hz
# Web interface settings ------------------------------------------------------
# Whether or not to show the recent events on the page
# Note that this does NOT filter events based on user view permissions,
# so be careful if you turn it on!
SHOW_RECENT_EVENTS_ON_HOME = False
# URL for viewing skymaps
SKYMAP_VIEWER_SERVICE_URL = \
"https://embb-dev.ligo.caltech.edu/skymap-viewer/aladin/skymap-viewer.cgi"
# Log entries with these tags are displayed in
# their own blocks in the web interface.
BLESSED_TAGS = [
'analyst_comments',
'em_follow',
'psd',
'data_quality',
'sky_loc',
'background',
'ext_coinc',
'strain',
'tfplots',
'pe',
'sig_info',
'audio',
]
# Lists of pipelines used for selecting templates to serve
COINC_PIPELINES = [
'gstlal',
'spiir',
'MBTAOnline',
'pycbc',
'MBTA',
'PyGRB',
]
GRB_PIPELINES = [
'Fermi',
'Swift',
'INTEGRAL',
'AGILE',
'CHIME',
'SVOM',
]
# List of pipelines that have been depreciated:
DEPRECIATED_PIPELINES = [
'X',
'Q',
'Omega',
]
UNAPPROVED_PIPELINES = []
# VOEvent stream --------------------------------------------------------------
VOEVENT_STREAM = 'gwnet/LVC'
# Stuff related to report/plot generation -------------------------------------
# Latency histograms. Where they go and max latency to bin.
LATENCY_REPORT_DEST_DIR = PROJECT_DATA_DIR
LATENCY_MAXIMUM_CHARTED = 1800
LATENCY_REPORT_WEB_PAGE_FILE_PATH = join(PROJECT_DATA_DIR, "latency.inc")
# Rate file location
RATE_INFO_FILE = join(PROJECT_DATA_DIR, "rate_info.json")
# URL prefix for serving report information (usually plots and tables)
REPORT_INFO_URL_PREFIX = "/report_info/"
# Directory for CBC IFAR Reports
REPORT_IFAR_IMAGE_DIR = PROJECT_DATA_DIR
# Stuff for the new rates plot
BINNED_COUNT_PIPELINES = ['gstlal', 'MBTAOnline', 'MBTA', 'CWB', 'oLIB', 'spiir']
BINNED_COUNT_FILE = join(PROJECT_DATA_DIR, "binned_counts.json")
# Defaults for RSS feed
FEED_MAX_RESULTS = 50
# Django and server settings --------------------------------------------------
# Location of database
GRACEDB_DATA_DIR = join(BASE_DIR, "..", "db_data")
# First level subdirs with 2 chars, second level with 1 char
# These DIR_DIGITS had better add up to a number less than 40 (which is
# the length of a SHA-1 hexdigest. Actually, it should be way less than
# 40--or you're a crazy person.
GRACEDB_DIR_DIGITS = [2, 1,]
# Cache settings - nested dictionary where each element maps
# cache aliases to a dictionary of options for an individual cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
},
# For API throttles
'throttles': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'api_throttle_cache', # Table name
},
}
# List of settings for all template engines. Each item is a dict
# containing options for an individual engine
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
join(PROJECT_ROOT, "templates"),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Defaults
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.contrib.messages.context_processors.messages',
# Extra additions
'django.template.context_processors.request',
'django.contrib.messages.context_processors.messages',
'ligoauth.context_processors.LigoAuthContext',
'core.context_processors.LigoDebugContext',
],
},
},
]
# Authentication settings -----------------------------------------------------
# Headers to use for Shibboleth authentication and user updates
SHIB_USER_HEADER = 'HTTP_REMOTE_USER'
SHIB_GROUPS_HEADER = 'HTTP_ISMEMBEROF'
SHIB_ATTRIBUTE_MAP = {
'email': 'HTTP_MAIL',
'first_name': 'HTTP_GIVENNAME',
'last_name': 'HTTP_SN',
}
# Headers to use for X509 authentication
X509_SUBJECT_DN_HEADER = 'HTTP_SSL_CLIENT_S_DN'
X509_ISSUER_DN_HEADER = 'HTTP_SSL_CLIENT_I_DN'
X509_CERT_HEADER = 'HTTP_X_FORWARDED_TLS_CLIENT_CERT'
X509_INFOS_HEADER = 'HTTP_X_FORWARDED_TLS_CLIENT_CERT_INFOS'
# Path to CA store for X509 certificate verification
CAPATH = '/etc/grid-security/certificates'
# SciTokens claims settings
SCITOKEN_ISSUER = ['https://cilogon.org/igwn', 'https://test.cilogon.org/igwn', 'https://osdf.igwn.org/cit']
SCITOKEN_AUDIENCE = ["ANY"]
SCITOKEN_SCOPE = "gracedb.read"
# List of authentication backends to use when attempting to authenticate
# a user. Will be used in this order. Authentication for the API is
# handled by the REST_FRAMEWORK dictionary.
AUTHENTICATION_BACKENDS = [
'ligoauth.backends.ShibbolethRemoteUserBackend',
'ligoauth.backends.ModelPermissionsForObjectBackend',
'guardian.backends.ObjectPermissionBackend',
]
# List of middleware classes to use.
MIDDLEWARE = [
'core.middleware.maintenance.MaintenanceModeMiddleware',
'events.middleware.PerformanceMiddleware',
'core.middleware.accept.AcceptMiddleware',
'core.middleware.api.ClientVersionMiddleware',
'core.middleware.api.CliExceptionMiddleware',
'django.middleware.common.CommonMiddleware',
'core.middleware.proxy.XForwardedForMiddleware',
'user_sessions.middleware.SessionMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'ligoauth.middleware.ShibbolethWebAuthMiddleware',
'ligoauth.middleware.ControlRoomMiddleware',
]
# Path to root URLconf
ROOT_URLCONF = '{module}.urls'.format(module=os.path.basename(CONFIG_ROOT))
# Database ID of the current site (for sites framework)
SITE_ID=1
# List of string designating all applications which are enabled.
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.admin',
'django_ses',
'django.contrib.contenttypes',
'user_sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'django.contrib.messages',
'alerts',
'annotations',
'api',
'core',
'events',
'ligoauth',
'search',
'superevents',
'gwtc',
'rest_framework',
'guardian',
'django_twilio',
'django_extensions',
'django.contrib.sessions',
'computedfields',
'django_postgres_vacuum',
'django_q',
]
# Aliases for django-extensions shell_plus
SHELL_PLUS_MODEL_ALIASES = {
# Two 'Group' models - auth.Group and gracedb.Group
'auth': {'Group': 'DjangoGroup'},
# Superevents models which have the same name as
# models in the events app
'superevents': {
'EMFootprint': 'SupereventEMFootprint',
'EMObservation': 'SupereventEMObservation',
'Label': 'SupereventLabel',
'Labelling': 'SupereventLabelling',
'Log': 'SupereventLog',
'Signoff': 'SupereventSignoff',
'VOEvent': 'SupereventVOEvent',
}
}
# Details used by REST API
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':
'api.versioning.NestedNamespaceVersioning',
#'rest_framework.versioning.NamespaceVersioning',
'DEFAULT_VERSION': 'default',
'ALLOWED_VERSIONS': ['default', 'v1', 'v2'],
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 1e7,
'DEFAULT_THROTTLE_CLASSES': (
'api.throttling.BurstAnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon_burst': '300/minute',
'event_creation': '50/second',
'annotation' : '50/second',
},
'DEFAULT_AUTHENTICATION_CLASSES': (
'api.backends.GraceDbAuthenticatedAuthentication',
'api.backends.GraceDbSciTokenAuthentication',
'api.backends.GraceDbX509Authentication',
'api.backends.GraceDbBasicAuthentication',
),
'COERCE_DECIMAL_TO_STRING': False,
'EXCEPTION_HANDLER':
'api.exceptions.gracedb_exception_handler',
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
# Change default permission classes based on UNAUTHENTICATED_ACCESS setting
if UNAUTHENTICATED_ACCESS is True:
REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'] = \
('rest_framework.permissions.IsAuthenticatedOrReadOnly',)
# Location of static components, CSS, JS, etc.
STATIC_ROOT = join(BASE_DIR, "static_root")
STATIC_URL = "/static/"
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
]
STATICFILES_DIRS = [
join(PROJECT_ROOT, "static"),
]
# Added in order to perform data migrations on Django apps
# and other third-party apps
MIGRATION_MODULES = {
'auth': 'migrations.auth',
'guardian': 'migrations.guardian',
'sites': 'migrations.sites',
}
# Forces test database to be created with syncdb rather than via
# migrations in South.
# TP (8 Aug 2017): not sure this is used anymore
SOUTH_TESTS_MIGRATE = False
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment, this must be set to the same as your
# system time zone.
TIME_ZONE = 'UTC'
GRACE_DATETIME_FORMAT = 'Y-m-d H:i:s T'
GRACE_STRFTIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# django-guardian configuration
# Note for upgrading: ANONYMOUS_USER_ID becomes ANONYMOUS_DEFAULT_USERNAME
# and USERNAME_FIELD in django-guardian 1.4.2
ANONYMOUS_USER_ID = -1
# Have guardian try to render a 403 response rather than return
# a contentless django.http.HttpResponseForbidden. Should set
# GUARDIAN_TEMPLATE_403 to a template to be used by this.
GUARDIAN_RENDER_403 = True
# Used by guardian for dealing with errors related to the user model
# See http://django-guardian.readthedocs.io/en/latest/userguide/custom-user-model.html
GUARDIAN_MONKEY_PATCH = False
# Lifetime of verification codes for contacts
VERIFICATION_CODE_LIFETIME = timedelta(hours=1)
# Basic auth passwords for LVEM scripted access expire after 365 days.
PASSWORD_EXPIRATION_TIME = timedelta(days=365)
# IP addresses of IFO control rooms
# Used to display signoff pages for operators
# TP (10 Apr 2017): Virgo IP received from Florent Robinet, Franco Carbognani,
# and Sarah Antier. Corresponds to ctrl1.virgo.infn.it.
CONTROL_ROOM_IPS = {
'H1': '198.129.208.178',
'L1': '208.69.128.41',
'V1': '90.147.136.220',
}
# Everything below here is logging --------------------------------------------
# Base logging settings
LOG_FILE_SIZE = 1024*1024 # 1 MB
LOG_FILE_BAK_CT = 10
LOG_FORMAT = 'extra_verbose'
LOG_LEVEL = 'DEBUG'
LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
LOG_DIR = abspath(join(BASE_DIR, "..", "logs"))
# Note that mode for log files is 'a' (append) by default
# The 'level' specifier on the handle is optional, and we
# don't need it since we're using custom filters.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '%(asctime)s | %(message)s',
'datefmt': LOG_DATEFMT,
},
'verbose': {
'format': '%(asctime)s | %(name)s | %(message)s',
'datefmt': LOG_DATEFMT,
},
'extra_verbose': {
'format': '%(asctime)s.%(msecs)03d | %(name)s | %(levelname)s | ' \
+ '%(filename)s, line %(lineno)s | %(message)s',
'datefmt': LOG_DATEFMT,
},
'console': {
'format': ('DJANGO | %(asctime)s.%(msecs)03d | {host} | {ip} | '
'%(name)s | %(levelname)s | %(filename)s, line %(lineno)s | '
'%(message)s').format(host=INTERNAL_HOSTNAME,
ip=INTERNAL_IP_ADDRESS),
'datefmt': LOG_DATEFMT,
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'debug_file': {
'class': 'logging.handlers.ConcurrentRotatingFileHandler',
'formatter': LOG_FORMAT,
'filename': join(LOG_DIR, "gracedb_debug.log"),
'maxBytes': (20*1024*1024),
'backupCount': LOG_FILE_BAK_CT,
'level': 'DEBUG',
},
'error_file': {
'class': 'logging.handlers.ConcurrentRotatingFileHandler',
'formatter': LOG_FORMAT,
'filename': join(LOG_DIR, "gracedb_error.log"),
'maxBytes': LOG_FILE_SIZE,
'backupCount': LOG_FILE_BAK_CT,
'level': 'ERROR',
},
'performance_file': {
'class': 'logging.handlers.ConcurrentRotatingFileHandler',
'maxBytes': 1024*1024,
'backupCount': 1,
'formatter': 'simple',
'filename': join(LOG_DIR, "gracedb_performance.log"),
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'class': 'logging.StreamHandler',
'formatter': 'console',
'level': 'DEBUG',
},
},
'loggers': {
'django': {
'handlers': ['null'],
'propagate': True,
'level': 'INFO',
},
'core': {
'handlers': ['debug_file','error_file'],
'propagate': True,
'level': LOG_LEVEL,
},
'events': {
'handlers': ['debug_file','error_file'],
'propagate': True,
'level': LOG_LEVEL,
},
'superevents': {
'handlers': ['debug_file','error_file'],
'propagate': True,
'level': LOG_LEVEL,
},
'performance': {
'handlers': ['performance_file'],
'propagate': True,
'level': 'INFO',
},
'ligoauth': {
'handlers': ['debug_file','error_file'],
'propagate': True,
'level': LOG_LEVEL,
},
'search': {
'handlers': ['debug_file','error_file'],
'propagate': True,
'level': LOG_LEVEL,
},
'api': {
'handlers': ['debug_file','error_file'],
'propagate': True,
'level': LOG_LEVEL,
},
'alerts': {
'handlers': ['debug_file','error_file'],
'propagate': True,
'level': LOG_LEVEL,
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
},
}
# Turn off debug/error emails when in maintenance mode.
if MAINTENANCE_MODE:
LOGGING['loggers']['django.request']['handlers'].remove('mail_admins')
# Turn off logging emails of django requests:
# FIXME: figure out more reliable logging solution
LOGGING['loggers']['django.request']['handlers'].remove('mail_admins')
# Define some words for the instance stub:
ENABLED = {True: "enabled", False: "disabled"}
# Upgrading to django 3.2 produces warning: "Auto-created primary key used
# when not defining a primary key type, by default 'django.db.models.AutoField'.
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
# Define window for neighbouring s events of a given g event.
EVENT_SUPEREVENT_WINDOW_BEFORE = 100
EVENT_SUPEREVENT_WINDOW_AFTER = 100
# Define which observation periods to show on the public events page:
# TODO: Group O4b and O4a under O4, once implemented.
PUBLIC_PAGE_RUNS = ['O4', 'O4c', 'O4b', 'O4a', 'ER16', 'ER15', 'O3']
# Define how long to cache the public page:
PUBLIC_PAGE_CACHING = int(get_from_env('DJANGO_PUBLIC_PAGE_CACHING',
fail_if_not_found=False, default_value=300))
# Define the number of results per page on the public page:
PUBLIC_PAGE_RESULTS = int(get_from_env('DJANGO_PUBLIC_PAGE_RESULTS',
fail_if_not_found=False, default_value=15))
# Define DATA_UPLOAD_MAX_MEMORY_SIZE for larger uploads:
DATA_UPLOAD_MAX_MEMORY_SIZE = int(get_from_env('DJANGO_DATA_UPLOAD_MAX_MEMORY_SIZE',
fail_if_not_found=False, default_value=20*1024*1024))
# Choose whether to use to Julian or Civil definition of year
# when displaying far's in /year:
DISPLAY_CIVIL_YEAR_FAR = parse_envvar_bool(
get_from_env('DJANGO_DISPLAY_CIVIL_YEAR_FAR',
fail_if_not_found=False, default_value="false")
)
if DISPLAY_CIVIL_YEAR_FAR:
DAYS_PER_YEAR = 365.0
else:
DAYS_PER_YEAR = 365.25
# Put in some setting for the redis queue backend
ENABLE_REDIS_QUEUE = parse_envvar_bool(
get_from_env('DJANGO_ENABLE_REDIS_QUEUE',
fail_if_not_found=False, default_value="false")
)
REDIS_QUEUE_ADDRESS = get_from_env('DJANGO_REDIS_QUEUE_ADDRESS',
fail_if_not_found=False, default_value="127.0.0.1")
REDIS_QUEUE_PORT = int(get_from_env('DJANGO_REDIS_QUEUE_PORT',
fail_if_not_found=False, default_value="6379")
)
REDIS_QUEUE_DATABASE = int(get_from_env('DJANGO_REDIS_QUEUE_DATABASE',
fail_if_not_found=False, default_value=0)
)
REDIS_QUEUE_WORKERS = int(get_from_env('DJANGO_REDIS_QUEUE_WORKERS',
default_value=multiprocessing.cpu_count(),
fail_if_not_found=False))
REDIS_QUEUE_RETRY = int(get_from_env('DJANGO_REDIS_QUEUE_RETRY',
default_value=40,
fail_if_not_found=False))
REDIS_QUEUE_TIMEOUT = int(get_from_env('DJANGO_REDIS_QUEUE_TIMEOUT',
default_value=30,
fail_if_not_found=False))
REDIS_QUEUE_RECYCLE = int(get_from_env('DJANGO_REDIS_QUEUE_RECYCLE',
default_value=500,
fail_if_not_found=False))
ENABLE_REDIS_CLUSTERED = parse_envvar_bool(
get_from_env('DJANGO_ENABLE_REDIS_CLUSTERED',
fail_if_not_found=False, default_value="false")
)
# Define some defaults for the q-cluster parameters:
Q_CLUSTER_NAME = 'gracedb-async-queue'
Q_CLUSTER_LABEL = 'gracedb q cluster'
if not ENABLE_REDIS_CLUSTERED:
Q_CLUSTER_NAME+=f'-{INTERNAL_HOSTNAME}'
Q_CLUSTER_LABEL+=f', {INTERNAL_HOSTNAME}'
# Define MAX_DATATABLES_RESULTS to limit memory usage for web queries:
MAX_DATATABLES_RESULTS = int(get_from_env('DJANGO_MAX_DATATABLES_RESULTS',
fail_if_not_found=False, default_value=1000))
File moved
# For running a containerized version of the service that gets secrets
# from environment variables. Builds on base.py settings.
import os
from django.core.exceptions import ImproperlyConfigured
from ..base import *
# Get required variables from environment variables ---------------------------
# Get database user from environment and check
db_user = os.environ.get('DJANGO_DB_USER', None)
if db_user is None:
raise ImproperlyConfigured('Could not get database user from envvars.')
# Get database password from environment and check
db_password = os.environ.get('DJANGO_DB_PASSWORD', None)
if db_password is None:
raise ImproperlyConfigured('Could not get database password from envvars.')
# Get database name from environment and check
db_name = os.environ.get('DJANGO_DB_NAME', None)
if db_name is None:
raise ImproperlyConfigured('Could not get database name from envvars.')
# Secret key for a Django installation
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', None)
if SECRET_KEY is None:
raise ImproperlyConfigured('Could not get secret key from envvars.')
# Get primary FQDN
SERVER_FQDN = os.environ.get('DJANGO_PRIMARY_FQDN', None)
if SERVER_FQDN is None:
raise ImproperlyConfigured('Could not get FQDN from envvars.')
LIGO_FQDN = SERVER_FQDN
## EGAD (External GraceDB Alert Dispatcher) configuration
ENABLE_EGAD_EMAIL = parse_envvar_bool(
get_from_env('ENABLE_EGAD_EMAIL',
fail_if_not_found=False, default_value="false")
)
ENABLE_EGAD_KAFKA = parse_envvar_bool(
get_from_env('ENABLE_EGAD_KAFKA',
fail_if_not_found=False, default_value="false")
)
ENABLE_EGAD_MATTERMOST = parse_envvar_bool(
get_from_env('ENABLE_EGAD_MATTERMOST',
fail_if_not_found=False, default_value="false")
)
ENABLE_EGAD_PHONE = parse_envvar_bool(
get_from_env('ENABLE_EGAD_PHONE',
fail_if_not_found=False, default_value="false")
)
ENABLE_EGAD = (
ENABLE_EGAD_EMAIL or ENABLE_EGAD_KAFKA
or ENABLE_EGAD_MATTERMOST or ENABLE_EGAD_PHONE
)
EGAD_URL = get_from_env('EGAD_URL',
fail_if_not_found=ENABLE_EGAD, default_value=None)
EGAD_API_KEY = get_from_env('EGAD_API_KEY',
fail_if_not_found=ENABLE_EGAD, default_value=None)
# Turn LVAlert on/off from the environment. Adding this
# to turn lvalerts on/off from docker compose/update instead
# of having to rebuild containers. If the environment variable
# isn't set, then revert to the hardwired behavior:
xmpp_env_var = get_from_env('SEND_LVALERT_XMPP_ALERTS',
default_value=SEND_XMPP_ALERTS,
fail_if_not_found=False)
# Fix for other boolean values:
if (isinstance(xmpp_env_var, str) and
xmpp_env_var.lower() in ['true','t','1']):
SEND_XMPP_ALERTS=True
elif (isinstance(xmpp_env_var, str) and
xmpp_env_var.lower() in ['false','f','0']):
SEND_XMPP_ALERTS=False
else:
SEND_XMPP_ALERTS = True
# Get igwn_alert_overseer status:
igwn_alert_on = get_from_env(
'ENABLE_IGWN_OVERSEER',
default_value=False,
fail_if_not_found=False
)
if (isinstance(igwn_alert_on, str) and
igwn_alert_on.lower() in ['true', 't', '1']):
igwn_alert_overseer_on = True
else:
igwn_alert_overseer_on = False
# Get igwn-alert server
igwn_alert_server = os.environ.get('IGWN_ALERT_SERVER', None)
if igwn_alert_server is None:
raise ImproperlyConfigured('Could not get igwn-alert server from envvars.')
# Get igwn-alert Overseer listen port
igwn_alert_overseer_port = os.environ.get('IGWN_ALERT_OVERSEER_PORT', None)
if igwn_alert_overseer_port is None:
raise ImproperlyConfigured('Could not get igwn-alert overseer port '
'from envvars.')
# Get igwn-alert group from envirnment:
igwn_alert_group = os.environ.get('IGWN_ALERT_GROUP', DEFAULT_IGWN_ALERT_GROUP)
# Get igwn-alert username
igwn_alert_user = os.environ.get('IGWN_ALERT_USER', None)
if igwn_alert_user is None:
raise ImproperlyConfigured('Could not get igwn-alert username from envvars.')
# Get igwn-alert password
igwn_alert_password = os.environ.get('IGWN_ALERT_PASSWORD', None)
if igwn_alert_password is None:
raise ImproperlyConfigured('Could not get igwn-alert password from envvars.')
# Get Twilio account information from environment
TWILIO_ACCOUNT_SID = os.environ.get('DJANGO_TWILIO_ACCOUNT_SID', None)
if TWILIO_ACCOUNT_SID is None:
raise ImproperlyConfigured('Could not get Twilio acct SID from envvars.')
TWILIO_AUTH_TOKEN = os.environ.get('DJANGO_TWILIO_AUTH_TOKEN', None)
if TWILIO_AUTH_TOKEN is None:
raise ImproperlyConfigured('Could not get Twilio auth token from envvars.')
# Get maintenance mode settings from environment
maintenance_mode = get_from_env(
'DJANGO_MAINTENANCE_MODE_ACTIVE',
default_value=False,
fail_if_not_found=False
)
# DB "cool-down" factor for when a db conflict is detected. This
# factor scales a random number of seconds between zero and one.
DB_SLEEP_FACTOR = get_from_env(
'DJANGO_DB_SLEEP_FACTOR',
default_value=1.0,
fail_if_not_found=False
)
# Fix the factor (str to float)
try:
DB_SLEEP_FACTOR = float(DB_SLEEP_FACTOR)
except:
DB_SLEEP_FACTOR = 1.0
if (isinstance(maintenance_mode, str) and
maintenance_mode.lower() in ['true', 't', '1']):
MAINTENANCE_MODE = True
MAINTENANCE_MODE_MESSAGE = \
get_from_env('DJANGO_MAINTENANCE_MODE_MESSAGE', fail_if_not_found=False)
# Get info banner settings from environment
info_banner_enabled = get_from_env(
'DJANGO_INFO_BANNER_ENABLED',
default_value=False,
fail_if_not_found=False
)
# fix for other booleans:
if (isinstance(info_banner_enabled, str) and
info_banner_enabled.lower() in ['true','t','1']):
INFO_BANNER_ENABLED = True
INFO_BANNER_MESSAGE = \
get_from_env('DJANGO_INFO_BANNER_MESSAGE', fail_if_not_found=False)
# Get reports page boolean:
beta_reports_link = get_from_env(
'DJANGO_BETA_REPORTS_LINK',
default_value=False,
fail_if_not_found=False
)
# fix for other booleans:
if (isinstance(beta_reports_link, str) and
beta_reports_link.lower() in ['true','t','1']):
BETA_REPORTS_LINK = True
# Get email settings from environment
EMAIL_BACKEND = 'django_ses.SESBackend'
AWS_SES_ACCESS_KEY_ID = get_from_env('AWS_SES_ACCESS_KEY_ID')
AWS_SES_SECRET_ACCESS_KEY = get_from_env('AWS_SES_SECRET_ACCESS_KEY')
AWS_SES_REGION_NAME = get_from_env('AWS_SES_REGION_NAME',
default_value='us-west-2', fail_if_not_found=False)
AWS_SES_REGION_ENDPOINT = get_from_env('AWS_SES_REGION_ENDPOINT',
default_value='email.us-west-2.amazonaws.com', fail_if_not_found=False)
AWS_SES_AUTO_THROTTLE = 0.25
ALERT_EMAIL_FROM = get_from_env('DJANGO_ALERT_EMAIL_FROM')
# memcached settings. this variable should be set in the deployment to the
# same name as the service name in the docker deployment.
DOCKER_MEMCACHED_ADDR = get_from_env('DJANGO_DOCKER_MEMCACHED_ADDR',
default_value="memcached:11211",
fail_if_not_found=False)
DOCKER_MEMCACHED_SECONDS = get_from_env('DJANGO_DOCKER_MEMCACHED_SECONDS',
default_value="15",
fail_if_not_found=False)
try:
CACHE_MIDDLEWARE_SECONDS = int(DOCKER_MEMCACHED_SECONDS)
except:
CACHE_MIDDLEWARE_SECONDS = 15
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
'LOCATION': DOCKER_MEMCACHED_ADDR,
'OPTIONS': {
'ignore_exc': True,
}
},
# For API throttles
'throttles': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'api_throttle_cache', # Table name
},
}
if ENABLE_REDIS_QUEUE:
# For async alert follow-up:
CACHES.update({"async_followup": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": f"redis://{REDIS_QUEUE_ADDRESS}:{REDIS_QUEUE_PORT}/{REDIS_QUEUE_DATABASE}",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}})
# Set queue backend for async django tasks:
# example django-redis connection
Q_CLUSTER = {
'name': Q_CLUSTER_NAME,
'label': Q_CLUSTER_LABEL,
'retry': REDIS_QUEUE_RETRY,
'timeout': REDIS_QUEUE_TIMEOUT,
'workers': REDIS_QUEUE_WORKERS,
'recycle': REDIS_QUEUE_RECYCLE,
'django_redis': 'async_followup'
}
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
'core.middleware.maintenance.MaintenanceModeMiddleware',
'events.middleware.PerformanceMiddleware',
'core.middleware.accept.AcceptMiddleware',
'core.middleware.api.ClientVersionMiddleware',
'core.middleware.api.CliExceptionMiddleware',
'django.middleware.common.CommonMiddleware',
'core.middleware.proxy.XForwardedForMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'user_sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'ligoauth.middleware.ShibbolethWebAuthMiddleware',
'ligoauth.middleware.ControlRoomMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
# Set up AWS X-ray patching if enabled
ENABLE_AWS_XRAY = (
get_from_env("ENABLE_AWS_XRAY",
default_value="false", fail_if_not_found=False).lower()
in ['true', 't', '1']
)
if ENABLE_AWS_XRAY:
# AWS X-ray middleware must be first in the list to measure timing
# accurately
MIDDLEWARE.insert(0, 'aws_xray_sdk.ext.django.middleware.XRayMiddleware')
# Include X-ray as an installed app in order to allow configuration beyond
# the default
INSTALLED_APPS.append('aws_xray_sdk.ext.django')
# Settings for AWS X-ray
XRAY_RECORDER = {
'AWS_XRAY_DAEMON_ADDRESS': '127.0.0.1:2000',
'AUTO_INSTRUMENT': True,
'AWS_XRAY_CONTEXT_MISSING': 'LOG_ERROR',
'PLUGINS': (),
'SAMPLING': True,
'SAMPLING_RULES': None,
'AWS_XRAY_TRACING_NAME': 'GraceDB',
'DYNAMIC_NAMING': None,
'STREAMING_THRESHOLD': None,
}
# Priority server settings ----------------------------------------------------
PRIORITY_SERVER = False
is_priority_server = get_from_env('DJANGO_PRIORITY_SERVER', None,
fail_if_not_found=False)
if (isinstance(is_priority_server, str) and
is_priority_server.lower() in ['true', 't']):
PRIORITY_SERVER = True
# If priority server, only allow priority users to the API
if PRIORITY_SERVER:
# Add custom permissions for the API
default_perms = list(REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'])
default_perms = ['api.permissions.IsPriorityUser'] + default_perms
REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'] = tuple(default_perms)
# Database settings -----------------------------------------------------------
# New postgresql database
# Configured for the CI pipeline:
# https://docs.gitlab.com/ee/ci/services/postgres.html
DATABASES = {
'default' : {
'NAME': db_name,
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': db_user,
'PASSWORD': db_password,
'HOST': os.environ.get('DJANGO_DB_HOST', ''),
'PORT': os.environ.get('DJANGO_DB_PORT', ''),
'CONN_MAX_AGE': 3600,
'TEST' : {
'NAME': 'gracedb_test_db',
},
},
}
# Main server "hostname" - a little hacky but OK
SERVER_HOSTNAME = SERVER_FQDN.split('.')[0]
# igwn_alert Overseer settings - get from environment
LVALERT_OVERSEER_INSTANCES = []
LVALERT_OVERSEER_INSTANCES.append(
{
"lvalert_server": igwn_alert_server,
"listen_port": int(igwn_alert_overseer_port),
"igwn_alert_group": igwn_alert_group,
"username": igwn_alert_user,
"password": igwn_alert_password,
}
)
# Pull in remaining (phone/email) alert variables from
# the environment. Default to false.
SEND_PHONE_ALERTS = parse_envvar_bool(get_from_env(
'SEND_PHONE_ALERTS',
default_value='False',
fail_if_not_found=False
))
SEND_EMAIL_ALERTS = parse_envvar_bool(get_from_env(
'SEND_EMAIL_ALERTS',
default_value='False',
fail_if_not_found=False
))
SEND_MATTERMOST_ALERTS = parse_envvar_bool(get_from_env(
'SEND_MATTERMOST_ALERTS',
default_value='False',
fail_if_not_found=False
))
INSTANCE_STUB = """
<li>Phone alerts (calls/SMS) are {0}</li>
<li>Email alerts are {1}</li>
<li><span class="text-monospace">igwn-alert</span> messages to <span class="text-monospace">{2}</span> are {3}</li>
"""
INSTANCE_LIST = INSTANCE_STUB.format(ENABLED[SEND_PHONE_ALERTS],
ENABLED[SEND_EMAIL_ALERTS],
LVALERT_OVERSEER_INSTANCES[0]['lvalert_server'],
ENABLED[SEND_XMPP_ALERTS])
# Use full client certificate to authenticate
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] = (
'api.backends.GraceDbAuthenticatedAuthentication',
'api.backends.GraceDbSciTokenAuthentication',
'api.backends.GraceDbX509FullCertAuthentication',
'api.backends.GraceDbBasicAuthentication',
)
# Update allowed hosts from environment variables -----------------------------
hosts_from_env = os.environ.get('DJANGO_ALLOWED_HOSTS', None)
if hosts_from_env is not None:
ALLOWED_HOSTS += hosts_from_env.split(',')
ALLOWED_HOSTS += [SERVER_FQDN]
# Email settings - dependent on server hostname and FQDN ----------------------
SERVER_EMAIL = ALERT_EMAIL_FROM
ALERT_EMAIL_TO = []
ALERT_EMAIL_BCC = []
ALERT_TEST_EMAIL_FROM = ALERT_EMAIL_FROM
ALERT_TEST_EMAIL_TO = []
# EMBB email settings
EMBB_MAIL_ADDRESS = 'embb@{fqdn}.ligo.org'.format(fqdn=SERVER_FQDN)
EMBB_SMTP_SERVER = 'localhost'
EMBB_MAIL_ADMINS = [admin[1] for admin in ADMINS]
EMBB_IGNORE_ADDRESSES = ['Mailer-Daemon@{fqdn}'.format(fqdn=SERVER_FQDN)]
# Set up logging to stdout only
for key in LOGGING['loggers']:
LOGGING['loggers'][key]['handlers'] = ['console']
LOGGING['loggers']['django.request']['handlers'].append('mail_admins')
# Turn off debug/error emails when in maintenance mode.
if MAINTENANCE_MODE:
LOGGING['loggers']['django.request']['handlers'].remove('mail_admins')
# Set SciToken accepted audience to server FQDN
SCITOKEN_AUDIENCE = ["https://" + SERVER_FQDN, "https://" + LIGO_FQDN]
# Settings for a test/dev GraceDB instance running in a container
from .base import *
TIER = "dev"
CONFIG_NAME = "DEV"
# Debug settings
DEBUG = True
# Override EMBB email address
# TP (8 Aug 2017): not sure why?
EMBB_MAIL_ADDRESS = 'gracedb@{fqdn}'.format(fqdn=SERVER_FQDN)
# Add middleware
debug_middleware = 'debug_toolbar.middleware.DebugToolbarMiddleware'
MIDDLEWARE += [
debug_middleware,
#'silk.middleware.SilkyMiddleware',
#'core.middleware.profiling.ProfileMiddleware',
#'core.middleware.admin.AdminsOnlyMiddleware',
]
# Add to installed apps
INSTALLED_APPS += [
'debug_toolbar',
#'silk'
]
# Add testserver to ALLOWED_HOSTS
ALLOWED_HOSTS += ['testserver']
# Enforce that phone and email alerts are off XXX: Set by deployment variables!
#SEND_PHONE_ALERTS = False
#SEND_EMAIL_ALERTS = False
#SEND_MATTERMOST_ALERTS = True
# Settings for django-silk profiler
SILKY_AUTHENTICATION = True
SILKY_AUTHORISATION = True
if 'silk' in INSTALLED_APPS:
# Needed to prevent RequestDataTooBig for files > 2.5 MB
# when silk is being used. This setting is typically used to
# prevent DOS attacks, so should not be changed in production.
DATA_UPLOAD_MAX_MEMORY_SIZE = 20*(1024**2)
# Tuple of IPs which are marked as internal, useful for debugging.
# Tanner (5 Dec. 2017): DON'T CHANGE THIS! Django Debug Toolbar exposes
# some headers which we want to keep hidden. So to be safe, we only allow
# it to be used through this server. You need to configure a SOCKS proxy
# on your local machine to use DJDT (see admin docs).
INTERNAL_IPS = [
INTERNAL_IP_ADDRESS,
]
# Set up Sentry for error logging
sentry_dsn = get_from_env('DJANGO_SENTRY_DSN', fail_if_not_found=False)
if sentry_dsn is not None:
USE_SENTRY = True
# Set up Sentry
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
environment='dev',
dsn=sentry_dsn,
integrations=[DjangoIntegration()],
before_send=before_send,
)
# Turn off default admin error emails
LOGGING['loggers']['django.request']['handlers'] = []
# Home page stuff
INSTANCE_TITLE = 'GraceDB Development VM'
# Add sub-bullet with igwn-alert group:
group_sub_bullet = """<ul>
<li> Messages are sent to group: <span class="text-monospace"> {0} </span></li>
</ul>""".format(LVALERT_OVERSEER_INSTANCES[0]['igwn_alert_group'])
INSTANCE_LIST = INSTANCE_LIST + group_sub_bullet
INSTANCE_TITLE = 'GraceDB Development Server'
INSTANCE_INFO = """
<h5>Development Instance</h5>
<hr>
<p>
This GraceDB instance is designed for GraceDB maintainers to develop and
test in the AWS cloud architecture. There is <b>no guarantee</b> that the
behavior of this instance will mimic the production system at any time.
Events and associated data may change or be removed at any time.
</p>
<ul>
{}
<li>Only LIGO logins are provided (no login via InCommon or Google).</li>
</ul>
""".format(INSTANCE_LIST)