id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
225,000 | django-extensions/django-extensions | django_extensions/management/commands/sync_s3.py | Command.invalidate_objects_cf | def invalidate_objects_cf(self):
"""Split the invalidation request in groups of 1000 objects"""
if not self.AWS_CLOUDFRONT_DISTRIBUTION:
raise CommandError(
'An object invalidation was requested but the variable '
'AWS_CLOUDFRONT_DISTRIBUTION is not present in your settings.')
# We can't send more than 1000 objects in the same invalidation
# request.
chunk = 1000
# Connecting to CloudFront
conn = self.open_cf()
# Splitting the object list
objs = self.uploaded_files
chunks = [objs[i:i + chunk] for i in range(0, len(objs), chunk)]
# Invalidation requests
for paths in chunks:
conn.create_invalidation_request(
self.AWS_CLOUDFRONT_DISTRIBUTION, paths) | python | def invalidate_objects_cf(self):
"""Split the invalidation request in groups of 1000 objects"""
if not self.AWS_CLOUDFRONT_DISTRIBUTION:
raise CommandError(
'An object invalidation was requested but the variable '
'AWS_CLOUDFRONT_DISTRIBUTION is not present in your settings.')
# We can't send more than 1000 objects in the same invalidation
# request.
chunk = 1000
# Connecting to CloudFront
conn = self.open_cf()
# Splitting the object list
objs = self.uploaded_files
chunks = [objs[i:i + chunk] for i in range(0, len(objs), chunk)]
# Invalidation requests
for paths in chunks:
conn.create_invalidation_request(
self.AWS_CLOUDFRONT_DISTRIBUTION, paths) | [
"def",
"invalidate_objects_cf",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"AWS_CLOUDFRONT_DISTRIBUTION",
":",
"raise",
"CommandError",
"(",
"'An object invalidation was requested but the variable '",
"'AWS_CLOUDFRONT_DISTRIBUTION is not present in your settings.'",
")",
"#... | Split the invalidation request in groups of 1000 objects | [
"Split",
"the",
"invalidation",
"request",
"in",
"groups",
"of",
"1000",
"objects"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sync_s3.py#L253-L274 |
225,001 | django-extensions/django-extensions | django_extensions/management/commands/sync_s3.py | Command.open_s3 | def open_s3(self):
"""Open connection to S3 returning bucket and key"""
conn = boto.connect_s3(
self.AWS_ACCESS_KEY_ID,
self.AWS_SECRET_ACCESS_KEY,
**self.get_s3connection_kwargs())
try:
bucket = conn.get_bucket(self.AWS_BUCKET_NAME)
except boto.exception.S3ResponseError:
bucket = conn.create_bucket(self.AWS_BUCKET_NAME)
return bucket, boto.s3.key.Key(bucket) | python | def open_s3(self):
"""Open connection to S3 returning bucket and key"""
conn = boto.connect_s3(
self.AWS_ACCESS_KEY_ID,
self.AWS_SECRET_ACCESS_KEY,
**self.get_s3connection_kwargs())
try:
bucket = conn.get_bucket(self.AWS_BUCKET_NAME)
except boto.exception.S3ResponseError:
bucket = conn.create_bucket(self.AWS_BUCKET_NAME)
return bucket, boto.s3.key.Key(bucket) | [
"def",
"open_s3",
"(",
"self",
")",
":",
"conn",
"=",
"boto",
".",
"connect_s3",
"(",
"self",
".",
"AWS_ACCESS_KEY_ID",
",",
"self",
".",
"AWS_SECRET_ACCESS_KEY",
",",
"*",
"*",
"self",
".",
"get_s3connection_kwargs",
"(",
")",
")",
"try",
":",
"bucket",
... | Open connection to S3 returning bucket and key | [
"Open",
"connection",
"to",
"S3",
"returning",
"bucket",
"and",
"key"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sync_s3.py#L298-L308 |
225,002 | django-extensions/django-extensions | django_extensions/management/commands/shell_plus.py | Command.set_application_name | def set_application_name(self, options):
"""
Set the application_name on PostgreSQL connection
Use the fallback_application_name to let the user override
it with PGAPPNAME env variable
http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS # noqa
"""
supported_backends = ['django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2']
opt_name = 'fallback_application_name'
default_app_name = 'django_shell'
app_name = default_app_name
dbs = getattr(settings, 'DATABASES', [])
# lookup over all the databases entry
for db in dbs.keys():
if dbs[db]['ENGINE'] in supported_backends:
try:
options = dbs[db]['OPTIONS']
except KeyError:
options = {}
# dot not override a defined value
if opt_name in options.keys():
app_name = dbs[db]['OPTIONS'][opt_name]
else:
dbs[db].setdefault('OPTIONS', {}).update({opt_name: default_app_name})
app_name = default_app_name
return app_name | python | def set_application_name(self, options):
"""
Set the application_name on PostgreSQL connection
Use the fallback_application_name to let the user override
it with PGAPPNAME env variable
http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS # noqa
"""
supported_backends = ['django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2']
opt_name = 'fallback_application_name'
default_app_name = 'django_shell'
app_name = default_app_name
dbs = getattr(settings, 'DATABASES', [])
# lookup over all the databases entry
for db in dbs.keys():
if dbs[db]['ENGINE'] in supported_backends:
try:
options = dbs[db]['OPTIONS']
except KeyError:
options = {}
# dot not override a defined value
if opt_name in options.keys():
app_name = dbs[db]['OPTIONS'][opt_name]
else:
dbs[db].setdefault('OPTIONS', {}).update({opt_name: default_app_name})
app_name = default_app_name
return app_name | [
"def",
"set_application_name",
"(",
"self",
",",
"options",
")",
":",
"supported_backends",
"=",
"[",
"'django.db.backends.postgresql'",
",",
"'django.db.backends.postgresql_psycopg2'",
"]",
"opt_name",
"=",
"'fallback_application_name'",
"default_app_name",
"=",
"'django_she... | Set the application_name on PostgreSQL connection
Use the fallback_application_name to let the user override
it with PGAPPNAME env variable
http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS # noqa | [
"Set",
"the",
"application_name",
"on",
"PostgreSQL",
"connection"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/shell_plus.py#L394-L425 |
225,003 | django-extensions/django-extensions | django_extensions/management/commands/mail_debug.py | ExtensionDebuggingServer.process_message | def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
"""Output will be sent to the module logger at INFO level."""
inheaders = 1
lines = data.split('\n')
logger.info('---------- MESSAGE FOLLOWS ----------')
for line in lines:
# headers first
if inheaders and not line:
logger.info('X-Peer: %s' % peer[0])
inheaders = 0
logger.info(line)
logger.info('------------ END MESSAGE ------------') | python | def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
"""Output will be sent to the module logger at INFO level."""
inheaders = 1
lines = data.split('\n')
logger.info('---------- MESSAGE FOLLOWS ----------')
for line in lines:
# headers first
if inheaders and not line:
logger.info('X-Peer: %s' % peer[0])
inheaders = 0
logger.info(line)
logger.info('------------ END MESSAGE ------------') | [
"def",
"process_message",
"(",
"self",
",",
"peer",
",",
"mailfrom",
",",
"rcpttos",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"inheaders",
"=",
"1",
"lines",
"=",
"data",
".",
"split",
"(",
"'\\n'",
")",
"logger",
".",
"info",
"(",
"'---------... | Output will be sent to the module logger at INFO level. | [
"Output",
"will",
"be",
"sent",
"to",
"the",
"module",
"logger",
"at",
"INFO",
"level",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/mail_debug.py#L20-L31 |
225,004 | django-extensions/django-extensions | django_extensions/management/email_notifications.py | EmailNotificationCommand.run_from_argv | def run_from_argv(self, argv):
"""Overriden in order to access the command line arguments."""
self.argv_string = ' '.join(argv)
super(EmailNotificationCommand, self).run_from_argv(argv) | python | def run_from_argv(self, argv):
"""Overriden in order to access the command line arguments."""
self.argv_string = ' '.join(argv)
super(EmailNotificationCommand, self).run_from_argv(argv) | [
"def",
"run_from_argv",
"(",
"self",
",",
"argv",
")",
":",
"self",
".",
"argv_string",
"=",
"' '",
".",
"join",
"(",
"argv",
")",
"super",
"(",
"EmailNotificationCommand",
",",
"self",
")",
".",
"run_from_argv",
"(",
"argv",
")"
] | Overriden in order to access the command line arguments. | [
"Overriden",
"in",
"order",
"to",
"access",
"the",
"command",
"line",
"arguments",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/email_notifications.py#L62-L65 |
225,005 | django-extensions/django-extensions | django_extensions/management/email_notifications.py | EmailNotificationCommand.execute | def execute(self, *args, **options):
"""
Overriden in order to send emails on unhandled exception.
If an unhandled exception in ``def handle(self, *args, **options)``
occurs and `--email-exception` is set or `self.email_exception` is
set to True send an email to ADMINS with the traceback and then
reraise the exception.
"""
try:
super(EmailNotificationCommand, self).execute(*args, **options)
except Exception:
if options['email_exception'] or getattr(self, 'email_exception', False):
self.send_email_notification(include_traceback=True)
raise | python | def execute(self, *args, **options):
"""
Overriden in order to send emails on unhandled exception.
If an unhandled exception in ``def handle(self, *args, **options)``
occurs and `--email-exception` is set or `self.email_exception` is
set to True send an email to ADMINS with the traceback and then
reraise the exception.
"""
try:
super(EmailNotificationCommand, self).execute(*args, **options)
except Exception:
if options['email_exception'] or getattr(self, 'email_exception', False):
self.send_email_notification(include_traceback=True)
raise | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"try",
":",
"super",
"(",
"EmailNotificationCommand",
",",
"self",
")",
".",
"execute",
"(",
"*",
"args",
",",
"*",
"*",
"options",
")",
"except",
"Exception",
":",
... | Overriden in order to send emails on unhandled exception.
If an unhandled exception in ``def handle(self, *args, **options)``
occurs and `--email-exception` is set or `self.email_exception` is
set to True send an email to ADMINS with the traceback and then
reraise the exception. | [
"Overriden",
"in",
"order",
"to",
"send",
"emails",
"on",
"unhandled",
"exception",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/email_notifications.py#L67-L81 |
225,006 | django-extensions/django-extensions | django_extensions/management/email_notifications.py | EmailNotificationCommand.send_email_notification | def send_email_notification(self, notification_id=None, include_traceback=False, verbosity=1):
"""
Send email notifications.
Reads settings from settings.EMAIL_NOTIFICATIONS dict, if available,
using ``notification_id`` as a key or else provides reasonable
defaults.
"""
# Load email notification settings if available
if notification_id is not None:
try:
email_settings = settings.EMAIL_NOTIFICATIONS.get(notification_id, {})
except AttributeError:
email_settings = {}
else:
email_settings = {}
# Exit if no traceback found and not in 'notify always' mode
if not include_traceback and not email_settings.get('notification_level', 0):
print(self.style.ERROR("Exiting, not in 'notify always' mode."))
return
# Set email fields.
subject = email_settings.get('subject', "Django extensions email notification.")
command_name = self.__module__.split('.')[-1]
body = email_settings.get(
'body',
"Reporting execution of command: '%s'" % command_name
)
# Include traceback
if include_traceback and not email_settings.get('no_traceback', False):
try:
exc_type, exc_value, exc_traceback = sys.exc_info()
trb = ''.join(traceback.format_tb(exc_traceback))
body += "\n\nTraceback:\n\n%s\n" % trb
finally:
del exc_traceback
# Set from address
from_email = email_settings.get('from_email', settings.DEFAULT_FROM_EMAIL)
# Calculate recipients
recipients = list(email_settings.get('recipients', []))
if not email_settings.get('no_admins', False):
recipients.extend(settings.ADMINS)
if not recipients:
if verbosity > 0:
print(self.style.ERROR("No email recipients available."))
return
# Send email...
send_mail(subject, body, from_email, recipients,
fail_silently=email_settings.get('fail_silently', True)) | python | def send_email_notification(self, notification_id=None, include_traceback=False, verbosity=1):
"""
Send email notifications.
Reads settings from settings.EMAIL_NOTIFICATIONS dict, if available,
using ``notification_id`` as a key or else provides reasonable
defaults.
"""
# Load email notification settings if available
if notification_id is not None:
try:
email_settings = settings.EMAIL_NOTIFICATIONS.get(notification_id, {})
except AttributeError:
email_settings = {}
else:
email_settings = {}
# Exit if no traceback found and not in 'notify always' mode
if not include_traceback and not email_settings.get('notification_level', 0):
print(self.style.ERROR("Exiting, not in 'notify always' mode."))
return
# Set email fields.
subject = email_settings.get('subject', "Django extensions email notification.")
command_name = self.__module__.split('.')[-1]
body = email_settings.get(
'body',
"Reporting execution of command: '%s'" % command_name
)
# Include traceback
if include_traceback and not email_settings.get('no_traceback', False):
try:
exc_type, exc_value, exc_traceback = sys.exc_info()
trb = ''.join(traceback.format_tb(exc_traceback))
body += "\n\nTraceback:\n\n%s\n" % trb
finally:
del exc_traceback
# Set from address
from_email = email_settings.get('from_email', settings.DEFAULT_FROM_EMAIL)
# Calculate recipients
recipients = list(email_settings.get('recipients', []))
if not email_settings.get('no_admins', False):
recipients.extend(settings.ADMINS)
if not recipients:
if verbosity > 0:
print(self.style.ERROR("No email recipients available."))
return
# Send email...
send_mail(subject, body, from_email, recipients,
fail_silently=email_settings.get('fail_silently', True)) | [
"def",
"send_email_notification",
"(",
"self",
",",
"notification_id",
"=",
"None",
",",
"include_traceback",
"=",
"False",
",",
"verbosity",
"=",
"1",
")",
":",
"# Load email notification settings if available",
"if",
"notification_id",
"is",
"not",
"None",
":",
"t... | Send email notifications.
Reads settings from settings.EMAIL_NOTIFICATIONS dict, if available,
using ``notification_id`` as a key or else provides reasonable
defaults. | [
"Send",
"email",
"notifications",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/email_notifications.py#L83-L140 |
225,007 | django-extensions/django-extensions | django_extensions/compat.py | load_tag_library | def load_tag_library(libname):
"""
Load a templatetag library on multiple Django versions.
Returns None if the library isn't loaded.
"""
from django.template.backends.django import get_installed_libraries
from django.template.library import InvalidTemplateLibrary
try:
lib = get_installed_libraries()[libname]
lib = importlib.import_module(lib).register
return lib
except (InvalidTemplateLibrary, KeyError):
return None | python | def load_tag_library(libname):
"""
Load a templatetag library on multiple Django versions.
Returns None if the library isn't loaded.
"""
from django.template.backends.django import get_installed_libraries
from django.template.library import InvalidTemplateLibrary
try:
lib = get_installed_libraries()[libname]
lib = importlib.import_module(lib).register
return lib
except (InvalidTemplateLibrary, KeyError):
return None | [
"def",
"load_tag_library",
"(",
"libname",
")",
":",
"from",
"django",
".",
"template",
".",
"backends",
".",
"django",
"import",
"get_installed_libraries",
"from",
"django",
".",
"template",
".",
"library",
"import",
"InvalidTemplateLibrary",
"try",
":",
"lib",
... | Load a templatetag library on multiple Django versions.
Returns None if the library isn't loaded. | [
"Load",
"a",
"templatetag",
"library",
"on",
"multiple",
"Django",
"versions",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/compat.py#L17-L30 |
225,008 | django-extensions/django-extensions | django_extensions/compat.py | get_template_setting | def get_template_setting(template_key, default=None):
""" Read template settings """
templates_var = getattr(settings, 'TEMPLATES', None)
if templates_var:
for tdict in templates_var:
if template_key in tdict:
return tdict[template_key]
return default | python | def get_template_setting(template_key, default=None):
""" Read template settings """
templates_var = getattr(settings, 'TEMPLATES', None)
if templates_var:
for tdict in templates_var:
if template_key in tdict:
return tdict[template_key]
return default | [
"def",
"get_template_setting",
"(",
"template_key",
",",
"default",
"=",
"None",
")",
":",
"templates_var",
"=",
"getattr",
"(",
"settings",
",",
"'TEMPLATES'",
",",
"None",
")",
"if",
"templates_var",
":",
"for",
"tdict",
"in",
"templates_var",
":",
"if",
"... | Read template settings | [
"Read",
"template",
"settings"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/compat.py#L33-L40 |
225,009 | django-extensions/django-extensions | django_extensions/management/modelviz.py | ModelGraph.use_model | def use_model(self, model_name):
"""
Decide whether to use a model, based on the model name and the lists of
models to exclude and include.
"""
# Check against exclude list.
if self.exclude_models:
for model_pattern in self.exclude_models:
model_pattern = '^%s$' % model_pattern.replace('*', '.*')
if re.search(model_pattern, model_name):
return False
# Check against exclude list.
elif self.include_models:
for model_pattern in self.include_models:
model_pattern = '^%s$' % model_pattern.replace('*', '.*')
if re.search(model_pattern, model_name):
return True
# Return `True` if `include_models` is falsey, otherwise return `False`.
return not self.include_models | python | def use_model(self, model_name):
"""
Decide whether to use a model, based on the model name and the lists of
models to exclude and include.
"""
# Check against exclude list.
if self.exclude_models:
for model_pattern in self.exclude_models:
model_pattern = '^%s$' % model_pattern.replace('*', '.*')
if re.search(model_pattern, model_name):
return False
# Check against exclude list.
elif self.include_models:
for model_pattern in self.include_models:
model_pattern = '^%s$' % model_pattern.replace('*', '.*')
if re.search(model_pattern, model_name):
return True
# Return `True` if `include_models` is falsey, otherwise return `False`.
return not self.include_models | [
"def",
"use_model",
"(",
"self",
",",
"model_name",
")",
":",
"# Check against exclude list.",
"if",
"self",
".",
"exclude_models",
":",
"for",
"model_pattern",
"in",
"self",
".",
"exclude_models",
":",
"model_pattern",
"=",
"'^%s$'",
"%",
"model_pattern",
".",
... | Decide whether to use a model, based on the model name and the lists of
models to exclude and include. | [
"Decide",
"whether",
"to",
"use",
"a",
"model",
"based",
"on",
"the",
"model",
"name",
"and",
"the",
"lists",
"of",
"models",
"to",
"exclude",
"and",
"include",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/modelviz.py#L359-L377 |
225,010 | google/transitfeed | transitfeed/shapelib.py | GetClosestPoint | def GetClosestPoint(x, a, b):
"""
Returns the point on the great circle segment ab closest to x.
"""
assert(x.IsUnitLength())
assert(a.IsUnitLength())
assert(b.IsUnitLength())
a_cross_b = a.RobustCrossProd(b)
# project to the great circle going through a and b
p = x.Minus(
a_cross_b.Times(
x.DotProd(a_cross_b) / a_cross_b.Norm2()))
# if p lies between a and b, return it
if SimpleCCW(a_cross_b, a, p) and SimpleCCW(p, b, a_cross_b):
return p.Normalize()
# otherwise return the closer of a or b
if x.Minus(a).Norm2() <= x.Minus(b).Norm2():
return a
else:
return b | python | def GetClosestPoint(x, a, b):
"""
Returns the point on the great circle segment ab closest to x.
"""
assert(x.IsUnitLength())
assert(a.IsUnitLength())
assert(b.IsUnitLength())
a_cross_b = a.RobustCrossProd(b)
# project to the great circle going through a and b
p = x.Minus(
a_cross_b.Times(
x.DotProd(a_cross_b) / a_cross_b.Norm2()))
# if p lies between a and b, return it
if SimpleCCW(a_cross_b, a, p) and SimpleCCW(p, b, a_cross_b):
return p.Normalize()
# otherwise return the closer of a or b
if x.Minus(a).Norm2() <= x.Minus(b).Norm2():
return a
else:
return b | [
"def",
"GetClosestPoint",
"(",
"x",
",",
"a",
",",
"b",
")",
":",
"assert",
"(",
"x",
".",
"IsUnitLength",
"(",
")",
")",
"assert",
"(",
"a",
".",
"IsUnitLength",
"(",
")",
")",
"assert",
"(",
"b",
".",
"IsUnitLength",
"(",
")",
")",
"a_cross_b",
... | Returns the point on the great circle segment ab closest to x. | [
"Returns",
"the",
"point",
"on",
"the",
"great",
"circle",
"segment",
"ab",
"closest",
"to",
"x",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L221-L243 |
225,011 | google/transitfeed | transitfeed/shapelib.py | Point.Plus | def Plus(self, other):
"""
Returns a new point which is the pointwise sum of self and other.
"""
return Point(self.x + other.x,
self.y + other.y,
self.z + other.z) | python | def Plus(self, other):
"""
Returns a new point which is the pointwise sum of self and other.
"""
return Point(self.x + other.x,
self.y + other.y,
self.z + other.z) | [
"def",
"Plus",
"(",
"self",
",",
"other",
")",
":",
"return",
"Point",
"(",
"self",
".",
"x",
"+",
"other",
".",
"x",
",",
"self",
".",
"y",
"+",
"other",
".",
"y",
",",
"self",
".",
"z",
"+",
"other",
".",
"z",
")"
] | Returns a new point which is the pointwise sum of self and other. | [
"Returns",
"a",
"new",
"point",
"which",
"is",
"the",
"pointwise",
"sum",
"of",
"self",
"and",
"other",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L79-L85 |
225,012 | google/transitfeed | transitfeed/shapelib.py | Point.Minus | def Minus(self, other):
"""
Returns a new point which is the pointwise subtraction of other from
self.
"""
return Point(self.x - other.x,
self.y - other.y,
self.z - other.z) | python | def Minus(self, other):
"""
Returns a new point which is the pointwise subtraction of other from
self.
"""
return Point(self.x - other.x,
self.y - other.y,
self.z - other.z) | [
"def",
"Minus",
"(",
"self",
",",
"other",
")",
":",
"return",
"Point",
"(",
"self",
".",
"x",
"-",
"other",
".",
"x",
",",
"self",
".",
"y",
"-",
"other",
".",
"y",
",",
"self",
".",
"z",
"-",
"other",
".",
"z",
")"
] | Returns a new point which is the pointwise subtraction of other from
self. | [
"Returns",
"a",
"new",
"point",
"which",
"is",
"the",
"pointwise",
"subtraction",
"of",
"other",
"from",
"self",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L87-L94 |
225,013 | google/transitfeed | transitfeed/shapelib.py | Point.Times | def Times(self, val):
"""
Returns a new point which is pointwise multiplied by val.
"""
return Point(self.x * val, self.y * val, self.z * val) | python | def Times(self, val):
"""
Returns a new point which is pointwise multiplied by val.
"""
return Point(self.x * val, self.y * val, self.z * val) | [
"def",
"Times",
"(",
"self",
",",
"val",
")",
":",
"return",
"Point",
"(",
"self",
".",
"x",
"*",
"val",
",",
"self",
".",
"y",
"*",
"val",
",",
"self",
".",
"z",
"*",
"val",
")"
] | Returns a new point which is pointwise multiplied by val. | [
"Returns",
"a",
"new",
"point",
"which",
"is",
"pointwise",
"multiplied",
"by",
"val",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L102-L106 |
225,014 | google/transitfeed | transitfeed/shapelib.py | Point.Ortho | def Ortho(self):
"""Returns a unit-length point orthogonal to this point"""
(index, val) = self.LargestComponent()
index = index - 1
if index < 0:
index = 2
temp = Point(0.012, 0.053, 0.00457)
if index == 0:
temp.x = 1
elif index == 1:
temp.y = 1
elif index == 2:
temp.z = 1
return self.CrossProd(temp).Normalize() | python | def Ortho(self):
"""Returns a unit-length point orthogonal to this point"""
(index, val) = self.LargestComponent()
index = index - 1
if index < 0:
index = 2
temp = Point(0.012, 0.053, 0.00457)
if index == 0:
temp.x = 1
elif index == 1:
temp.y = 1
elif index == 2:
temp.z = 1
return self.CrossProd(temp).Normalize() | [
"def",
"Ortho",
"(",
"self",
")",
":",
"(",
"index",
",",
"val",
")",
"=",
"self",
".",
"LargestComponent",
"(",
")",
"index",
"=",
"index",
"-",
"1",
"if",
"index",
"<",
"0",
":",
"index",
"=",
"2",
"temp",
"=",
"Point",
"(",
"0.012",
",",
"0.... | Returns a unit-length point orthogonal to this point | [
"Returns",
"a",
"unit",
"-",
"length",
"point",
"orthogonal",
"to",
"this",
"point"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L145-L158 |
225,015 | google/transitfeed | transitfeed/shapelib.py | Point.CrossProd | def CrossProd(self, other):
"""
Returns the cross product of self and other.
"""
return Point(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x) | python | def CrossProd(self, other):
"""
Returns the cross product of self and other.
"""
return Point(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x) | [
"def",
"CrossProd",
"(",
"self",
",",
"other",
")",
":",
"return",
"Point",
"(",
"self",
".",
"y",
"*",
"other",
".",
"z",
"-",
"self",
".",
"z",
"*",
"other",
".",
"y",
",",
"self",
".",
"z",
"*",
"other",
".",
"x",
"-",
"self",
".",
"x",
... | Returns the cross product of self and other. | [
"Returns",
"the",
"cross",
"product",
"of",
"self",
"and",
"other",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L160-L167 |
225,016 | google/transitfeed | transitfeed/shapelib.py | Point.Equals | def Equals(self, other):
"""
Returns true of self and other are approximately equal.
"""
return (self._approxEq(self.x, other.x)
and self._approxEq(self.y, other.y)
and self._approxEq(self.z, other.z)) | python | def Equals(self, other):
"""
Returns true of self and other are approximately equal.
"""
return (self._approxEq(self.x, other.x)
and self._approxEq(self.y, other.y)
and self._approxEq(self.z, other.z)) | [
"def",
"Equals",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"_approxEq",
"(",
"self",
".",
"x",
",",
"other",
".",
"x",
")",
"and",
"self",
".",
"_approxEq",
"(",
"self",
".",
"y",
",",
"other",
".",
"y",
")",
"and",
"self... | Returns true of self and other are approximately equal. | [
"Returns",
"true",
"of",
"self",
"and",
"other",
"are",
"approximately",
"equal",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L173-L179 |
225,017 | google/transitfeed | transitfeed/shapelib.py | Point.Angle | def Angle(self, other):
"""
Returns the angle in radians between self and other.
"""
return math.atan2(self.CrossProd(other).Norm2(),
self.DotProd(other)) | python | def Angle(self, other):
"""
Returns the angle in radians between self and other.
"""
return math.atan2(self.CrossProd(other).Norm2(),
self.DotProd(other)) | [
"def",
"Angle",
"(",
"self",
",",
"other",
")",
":",
"return",
"math",
".",
"atan2",
"(",
"self",
".",
"CrossProd",
"(",
"other",
")",
".",
"Norm2",
"(",
")",
",",
"self",
".",
"DotProd",
"(",
"other",
")",
")"
] | Returns the angle in radians between self and other. | [
"Returns",
"the",
"angle",
"in",
"radians",
"between",
"self",
"and",
"other",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L181-L186 |
225,018 | google/transitfeed | transitfeed/shapelib.py | Point.ToLatLng | def ToLatLng(self):
"""
Returns that latitude and longitude that this point represents
under a spherical Earth model.
"""
rad_lat = math.atan2(self.z, math.sqrt(self.x * self.x + self.y * self.y))
rad_lng = math.atan2(self.y, self.x)
return (rad_lat * 180.0 / math.pi, rad_lng * 180.0 / math.pi) | python | def ToLatLng(self):
"""
Returns that latitude and longitude that this point represents
under a spherical Earth model.
"""
rad_lat = math.atan2(self.z, math.sqrt(self.x * self.x + self.y * self.y))
rad_lng = math.atan2(self.y, self.x)
return (rad_lat * 180.0 / math.pi, rad_lng * 180.0 / math.pi) | [
"def",
"ToLatLng",
"(",
"self",
")",
":",
"rad_lat",
"=",
"math",
".",
"atan2",
"(",
"self",
".",
"z",
",",
"math",
".",
"sqrt",
"(",
"self",
".",
"x",
"*",
"self",
".",
"x",
"+",
"self",
".",
"y",
"*",
"self",
".",
"y",
")",
")",
"rad_lng",
... | Returns that latitude and longitude that this point represents
under a spherical Earth model. | [
"Returns",
"that",
"latitude",
"and",
"longitude",
"that",
"this",
"point",
"represents",
"under",
"a",
"spherical",
"Earth",
"model",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L188-L195 |
225,019 | google/transitfeed | transitfeed/shapelib.py | Point.FromLatLng | def FromLatLng(lat, lng):
"""
Returns a new point representing this latitude and longitude under
a spherical Earth model.
"""
phi = lat * (math.pi / 180.0)
theta = lng * (math.pi / 180.0)
cosphi = math.cos(phi)
return Point(math.cos(theta) * cosphi,
math.sin(theta) * cosphi,
math.sin(phi)) | python | def FromLatLng(lat, lng):
"""
Returns a new point representing this latitude and longitude under
a spherical Earth model.
"""
phi = lat * (math.pi / 180.0)
theta = lng * (math.pi / 180.0)
cosphi = math.cos(phi)
return Point(math.cos(theta) * cosphi,
math.sin(theta) * cosphi,
math.sin(phi)) | [
"def",
"FromLatLng",
"(",
"lat",
",",
"lng",
")",
":",
"phi",
"=",
"lat",
"*",
"(",
"math",
".",
"pi",
"/",
"180.0",
")",
"theta",
"=",
"lng",
"*",
"(",
"math",
".",
"pi",
"/",
"180.0",
")",
"cosphi",
"=",
"math",
".",
"cos",
"(",
"phi",
")",... | Returns a new point representing this latitude and longitude under
a spherical Earth model. | [
"Returns",
"a",
"new",
"point",
"representing",
"this",
"latitude",
"and",
"longitude",
"under",
"a",
"spherical",
"Earth",
"model",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L198-L208 |
225,020 | google/transitfeed | transitfeed/shapelib.py | Poly.LengthMeters | def LengthMeters(self):
"""Return length of this polyline in meters."""
assert(len(self._points) > 0)
length = 0
for i in range(0, len(self._points) - 1):
length += self._points[i].GetDistanceMeters(self._points[i+1])
return length | python | def LengthMeters(self):
"""Return length of this polyline in meters."""
assert(len(self._points) > 0)
length = 0
for i in range(0, len(self._points) - 1):
length += self._points[i].GetDistanceMeters(self._points[i+1])
return length | [
"def",
"LengthMeters",
"(",
"self",
")",
":",
"assert",
"(",
"len",
"(",
"self",
".",
"_points",
")",
">",
"0",
")",
"length",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"_points",
")",
"-",
"1",
")",
":",
"l... | Return length of this polyline in meters. | [
"Return",
"length",
"of",
"this",
"polyline",
"in",
"meters",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L299-L305 |
225,021 | google/transitfeed | transitfeed/shapelib.py | Poly.CutAtClosestPoint | def CutAtClosestPoint(self, p):
"""
Let x be the point on the polyline closest to p. Then
CutAtClosestPoint returns two new polylines, one representing
the polyline from the beginning up to x, and one representing
x onwards to the end of the polyline. x is the first point
returned in the second polyline.
"""
(closest, i) = self.GetClosestPoint(p)
tmp = [closest]
tmp.extend(self._points[i+1:])
return (Poly(self._points[0:i+1]),
Poly(tmp)) | python | def CutAtClosestPoint(self, p):
"""
Let x be the point on the polyline closest to p. Then
CutAtClosestPoint returns two new polylines, one representing
the polyline from the beginning up to x, and one representing
x onwards to the end of the polyline. x is the first point
returned in the second polyline.
"""
(closest, i) = self.GetClosestPoint(p)
tmp = [closest]
tmp.extend(self._points[i+1:])
return (Poly(self._points[0:i+1]),
Poly(tmp)) | [
"def",
"CutAtClosestPoint",
"(",
"self",
",",
"p",
")",
":",
"(",
"closest",
",",
"i",
")",
"=",
"self",
".",
"GetClosestPoint",
"(",
"p",
")",
"tmp",
"=",
"[",
"closest",
"]",
"tmp",
".",
"extend",
"(",
"self",
".",
"_points",
"[",
"i",
"+",
"1"... | Let x be the point on the polyline closest to p. Then
CutAtClosestPoint returns two new polylines, one representing
the polyline from the beginning up to x, and one representing
x onwards to the end of the polyline. x is the first point
returned in the second polyline. | [
"Let",
"x",
"be",
"the",
"point",
"on",
"the",
"polyline",
"closest",
"to",
"p",
".",
"Then",
"CutAtClosestPoint",
"returns",
"two",
"new",
"polylines",
"one",
"representing",
"the",
"polyline",
"from",
"the",
"beginning",
"up",
"to",
"x",
"and",
"one",
"r... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L311-L324 |
225,022 | google/transitfeed | transitfeed/shapelib.py | Poly.GreedyPolyMatchDist | def GreedyPolyMatchDist(self, shape):
"""
Tries a greedy matching algorithm to match self to the
given shape. Returns the maximum distance in meters of
any point in self to its matched point in shape under the
algorithm.
Args: shape, a Poly object.
"""
tmp_shape = Poly(shape.GetPoints())
max_radius = 0
for (i, point) in enumerate(self._points):
tmp_shape = tmp_shape.CutAtClosestPoint(point)[1]
dist = tmp_shape.GetPoint(0).GetDistanceMeters(point)
max_radius = max(max_radius, dist)
return max_radius | python | def GreedyPolyMatchDist(self, shape):
"""
Tries a greedy matching algorithm to match self to the
given shape. Returns the maximum distance in meters of
any point in self to its matched point in shape under the
algorithm.
Args: shape, a Poly object.
"""
tmp_shape = Poly(shape.GetPoints())
max_radius = 0
for (i, point) in enumerate(self._points):
tmp_shape = tmp_shape.CutAtClosestPoint(point)[1]
dist = tmp_shape.GetPoint(0).GetDistanceMeters(point)
max_radius = max(max_radius, dist)
return max_radius | [
"def",
"GreedyPolyMatchDist",
"(",
"self",
",",
"shape",
")",
":",
"tmp_shape",
"=",
"Poly",
"(",
"shape",
".",
"GetPoints",
"(",
")",
")",
"max_radius",
"=",
"0",
"for",
"(",
"i",
",",
"point",
")",
"in",
"enumerate",
"(",
"self",
".",
"_points",
")... | Tries a greedy matching algorithm to match self to the
given shape. Returns the maximum distance in meters of
any point in self to its matched point in shape under the
algorithm.
Args: shape, a Poly object. | [
"Tries",
"a",
"greedy",
"matching",
"algorithm",
"to",
"match",
"self",
"to",
"the",
"given",
"shape",
".",
"Returns",
"the",
"maximum",
"distance",
"in",
"meters",
"of",
"any",
"point",
"in",
"self",
"to",
"its",
"matched",
"point",
"in",
"shape",
"under"... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L326-L341 |
225,023 | google/transitfeed | transitfeed/shapelib.py | PolyCollection.AddPoly | def AddPoly(self, poly, smart_duplicate_handling=True):
"""
Adds a new polyline to the collection.
"""
inserted_name = poly.GetName()
if poly.GetName() in self._name_to_shape:
if not smart_duplicate_handling:
raise ShapeError("Duplicate shape found: " + poly.GetName())
print ("Warning: duplicate shape id being added to collection: " +
poly.GetName())
if poly.GreedyPolyMatchDist(self._name_to_shape[poly.GetName()]) < 10:
print(" (Skipping as it apears to be an exact duplicate)")
else:
print(" (Adding new shape variant with uniquified name)")
inserted_name = "%s-%d" % (inserted_name, len(self._name_to_shape))
self._name_to_shape[inserted_name] = poly | python | def AddPoly(self, poly, smart_duplicate_handling=True):
"""
Adds a new polyline to the collection.
"""
inserted_name = poly.GetName()
if poly.GetName() in self._name_to_shape:
if not smart_duplicate_handling:
raise ShapeError("Duplicate shape found: " + poly.GetName())
print ("Warning: duplicate shape id being added to collection: " +
poly.GetName())
if poly.GreedyPolyMatchDist(self._name_to_shape[poly.GetName()]) < 10:
print(" (Skipping as it apears to be an exact duplicate)")
else:
print(" (Adding new shape variant with uniquified name)")
inserted_name = "%s-%d" % (inserted_name, len(self._name_to_shape))
self._name_to_shape[inserted_name] = poly | [
"def",
"AddPoly",
"(",
"self",
",",
"poly",
",",
"smart_duplicate_handling",
"=",
"True",
")",
":",
"inserted_name",
"=",
"poly",
".",
"GetName",
"(",
")",
"if",
"poly",
".",
"GetName",
"(",
")",
"in",
"self",
".",
"_name_to_shape",
":",
"if",
"not",
"... | Adds a new polyline to the collection. | [
"Adds",
"a",
"new",
"polyline",
"to",
"the",
"collection",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L392-L408 |
225,024 | google/transitfeed | transitfeed/shapelib.py | PolyCollection.FindMatchingPolys | def FindMatchingPolys(self, start_point, end_point, max_radius=150):
"""
Returns a list of polylines in the collection that have endpoints
within max_radius of the given start and end points.
"""
matches = []
for shape in self._name_to_shape.itervalues():
if start_point.GetDistanceMeters(shape.GetPoint(0)) < max_radius and \
end_point.GetDistanceMeters(shape.GetPoint(-1)) < max_radius:
matches.append(shape)
return matches | python | def FindMatchingPolys(self, start_point, end_point, max_radius=150):
"""
Returns a list of polylines in the collection that have endpoints
within max_radius of the given start and end points.
"""
matches = []
for shape in self._name_to_shape.itervalues():
if start_point.GetDistanceMeters(shape.GetPoint(0)) < max_radius and \
end_point.GetDistanceMeters(shape.GetPoint(-1)) < max_radius:
matches.append(shape)
return matches | [
"def",
"FindMatchingPolys",
"(",
"self",
",",
"start_point",
",",
"end_point",
",",
"max_radius",
"=",
"150",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"shape",
"in",
"self",
".",
"_name_to_shape",
".",
"itervalues",
"(",
")",
":",
"if",
"start_point",
... | Returns a list of polylines in the collection that have endpoints
within max_radius of the given start and end points. | [
"Returns",
"a",
"list",
"of",
"polylines",
"in",
"the",
"collection",
"that",
"have",
"endpoints",
"within",
"max_radius",
"of",
"the",
"given",
"start",
"and",
"end",
"points",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L413-L423 |
225,025 | google/transitfeed | transitfeed/shapelib.py | PolyGraph._ReconstructPath | def _ReconstructPath(self, came_from, current_node):
"""
Helper method for ShortestPath, to reconstruct path.
Arguments:
came_from: a dictionary mapping Point to (Point, Poly) tuples.
This dictionary keeps track of the previous neighbor to a node, and
the edge used to get from the previous neighbor to the node.
current_node: the current Point in the path.
Returns:
A Poly that represents the path through the graph from the start of the
search to current_node.
"""
if current_node in came_from:
(previous_node, previous_edge) = came_from[current_node]
if previous_edge.GetPoint(0) == current_node:
previous_edge = previous_edge.Reversed()
p = self._ReconstructPath(came_from, previous_node)
return Poly.MergePolys([p, previous_edge], merge_point_threshold=0)
else:
return Poly([], '') | python | def _ReconstructPath(self, came_from, current_node):
"""
Helper method for ShortestPath, to reconstruct path.
Arguments:
came_from: a dictionary mapping Point to (Point, Poly) tuples.
This dictionary keeps track of the previous neighbor to a node, and
the edge used to get from the previous neighbor to the node.
current_node: the current Point in the path.
Returns:
A Poly that represents the path through the graph from the start of the
search to current_node.
"""
if current_node in came_from:
(previous_node, previous_edge) = came_from[current_node]
if previous_edge.GetPoint(0) == current_node:
previous_edge = previous_edge.Reversed()
p = self._ReconstructPath(came_from, previous_node)
return Poly.MergePolys([p, previous_edge], merge_point_threshold=0)
else:
return Poly([], '') | [
"def",
"_ReconstructPath",
"(",
"self",
",",
"came_from",
",",
"current_node",
")",
":",
"if",
"current_node",
"in",
"came_from",
":",
"(",
"previous_node",
",",
"previous_edge",
")",
"=",
"came_from",
"[",
"current_node",
"]",
"if",
"previous_edge",
".",
"Get... | Helper method for ShortestPath, to reconstruct path.
Arguments:
came_from: a dictionary mapping Point to (Point, Poly) tuples.
This dictionary keeps track of the previous neighbor to a node, and
the edge used to get from the previous neighbor to the node.
current_node: the current Point in the path.
Returns:
A Poly that represents the path through the graph from the start of the
search to current_node. | [
"Helper",
"method",
"for",
"ShortestPath",
"to",
"reconstruct",
"path",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L505-L526 |
225,026 | google/transitfeed | transitfeed/schedule.py | Schedule.AddTableColumn | def AddTableColumn(self, table, column):
"""Add column to table if it is not already there."""
if column not in self._table_columns[table]:
self._table_columns[table].append(column) | python | def AddTableColumn(self, table, column):
"""Add column to table if it is not already there."""
if column not in self._table_columns[table]:
self._table_columns[table].append(column) | [
"def",
"AddTableColumn",
"(",
"self",
",",
"table",
",",
"column",
")",
":",
"if",
"column",
"not",
"in",
"self",
".",
"_table_columns",
"[",
"table",
"]",
":",
"self",
".",
"_table_columns",
"[",
"table",
"]",
".",
"append",
"(",
"column",
")"
] | Add column to table if it is not already there. | [
"Add",
"column",
"to",
"table",
"if",
"it",
"is",
"not",
"already",
"there",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L87-L90 |
225,027 | google/transitfeed | transitfeed/schedule.py | Schedule.AddTableColumns | def AddTableColumns(self, table, columns):
"""Add columns to table if they are not already there.
Args:
table: table name as a string
columns: an iterable of column names"""
table_columns = self._table_columns.setdefault(table, [])
for attr in columns:
if attr not in table_columns:
table_columns.append(attr) | python | def AddTableColumns(self, table, columns):
"""Add columns to table if they are not already there.
Args:
table: table name as a string
columns: an iterable of column names"""
table_columns = self._table_columns.setdefault(table, [])
for attr in columns:
if attr not in table_columns:
table_columns.append(attr) | [
"def",
"AddTableColumns",
"(",
"self",
",",
"table",
",",
"columns",
")",
":",
"table_columns",
"=",
"self",
".",
"_table_columns",
".",
"setdefault",
"(",
"table",
",",
"[",
"]",
")",
"for",
"attr",
"in",
"columns",
":",
"if",
"attr",
"not",
"in",
"ta... | Add columns to table if they are not already there.
Args:
table: table name as a string
columns: an iterable of column names | [
"Add",
"columns",
"to",
"table",
"if",
"they",
"are",
"not",
"already",
"there",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L92-L101 |
225,028 | google/transitfeed | transitfeed/schedule.py | Schedule.AddAgency | def AddAgency(self, name, url, timezone, agency_id=None):
"""Adds an agency to this schedule."""
agency = self._gtfs_factory.Agency(name, url, timezone, agency_id)
self.AddAgencyObject(agency)
return agency | python | def AddAgency(self, name, url, timezone, agency_id=None):
"""Adds an agency to this schedule."""
agency = self._gtfs_factory.Agency(name, url, timezone, agency_id)
self.AddAgencyObject(agency)
return agency | [
"def",
"AddAgency",
"(",
"self",
",",
"name",
",",
"url",
",",
"timezone",
",",
"agency_id",
"=",
"None",
")",
":",
"agency",
"=",
"self",
".",
"_gtfs_factory",
".",
"Agency",
"(",
"name",
",",
"url",
",",
"timezone",
",",
"agency_id",
")",
"self",
"... | Adds an agency to this schedule. | [
"Adds",
"an",
"agency",
"to",
"this",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L157-L161 |
225,029 | google/transitfeed | transitfeed/schedule.py | Schedule.GetDefaultAgency | def GetDefaultAgency(self):
"""Return the default Agency. If no default Agency has been set select the
default depending on how many Agency objects are in the Schedule. If there
are 0 make a new Agency the default, if there is 1 it becomes the default,
if there is more than 1 then return None.
"""
if not self._default_agency:
if len(self._agencies) == 0:
self.NewDefaultAgency()
elif len(self._agencies) == 1:
self._default_agency = self._agencies.values()[0]
return self._default_agency | python | def GetDefaultAgency(self):
"""Return the default Agency. If no default Agency has been set select the
default depending on how many Agency objects are in the Schedule. If there
are 0 make a new Agency the default, if there is 1 it becomes the default,
if there is more than 1 then return None.
"""
if not self._default_agency:
if len(self._agencies) == 0:
self.NewDefaultAgency()
elif len(self._agencies) == 1:
self._default_agency = self._agencies.values()[0]
return self._default_agency | [
"def",
"GetDefaultAgency",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_default_agency",
":",
"if",
"len",
"(",
"self",
".",
"_agencies",
")",
"==",
"0",
":",
"self",
".",
"NewDefaultAgency",
"(",
")",
"elif",
"len",
"(",
"self",
".",
"_agencies"... | Return the default Agency. If no default Agency has been set select the
default depending on how many Agency objects are in the Schedule. If there
are 0 make a new Agency the default, if there is 1 it becomes the default,
if there is more than 1 then return None. | [
"Return",
"the",
"default",
"Agency",
".",
"If",
"no",
"default",
"Agency",
"has",
"been",
"set",
"select",
"the",
"default",
"depending",
"on",
"how",
"many",
"Agency",
"objects",
"are",
"in",
"the",
"Schedule",
".",
"If",
"there",
"are",
"0",
"make",
"... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L184-L195 |
225,030 | google/transitfeed | transitfeed/schedule.py | Schedule.NewDefaultAgency | def NewDefaultAgency(self, **kwargs):
"""Create a new Agency object and make it the default agency for this Schedule"""
agency = self._gtfs_factory.Agency(**kwargs)
if not agency.agency_id:
agency.agency_id = util.FindUniqueId(self._agencies)
self._default_agency = agency
self.SetDefaultAgency(agency, validate=False) # Blank agency won't validate
return agency | python | def NewDefaultAgency(self, **kwargs):
"""Create a new Agency object and make it the default agency for this Schedule"""
agency = self._gtfs_factory.Agency(**kwargs)
if not agency.agency_id:
agency.agency_id = util.FindUniqueId(self._agencies)
self._default_agency = agency
self.SetDefaultAgency(agency, validate=False) # Blank agency won't validate
return agency | [
"def",
"NewDefaultAgency",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"agency",
"=",
"self",
".",
"_gtfs_factory",
".",
"Agency",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"agency",
".",
"agency_id",
":",
"agency",
".",
"agency_id",
"=",
"util",
... | Create a new Agency object and make it the default agency for this Schedule | [
"Create",
"a",
"new",
"Agency",
"object",
"and",
"make",
"it",
"the",
"default",
"agency",
"for",
"this",
"Schedule"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L197-L204 |
225,031 | google/transitfeed | transitfeed/schedule.py | Schedule.SetDefaultAgency | def SetDefaultAgency(self, agency, validate=True):
"""Make agency the default and add it to the schedule if not already added"""
assert isinstance(agency, self._gtfs_factory.Agency)
self._default_agency = agency
if agency.agency_id not in self._agencies:
self.AddAgencyObject(agency, validate=validate) | python | def SetDefaultAgency(self, agency, validate=True):
"""Make agency the default and add it to the schedule if not already added"""
assert isinstance(agency, self._gtfs_factory.Agency)
self._default_agency = agency
if agency.agency_id not in self._agencies:
self.AddAgencyObject(agency, validate=validate) | [
"def",
"SetDefaultAgency",
"(",
"self",
",",
"agency",
",",
"validate",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"agency",
",",
"self",
".",
"_gtfs_factory",
".",
"Agency",
")",
"self",
".",
"_default_agency",
"=",
"agency",
"if",
"agency",
".",... | Make agency the default and add it to the schedule if not already added | [
"Make",
"agency",
"the",
"default",
"and",
"add",
"it",
"to",
"the",
"schedule",
"if",
"not",
"already",
"added"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L206-L211 |
225,032 | google/transitfeed | transitfeed/schedule.py | Schedule.GetDefaultServicePeriod | def GetDefaultServicePeriod(self):
"""Return the default ServicePeriod. If no default ServicePeriod has been
set select the default depending on how many ServicePeriod objects are in
the Schedule. If there are 0 make a new ServicePeriod the default, if there
is 1 it becomes the default, if there is more than 1 then return None.
"""
if not self._default_service_period:
if len(self.service_periods) == 0:
self.NewDefaultServicePeriod()
elif len(self.service_periods) == 1:
self._default_service_period = self.service_periods.values()[0]
return self._default_service_period | python | def GetDefaultServicePeriod(self):
"""Return the default ServicePeriod. If no default ServicePeriod has been
set select the default depending on how many ServicePeriod objects are in
the Schedule. If there are 0 make a new ServicePeriod the default, if there
is 1 it becomes the default, if there is more than 1 then return None.
"""
if not self._default_service_period:
if len(self.service_periods) == 0:
self.NewDefaultServicePeriod()
elif len(self.service_periods) == 1:
self._default_service_period = self.service_periods.values()[0]
return self._default_service_period | [
"def",
"GetDefaultServicePeriod",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_default_service_period",
":",
"if",
"len",
"(",
"self",
".",
"service_periods",
")",
"==",
"0",
":",
"self",
".",
"NewDefaultServicePeriod",
"(",
")",
"elif",
"len",
"(",
... | Return the default ServicePeriod. If no default ServicePeriod has been
set select the default depending on how many ServicePeriod objects are in
the Schedule. If there are 0 make a new ServicePeriod the default, if there
is 1 it becomes the default, if there is more than 1 then return None. | [
"Return",
"the",
"default",
"ServicePeriod",
".",
"If",
"no",
"default",
"ServicePeriod",
"has",
"been",
"set",
"select",
"the",
"default",
"depending",
"on",
"how",
"many",
"ServicePeriod",
"objects",
"are",
"in",
"the",
"Schedule",
".",
"If",
"there",
"are",... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L221-L232 |
225,033 | google/transitfeed | transitfeed/schedule.py | Schedule.NewDefaultServicePeriod | def NewDefaultServicePeriod(self):
"""Create a new ServicePeriod object, make it the default service period and
return it. The default service period is used when you create a trip without
providing an explict service period. """
service_period = self._gtfs_factory.ServicePeriod()
service_period.service_id = util.FindUniqueId(self.service_periods)
# blank service won't validate in AddServicePeriodObject
self.SetDefaultServicePeriod(service_period, validate=False)
return service_period | python | def NewDefaultServicePeriod(self):
"""Create a new ServicePeriod object, make it the default service period and
return it. The default service period is used when you create a trip without
providing an explict service period. """
service_period = self._gtfs_factory.ServicePeriod()
service_period.service_id = util.FindUniqueId(self.service_periods)
# blank service won't validate in AddServicePeriodObject
self.SetDefaultServicePeriod(service_period, validate=False)
return service_period | [
"def",
"NewDefaultServicePeriod",
"(",
"self",
")",
":",
"service_period",
"=",
"self",
".",
"_gtfs_factory",
".",
"ServicePeriod",
"(",
")",
"service_period",
".",
"service_id",
"=",
"util",
".",
"FindUniqueId",
"(",
"self",
".",
"service_periods",
")",
"# blan... | Create a new ServicePeriod object, make it the default service period and
return it. The default service period is used when you create a trip without
providing an explict service period. | [
"Create",
"a",
"new",
"ServicePeriod",
"object",
"make",
"it",
"the",
"default",
"service",
"period",
"and",
"return",
"it",
".",
"The",
"default",
"service",
"period",
"is",
"used",
"when",
"you",
"create",
"a",
"trip",
"without",
"providing",
"an",
"explic... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L234-L242 |
225,034 | google/transitfeed | transitfeed/schedule.py | Schedule.AddStop | def AddStop(self, lat, lng, name, stop_id=None):
"""Add a stop to this schedule.
Args:
lat: Latitude of the stop as a float or string
lng: Longitude of the stop as a float or string
name: Name of the stop, which will appear in the feed
stop_id: stop_id of the stop or None, in which case a unique id is picked
Returns:
A new Stop object
"""
if stop_id is None:
stop_id = util.FindUniqueId(self.stops)
stop = self._gtfs_factory.Stop(stop_id=stop_id, lat=lat, lng=lng, name=name)
self.AddStopObject(stop)
return stop | python | def AddStop(self, lat, lng, name, stop_id=None):
"""Add a stop to this schedule.
Args:
lat: Latitude of the stop as a float or string
lng: Longitude of the stop as a float or string
name: Name of the stop, which will appear in the feed
stop_id: stop_id of the stop or None, in which case a unique id is picked
Returns:
A new Stop object
"""
if stop_id is None:
stop_id = util.FindUniqueId(self.stops)
stop = self._gtfs_factory.Stop(stop_id=stop_id, lat=lat, lng=lng, name=name)
self.AddStopObject(stop)
return stop | [
"def",
"AddStop",
"(",
"self",
",",
"lat",
",",
"lng",
",",
"name",
",",
"stop_id",
"=",
"None",
")",
":",
"if",
"stop_id",
"is",
"None",
":",
"stop_id",
"=",
"util",
".",
"FindUniqueId",
"(",
"self",
".",
"stops",
")",
"stop",
"=",
"self",
".",
... | Add a stop to this schedule.
Args:
lat: Latitude of the stop as a float or string
lng: Longitude of the stop as a float or string
name: Name of the stop, which will appear in the feed
stop_id: stop_id of the stop or None, in which case a unique id is picked
Returns:
A new Stop object | [
"Add",
"a",
"stop",
"to",
"this",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L340-L356 |
225,035 | google/transitfeed | transitfeed/schedule.py | Schedule.AddStopObject | def AddStopObject(self, stop, problem_reporter=None):
"""Add Stop object to this schedule if stop_id is non-blank."""
assert stop._schedule is None
if not problem_reporter:
problem_reporter = self.problem_reporter
if not stop.stop_id:
return
if stop.stop_id in self.stops:
problem_reporter.DuplicateID('stop_id', stop.stop_id)
return
stop._schedule = weakref.proxy(self)
self.AddTableColumns('stops', stop._ColumnNames())
self.stops[stop.stop_id] = stop
if hasattr(stop, 'zone_id') and stop.zone_id:
self.fare_zones[stop.zone_id] = True | python | def AddStopObject(self, stop, problem_reporter=None):
"""Add Stop object to this schedule if stop_id is non-blank."""
assert stop._schedule is None
if not problem_reporter:
problem_reporter = self.problem_reporter
if not stop.stop_id:
return
if stop.stop_id in self.stops:
problem_reporter.DuplicateID('stop_id', stop.stop_id)
return
stop._schedule = weakref.proxy(self)
self.AddTableColumns('stops', stop._ColumnNames())
self.stops[stop.stop_id] = stop
if hasattr(stop, 'zone_id') and stop.zone_id:
self.fare_zones[stop.zone_id] = True | [
"def",
"AddStopObject",
"(",
"self",
",",
"stop",
",",
"problem_reporter",
"=",
"None",
")",
":",
"assert",
"stop",
".",
"_schedule",
"is",
"None",
"if",
"not",
"problem_reporter",
":",
"problem_reporter",
"=",
"self",
".",
"problem_reporter",
"if",
"not",
"... | Add Stop object to this schedule if stop_id is non-blank. | [
"Add",
"Stop",
"object",
"to",
"this",
"schedule",
"if",
"stop_id",
"is",
"non",
"-",
"blank",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L358-L375 |
225,036 | google/transitfeed | transitfeed/schedule.py | Schedule.AddRoute | def AddRoute(self, short_name, long_name, route_type, route_id=None):
"""Add a route to this schedule.
Args:
short_name: Short name of the route, such as "71L"
long_name: Full name of the route, such as "NW 21st Ave/St Helens Rd"
route_type: A type such as "Tram", "Subway" or "Bus"
route_id: id of the route or None, in which case a unique id is picked
Returns:
A new Route object
"""
if route_id is None:
route_id = util.FindUniqueId(self.routes)
route = self._gtfs_factory.Route(short_name=short_name, long_name=long_name,
route_type=route_type, route_id=route_id)
route.agency_id = self.GetDefaultAgency().agency_id
self.AddRouteObject(route)
return route | python | def AddRoute(self, short_name, long_name, route_type, route_id=None):
"""Add a route to this schedule.
Args:
short_name: Short name of the route, such as "71L"
long_name: Full name of the route, such as "NW 21st Ave/St Helens Rd"
route_type: A type such as "Tram", "Subway" or "Bus"
route_id: id of the route or None, in which case a unique id is picked
Returns:
A new Route object
"""
if route_id is None:
route_id = util.FindUniqueId(self.routes)
route = self._gtfs_factory.Route(short_name=short_name, long_name=long_name,
route_type=route_type, route_id=route_id)
route.agency_id = self.GetDefaultAgency().agency_id
self.AddRouteObject(route)
return route | [
"def",
"AddRoute",
"(",
"self",
",",
"short_name",
",",
"long_name",
",",
"route_type",
",",
"route_id",
"=",
"None",
")",
":",
"if",
"route_id",
"is",
"None",
":",
"route_id",
"=",
"util",
".",
"FindUniqueId",
"(",
"self",
".",
"routes",
")",
"route",
... | Add a route to this schedule.
Args:
short_name: Short name of the route, such as "71L"
long_name: Full name of the route, such as "NW 21st Ave/St Helens Rd"
route_type: A type such as "Tram", "Subway" or "Bus"
route_id: id of the route or None, in which case a unique id is picked
Returns:
A new Route object | [
"Add",
"a",
"route",
"to",
"this",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L380-L397 |
225,037 | google/transitfeed | transitfeed/schedule.py | Schedule.AddFareObject | def AddFareObject(self, fare, problem_reporter=None):
"""Deprecated. Please use AddFareAttributeObject."""
warnings.warn("No longer supported. The Fare class was renamed to "
"FareAttribute, and all related functions were renamed "
"accordingly.", DeprecationWarning)
self.AddFareAttributeObject(fare, problem_reporter) | python | def AddFareObject(self, fare, problem_reporter=None):
"""Deprecated. Please use AddFareAttributeObject."""
warnings.warn("No longer supported. The Fare class was renamed to "
"FareAttribute, and all related functions were renamed "
"accordingly.", DeprecationWarning)
self.AddFareAttributeObject(fare, problem_reporter) | [
"def",
"AddFareObject",
"(",
"self",
",",
"fare",
",",
"problem_reporter",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"No longer supported. The Fare class was renamed to \"",
"\"FareAttribute, and all related functions were renamed \"",
"\"accordingly.\"",
",",
"D... | Deprecated. Please use AddFareAttributeObject. | [
"Deprecated",
".",
"Please",
"use",
"AddFareAttributeObject",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L475-L480 |
225,038 | google/transitfeed | transitfeed/schedule.py | Schedule.GetNearestStops | def GetNearestStops(self, lat, lon, n=1):
"""Return the n nearest stops to lat,lon"""
dist_stop_list = []
for s in self.stops.values():
# TODO: Use util.ApproximateDistanceBetweenStops?
dist = (s.stop_lat - lat)**2 + (s.stop_lon - lon)**2
if len(dist_stop_list) < n:
bisect.insort(dist_stop_list, (dist, s))
elif dist < dist_stop_list[-1][0]:
bisect.insort(dist_stop_list, (dist, s))
dist_stop_list.pop() # Remove stop with greatest distance
return [stop for dist, stop in dist_stop_list] | python | def GetNearestStops(self, lat, lon, n=1):
"""Return the n nearest stops to lat,lon"""
dist_stop_list = []
for s in self.stops.values():
# TODO: Use util.ApproximateDistanceBetweenStops?
dist = (s.stop_lat - lat)**2 + (s.stop_lon - lon)**2
if len(dist_stop_list) < n:
bisect.insort(dist_stop_list, (dist, s))
elif dist < dist_stop_list[-1][0]:
bisect.insort(dist_stop_list, (dist, s))
dist_stop_list.pop() # Remove stop with greatest distance
return [stop for dist, stop in dist_stop_list] | [
"def",
"GetNearestStops",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"n",
"=",
"1",
")",
":",
"dist_stop_list",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"stops",
".",
"values",
"(",
")",
":",
"# TODO: Use util.ApproximateDistanceBetweenStops?",
"dist",... | Return the n nearest stops to lat,lon | [
"Return",
"the",
"n",
"nearest",
"stops",
"to",
"lat",
"lon"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L584-L595 |
225,039 | google/transitfeed | transitfeed/schedule.py | Schedule.GetStopsInBoundingBox | def GetStopsInBoundingBox(self, north, east, south, west, n):
"""Return a sample of up to n stops in a bounding box"""
stop_list = []
for s in self.stops.values():
if (s.stop_lat <= north and s.stop_lat >= south and
s.stop_lon <= east and s.stop_lon >= west):
stop_list.append(s)
if len(stop_list) == n:
break
return stop_list | python | def GetStopsInBoundingBox(self, north, east, south, west, n):
"""Return a sample of up to n stops in a bounding box"""
stop_list = []
for s in self.stops.values():
if (s.stop_lat <= north and s.stop_lat >= south and
s.stop_lon <= east and s.stop_lon >= west):
stop_list.append(s)
if len(stop_list) == n:
break
return stop_list | [
"def",
"GetStopsInBoundingBox",
"(",
"self",
",",
"north",
",",
"east",
",",
"south",
",",
"west",
",",
"n",
")",
":",
"stop_list",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"stops",
".",
"values",
"(",
")",
":",
"if",
"(",
"s",
".",
"stop_la... | Return a sample of up to n stops in a bounding box | [
"Return",
"a",
"sample",
"of",
"up",
"to",
"n",
"stops",
"in",
"a",
"bounding",
"box"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L597-L606 |
225,040 | google/transitfeed | transitfeed/schedule.py | Schedule.ValidateFeedStartAndExpirationDates | def ValidateFeedStartAndExpirationDates(self, problems, first_date, last_date,
first_date_origin, last_date_origin,
today):
"""Validate the start and expiration dates of the feed.
Issue a warning if it only starts in the future, or if
it expires within 60 days.
Args:
problems: The problem reporter object
first_date: A date object representing the first day the feed is active
last_date: A date object representing the last day the feed is active
today: A date object representing the date the validation is being run on
Returns:
None
"""
warning_cutoff = today + datetime.timedelta(days=60)
if last_date < warning_cutoff:
problems.ExpirationDate(time.mktime(last_date.timetuple()),
last_date_origin)
if first_date > today:
problems.FutureService(time.mktime(first_date.timetuple()),
first_date_origin) | python | def ValidateFeedStartAndExpirationDates(self, problems, first_date, last_date,
first_date_origin, last_date_origin,
today):
"""Validate the start and expiration dates of the feed.
Issue a warning if it only starts in the future, or if
it expires within 60 days.
Args:
problems: The problem reporter object
first_date: A date object representing the first day the feed is active
last_date: A date object representing the last day the feed is active
today: A date object representing the date the validation is being run on
Returns:
None
"""
warning_cutoff = today + datetime.timedelta(days=60)
if last_date < warning_cutoff:
problems.ExpirationDate(time.mktime(last_date.timetuple()),
last_date_origin)
if first_date > today:
problems.FutureService(time.mktime(first_date.timetuple()),
first_date_origin) | [
"def",
"ValidateFeedStartAndExpirationDates",
"(",
"self",
",",
"problems",
",",
"first_date",
",",
"last_date",
",",
"first_date_origin",
",",
"last_date_origin",
",",
"today",
")",
":",
"warning_cutoff",
"=",
"today",
"+",
"datetime",
".",
"timedelta",
"(",
"day... | Validate the start and expiration dates of the feed.
Issue a warning if it only starts in the future, or if
it expires within 60 days.
Args:
problems: The problem reporter object
first_date: A date object representing the first day the feed is active
last_date: A date object representing the last day the feed is active
today: A date object representing the date the validation is being run on
Returns:
None | [
"Validate",
"the",
"start",
"and",
"expiration",
"dates",
"of",
"the",
"feed",
".",
"Issue",
"a",
"warning",
"if",
"it",
"only",
"starts",
"in",
"the",
"future",
"or",
"if",
"it",
"expires",
"within",
"60",
"days",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L829-L852 |
225,041 | google/transitfeed | transitfeed/schedule.py | Schedule.ValidateServiceGaps | def ValidateServiceGaps(self,
problems,
validation_start_date,
validation_end_date,
service_gap_interval):
"""Validate consecutive dates without service in the feed.
Issue a warning if it finds service gaps of at least
"service_gap_interval" consecutive days in the date range
[validation_start_date, last_service_date)
Args:
problems: The problem reporter object
validation_start_date: A date object representing the date from which the
validation should take place
validation_end_date: A date object representing the first day the feed is
active
service_gap_interval: An integer indicating how many consecutive days the
service gaps need to have for a warning to be issued
Returns:
None
"""
if service_gap_interval is None:
return
departures = self.GenerateDateTripsDeparturesList(validation_start_date,
validation_end_date)
# The first day without service of the _current_ gap
first_day_without_service = validation_start_date
# The last day without service of the _current_ gap
last_day_without_service = validation_start_date
consecutive_days_without_service = 0
for day_date, day_trips, _ in departures:
if day_trips == 0:
if consecutive_days_without_service == 0:
first_day_without_service = day_date
consecutive_days_without_service += 1
last_day_without_service = day_date
else:
if consecutive_days_without_service >= service_gap_interval:
problems.TooManyDaysWithoutService(first_day_without_service,
last_day_without_service,
consecutive_days_without_service)
consecutive_days_without_service = 0
# We have to check if there is a gap at the end of the specified date range
if consecutive_days_without_service >= service_gap_interval:
problems.TooManyDaysWithoutService(first_day_without_service,
last_day_without_service,
consecutive_days_without_service) | python | def ValidateServiceGaps(self,
problems,
validation_start_date,
validation_end_date,
service_gap_interval):
"""Validate consecutive dates without service in the feed.
Issue a warning if it finds service gaps of at least
"service_gap_interval" consecutive days in the date range
[validation_start_date, last_service_date)
Args:
problems: The problem reporter object
validation_start_date: A date object representing the date from which the
validation should take place
validation_end_date: A date object representing the first day the feed is
active
service_gap_interval: An integer indicating how many consecutive days the
service gaps need to have for a warning to be issued
Returns:
None
"""
if service_gap_interval is None:
return
departures = self.GenerateDateTripsDeparturesList(validation_start_date,
validation_end_date)
# The first day without service of the _current_ gap
first_day_without_service = validation_start_date
# The last day without service of the _current_ gap
last_day_without_service = validation_start_date
consecutive_days_without_service = 0
for day_date, day_trips, _ in departures:
if day_trips == 0:
if consecutive_days_without_service == 0:
first_day_without_service = day_date
consecutive_days_without_service += 1
last_day_without_service = day_date
else:
if consecutive_days_without_service >= service_gap_interval:
problems.TooManyDaysWithoutService(first_day_without_service,
last_day_without_service,
consecutive_days_without_service)
consecutive_days_without_service = 0
# We have to check if there is a gap at the end of the specified date range
if consecutive_days_without_service >= service_gap_interval:
problems.TooManyDaysWithoutService(first_day_without_service,
last_day_without_service,
consecutive_days_without_service) | [
"def",
"ValidateServiceGaps",
"(",
"self",
",",
"problems",
",",
"validation_start_date",
",",
"validation_end_date",
",",
"service_gap_interval",
")",
":",
"if",
"service_gap_interval",
"is",
"None",
":",
"return",
"departures",
"=",
"self",
".",
"GenerateDateTripsDe... | Validate consecutive dates without service in the feed.
Issue a warning if it finds service gaps of at least
"service_gap_interval" consecutive days in the date range
[validation_start_date, last_service_date)
Args:
problems: The problem reporter object
validation_start_date: A date object representing the date from which the
validation should take place
validation_end_date: A date object representing the first day the feed is
active
service_gap_interval: An integer indicating how many consecutive days the
service gaps need to have for a warning to be issued
Returns:
None | [
"Validate",
"consecutive",
"dates",
"without",
"service",
"in",
"the",
"feed",
".",
"Issue",
"a",
"warning",
"if",
"it",
"finds",
"service",
"gaps",
"of",
"at",
"least",
"service_gap_interval",
"consecutive",
"days",
"in",
"the",
"date",
"range",
"[",
"validat... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L854-L907 |
225,042 | google/transitfeed | transitfeed/schedule.py | Schedule.ValidateStopTimesForTrip | def ValidateStopTimesForTrip(self, problems, trip, stop_times):
"""Checks for the stop times of a trip.
Ensure that a trip does not have too many consecutive stop times with the
same departure/arrival time."""
prev_departure_secs = -1
consecutive_stop_times_with_potentially_same_time = 0
consecutive_stop_times_with_fully_specified_same_time = 0
def CheckSameTimeCount():
# More than five consecutive stop times with the same time? Seems not
# very likely (a stop every 10 seconds?). In practice, this warning
# affects about 0.5% of current GTFS trips.
if (prev_departure_secs != -1 and
consecutive_stop_times_with_fully_specified_same_time > 5):
problems.TooManyConsecutiveStopTimesWithSameTime(trip.trip_id,
consecutive_stop_times_with_fully_specified_same_time,
prev_departure_secs)
for index, st in enumerate(stop_times):
if st.arrival_secs is None or st.departure_secs is None:
consecutive_stop_times_with_potentially_same_time += 1
continue
if (prev_departure_secs == st.arrival_secs and
st.arrival_secs == st.departure_secs):
consecutive_stop_times_with_potentially_same_time += 1
consecutive_stop_times_with_fully_specified_same_time = (
consecutive_stop_times_with_potentially_same_time)
else:
CheckSameTimeCount()
consecutive_stop_times_with_potentially_same_time = 1
consecutive_stop_times_with_fully_specified_same_time = 1
prev_departure_secs = st.departure_secs
# Make sure to check one last time at the end
CheckSameTimeCount() | python | def ValidateStopTimesForTrip(self, problems, trip, stop_times):
"""Checks for the stop times of a trip.
Ensure that a trip does not have too many consecutive stop times with the
same departure/arrival time."""
prev_departure_secs = -1
consecutive_stop_times_with_potentially_same_time = 0
consecutive_stop_times_with_fully_specified_same_time = 0
def CheckSameTimeCount():
# More than five consecutive stop times with the same time? Seems not
# very likely (a stop every 10 seconds?). In practice, this warning
# affects about 0.5% of current GTFS trips.
if (prev_departure_secs != -1 and
consecutive_stop_times_with_fully_specified_same_time > 5):
problems.TooManyConsecutiveStopTimesWithSameTime(trip.trip_id,
consecutive_stop_times_with_fully_specified_same_time,
prev_departure_secs)
for index, st in enumerate(stop_times):
if st.arrival_secs is None or st.departure_secs is None:
consecutive_stop_times_with_potentially_same_time += 1
continue
if (prev_departure_secs == st.arrival_secs and
st.arrival_secs == st.departure_secs):
consecutive_stop_times_with_potentially_same_time += 1
consecutive_stop_times_with_fully_specified_same_time = (
consecutive_stop_times_with_potentially_same_time)
else:
CheckSameTimeCount()
consecutive_stop_times_with_potentially_same_time = 1
consecutive_stop_times_with_fully_specified_same_time = 1
prev_departure_secs = st.departure_secs
# Make sure to check one last time at the end
CheckSameTimeCount() | [
"def",
"ValidateStopTimesForTrip",
"(",
"self",
",",
"problems",
",",
"trip",
",",
"stop_times",
")",
":",
"prev_departure_secs",
"=",
"-",
"1",
"consecutive_stop_times_with_potentially_same_time",
"=",
"0",
"consecutive_stop_times_with_fully_specified_same_time",
"=",
"0",... | Checks for the stop times of a trip.
Ensure that a trip does not have too many consecutive stop times with the
same departure/arrival time. | [
"Checks",
"for",
"the",
"stop",
"times",
"of",
"a",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L1169-L1203 |
225,043 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph.Draw | def Draw(self, stoplist=None, triplist=None, height=520):
"""Main interface for drawing the marey graph.
If called without arguments, the data generated in the previous call
will be used. New decorators can be added between calls.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
Returns:
# A string that contain a svg/xml web-page with a marey graph.
" <svg width="1440" height="520" version="1.1" ... "
"""
output = str()
if not triplist:
triplist = []
if not stoplist:
stoplist = []
if not self._cache or triplist or stoplist:
self._gheight = height
self._tlist=triplist
self._slist=stoplist
self._decorators = []
self._stations = self._BuildStations(stoplist)
self._cache = "%s %s %s %s" % (self._DrawBox(),
self._DrawHours(),
self._DrawStations(),
self._DrawTrips(triplist))
output = "%s %s %s %s" % (self._DrawHeader(),
self._cache,
self._DrawDecorators(),
self._DrawFooter())
return output | python | def Draw(self, stoplist=None, triplist=None, height=520):
"""Main interface for drawing the marey graph.
If called without arguments, the data generated in the previous call
will be used. New decorators can be added between calls.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
Returns:
# A string that contain a svg/xml web-page with a marey graph.
" <svg width="1440" height="520" version="1.1" ... "
"""
output = str()
if not triplist:
triplist = []
if not stoplist:
stoplist = []
if not self._cache or triplist or stoplist:
self._gheight = height
self._tlist=triplist
self._slist=stoplist
self._decorators = []
self._stations = self._BuildStations(stoplist)
self._cache = "%s %s %s %s" % (self._DrawBox(),
self._DrawHours(),
self._DrawStations(),
self._DrawTrips(triplist))
output = "%s %s %s %s" % (self._DrawHeader(),
self._cache,
self._DrawDecorators(),
self._DrawFooter())
return output | [
"def",
"Draw",
"(",
"self",
",",
"stoplist",
"=",
"None",
",",
"triplist",
"=",
"None",
",",
"height",
"=",
"520",
")",
":",
"output",
"=",
"str",
"(",
")",
"if",
"not",
"triplist",
":",
"triplist",
"=",
"[",
"]",
"if",
"not",
"stoplist",
":",
"s... | Main interface for drawing the marey graph.
If called without arguments, the data generated in the previous call
will be used. New decorators can be added between calls.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
Returns:
# A string that contain a svg/xml web-page with a marey graph.
" <svg width="1440" height="520" version="1.1" ... " | [
"Main",
"interface",
"for",
"drawing",
"the",
"marey",
"graph",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L73-L112 |
225,044 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph._BuildStations | def _BuildStations(self, stoplist):
"""Dispatches the best algorithm for calculating station line position.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
Returns:
# One integer y-coordinate for each station normalized between
# 0 and X, where X is the height of the graph in pixels
[0, 33, 140, ... , X]
"""
stations = []
dists = self._EuclidianDistances(stoplist)
stations = self._CalculateYLines(dists)
return stations | python | def _BuildStations(self, stoplist):
"""Dispatches the best algorithm for calculating station line position.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
Returns:
# One integer y-coordinate for each station normalized between
# 0 and X, where X is the height of the graph in pixels
[0, 33, 140, ... , X]
"""
stations = []
dists = self._EuclidianDistances(stoplist)
stations = self._CalculateYLines(dists)
return stations | [
"def",
"_BuildStations",
"(",
"self",
",",
"stoplist",
")",
":",
"stations",
"=",
"[",
"]",
"dists",
"=",
"self",
".",
"_EuclidianDistances",
"(",
"stoplist",
")",
"stations",
"=",
"self",
".",
"_CalculateYLines",
"(",
"dists",
")",
"return",
"stations"
] | Dispatches the best algorithm for calculating station line position.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
Returns:
# One integer y-coordinate for each station normalized between
# 0 and X, where X is the height of the graph in pixels
[0, 33, 140, ... , X] | [
"Dispatches",
"the",
"best",
"algorithm",
"for",
"calculating",
"station",
"line",
"position",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L196-L213 |
225,045 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph._EuclidianDistances | def _EuclidianDistances(self,slist):
"""Calculate euclidian distances between stops.
Uses the stoplists long/lats to approximate distances
between stations and build a list with y-coordinates for the
horizontal lines in the graph.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
Returns:
# One integer for each pair of stations
# indicating the approximate distance
[0,33,140, ... ,X]
"""
e_dists2 = [transitfeed.ApproximateDistanceBetweenStops(stop, tail) for
(stop,tail) in itertools.izip(slist, slist[1:])]
return e_dists2 | python | def _EuclidianDistances(self,slist):
"""Calculate euclidian distances between stops.
Uses the stoplists long/lats to approximate distances
between stations and build a list with y-coordinates for the
horizontal lines in the graph.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
Returns:
# One integer for each pair of stations
# indicating the approximate distance
[0,33,140, ... ,X]
"""
e_dists2 = [transitfeed.ApproximateDistanceBetweenStops(stop, tail) for
(stop,tail) in itertools.izip(slist, slist[1:])]
return e_dists2 | [
"def",
"_EuclidianDistances",
"(",
"self",
",",
"slist",
")",
":",
"e_dists2",
"=",
"[",
"transitfeed",
".",
"ApproximateDistanceBetweenStops",
"(",
"stop",
",",
"tail",
")",
"for",
"(",
"stop",
",",
"tail",
")",
"in",
"itertools",
".",
"izip",
"(",
"slist... | Calculate euclidian distances between stops.
Uses the stoplists long/lats to approximate distances
between stations and build a list with y-coordinates for the
horizontal lines in the graph.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
Returns:
# One integer for each pair of stations
# indicating the approximate distance
[0,33,140, ... ,X] | [
"Calculate",
"euclidian",
"distances",
"between",
"stops",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L215-L234 |
225,046 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph._CalculateYLines | def _CalculateYLines(self, dists):
"""Builds a list with y-coordinates for the horizontal lines in the graph.
Args:
# One integer for each pair of stations
# indicating the approximate distance
dists: [0,33,140, ... ,X]
Returns:
# One integer y-coordinate for each station normalized between
# 0 and X, where X is the height of the graph in pixels
[0, 33, 140, ... , X]
"""
tot_dist = sum(dists)
if tot_dist > 0:
pixel_dist = [float(d * (self._gheight-20))/tot_dist for d in dists]
pixel_grid = [0]+[int(pd + sum(pixel_dist[0:i])) for i,pd in
enumerate(pixel_dist)]
else:
pixel_grid = []
return pixel_grid | python | def _CalculateYLines(self, dists):
"""Builds a list with y-coordinates for the horizontal lines in the graph.
Args:
# One integer for each pair of stations
# indicating the approximate distance
dists: [0,33,140, ... ,X]
Returns:
# One integer y-coordinate for each station normalized between
# 0 and X, where X is the height of the graph in pixels
[0, 33, 140, ... , X]
"""
tot_dist = sum(dists)
if tot_dist > 0:
pixel_dist = [float(d * (self._gheight-20))/tot_dist for d in dists]
pixel_grid = [0]+[int(pd + sum(pixel_dist[0:i])) for i,pd in
enumerate(pixel_dist)]
else:
pixel_grid = []
return pixel_grid | [
"def",
"_CalculateYLines",
"(",
"self",
",",
"dists",
")",
":",
"tot_dist",
"=",
"sum",
"(",
"dists",
")",
"if",
"tot_dist",
">",
"0",
":",
"pixel_dist",
"=",
"[",
"float",
"(",
"d",
"*",
"(",
"self",
".",
"_gheight",
"-",
"20",
")",
")",
"/",
"t... | Builds a list with y-coordinates for the horizontal lines in the graph.
Args:
# One integer for each pair of stations
# indicating the approximate distance
dists: [0,33,140, ... ,X]
Returns:
# One integer y-coordinate for each station normalized between
# 0 and X, where X is the height of the graph in pixels
[0, 33, 140, ... , X] | [
"Builds",
"a",
"list",
"with",
"y",
"-",
"coordinates",
"for",
"the",
"horizontal",
"lines",
"in",
"the",
"graph",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L236-L257 |
225,047 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph._TravelTimes | def _TravelTimes(self,triplist,index=0):
""" Calculate distances and plot stops.
Uses a timetable to approximate distances
between stations
Args:
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
# (Optional) Index of Triplist prefered for timetable Calculation
index: 3
Returns:
# One integer for each pair of stations
# indicating the approximate distance
[0,33,140, ... ,X]
"""
def DistanceInTravelTime(dep_secs, arr_secs):
t_dist = arr_secs-dep_secs
if t_dist<0:
t_dist = self._DUMMY_SEPARATOR # min separation
return t_dist
if not triplist:
return []
if 0 < index < len(triplist):
trip = triplist[index]
else:
trip = triplist[0]
t_dists2 = [DistanceInTravelTime(stop[3],tail[2]) for (stop,tail)
in itertools.izip(trip.GetTimeStops(),trip.GetTimeStops()[1:])]
return t_dists2 | python | def _TravelTimes(self,triplist,index=0):
""" Calculate distances and plot stops.
Uses a timetable to approximate distances
between stations
Args:
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
# (Optional) Index of Triplist prefered for timetable Calculation
index: 3
Returns:
# One integer for each pair of stations
# indicating the approximate distance
[0,33,140, ... ,X]
"""
def DistanceInTravelTime(dep_secs, arr_secs):
t_dist = arr_secs-dep_secs
if t_dist<0:
t_dist = self._DUMMY_SEPARATOR # min separation
return t_dist
if not triplist:
return []
if 0 < index < len(triplist):
trip = triplist[index]
else:
trip = triplist[0]
t_dists2 = [DistanceInTravelTime(stop[3],tail[2]) for (stop,tail)
in itertools.izip(trip.GetTimeStops(),trip.GetTimeStops()[1:])]
return t_dists2 | [
"def",
"_TravelTimes",
"(",
"self",
",",
"triplist",
",",
"index",
"=",
"0",
")",
":",
"def",
"DistanceInTravelTime",
"(",
"dep_secs",
",",
"arr_secs",
")",
":",
"t_dist",
"=",
"arr_secs",
"-",
"dep_secs",
"if",
"t_dist",
"<",
"0",
":",
"t_dist",
"=",
... | Calculate distances and plot stops.
Uses a timetable to approximate distances
between stations
Args:
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
# (Optional) Index of Triplist prefered for timetable Calculation
index: 3
Returns:
# One integer for each pair of stations
# indicating the approximate distance
[0,33,140, ... ,X] | [
"Calculate",
"distances",
"and",
"plot",
"stops",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L259-L293 |
225,048 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph._DrawTrips | def _DrawTrips(self,triplist,colpar=""):
"""Generates svg polylines for each transit trip.
Args:
# Class Trip is defined in transitfeed.py
[Trip, Trip, ...]
Returns:
# A string containing a polyline tag for each trip
' <polyline class="T" stroke="#336633" points="433,0 ...'
"""
stations = []
if not self._stations and triplist:
self._stations = self._CalculateYLines(self._TravelTimes(triplist))
if not self._stations:
self._AddWarning("Failed to use traveltimes for graph")
self._stations = self._CalculateYLines(self._Uniform(triplist))
if not self._stations:
self._AddWarning("Failed to calculate station distances")
return
stations = self._stations
tmpstrs = []
servlist = []
for t in triplist:
if not colpar:
if t.service_id not in servlist:
servlist.append(t.service_id)
shade = int(servlist.index(t.service_id) * (200/len(servlist))+55)
color = "#00%s00" % hex(shade)[2:4]
else:
color=colpar
start_offsets = [0]
first_stop = t.GetTimeStops()[0]
for j,freq_offset in enumerate(start_offsets):
if j>0 and not colpar:
color="purple"
scriptcall = 'onmouseover="LineClick(\'%s\',\'Trip %s starting %s\')"' % (t.trip_id,
t.trip_id, transitfeed.FormatSecondsSinceMidnight(t.GetStartTime()))
tmpstrhead = '<polyline class="T" id="%s" stroke="%s" %s points="' % \
(str(t.trip_id),color, scriptcall)
tmpstrs.append(tmpstrhead)
for i, s in enumerate(t.GetTimeStops()):
arr_t = s[0]
dep_t = s[1]
if arr_t is None or dep_t is None:
continue
arr_x = int(arr_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset
dep_x = int(dep_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset
tmpstrs.append("%s,%s " % (int(arr_x+20), int(stations[i]+20)))
tmpstrs.append("%s,%s " % (int(dep_x+20), int(stations[i]+20)))
tmpstrs.append('" />')
return "".join(tmpstrs) | python | def _DrawTrips(self,triplist,colpar=""):
"""Generates svg polylines for each transit trip.
Args:
# Class Trip is defined in transitfeed.py
[Trip, Trip, ...]
Returns:
# A string containing a polyline tag for each trip
' <polyline class="T" stroke="#336633" points="433,0 ...'
"""
stations = []
if not self._stations and triplist:
self._stations = self._CalculateYLines(self._TravelTimes(triplist))
if not self._stations:
self._AddWarning("Failed to use traveltimes for graph")
self._stations = self._CalculateYLines(self._Uniform(triplist))
if not self._stations:
self._AddWarning("Failed to calculate station distances")
return
stations = self._stations
tmpstrs = []
servlist = []
for t in triplist:
if not colpar:
if t.service_id not in servlist:
servlist.append(t.service_id)
shade = int(servlist.index(t.service_id) * (200/len(servlist))+55)
color = "#00%s00" % hex(shade)[2:4]
else:
color=colpar
start_offsets = [0]
first_stop = t.GetTimeStops()[0]
for j,freq_offset in enumerate(start_offsets):
if j>0 and not colpar:
color="purple"
scriptcall = 'onmouseover="LineClick(\'%s\',\'Trip %s starting %s\')"' % (t.trip_id,
t.trip_id, transitfeed.FormatSecondsSinceMidnight(t.GetStartTime()))
tmpstrhead = '<polyline class="T" id="%s" stroke="%s" %s points="' % \
(str(t.trip_id),color, scriptcall)
tmpstrs.append(tmpstrhead)
for i, s in enumerate(t.GetTimeStops()):
arr_t = s[0]
dep_t = s[1]
if arr_t is None or dep_t is None:
continue
arr_x = int(arr_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset
dep_x = int(dep_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset
tmpstrs.append("%s,%s " % (int(arr_x+20), int(stations[i]+20)))
tmpstrs.append("%s,%s " % (int(dep_x+20), int(stations[i]+20)))
tmpstrs.append('" />')
return "".join(tmpstrs) | [
"def",
"_DrawTrips",
"(",
"self",
",",
"triplist",
",",
"colpar",
"=",
"\"\"",
")",
":",
"stations",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"_stations",
"and",
"triplist",
":",
"self",
".",
"_stations",
"=",
"self",
".",
"_CalculateYLines",
"(",
"sel... | Generates svg polylines for each transit trip.
Args:
# Class Trip is defined in transitfeed.py
[Trip, Trip, ...]
Returns:
# A string containing a polyline tag for each trip
' <polyline class="T" stroke="#336633" points="433,0 ...' | [
"Generates",
"svg",
"polylines",
"for",
"each",
"transit",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L298-L354 |
225,049 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph._Uniform | def _Uniform(self, triplist):
"""Fallback to assuming uniform distance between stations"""
# This should not be neseccary, but we are in fallback mode
longest = max([len(t.GetTimeStops()) for t in triplist])
return [100] * longest | python | def _Uniform(self, triplist):
"""Fallback to assuming uniform distance between stations"""
# This should not be neseccary, but we are in fallback mode
longest = max([len(t.GetTimeStops()) for t in triplist])
return [100] * longest | [
"def",
"_Uniform",
"(",
"self",
",",
"triplist",
")",
":",
"# This should not be neseccary, but we are in fallback mode",
"longest",
"=",
"max",
"(",
"[",
"len",
"(",
"t",
".",
"GetTimeStops",
"(",
")",
")",
"for",
"t",
"in",
"triplist",
"]",
")",
"return",
... | Fallback to assuming uniform distance between stations | [
"Fallback",
"to",
"assuming",
"uniform",
"distance",
"between",
"stations"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L356-L360 |
225,050 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph._DrawHours | def _DrawHours(self):
"""Generates svg to show a vertical hour and sub-hour grid
Returns:
# A string containing a polyline tag for each grid line
" <polyline class="FullHour" points="20,0 ..."
"""
tmpstrs = []
for i in range(0, self._gwidth, self._min_grid):
if i % self._hour_grid == 0:
tmpstrs.append('<polyline class="FullHour" points="%d,%d, %d,%d" />' \
% (i + .5 + 20, 20, i + .5 + 20, self._gheight))
tmpstrs.append('<text class="Label" x="%d" y="%d">%d</text>'
% (i + 20, 20,
(i / self._hour_grid + self._offset) % 24))
else:
tmpstrs.append('<polyline class="SubHour" points="%d,%d,%d,%d" />' \
% (i + .5 + 20, 20, i + .5 + 20, self._gheight))
return "".join(tmpstrs) | python | def _DrawHours(self):
"""Generates svg to show a vertical hour and sub-hour grid
Returns:
# A string containing a polyline tag for each grid line
" <polyline class="FullHour" points="20,0 ..."
"""
tmpstrs = []
for i in range(0, self._gwidth, self._min_grid):
if i % self._hour_grid == 0:
tmpstrs.append('<polyline class="FullHour" points="%d,%d, %d,%d" />' \
% (i + .5 + 20, 20, i + .5 + 20, self._gheight))
tmpstrs.append('<text class="Label" x="%d" y="%d">%d</text>'
% (i + 20, 20,
(i / self._hour_grid + self._offset) % 24))
else:
tmpstrs.append('<polyline class="SubHour" points="%d,%d,%d,%d" />' \
% (i + .5 + 20, 20, i + .5 + 20, self._gheight))
return "".join(tmpstrs) | [
"def",
"_DrawHours",
"(",
"self",
")",
":",
"tmpstrs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"_gwidth",
",",
"self",
".",
"_min_grid",
")",
":",
"if",
"i",
"%",
"self",
".",
"_hour_grid",
"==",
"0",
":",
"tmpstrs",... | Generates svg to show a vertical hour and sub-hour grid
Returns:
# A string containing a polyline tag for each grid line
" <polyline class="FullHour" points="20,0 ..." | [
"Generates",
"svg",
"to",
"show",
"a",
"vertical",
"hour",
"and",
"sub",
"-",
"hour",
"grid"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L380-L398 |
225,051 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph.AddStationDecoration | def AddStationDecoration(self, index, color="#f00"):
"""Flushes existing decorations and highlights the given station-line.
Args:
# Integer, index of stop to be highlighted.
index: 4
# An optional string with a html color code
color: "#fff"
"""
tmpstr = str()
num_stations = len(self._stations)
ind = int(index)
if self._stations:
if 0<ind<num_stations:
y = self._stations[ind]
tmpstr = '<polyline class="Dec" stroke="%s" points="%s,%s,%s,%s" />' \
% (color, 20, 20+y+.5, self._gwidth+20, 20+y+.5)
self._decorators.append(tmpstr) | python | def AddStationDecoration(self, index, color="#f00"):
"""Flushes existing decorations and highlights the given station-line.
Args:
# Integer, index of stop to be highlighted.
index: 4
# An optional string with a html color code
color: "#fff"
"""
tmpstr = str()
num_stations = len(self._stations)
ind = int(index)
if self._stations:
if 0<ind<num_stations:
y = self._stations[ind]
tmpstr = '<polyline class="Dec" stroke="%s" points="%s,%s,%s,%s" />' \
% (color, 20, 20+y+.5, self._gwidth+20, 20+y+.5)
self._decorators.append(tmpstr) | [
"def",
"AddStationDecoration",
"(",
"self",
",",
"index",
",",
"color",
"=",
"\"#f00\"",
")",
":",
"tmpstr",
"=",
"str",
"(",
")",
"num_stations",
"=",
"len",
"(",
"self",
".",
"_stations",
")",
"ind",
"=",
"int",
"(",
"index",
")",
"if",
"self",
"."... | Flushes existing decorations and highlights the given station-line.
Args:
# Integer, index of stop to be highlighted.
index: 4
# An optional string with a html color code
color: "#fff" | [
"Flushes",
"existing",
"decorations",
"and",
"highlights",
"the",
"given",
"station",
"-",
"line",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L400-L417 |
225,052 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph.AddTripDecoration | def AddTripDecoration(self, triplist, color="#f00"):
"""Flushes existing decorations and highlights the given trips.
Args:
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
# An optional string with a html color code
color: "#fff"
"""
tmpstr = self._DrawTrips(triplist,color)
self._decorators.append(tmpstr) | python | def AddTripDecoration(self, triplist, color="#f00"):
"""Flushes existing decorations and highlights the given trips.
Args:
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
# An optional string with a html color code
color: "#fff"
"""
tmpstr = self._DrawTrips(triplist,color)
self._decorators.append(tmpstr) | [
"def",
"AddTripDecoration",
"(",
"self",
",",
"triplist",
",",
"color",
"=",
"\"#f00\"",
")",
":",
"tmpstr",
"=",
"self",
".",
"_DrawTrips",
"(",
"triplist",
",",
"color",
")",
"self",
".",
"_decorators",
".",
"append",
"(",
"tmpstr",
")"
] | Flushes existing decorations and highlights the given trips.
Args:
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
# An optional string with a html color code
color: "#fff" | [
"Flushes",
"existing",
"decorations",
"and",
"highlights",
"the",
"given",
"trips",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L419-L429 |
225,053 | google/transitfeed | gtfsscheduleviewer/marey_graph.py | MareyGraph.ChangeScaleFactor | def ChangeScaleFactor(self, newfactor):
"""Changes the zoom of the graph manually.
1.0 is the original canvas size.
Args:
# float value between 0.0 and 5.0
newfactor: 0.7
"""
if float(newfactor) > 0 and float(newfactor) < self._MAX_ZOOM:
self._zoomfactor = newfactor | python | def ChangeScaleFactor(self, newfactor):
"""Changes the zoom of the graph manually.
1.0 is the original canvas size.
Args:
# float value between 0.0 and 5.0
newfactor: 0.7
"""
if float(newfactor) > 0 and float(newfactor) < self._MAX_ZOOM:
self._zoomfactor = newfactor | [
"def",
"ChangeScaleFactor",
"(",
"self",
",",
"newfactor",
")",
":",
"if",
"float",
"(",
"newfactor",
")",
">",
"0",
"and",
"float",
"(",
"newfactor",
")",
"<",
"self",
".",
"_MAX_ZOOM",
":",
"self",
".",
"_zoomfactor",
"=",
"newfactor"
] | Changes the zoom of the graph manually.
1.0 is the original canvas size.
Args:
# float value between 0.0 and 5.0
newfactor: 0.7 | [
"Changes",
"the",
"zoom",
"of",
"the",
"graph",
"manually",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L431-L441 |
225,054 | google/transitfeed | kmlwriter.py | KMLWriter._CreateFolder | def _CreateFolder(self, parent, name, visible=True, description=None):
"""Create a KML Folder element.
Args:
parent: The parent ElementTree.Element instance.
name: The folder name as a string.
visible: Whether the folder is initially visible or not.
description: A description string or None.
Returns:
The folder ElementTree.Element instance.
"""
folder = ET.SubElement(parent, 'Folder')
name_tag = ET.SubElement(folder, 'name')
name_tag.text = name
if description is not None:
desc_tag = ET.SubElement(folder, 'description')
desc_tag.text = description
if not visible:
visibility = ET.SubElement(folder, 'visibility')
visibility.text = '0'
return folder | python | def _CreateFolder(self, parent, name, visible=True, description=None):
"""Create a KML Folder element.
Args:
parent: The parent ElementTree.Element instance.
name: The folder name as a string.
visible: Whether the folder is initially visible or not.
description: A description string or None.
Returns:
The folder ElementTree.Element instance.
"""
folder = ET.SubElement(parent, 'Folder')
name_tag = ET.SubElement(folder, 'name')
name_tag.text = name
if description is not None:
desc_tag = ET.SubElement(folder, 'description')
desc_tag.text = description
if not visible:
visibility = ET.SubElement(folder, 'visibility')
visibility.text = '0'
return folder | [
"def",
"_CreateFolder",
"(",
"self",
",",
"parent",
",",
"name",
",",
"visible",
"=",
"True",
",",
"description",
"=",
"None",
")",
":",
"folder",
"=",
"ET",
".",
"SubElement",
"(",
"parent",
",",
"'Folder'",
")",
"name_tag",
"=",
"ET",
".",
"SubElemen... | Create a KML Folder element.
Args:
parent: The parent ElementTree.Element instance.
name: The folder name as a string.
visible: Whether the folder is initially visible or not.
description: A description string or None.
Returns:
The folder ElementTree.Element instance. | [
"Create",
"a",
"KML",
"Folder",
"element",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L132-L153 |
225,055 | google/transitfeed | kmlwriter.py | KMLWriter._CreateStyleForRoute | def _CreateStyleForRoute(self, doc, route):
"""Create a KML Style element for the route.
The style sets the line colour if the route colour is specified. The
line thickness is set depending on the vehicle type.
Args:
doc: The KML Document ElementTree.Element instance.
route: The transitfeed.Route to create the style for.
Returns:
The id of the style as a string.
"""
style_id = 'route_%s' % route.route_id
style = ET.SubElement(doc, 'Style', {'id': style_id})
linestyle = ET.SubElement(style, 'LineStyle')
width = ET.SubElement(linestyle, 'width')
type_to_width = {0: '3', # Tram
1: '3', # Subway
2: '5', # Rail
3: '1'} # Bus
width.text = type_to_width.get(route.route_type, '1')
if route.route_color:
color = ET.SubElement(linestyle, 'color')
red = route.route_color[0:2].lower()
green = route.route_color[2:4].lower()
blue = route.route_color[4:6].lower()
color.text = 'ff%s%s%s' % (blue, green, red)
return style_id | python | def _CreateStyleForRoute(self, doc, route):
"""Create a KML Style element for the route.
The style sets the line colour if the route colour is specified. The
line thickness is set depending on the vehicle type.
Args:
doc: The KML Document ElementTree.Element instance.
route: The transitfeed.Route to create the style for.
Returns:
The id of the style as a string.
"""
style_id = 'route_%s' % route.route_id
style = ET.SubElement(doc, 'Style', {'id': style_id})
linestyle = ET.SubElement(style, 'LineStyle')
width = ET.SubElement(linestyle, 'width')
type_to_width = {0: '3', # Tram
1: '3', # Subway
2: '5', # Rail
3: '1'} # Bus
width.text = type_to_width.get(route.route_type, '1')
if route.route_color:
color = ET.SubElement(linestyle, 'color')
red = route.route_color[0:2].lower()
green = route.route_color[2:4].lower()
blue = route.route_color[4:6].lower()
color.text = 'ff%s%s%s' % (blue, green, red)
return style_id | [
"def",
"_CreateStyleForRoute",
"(",
"self",
",",
"doc",
",",
"route",
")",
":",
"style_id",
"=",
"'route_%s'",
"%",
"route",
".",
"route_id",
"style",
"=",
"ET",
".",
"SubElement",
"(",
"doc",
",",
"'Style'",
",",
"{",
"'id'",
":",
"style_id",
"}",
")"... | Create a KML Style element for the route.
The style sets the line colour if the route colour is specified. The
line thickness is set depending on the vehicle type.
Args:
doc: The KML Document ElementTree.Element instance.
route: The transitfeed.Route to create the style for.
Returns:
The id of the style as a string. | [
"Create",
"a",
"KML",
"Style",
"element",
"for",
"the",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L155-L183 |
225,056 | google/transitfeed | kmlwriter.py | KMLWriter._CreatePlacemark | def _CreatePlacemark(self, parent, name, style_id=None, visible=True,
description=None):
"""Create a KML Placemark element.
Args:
parent: The parent ElementTree.Element instance.
name: The placemark name as a string.
style_id: If not None, the id of a style to use for the placemark.
visible: Whether the placemark is initially visible or not.
description: A description string or None.
Returns:
The placemark ElementTree.Element instance.
"""
placemark = ET.SubElement(parent, 'Placemark')
placemark_name = ET.SubElement(placemark, 'name')
placemark_name.text = name
if description is not None:
desc_tag = ET.SubElement(placemark, 'description')
desc_tag.text = description
if style_id is not None:
styleurl = ET.SubElement(placemark, 'styleUrl')
styleurl.text = '#%s' % style_id
if not visible:
visibility = ET.SubElement(placemark, 'visibility')
visibility.text = '0'
return placemark | python | def _CreatePlacemark(self, parent, name, style_id=None, visible=True,
description=None):
"""Create a KML Placemark element.
Args:
parent: The parent ElementTree.Element instance.
name: The placemark name as a string.
style_id: If not None, the id of a style to use for the placemark.
visible: Whether the placemark is initially visible or not.
description: A description string or None.
Returns:
The placemark ElementTree.Element instance.
"""
placemark = ET.SubElement(parent, 'Placemark')
placemark_name = ET.SubElement(placemark, 'name')
placemark_name.text = name
if description is not None:
desc_tag = ET.SubElement(placemark, 'description')
desc_tag.text = description
if style_id is not None:
styleurl = ET.SubElement(placemark, 'styleUrl')
styleurl.text = '#%s' % style_id
if not visible:
visibility = ET.SubElement(placemark, 'visibility')
visibility.text = '0'
return placemark | [
"def",
"_CreatePlacemark",
"(",
"self",
",",
"parent",
",",
"name",
",",
"style_id",
"=",
"None",
",",
"visible",
"=",
"True",
",",
"description",
"=",
"None",
")",
":",
"placemark",
"=",
"ET",
".",
"SubElement",
"(",
"parent",
",",
"'Placemark'",
")",
... | Create a KML Placemark element.
Args:
parent: The parent ElementTree.Element instance.
name: The placemark name as a string.
style_id: If not None, the id of a style to use for the placemark.
visible: Whether the placemark is initially visible or not.
description: A description string or None.
Returns:
The placemark ElementTree.Element instance. | [
"Create",
"a",
"KML",
"Placemark",
"element",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L185-L211 |
225,057 | google/transitfeed | kmlwriter.py | KMLWriter._CreateLineString | def _CreateLineString(self, parent, coordinate_list):
"""Create a KML LineString element.
The points of the string are given in coordinate_list. Every element of
coordinate_list should be one of a tuple (longitude, latitude) or a tuple
(longitude, latitude, altitude).
Args:
parent: The parent ElementTree.Element instance.
coordinate_list: The list of coordinates.
Returns:
The LineString ElementTree.Element instance or None if coordinate_list is
empty.
"""
if not coordinate_list:
return None
linestring = ET.SubElement(parent, 'LineString')
tessellate = ET.SubElement(linestring, 'tessellate')
tessellate.text = '1'
if len(coordinate_list[0]) == 3:
altitude_mode = ET.SubElement(linestring, 'altitudeMode')
altitude_mode.text = 'absolute'
coordinates = ET.SubElement(linestring, 'coordinates')
if len(coordinate_list[0]) == 3:
coordinate_str_list = ['%f,%f,%f' % t for t in coordinate_list]
else:
coordinate_str_list = ['%f,%f' % t for t in coordinate_list]
coordinates.text = ' '.join(coordinate_str_list)
return linestring | python | def _CreateLineString(self, parent, coordinate_list):
"""Create a KML LineString element.
The points of the string are given in coordinate_list. Every element of
coordinate_list should be one of a tuple (longitude, latitude) or a tuple
(longitude, latitude, altitude).
Args:
parent: The parent ElementTree.Element instance.
coordinate_list: The list of coordinates.
Returns:
The LineString ElementTree.Element instance or None if coordinate_list is
empty.
"""
if not coordinate_list:
return None
linestring = ET.SubElement(parent, 'LineString')
tessellate = ET.SubElement(linestring, 'tessellate')
tessellate.text = '1'
if len(coordinate_list[0]) == 3:
altitude_mode = ET.SubElement(linestring, 'altitudeMode')
altitude_mode.text = 'absolute'
coordinates = ET.SubElement(linestring, 'coordinates')
if len(coordinate_list[0]) == 3:
coordinate_str_list = ['%f,%f,%f' % t for t in coordinate_list]
else:
coordinate_str_list = ['%f,%f' % t for t in coordinate_list]
coordinates.text = ' '.join(coordinate_str_list)
return linestring | [
"def",
"_CreateLineString",
"(",
"self",
",",
"parent",
",",
"coordinate_list",
")",
":",
"if",
"not",
"coordinate_list",
":",
"return",
"None",
"linestring",
"=",
"ET",
".",
"SubElement",
"(",
"parent",
",",
"'LineString'",
")",
"tessellate",
"=",
"ET",
"."... | Create a KML LineString element.
The points of the string are given in coordinate_list. Every element of
coordinate_list should be one of a tuple (longitude, latitude) or a tuple
(longitude, latitude, altitude).
Args:
parent: The parent ElementTree.Element instance.
coordinate_list: The list of coordinates.
Returns:
The LineString ElementTree.Element instance or None if coordinate_list is
empty. | [
"Create",
"a",
"KML",
"LineString",
"element",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L213-L242 |
225,058 | google/transitfeed | kmlwriter.py | KMLWriter._CreateLineStringForShape | def _CreateLineStringForShape(self, parent, shape):
"""Create a KML LineString using coordinates from a shape.
Args:
parent: The parent ElementTree.Element instance.
shape: The transitfeed.Shape instance.
Returns:
The LineString ElementTree.Element instance or None if coordinate_list is
empty.
"""
coordinate_list = [(longitude, latitude) for
(latitude, longitude, distance) in shape.points]
return self._CreateLineString(parent, coordinate_list) | python | def _CreateLineStringForShape(self, parent, shape):
"""Create a KML LineString using coordinates from a shape.
Args:
parent: The parent ElementTree.Element instance.
shape: The transitfeed.Shape instance.
Returns:
The LineString ElementTree.Element instance or None if coordinate_list is
empty.
"""
coordinate_list = [(longitude, latitude) for
(latitude, longitude, distance) in shape.points]
return self._CreateLineString(parent, coordinate_list) | [
"def",
"_CreateLineStringForShape",
"(",
"self",
",",
"parent",
",",
"shape",
")",
":",
"coordinate_list",
"=",
"[",
"(",
"longitude",
",",
"latitude",
")",
"for",
"(",
"latitude",
",",
"longitude",
",",
"distance",
")",
"in",
"shape",
".",
"points",
"]",
... | Create a KML LineString using coordinates from a shape.
Args:
parent: The parent ElementTree.Element instance.
shape: The transitfeed.Shape instance.
Returns:
The LineString ElementTree.Element instance or None if coordinate_list is
empty. | [
"Create",
"a",
"KML",
"LineString",
"using",
"coordinates",
"from",
"a",
"shape",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L244-L257 |
225,059 | google/transitfeed | kmlwriter.py | KMLWriter._CreateStopsFolder | def _CreateStopsFolder(self, schedule, doc):
"""Create a KML Folder containing placemarks for each stop in the schedule.
If there are no stops in the schedule then no folder is created.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The Folder ElementTree.Element instance or None if there are no stops.
"""
if not schedule.GetStopList():
return None
stop_folder = self._CreateFolder(doc, 'Stops')
stop_folder_selection = self._StopFolderSelectionMethod(stop_folder)
stop_style_selection = self._StopStyleSelectionMethod(doc)
stops = list(schedule.GetStopList())
stops.sort(key=lambda x: x.stop_name)
for stop in stops:
(folder, pathway_folder) = stop_folder_selection(stop)
(style_id, pathway_style_id) = stop_style_selection(stop)
self._CreateStopPlacemark(folder, stop, style_id)
if (self.show_stop_hierarchy and
stop.location_type != transitfeed.Stop.LOCATION_TYPE_STATION and
stop.parent_station and stop.parent_station in schedule.stops):
placemark = self._CreatePlacemark(
pathway_folder, stop.stop_name, pathway_style_id)
parent_station = schedule.stops[stop.parent_station]
coordinates = [(stop.stop_lon, stop.stop_lat),
(parent_station.stop_lon, parent_station.stop_lat)]
self._CreateLineString(placemark, coordinates)
return stop_folder | python | def _CreateStopsFolder(self, schedule, doc):
"""Create a KML Folder containing placemarks for each stop in the schedule.
If there are no stops in the schedule then no folder is created.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The Folder ElementTree.Element instance or None if there are no stops.
"""
if not schedule.GetStopList():
return None
stop_folder = self._CreateFolder(doc, 'Stops')
stop_folder_selection = self._StopFolderSelectionMethod(stop_folder)
stop_style_selection = self._StopStyleSelectionMethod(doc)
stops = list(schedule.GetStopList())
stops.sort(key=lambda x: x.stop_name)
for stop in stops:
(folder, pathway_folder) = stop_folder_selection(stop)
(style_id, pathway_style_id) = stop_style_selection(stop)
self._CreateStopPlacemark(folder, stop, style_id)
if (self.show_stop_hierarchy and
stop.location_type != transitfeed.Stop.LOCATION_TYPE_STATION and
stop.parent_station and stop.parent_station in schedule.stops):
placemark = self._CreatePlacemark(
pathway_folder, stop.stop_name, pathway_style_id)
parent_station = schedule.stops[stop.parent_station]
coordinates = [(stop.stop_lon, stop.stop_lat),
(parent_station.stop_lon, parent_station.stop_lat)]
self._CreateLineString(placemark, coordinates)
return stop_folder | [
"def",
"_CreateStopsFolder",
"(",
"self",
",",
"schedule",
",",
"doc",
")",
":",
"if",
"not",
"schedule",
".",
"GetStopList",
"(",
")",
":",
"return",
"None",
"stop_folder",
"=",
"self",
".",
"_CreateFolder",
"(",
"doc",
",",
"'Stops'",
")",
"stop_folder_s... | Create a KML Folder containing placemarks for each stop in the schedule.
If there are no stops in the schedule then no folder is created.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The Folder ElementTree.Element instance or None if there are no stops. | [
"Create",
"a",
"KML",
"Folder",
"containing",
"placemarks",
"for",
"each",
"stop",
"in",
"the",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L259-L291 |
225,060 | google/transitfeed | kmlwriter.py | KMLWriter._StopFolderSelectionMethod | def _StopFolderSelectionMethod(self, stop_folder):
"""Create a method to determine which KML folder a stop should go in.
Args:
stop_folder: the parent folder element for all stops.
Returns:
A function that should accept a Stop argument and return a tuple of
(stop KML folder, pathways KML folder).
Given a Stop, we need to determine which folder the stop should go in. In
the most basic case, that's the root Stops folder. However, if
show_stop_hierarchy is enabled, we put a stop in a separate sub-folder
depending on if the stop is a station, a platform, an entrance, or just a
plain-old stand-alone stop. This method returns a function that is used
to pick which folder a stop stop should go in. It also optionally returns
a folder where any line-string connections associated with a stop (eg. to
show the pathway between an entrance and a station) should be added.
"""
if not self.show_stop_hierarchy:
return lambda stop: (stop_folder, None)
# Create the various sub-folders for showing the stop hierarchy
station_folder = self._CreateFolder(stop_folder, 'Stations')
platform_folder = self._CreateFolder(stop_folder, 'Platforms')
platform_connections = self._CreateFolder(platform_folder, 'Connections')
entrance_folder = self._CreateFolder(stop_folder, 'Entrances')
entrance_connections = self._CreateFolder(entrance_folder, 'Connections')
standalone_folder = self._CreateFolder(stop_folder, 'Stand-Alone')
def FolderSelectionMethod(stop):
if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION:
return (station_folder, None)
elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE:
return (entrance_folder, entrance_connections)
elif stop.parent_station:
return (platform_folder, platform_connections)
return (standalone_folder, None)
return FolderSelectionMethod | python | def _StopFolderSelectionMethod(self, stop_folder):
"""Create a method to determine which KML folder a stop should go in.
Args:
stop_folder: the parent folder element for all stops.
Returns:
A function that should accept a Stop argument and return a tuple of
(stop KML folder, pathways KML folder).
Given a Stop, we need to determine which folder the stop should go in. In
the most basic case, that's the root Stops folder. However, if
show_stop_hierarchy is enabled, we put a stop in a separate sub-folder
depending on if the stop is a station, a platform, an entrance, or just a
plain-old stand-alone stop. This method returns a function that is used
to pick which folder a stop stop should go in. It also optionally returns
a folder where any line-string connections associated with a stop (eg. to
show the pathway between an entrance and a station) should be added.
"""
if not self.show_stop_hierarchy:
return lambda stop: (stop_folder, None)
# Create the various sub-folders for showing the stop hierarchy
station_folder = self._CreateFolder(stop_folder, 'Stations')
platform_folder = self._CreateFolder(stop_folder, 'Platforms')
platform_connections = self._CreateFolder(platform_folder, 'Connections')
entrance_folder = self._CreateFolder(stop_folder, 'Entrances')
entrance_connections = self._CreateFolder(entrance_folder, 'Connections')
standalone_folder = self._CreateFolder(stop_folder, 'Stand-Alone')
def FolderSelectionMethod(stop):
if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION:
return (station_folder, None)
elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE:
return (entrance_folder, entrance_connections)
elif stop.parent_station:
return (platform_folder, platform_connections)
return (standalone_folder, None)
return FolderSelectionMethod | [
"def",
"_StopFolderSelectionMethod",
"(",
"self",
",",
"stop_folder",
")",
":",
"if",
"not",
"self",
".",
"show_stop_hierarchy",
":",
"return",
"lambda",
"stop",
":",
"(",
"stop_folder",
",",
"None",
")",
"# Create the various sub-folders for showing the stop hierarchy"... | Create a method to determine which KML folder a stop should go in.
Args:
stop_folder: the parent folder element for all stops.
Returns:
A function that should accept a Stop argument and return a tuple of
(stop KML folder, pathways KML folder).
Given a Stop, we need to determine which folder the stop should go in. In
the most basic case, that's the root Stops folder. However, if
show_stop_hierarchy is enabled, we put a stop in a separate sub-folder
depending on if the stop is a station, a platform, an entrance, or just a
plain-old stand-alone stop. This method returns a function that is used
to pick which folder a stop stop should go in. It also optionally returns
a folder where any line-string connections associated with a stop (eg. to
show the pathway between an entrance and a station) should be added. | [
"Create",
"a",
"method",
"to",
"determine",
"which",
"KML",
"folder",
"a",
"stop",
"should",
"go",
"in",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L293-L332 |
225,061 | google/transitfeed | kmlwriter.py | KMLWriter._StopStyleSelectionMethod | def _StopStyleSelectionMethod(self, doc):
"""Create a method to determine which style to apply to a stop placemark.
Args:
doc: the KML document.
Returns:
A function that should accept a Stop argument and return a tuple of
(stop placemark style id, pathway placemark style id). Either style id
can be None, indicating no style should be set.
Given a Stop, we need to determine what KML style to apply to the stops'
placemark. In the most basic case, no styling is applied. However, if
show_stop_hierarchy is enabled, we style each type of stop differently
depending on if the stop is a station, platform, entrance, etc. This method
returns a function that is used to pick which style id should be associated
with a stop placemark, or None if no style should be applied. It also
optionally returns a style id to associate with any line-string connections
associated with a stop (eg. to show the pathway between an entrance and a
station).
"""
if not self.show_stop_hierarchy:
return lambda stop: (None, None)
# Create the various styles for showing the stop hierarchy
self._CreateStyle(
doc, 'stop_entrance', {'IconStyle': {'color': 'ff0000ff'}})
self._CreateStyle(
doc,
'entrance_connection',
{'LineStyle': {'color': 'ff0000ff', 'width': '2'}})
self._CreateStyle(
doc, 'stop_platform', {'IconStyle': {'color': 'ffff0000'}})
self._CreateStyle(
doc,
'platform_connection',
{'LineStyle': {'color': 'ffff0000', 'width': '2'}})
self._CreateStyle(
doc, 'stop_standalone', {'IconStyle': {'color': 'ff00ff00'}})
def StyleSelectionMethod(stop):
if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION:
return ('stop_station', None)
elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE:
return ('stop_entrance', 'entrance_connection')
elif stop.parent_station:
return ('stop_platform', 'platform_connection')
return ('stop_standalone', None)
return StyleSelectionMethod | python | def _StopStyleSelectionMethod(self, doc):
"""Create a method to determine which style to apply to a stop placemark.
Args:
doc: the KML document.
Returns:
A function that should accept a Stop argument and return a tuple of
(stop placemark style id, pathway placemark style id). Either style id
can be None, indicating no style should be set.
Given a Stop, we need to determine what KML style to apply to the stops'
placemark. In the most basic case, no styling is applied. However, if
show_stop_hierarchy is enabled, we style each type of stop differently
depending on if the stop is a station, platform, entrance, etc. This method
returns a function that is used to pick which style id should be associated
with a stop placemark, or None if no style should be applied. It also
optionally returns a style id to associate with any line-string connections
associated with a stop (eg. to show the pathway between an entrance and a
station).
"""
if not self.show_stop_hierarchy:
return lambda stop: (None, None)
# Create the various styles for showing the stop hierarchy
self._CreateStyle(
doc, 'stop_entrance', {'IconStyle': {'color': 'ff0000ff'}})
self._CreateStyle(
doc,
'entrance_connection',
{'LineStyle': {'color': 'ff0000ff', 'width': '2'}})
self._CreateStyle(
doc, 'stop_platform', {'IconStyle': {'color': 'ffff0000'}})
self._CreateStyle(
doc,
'platform_connection',
{'LineStyle': {'color': 'ffff0000', 'width': '2'}})
self._CreateStyle(
doc, 'stop_standalone', {'IconStyle': {'color': 'ff00ff00'}})
def StyleSelectionMethod(stop):
if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION:
return ('stop_station', None)
elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE:
return ('stop_entrance', 'entrance_connection')
elif stop.parent_station:
return ('stop_platform', 'platform_connection')
return ('stop_standalone', None)
return StyleSelectionMethod | [
"def",
"_StopStyleSelectionMethod",
"(",
"self",
",",
"doc",
")",
":",
"if",
"not",
"self",
".",
"show_stop_hierarchy",
":",
"return",
"lambda",
"stop",
":",
"(",
"None",
",",
"None",
")",
"# Create the various styles for showing the stop hierarchy",
"self",
".",
... | Create a method to determine which style to apply to a stop placemark.
Args:
doc: the KML document.
Returns:
A function that should accept a Stop argument and return a tuple of
(stop placemark style id, pathway placemark style id). Either style id
can be None, indicating no style should be set.
Given a Stop, we need to determine what KML style to apply to the stops'
placemark. In the most basic case, no styling is applied. However, if
show_stop_hierarchy is enabled, we style each type of stop differently
depending on if the stop is a station, platform, entrance, etc. This method
returns a function that is used to pick which style id should be associated
with a stop placemark, or None if no style should be applied. It also
optionally returns a style id to associate with any line-string connections
associated with a stop (eg. to show the pathway between an entrance and a
station). | [
"Create",
"a",
"method",
"to",
"determine",
"which",
"style",
"to",
"apply",
"to",
"a",
"stop",
"placemark",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L334-L383 |
225,062 | google/transitfeed | kmlwriter.py | KMLWriter._CreateRoutePatternsFolder | def _CreateRoutePatternsFolder(self, parent, route,
style_id=None, visible=True):
"""Create a KML Folder containing placemarks for each pattern in the route.
A pattern is a sequence of stops used by one of the trips in the route.
If there are not patterns for the route then no folder is created and None
is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: The id of a style to use if not None.
visible: Whether the folder is initially visible or not.
Returns:
The Folder ElementTree.Element instance or None if there are no patterns.
"""
pattern_id_to_trips = route.GetPatternIdTripDict()
if not pattern_id_to_trips:
return None
# sort by number of trips using the pattern
pattern_trips = pattern_id_to_trips.values()
pattern_trips.sort(lambda a, b: cmp(len(b), len(a)))
folder = self._CreateFolder(parent, 'Patterns', visible)
for n, trips in enumerate(pattern_trips):
trip_ids = [trip.trip_id for trip in trips]
name = 'Pattern %d (trips: %d)' % (n+1, len(trips))
description = 'Trips using this pattern (%d in total): %s' % (
len(trips), ', '.join(trip_ids))
placemark = self._CreatePlacemark(folder, name, style_id, visible,
description)
coordinates = [(stop.stop_lon, stop.stop_lat)
for stop in trips[0].GetPattern()]
self._CreateLineString(placemark, coordinates)
return folder | python | def _CreateRoutePatternsFolder(self, parent, route,
style_id=None, visible=True):
"""Create a KML Folder containing placemarks for each pattern in the route.
A pattern is a sequence of stops used by one of the trips in the route.
If there are not patterns for the route then no folder is created and None
is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: The id of a style to use if not None.
visible: Whether the folder is initially visible or not.
Returns:
The Folder ElementTree.Element instance or None if there are no patterns.
"""
pattern_id_to_trips = route.GetPatternIdTripDict()
if not pattern_id_to_trips:
return None
# sort by number of trips using the pattern
pattern_trips = pattern_id_to_trips.values()
pattern_trips.sort(lambda a, b: cmp(len(b), len(a)))
folder = self._CreateFolder(parent, 'Patterns', visible)
for n, trips in enumerate(pattern_trips):
trip_ids = [trip.trip_id for trip in trips]
name = 'Pattern %d (trips: %d)' % (n+1, len(trips))
description = 'Trips using this pattern (%d in total): %s' % (
len(trips), ', '.join(trip_ids))
placemark = self._CreatePlacemark(folder, name, style_id, visible,
description)
coordinates = [(stop.stop_lon, stop.stop_lat)
for stop in trips[0].GetPattern()]
self._CreateLineString(placemark, coordinates)
return folder | [
"def",
"_CreateRoutePatternsFolder",
"(",
"self",
",",
"parent",
",",
"route",
",",
"style_id",
"=",
"None",
",",
"visible",
"=",
"True",
")",
":",
"pattern_id_to_trips",
"=",
"route",
".",
"GetPatternIdTripDict",
"(",
")",
"if",
"not",
"pattern_id_to_trips",
... | Create a KML Folder containing placemarks for each pattern in the route.
A pattern is a sequence of stops used by one of the trips in the route.
If there are not patterns for the route then no folder is created and None
is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: The id of a style to use if not None.
visible: Whether the folder is initially visible or not.
Returns:
The Folder ElementTree.Element instance or None if there are no patterns. | [
"Create",
"a",
"KML",
"Folder",
"containing",
"placemarks",
"for",
"each",
"pattern",
"in",
"the",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L438-L475 |
225,063 | google/transitfeed | kmlwriter.py | KMLWriter._CreateRouteShapesFolder | def _CreateRouteShapesFolder(self, schedule, parent, route,
style_id=None, visible=True):
"""Create a KML Folder for the shapes of a route.
The folder contains a placemark for each shape referenced by a trip in the
route. If there are no such shapes, no folder is created and None is
returned.
Args:
schedule: The transitfeed.Schedule instance.
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: The id of a style to use if not None.
visible: Whether the placemark is initially visible or not.
Returns:
The Folder ElementTree.Element instance or None.
"""
shape_id_to_trips = {}
for trip in route.trips:
if trip.shape_id:
shape_id_to_trips.setdefault(trip.shape_id, []).append(trip)
if not shape_id_to_trips:
return None
# sort by the number of trips using the shape
shape_id_to_trips_items = shape_id_to_trips.items()
shape_id_to_trips_items.sort(lambda a, b: cmp(len(b[1]), len(a[1])))
folder = self._CreateFolder(parent, 'Shapes', visible)
for shape_id, trips in shape_id_to_trips_items:
trip_ids = [trip.trip_id for trip in trips]
name = '%s (trips: %d)' % (shape_id, len(trips))
description = 'Trips using this shape (%d in total): %s' % (
len(trips), ', '.join(trip_ids))
placemark = self._CreatePlacemark(folder, name, style_id, visible,
description)
self._CreateLineStringForShape(placemark, schedule.GetShape(shape_id))
return folder | python | def _CreateRouteShapesFolder(self, schedule, parent, route,
style_id=None, visible=True):
"""Create a KML Folder for the shapes of a route.
The folder contains a placemark for each shape referenced by a trip in the
route. If there are no such shapes, no folder is created and None is
returned.
Args:
schedule: The transitfeed.Schedule instance.
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: The id of a style to use if not None.
visible: Whether the placemark is initially visible or not.
Returns:
The Folder ElementTree.Element instance or None.
"""
shape_id_to_trips = {}
for trip in route.trips:
if trip.shape_id:
shape_id_to_trips.setdefault(trip.shape_id, []).append(trip)
if not shape_id_to_trips:
return None
# sort by the number of trips using the shape
shape_id_to_trips_items = shape_id_to_trips.items()
shape_id_to_trips_items.sort(lambda a, b: cmp(len(b[1]), len(a[1])))
folder = self._CreateFolder(parent, 'Shapes', visible)
for shape_id, trips in shape_id_to_trips_items:
trip_ids = [trip.trip_id for trip in trips]
name = '%s (trips: %d)' % (shape_id, len(trips))
description = 'Trips using this shape (%d in total): %s' % (
len(trips), ', '.join(trip_ids))
placemark = self._CreatePlacemark(folder, name, style_id, visible,
description)
self._CreateLineStringForShape(placemark, schedule.GetShape(shape_id))
return folder | [
"def",
"_CreateRouteShapesFolder",
"(",
"self",
",",
"schedule",
",",
"parent",
",",
"route",
",",
"style_id",
"=",
"None",
",",
"visible",
"=",
"True",
")",
":",
"shape_id_to_trips",
"=",
"{",
"}",
"for",
"trip",
"in",
"route",
".",
"trips",
":",
"if",
... | Create a KML Folder for the shapes of a route.
The folder contains a placemark for each shape referenced by a trip in the
route. If there are no such shapes, no folder is created and None is
returned.
Args:
schedule: The transitfeed.Schedule instance.
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: The id of a style to use if not None.
visible: Whether the placemark is initially visible or not.
Returns:
The Folder ElementTree.Element instance or None. | [
"Create",
"a",
"KML",
"Folder",
"for",
"the",
"shapes",
"of",
"a",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L477-L515 |
225,064 | google/transitfeed | kmlwriter.py | KMLWriter._CreateRouteTripsFolder | def _CreateRouteTripsFolder(self, parent, route, style_id=None, schedule=None):
"""Create a KML Folder containing all the trips in the route.
The folder contains a placemark for each of these trips. If there are no
trips in the route, no folder is created and None is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: A style id string for the placemarks or None.
Returns:
The Folder ElementTree.Element instance or None.
"""
if not route.trips:
return None
trips = list(route.trips)
trips.sort(key=lambda x: x.trip_id)
trips_folder = self._CreateFolder(parent, 'Trips', visible=False)
for trip in trips:
if (self.date_filter and
not trip.service_period.IsActiveOn(self.date_filter)):
continue
if trip.trip_headsign:
description = 'Headsign: %s' % trip.trip_headsign
else:
description = None
coordinate_list = []
for secs, stoptime, tp in trip.GetTimeInterpolatedStops():
if self.altitude_per_sec > 0:
coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat,
(secs - 3600 * 4) * self.altitude_per_sec))
else:
coordinate_list.append((stoptime.stop.stop_lon,
stoptime.stop.stop_lat))
placemark = self._CreatePlacemark(trips_folder,
trip.trip_id,
style_id=style_id,
visible=False,
description=description)
self._CreateLineString(placemark, coordinate_list)
return trips_folder | python | def _CreateRouteTripsFolder(self, parent, route, style_id=None, schedule=None):
"""Create a KML Folder containing all the trips in the route.
The folder contains a placemark for each of these trips. If there are no
trips in the route, no folder is created and None is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: A style id string for the placemarks or None.
Returns:
The Folder ElementTree.Element instance or None.
"""
if not route.trips:
return None
trips = list(route.trips)
trips.sort(key=lambda x: x.trip_id)
trips_folder = self._CreateFolder(parent, 'Trips', visible=False)
for trip in trips:
if (self.date_filter and
not trip.service_period.IsActiveOn(self.date_filter)):
continue
if trip.trip_headsign:
description = 'Headsign: %s' % trip.trip_headsign
else:
description = None
coordinate_list = []
for secs, stoptime, tp in trip.GetTimeInterpolatedStops():
if self.altitude_per_sec > 0:
coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat,
(secs - 3600 * 4) * self.altitude_per_sec))
else:
coordinate_list.append((stoptime.stop.stop_lon,
stoptime.stop.stop_lat))
placemark = self._CreatePlacemark(trips_folder,
trip.trip_id,
style_id=style_id,
visible=False,
description=description)
self._CreateLineString(placemark, coordinate_list)
return trips_folder | [
"def",
"_CreateRouteTripsFolder",
"(",
"self",
",",
"parent",
",",
"route",
",",
"style_id",
"=",
"None",
",",
"schedule",
"=",
"None",
")",
":",
"if",
"not",
"route",
".",
"trips",
":",
"return",
"None",
"trips",
"=",
"list",
"(",
"route",
".",
"trips... | Create a KML Folder containing all the trips in the route.
The folder contains a placemark for each of these trips. If there are no
trips in the route, no folder is created and None is returned.
Args:
parent: The parent ElementTree.Element instance.
route: The transitfeed.Route instance.
style_id: A style id string for the placemarks or None.
Returns:
The Folder ElementTree.Element instance or None. | [
"Create",
"a",
"KML",
"Folder",
"containing",
"all",
"the",
"trips",
"in",
"the",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L517-L560 |
225,065 | google/transitfeed | kmlwriter.py | KMLWriter._CreateRoutesFolder | def _CreateRoutesFolder(self, schedule, doc, route_type=None):
"""Create a KML Folder containing routes in a schedule.
The folder contains a subfolder for each route in the schedule of type
route_type. If route_type is None, then all routes are selected. Each
subfolder contains a flattened graph placemark, a route shapes placemark
and, if show_trips is True, a subfolder containing placemarks for each of
the trips in the route.
If there are no routes in the schedule then no folder is created and None
is returned.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
route_type: The route type integer or None.
Returns:
The Folder ElementTree.Element instance or None.
"""
def GetRouteName(route):
"""Return a placemark name for the route.
Args:
route: The transitfeed.Route instance.
Returns:
The name as a string.
"""
name_parts = []
if route.route_short_name:
name_parts.append('<b>%s</b>' % route.route_short_name)
if route.route_long_name:
name_parts.append(route.route_long_name)
return ' - '.join(name_parts) or route.route_id
def GetRouteDescription(route):
"""Return a placemark description for the route.
Args:
route: The transitfeed.Route instance.
Returns:
The description as a string.
"""
desc_items = []
if route.route_desc:
desc_items.append(route.route_desc)
if route.route_url:
desc_items.append('Route info page: <a href="%s">%s</a>' % (
route.route_url, route.route_url))
description = '<br/>'.join(desc_items)
return description or None
routes = [route for route in schedule.GetRouteList()
if route_type is None or route.route_type == route_type]
if not routes:
return None
routes.sort(key=lambda x: GetRouteName(x))
if route_type is not None:
route_type_names = {0: 'Tram, Streetcar or Light rail',
1: 'Subway or Metro',
2: 'Rail',
3: 'Bus',
4: 'Ferry',
5: 'Cable car',
6: 'Gondola or suspended cable car',
7: 'Funicular'}
type_name = route_type_names.get(route_type, str(route_type))
folder_name = 'Routes - %s' % type_name
else:
folder_name = 'Routes'
routes_folder = self._CreateFolder(doc, folder_name, visible=False)
for route in routes:
style_id = self._CreateStyleForRoute(doc, route)
route_folder = self._CreateFolder(routes_folder,
GetRouteName(route),
description=GetRouteDescription(route))
self._CreateRouteShapesFolder(schedule, route_folder, route,
style_id, False)
self._CreateRoutePatternsFolder(route_folder, route, style_id, False)
if self.show_trips:
self._CreateRouteTripsFolder(route_folder, route, style_id, schedule)
return routes_folder | python | def _CreateRoutesFolder(self, schedule, doc, route_type=None):
"""Create a KML Folder containing routes in a schedule.
The folder contains a subfolder for each route in the schedule of type
route_type. If route_type is None, then all routes are selected. Each
subfolder contains a flattened graph placemark, a route shapes placemark
and, if show_trips is True, a subfolder containing placemarks for each of
the trips in the route.
If there are no routes in the schedule then no folder is created and None
is returned.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
route_type: The route type integer or None.
Returns:
The Folder ElementTree.Element instance or None.
"""
def GetRouteName(route):
"""Return a placemark name for the route.
Args:
route: The transitfeed.Route instance.
Returns:
The name as a string.
"""
name_parts = []
if route.route_short_name:
name_parts.append('<b>%s</b>' % route.route_short_name)
if route.route_long_name:
name_parts.append(route.route_long_name)
return ' - '.join(name_parts) or route.route_id
def GetRouteDescription(route):
"""Return a placemark description for the route.
Args:
route: The transitfeed.Route instance.
Returns:
The description as a string.
"""
desc_items = []
if route.route_desc:
desc_items.append(route.route_desc)
if route.route_url:
desc_items.append('Route info page: <a href="%s">%s</a>' % (
route.route_url, route.route_url))
description = '<br/>'.join(desc_items)
return description or None
routes = [route for route in schedule.GetRouteList()
if route_type is None or route.route_type == route_type]
if not routes:
return None
routes.sort(key=lambda x: GetRouteName(x))
if route_type is not None:
route_type_names = {0: 'Tram, Streetcar or Light rail',
1: 'Subway or Metro',
2: 'Rail',
3: 'Bus',
4: 'Ferry',
5: 'Cable car',
6: 'Gondola or suspended cable car',
7: 'Funicular'}
type_name = route_type_names.get(route_type, str(route_type))
folder_name = 'Routes - %s' % type_name
else:
folder_name = 'Routes'
routes_folder = self._CreateFolder(doc, folder_name, visible=False)
for route in routes:
style_id = self._CreateStyleForRoute(doc, route)
route_folder = self._CreateFolder(routes_folder,
GetRouteName(route),
description=GetRouteDescription(route))
self._CreateRouteShapesFolder(schedule, route_folder, route,
style_id, False)
self._CreateRoutePatternsFolder(route_folder, route, style_id, False)
if self.show_trips:
self._CreateRouteTripsFolder(route_folder, route, style_id, schedule)
return routes_folder | [
"def",
"_CreateRoutesFolder",
"(",
"self",
",",
"schedule",
",",
"doc",
",",
"route_type",
"=",
"None",
")",
":",
"def",
"GetRouteName",
"(",
"route",
")",
":",
"\"\"\"Return a placemark name for the route.\n\n Args:\n route: The transitfeed.Route instance.\n\n ... | Create a KML Folder containing routes in a schedule.
The folder contains a subfolder for each route in the schedule of type
route_type. If route_type is None, then all routes are selected. Each
subfolder contains a flattened graph placemark, a route shapes placemark
and, if show_trips is True, a subfolder containing placemarks for each of
the trips in the route.
If there are no routes in the schedule then no folder is created and None
is returned.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
route_type: The route type integer or None.
Returns:
The Folder ElementTree.Element instance or None. | [
"Create",
"a",
"KML",
"Folder",
"containing",
"routes",
"in",
"a",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L562-L648 |
225,066 | google/transitfeed | kmlwriter.py | KMLWriter._CreateShapesFolder | def _CreateShapesFolder(self, schedule, doc):
"""Create a KML Folder containing all the shapes in a schedule.
The folder contains a placemark for each shape. If there are no shapes in
the schedule then the folder is not created and None is returned.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The Folder ElementTree.Element instance or None.
"""
if not schedule.GetShapeList():
return None
shapes_folder = self._CreateFolder(doc, 'Shapes')
shapes = list(schedule.GetShapeList())
shapes.sort(key=lambda x: x.shape_id)
for shape in shapes:
placemark = self._CreatePlacemark(shapes_folder, shape.shape_id)
self._CreateLineStringForShape(placemark, shape)
if self.shape_points:
self._CreateShapePointFolder(shapes_folder, shape)
return shapes_folder | python | def _CreateShapesFolder(self, schedule, doc):
"""Create a KML Folder containing all the shapes in a schedule.
The folder contains a placemark for each shape. If there are no shapes in
the schedule then the folder is not created and None is returned.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The Folder ElementTree.Element instance or None.
"""
if not schedule.GetShapeList():
return None
shapes_folder = self._CreateFolder(doc, 'Shapes')
shapes = list(schedule.GetShapeList())
shapes.sort(key=lambda x: x.shape_id)
for shape in shapes:
placemark = self._CreatePlacemark(shapes_folder, shape.shape_id)
self._CreateLineStringForShape(placemark, shape)
if self.shape_points:
self._CreateShapePointFolder(shapes_folder, shape)
return shapes_folder | [
"def",
"_CreateShapesFolder",
"(",
"self",
",",
"schedule",
",",
"doc",
")",
":",
"if",
"not",
"schedule",
".",
"GetShapeList",
"(",
")",
":",
"return",
"None",
"shapes_folder",
"=",
"self",
".",
"_CreateFolder",
"(",
"doc",
",",
"'Shapes'",
")",
"shapes",... | Create a KML Folder containing all the shapes in a schedule.
The folder contains a placemark for each shape. If there are no shapes in
the schedule then the folder is not created and None is returned.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The Folder ElementTree.Element instance or None. | [
"Create",
"a",
"KML",
"Folder",
"containing",
"all",
"the",
"shapes",
"in",
"a",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L650-L673 |
225,067 | google/transitfeed | kmlwriter.py | KMLWriter._CreateShapePointFolder | def _CreateShapePointFolder(self, shapes_folder, shape):
"""Create a KML Folder containing all the shape points in a shape.
The folder contains placemarks for each shapepoint.
Args:
shapes_folder: A KML Shape Folder ElementTree.Element instance
shape: The shape to plot.
Returns:
The Folder ElementTree.Element instance or None.
"""
folder_name = shape.shape_id + ' Shape Points'
folder = self._CreateFolder(shapes_folder, folder_name, visible=False)
for (index, (lat, lon, dist)) in enumerate(shape.points):
placemark = self._CreatePlacemark(folder, str(index+1))
point = ET.SubElement(placemark, 'Point')
coordinates = ET.SubElement(point, 'coordinates')
coordinates.text = '%.6f,%.6f' % (lon, lat)
return folder | python | def _CreateShapePointFolder(self, shapes_folder, shape):
"""Create a KML Folder containing all the shape points in a shape.
The folder contains placemarks for each shapepoint.
Args:
shapes_folder: A KML Shape Folder ElementTree.Element instance
shape: The shape to plot.
Returns:
The Folder ElementTree.Element instance or None.
"""
folder_name = shape.shape_id + ' Shape Points'
folder = self._CreateFolder(shapes_folder, folder_name, visible=False)
for (index, (lat, lon, dist)) in enumerate(shape.points):
placemark = self._CreatePlacemark(folder, str(index+1))
point = ET.SubElement(placemark, 'Point')
coordinates = ET.SubElement(point, 'coordinates')
coordinates.text = '%.6f,%.6f' % (lon, lat)
return folder | [
"def",
"_CreateShapePointFolder",
"(",
"self",
",",
"shapes_folder",
",",
"shape",
")",
":",
"folder_name",
"=",
"shape",
".",
"shape_id",
"+",
"' Shape Points'",
"folder",
"=",
"self",
".",
"_CreateFolder",
"(",
"shapes_folder",
",",
"folder_name",
",",
"visibl... | Create a KML Folder containing all the shape points in a shape.
The folder contains placemarks for each shapepoint.
Args:
shapes_folder: A KML Shape Folder ElementTree.Element instance
shape: The shape to plot.
Returns:
The Folder ElementTree.Element instance or None. | [
"Create",
"a",
"KML",
"Folder",
"containing",
"all",
"the",
"shape",
"points",
"in",
"a",
"shape",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L675-L695 |
225,068 | google/transitfeed | kmlwriter.py | KMLWriter.Write | def Write(self, schedule, output_file):
"""Writes out a feed as KML.
Args:
schedule: A transitfeed.Schedule object containing the feed to write.
output_file: The name of the output KML file, or file object to use.
"""
# Generate the DOM to write
root = ET.Element('kml')
root.attrib['xmlns'] = 'http://earth.google.com/kml/2.1'
doc = ET.SubElement(root, 'Document')
open_tag = ET.SubElement(doc, 'open')
open_tag.text = '1'
self._CreateStopsFolder(schedule, doc)
if self.split_routes:
route_types = set()
for route in schedule.GetRouteList():
route_types.add(route.route_type)
route_types = list(route_types)
route_types.sort()
for route_type in route_types:
self._CreateRoutesFolder(schedule, doc, route_type)
else:
self._CreateRoutesFolder(schedule, doc)
self._CreateShapesFolder(schedule, doc)
# Make sure we pretty-print
self._SetIndentation(root)
# Now write the output
if isinstance(output_file, file):
output = output_file
else:
output = open(output_file, 'w')
output.write("""<?xml version="1.0" encoding="UTF-8"?>\n""")
ET.ElementTree(root).write(output, 'utf-8') | python | def Write(self, schedule, output_file):
"""Writes out a feed as KML.
Args:
schedule: A transitfeed.Schedule object containing the feed to write.
output_file: The name of the output KML file, or file object to use.
"""
# Generate the DOM to write
root = ET.Element('kml')
root.attrib['xmlns'] = 'http://earth.google.com/kml/2.1'
doc = ET.SubElement(root, 'Document')
open_tag = ET.SubElement(doc, 'open')
open_tag.text = '1'
self._CreateStopsFolder(schedule, doc)
if self.split_routes:
route_types = set()
for route in schedule.GetRouteList():
route_types.add(route.route_type)
route_types = list(route_types)
route_types.sort()
for route_type in route_types:
self._CreateRoutesFolder(schedule, doc, route_type)
else:
self._CreateRoutesFolder(schedule, doc)
self._CreateShapesFolder(schedule, doc)
# Make sure we pretty-print
self._SetIndentation(root)
# Now write the output
if isinstance(output_file, file):
output = output_file
else:
output = open(output_file, 'w')
output.write("""<?xml version="1.0" encoding="UTF-8"?>\n""")
ET.ElementTree(root).write(output, 'utf-8') | [
"def",
"Write",
"(",
"self",
",",
"schedule",
",",
"output_file",
")",
":",
"# Generate the DOM to write",
"root",
"=",
"ET",
".",
"Element",
"(",
"'kml'",
")",
"root",
".",
"attrib",
"[",
"'xmlns'",
"]",
"=",
"'http://earth.google.com/kml/2.1'",
"doc",
"=",
... | Writes out a feed as KML.
Args:
schedule: A transitfeed.Schedule object containing the feed to write.
output_file: The name of the output KML file, or file object to use. | [
"Writes",
"out",
"a",
"feed",
"as",
"KML",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L697-L732 |
225,069 | google/transitfeed | feedvalidator.py | RunValidationOutputFromOptions | def RunValidationOutputFromOptions(feed, options):
"""Validate feed, output results per options and return an exit code."""
if options.output.upper() == "CONSOLE":
return RunValidationOutputToConsole(feed, options)
else:
return RunValidationOutputToFilename(feed, options, options.output) | python | def RunValidationOutputFromOptions(feed, options):
"""Validate feed, output results per options and return an exit code."""
if options.output.upper() == "CONSOLE":
return RunValidationOutputToConsole(feed, options)
else:
return RunValidationOutputToFilename(feed, options, options.output) | [
"def",
"RunValidationOutputFromOptions",
"(",
"feed",
",",
"options",
")",
":",
"if",
"options",
".",
"output",
".",
"upper",
"(",
")",
"==",
"\"CONSOLE\"",
":",
"return",
"RunValidationOutputToConsole",
"(",
"feed",
",",
"options",
")",
"else",
":",
"return",... | Validate feed, output results per options and return an exit code. | [
"Validate",
"feed",
"output",
"results",
"per",
"options",
"and",
"return",
"an",
"exit",
"code",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L503-L508 |
225,070 | google/transitfeed | feedvalidator.py | RunValidationOutputToFilename | def RunValidationOutputToFilename(feed, options, output_filename):
"""Validate feed, save HTML at output_filename and return an exit code."""
try:
output_file = open(output_filename, 'w')
exit_code = RunValidationOutputToFile(feed, options, output_file)
output_file.close()
except IOError as e:
print('Error while writing %s: %s' % (output_filename, e))
output_filename = None
exit_code = 2
if options.manual_entry and output_filename:
webbrowser.open('file://%s' % os.path.abspath(output_filename))
return exit_code | python | def RunValidationOutputToFilename(feed, options, output_filename):
"""Validate feed, save HTML at output_filename and return an exit code."""
try:
output_file = open(output_filename, 'w')
exit_code = RunValidationOutputToFile(feed, options, output_file)
output_file.close()
except IOError as e:
print('Error while writing %s: %s' % (output_filename, e))
output_filename = None
exit_code = 2
if options.manual_entry and output_filename:
webbrowser.open('file://%s' % os.path.abspath(output_filename))
return exit_code | [
"def",
"RunValidationOutputToFilename",
"(",
"feed",
",",
"options",
",",
"output_filename",
")",
":",
"try",
":",
"output_file",
"=",
"open",
"(",
"output_filename",
",",
"'w'",
")",
"exit_code",
"=",
"RunValidationOutputToFile",
"(",
"feed",
",",
"options",
",... | Validate feed, save HTML at output_filename and return an exit code. | [
"Validate",
"feed",
"save",
"HTML",
"at",
"output_filename",
"and",
"return",
"an",
"exit",
"code",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L511-L525 |
225,071 | google/transitfeed | feedvalidator.py | RunValidationOutputToFile | def RunValidationOutputToFile(feed, options, output_file):
"""Validate feed, write HTML to output_file and return an exit code."""
accumulator = HTMLCountingProblemAccumulator(options.limit_per_type,
options.error_types_ignore_list)
problems = transitfeed.ProblemReporter(accumulator)
schedule, exit_code = RunValidation(feed, options, problems)
if isinstance(feed, basestring):
feed_location = feed
else:
feed_location = getattr(feed, 'name', repr(feed))
accumulator.WriteOutput(feed_location, output_file, schedule, options.extension)
return exit_code | python | def RunValidationOutputToFile(feed, options, output_file):
"""Validate feed, write HTML to output_file and return an exit code."""
accumulator = HTMLCountingProblemAccumulator(options.limit_per_type,
options.error_types_ignore_list)
problems = transitfeed.ProblemReporter(accumulator)
schedule, exit_code = RunValidation(feed, options, problems)
if isinstance(feed, basestring):
feed_location = feed
else:
feed_location = getattr(feed, 'name', repr(feed))
accumulator.WriteOutput(feed_location, output_file, schedule, options.extension)
return exit_code | [
"def",
"RunValidationOutputToFile",
"(",
"feed",
",",
"options",
",",
"output_file",
")",
":",
"accumulator",
"=",
"HTMLCountingProblemAccumulator",
"(",
"options",
".",
"limit_per_type",
",",
"options",
".",
"error_types_ignore_list",
")",
"problems",
"=",
"transitfe... | Validate feed, write HTML to output_file and return an exit code. | [
"Validate",
"feed",
"write",
"HTML",
"to",
"output_file",
"and",
"return",
"an",
"exit",
"code",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L528-L539 |
225,072 | google/transitfeed | feedvalidator.py | RunValidationOutputToConsole | def RunValidationOutputToConsole(feed, options):
"""Validate feed, print reports and return an exit code."""
accumulator = CountingConsoleProblemAccumulator(
options.error_types_ignore_list)
problems = transitfeed.ProblemReporter(accumulator)
_, exit_code = RunValidation(feed, options, problems)
return exit_code | python | def RunValidationOutputToConsole(feed, options):
"""Validate feed, print reports and return an exit code."""
accumulator = CountingConsoleProblemAccumulator(
options.error_types_ignore_list)
problems = transitfeed.ProblemReporter(accumulator)
_, exit_code = RunValidation(feed, options, problems)
return exit_code | [
"def",
"RunValidationOutputToConsole",
"(",
"feed",
",",
"options",
")",
":",
"accumulator",
"=",
"CountingConsoleProblemAccumulator",
"(",
"options",
".",
"error_types_ignore_list",
")",
"problems",
"=",
"transitfeed",
".",
"ProblemReporter",
"(",
"accumulator",
")",
... | Validate feed, print reports and return an exit code. | [
"Validate",
"feed",
"print",
"reports",
"and",
"return",
"an",
"exit",
"code",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L542-L548 |
225,073 | google/transitfeed | feedvalidator.py | RunValidation | def RunValidation(feed, options, problems):
"""Validate feed, returning the loaded Schedule and exit code.
Args:
feed: GTFS file, either path of the file as a string or a file object
options: options object returned by optparse
problems: transitfeed.ProblemReporter instance
Returns:
a transitfeed.Schedule object, exit code and plain text string of other
problems
Exit code is 2 if an extension is provided but can't be loaded, 1 if
problems are found and 0 if the Schedule is problem free.
plain text string is '' if no other problems are found.
"""
util.CheckVersion(problems, options.latest_version)
# TODO: Add tests for this flag in testfeedvalidator.py
if options.extension:
try:
__import__(options.extension)
extension_module = sys.modules[options.extension]
except ImportError:
# TODO: Document extensions in a wiki page, place link here
print("Could not import extension %s! Please ensure it is a proper "
"Python module." % options.extension)
exit(2)
else:
extension_module = transitfeed
gtfs_factory = extension_module.GetGtfsFactory()
print('validating %s' % feed)
print('FeedValidator extension used: %s' % options.extension)
loader = gtfs_factory.Loader(feed, problems=problems, extra_validation=False,
memory_db=options.memory_db,
check_duplicate_trips=\
options.check_duplicate_trips,
gtfs_factory=gtfs_factory)
schedule = loader.Load()
# Start validation: children are already validated by the loader.
schedule.Validate(service_gap_interval=options.service_gap_interval,
validate_children=False)
if feed == 'IWantMyvalidation-crash.txt':
# See tests/testfeedvalidator.py
raise Exception('For testing the feed validator crash handler.')
accumulator = problems.GetAccumulator()
if accumulator.HasIssues():
print('ERROR: %s found' % accumulator.FormatCount())
return schedule, 1
else:
print('feed validated successfully')
return schedule, 0 | python | def RunValidation(feed, options, problems):
"""Validate feed, returning the loaded Schedule and exit code.
Args:
feed: GTFS file, either path of the file as a string or a file object
options: options object returned by optparse
problems: transitfeed.ProblemReporter instance
Returns:
a transitfeed.Schedule object, exit code and plain text string of other
problems
Exit code is 2 if an extension is provided but can't be loaded, 1 if
problems are found and 0 if the Schedule is problem free.
plain text string is '' if no other problems are found.
"""
util.CheckVersion(problems, options.latest_version)
# TODO: Add tests for this flag in testfeedvalidator.py
if options.extension:
try:
__import__(options.extension)
extension_module = sys.modules[options.extension]
except ImportError:
# TODO: Document extensions in a wiki page, place link here
print("Could not import extension %s! Please ensure it is a proper "
"Python module." % options.extension)
exit(2)
else:
extension_module = transitfeed
gtfs_factory = extension_module.GetGtfsFactory()
print('validating %s' % feed)
print('FeedValidator extension used: %s' % options.extension)
loader = gtfs_factory.Loader(feed, problems=problems, extra_validation=False,
memory_db=options.memory_db,
check_duplicate_trips=\
options.check_duplicate_trips,
gtfs_factory=gtfs_factory)
schedule = loader.Load()
# Start validation: children are already validated by the loader.
schedule.Validate(service_gap_interval=options.service_gap_interval,
validate_children=False)
if feed == 'IWantMyvalidation-crash.txt':
# See tests/testfeedvalidator.py
raise Exception('For testing the feed validator crash handler.')
accumulator = problems.GetAccumulator()
if accumulator.HasIssues():
print('ERROR: %s found' % accumulator.FormatCount())
return schedule, 1
else:
print('feed validated successfully')
return schedule, 0 | [
"def",
"RunValidation",
"(",
"feed",
",",
"options",
",",
"problems",
")",
":",
"util",
".",
"CheckVersion",
"(",
"problems",
",",
"options",
".",
"latest_version",
")",
"# TODO: Add tests for this flag in testfeedvalidator.py",
"if",
"options",
".",
"extension",
":... | Validate feed, returning the loaded Schedule and exit code.
Args:
feed: GTFS file, either path of the file as a string or a file object
options: options object returned by optparse
problems: transitfeed.ProblemReporter instance
Returns:
a transitfeed.Schedule object, exit code and plain text string of other
problems
Exit code is 2 if an extension is provided but can't be loaded, 1 if
problems are found and 0 if the Schedule is problem free.
plain text string is '' if no other problems are found. | [
"Validate",
"feed",
"returning",
"the",
"loaded",
"Schedule",
"and",
"exit",
"code",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L551-L605 |
225,074 | google/transitfeed | feedvalidator.py | RunValidationFromOptions | def RunValidationFromOptions(feed, options):
"""Validate feed, run in profiler if in options, and return an exit code."""
if options.performance:
return ProfileRunValidationOutputFromOptions(feed, options)
else:
return RunValidationOutputFromOptions(feed, options) | python | def RunValidationFromOptions(feed, options):
"""Validate feed, run in profiler if in options, and return an exit code."""
if options.performance:
return ProfileRunValidationOutputFromOptions(feed, options)
else:
return RunValidationOutputFromOptions(feed, options) | [
"def",
"RunValidationFromOptions",
"(",
"feed",
",",
"options",
")",
":",
"if",
"options",
".",
"performance",
":",
"return",
"ProfileRunValidationOutputFromOptions",
"(",
"feed",
",",
"options",
")",
"else",
":",
"return",
"RunValidationOutputFromOptions",
"(",
"fe... | Validate feed, run in profiler if in options, and return an exit code. | [
"Validate",
"feed",
"run",
"in",
"profiler",
"if",
"in",
"options",
"and",
"return",
"an",
"exit",
"code",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L700-L705 |
225,075 | google/transitfeed | feedvalidator.py | ProfileRunValidationOutputFromOptions | def ProfileRunValidationOutputFromOptions(feed, options):
"""Run RunValidationOutputFromOptions, print profile and return exit code."""
import cProfile
import pstats
# runctx will modify a dict, but not locals(). We need a way to get rv back.
locals_for_exec = locals()
cProfile.runctx('rv = RunValidationOutputFromOptions(feed, options)',
globals(), locals_for_exec, 'validate-stats')
# Only available on Unix, http://docs.python.org/lib/module-resource.html
import resource
print("Time: %d seconds" % (
resource.getrusage(resource.RUSAGE_SELF).ru_utime +
resource.getrusage(resource.RUSAGE_SELF).ru_stime))
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222
# http://aspn.activestate.com/ASPN/Cookbook/ "The recipes are freely
# available for review and use."
def _VmB(VmKey):
"""Return size from proc status in bytes."""
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
raise Exception("no proc file %s" % _proc_status)
return 0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
try:
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
except:
return 0 # v is empty
if len(v) < 3:
raise Exception("%s" % v)
return 0 # invalid format?
# convert Vm value to bytes
return int(float(v[1]) * _scale[v[2]])
# I ran this on over a hundred GTFS files, comparing VmSize to VmRSS
# (resident set size). The difference was always under 2% or 3MB.
print("Virtual Memory Size: %d bytes" % _VmB('VmSize:'))
# Output report of where CPU time was spent.
p = pstats.Stats('validate-stats')
p.strip_dirs()
p.sort_stats('cumulative').print_stats(30)
p.sort_stats('cumulative').print_callers(30)
return locals_for_exec['rv'] | python | def ProfileRunValidationOutputFromOptions(feed, options):
"""Run RunValidationOutputFromOptions, print profile and return exit code."""
import cProfile
import pstats
# runctx will modify a dict, but not locals(). We need a way to get rv back.
locals_for_exec = locals()
cProfile.runctx('rv = RunValidationOutputFromOptions(feed, options)',
globals(), locals_for_exec, 'validate-stats')
# Only available on Unix, http://docs.python.org/lib/module-resource.html
import resource
print("Time: %d seconds" % (
resource.getrusage(resource.RUSAGE_SELF).ru_utime +
resource.getrusage(resource.RUSAGE_SELF).ru_stime))
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222
# http://aspn.activestate.com/ASPN/Cookbook/ "The recipes are freely
# available for review and use."
def _VmB(VmKey):
"""Return size from proc status in bytes."""
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
raise Exception("no proc file %s" % _proc_status)
return 0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
try:
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
except:
return 0 # v is empty
if len(v) < 3:
raise Exception("%s" % v)
return 0 # invalid format?
# convert Vm value to bytes
return int(float(v[1]) * _scale[v[2]])
# I ran this on over a hundred GTFS files, comparing VmSize to VmRSS
# (resident set size). The difference was always under 2% or 3MB.
print("Virtual Memory Size: %d bytes" % _VmB('VmSize:'))
# Output report of where CPU time was spent.
p = pstats.Stats('validate-stats')
p.strip_dirs()
p.sort_stats('cumulative').print_stats(30)
p.sort_stats('cumulative').print_callers(30)
return locals_for_exec['rv'] | [
"def",
"ProfileRunValidationOutputFromOptions",
"(",
"feed",
",",
"options",
")",
":",
"import",
"cProfile",
"import",
"pstats",
"# runctx will modify a dict, but not locals(). We need a way to get rv back.",
"locals_for_exec",
"=",
"locals",
"(",
")",
"cProfile",
".",
"runct... | Run RunValidationOutputFromOptions, print profile and return exit code. | [
"Run",
"RunValidationOutputFromOptions",
"print",
"profile",
"and",
"return",
"exit",
"code",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L708-L762 |
225,076 | google/transitfeed | feedvalidator.py | HTMLCountingProblemAccumulator.FormatType | def FormatType(self, level_name, class_problist):
"""Write the HTML dumping all problems of one type.
Args:
level_name: string such as "Error" or "Warning"
class_problist: sequence of tuples (class name,
BoundedProblemList object)
Returns:
HTML in a string
"""
class_problist.sort()
output = []
for classname, problist in class_problist:
output.append('<h4 class="issueHeader"><a name="%s%s">%s</a></h4><ul>\n' %
(level_name, classname, UnCamelCase(classname)))
for e in problist.problems:
self.FormatException(e, output)
if problist.dropped_count:
output.append('<li>and %d more of this type.' %
(problist.dropped_count))
output.append('</ul>\n')
return ''.join(output) | python | def FormatType(self, level_name, class_problist):
"""Write the HTML dumping all problems of one type.
Args:
level_name: string such as "Error" or "Warning"
class_problist: sequence of tuples (class name,
BoundedProblemList object)
Returns:
HTML in a string
"""
class_problist.sort()
output = []
for classname, problist in class_problist:
output.append('<h4 class="issueHeader"><a name="%s%s">%s</a></h4><ul>\n' %
(level_name, classname, UnCamelCase(classname)))
for e in problist.problems:
self.FormatException(e, output)
if problist.dropped_count:
output.append('<li>and %d more of this type.' %
(problist.dropped_count))
output.append('</ul>\n')
return ''.join(output) | [
"def",
"FormatType",
"(",
"self",
",",
"level_name",
",",
"class_problist",
")",
":",
"class_problist",
".",
"sort",
"(",
")",
"output",
"=",
"[",
"]",
"for",
"classname",
",",
"problist",
"in",
"class_problist",
":",
"output",
".",
"append",
"(",
"'<h4 cl... | Write the HTML dumping all problems of one type.
Args:
level_name: string such as "Error" or "Warning"
class_problist: sequence of tuples (class name,
BoundedProblemList object)
Returns:
HTML in a string | [
"Write",
"the",
"HTML",
"dumping",
"all",
"problems",
"of",
"one",
"type",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L254-L276 |
225,077 | google/transitfeed | feedvalidator.py | HTMLCountingProblemAccumulator.FormatTypeSummaryTable | def FormatTypeSummaryTable(self, level_name, name_to_problist):
"""Return an HTML table listing the number of problems by class name.
Args:
level_name: string such as "Error" or "Warning"
name_to_problist: dict mapping class name to an BoundedProblemList object
Returns:
HTML in a string
"""
output = []
output.append('<table>')
for classname in sorted(name_to_problist.keys()):
problist = name_to_problist[classname]
human_name = MaybePluralizeWord(problist.count, UnCamelCase(classname))
output.append('<tr><td>%d</td><td><a href="#%s%s">%s</a></td></tr>\n' %
(problist.count, level_name, classname, human_name))
output.append('</table>\n')
return ''.join(output) | python | def FormatTypeSummaryTable(self, level_name, name_to_problist):
"""Return an HTML table listing the number of problems by class name.
Args:
level_name: string such as "Error" or "Warning"
name_to_problist: dict mapping class name to an BoundedProblemList object
Returns:
HTML in a string
"""
output = []
output.append('<table>')
for classname in sorted(name_to_problist.keys()):
problist = name_to_problist[classname]
human_name = MaybePluralizeWord(problist.count, UnCamelCase(classname))
output.append('<tr><td>%d</td><td><a href="#%s%s">%s</a></td></tr>\n' %
(problist.count, level_name, classname, human_name))
output.append('</table>\n')
return ''.join(output) | [
"def",
"FormatTypeSummaryTable",
"(",
"self",
",",
"level_name",
",",
"name_to_problist",
")",
":",
"output",
"=",
"[",
"]",
"output",
".",
"append",
"(",
"'<table>'",
")",
"for",
"classname",
"in",
"sorted",
"(",
"name_to_problist",
".",
"keys",
"(",
")",
... | Return an HTML table listing the number of problems by class name.
Args:
level_name: string such as "Error" or "Warning"
name_to_problist: dict mapping class name to an BoundedProblemList object
Returns:
HTML in a string | [
"Return",
"an",
"HTML",
"table",
"listing",
"the",
"number",
"of",
"problems",
"by",
"class",
"name",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L278-L296 |
225,078 | google/transitfeed | feedvalidator.py | HTMLCountingProblemAccumulator.FormatException | def FormatException(self, e, output):
"""Append HTML version of e to list output."""
d = e.GetDictToFormat()
for k in ('file_name', 'feedname', 'column_name'):
if k in d.keys():
d[k] = '<code>%s</code>' % d[k]
if 'url' in d.keys():
d['url'] = '<a href="%(url)s">%(url)s</a>' % d
problem_text = e.FormatProblem(d).replace('\n', '<br>')
problem_class = 'problem'
if e.IsNotice():
problem_class += ' notice'
output.append('<li>')
output.append('<div class="%s">%s</div>' %
(problem_class, transitfeed.EncodeUnicode(problem_text)))
try:
if hasattr(e, 'row_num'):
line_str = 'line %d of ' % e.row_num
else:
line_str = ''
output.append('in %s<code>%s</code><br>\n' %
(line_str, transitfeed.EncodeUnicode(e.file_name)))
row = e.row
headers = e.headers
column_name = e.column_name
table_header = '' # HTML
table_data = '' # HTML
for header, value in zip(headers, row):
attributes = ''
if header == column_name:
attributes = ' class="problem"'
table_header += '<th%s>%s</th>' % (attributes, header)
table_data += '<td%s>%s</td>' % (attributes, value)
# Make sure output is encoded into UTF-8
output.append('<table class="dump"><tr>%s</tr>\n' %
transitfeed.EncodeUnicode(table_header))
output.append('<tr>%s</tr></table>\n' %
transitfeed.EncodeUnicode(table_data))
except AttributeError as e:
pass # Hope this was getting an attribute from e ;-)
output.append('<br></li>\n') | python | def FormatException(self, e, output):
"""Append HTML version of e to list output."""
d = e.GetDictToFormat()
for k in ('file_name', 'feedname', 'column_name'):
if k in d.keys():
d[k] = '<code>%s</code>' % d[k]
if 'url' in d.keys():
d['url'] = '<a href="%(url)s">%(url)s</a>' % d
problem_text = e.FormatProblem(d).replace('\n', '<br>')
problem_class = 'problem'
if e.IsNotice():
problem_class += ' notice'
output.append('<li>')
output.append('<div class="%s">%s</div>' %
(problem_class, transitfeed.EncodeUnicode(problem_text)))
try:
if hasattr(e, 'row_num'):
line_str = 'line %d of ' % e.row_num
else:
line_str = ''
output.append('in %s<code>%s</code><br>\n' %
(line_str, transitfeed.EncodeUnicode(e.file_name)))
row = e.row
headers = e.headers
column_name = e.column_name
table_header = '' # HTML
table_data = '' # HTML
for header, value in zip(headers, row):
attributes = ''
if header == column_name:
attributes = ' class="problem"'
table_header += '<th%s>%s</th>' % (attributes, header)
table_data += '<td%s>%s</td>' % (attributes, value)
# Make sure output is encoded into UTF-8
output.append('<table class="dump"><tr>%s</tr>\n' %
transitfeed.EncodeUnicode(table_header))
output.append('<tr>%s</tr></table>\n' %
transitfeed.EncodeUnicode(table_data))
except AttributeError as e:
pass # Hope this was getting an attribute from e ;-)
output.append('<br></li>\n') | [
"def",
"FormatException",
"(",
"self",
",",
"e",
",",
"output",
")",
":",
"d",
"=",
"e",
".",
"GetDictToFormat",
"(",
")",
"for",
"k",
"in",
"(",
"'file_name'",
",",
"'feedname'",
",",
"'column_name'",
")",
":",
"if",
"k",
"in",
"d",
".",
"keys",
"... | Append HTML version of e to list output. | [
"Append",
"HTML",
"version",
"of",
"e",
"to",
"list",
"output",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L298-L339 |
225,079 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.GetDateRange | def GetDateRange(self):
"""Return the range over which this ServicePeriod is valid.
The range includes exception dates that add service outside of
(start_date, end_date), but doesn't shrink the range if exception
dates take away service at the edges of the range.
Returns:
A tuple of "YYYYMMDD" strings, (start date, end date) or (None, None) if
no dates have been given.
"""
start = self.start_date
end = self.end_date
for date, (exception_type, _) in self.date_exceptions.items():
if exception_type == self._EXCEPTION_TYPE_REMOVE:
continue
if not start or (date < start):
start = date
if not end or (date > end):
end = date
if start is None:
start = end
elif end is None:
end = start
# If start and end are None we did a little harmless shuffling
return (start, end) | python | def GetDateRange(self):
"""Return the range over which this ServicePeriod is valid.
The range includes exception dates that add service outside of
(start_date, end_date), but doesn't shrink the range if exception
dates take away service at the edges of the range.
Returns:
A tuple of "YYYYMMDD" strings, (start date, end date) or (None, None) if
no dates have been given.
"""
start = self.start_date
end = self.end_date
for date, (exception_type, _) in self.date_exceptions.items():
if exception_type == self._EXCEPTION_TYPE_REMOVE:
continue
if not start or (date < start):
start = date
if not end or (date > end):
end = date
if start is None:
start = end
elif end is None:
end = start
# If start and end are None we did a little harmless shuffling
return (start, end) | [
"def",
"GetDateRange",
"(",
"self",
")",
":",
"start",
"=",
"self",
".",
"start_date",
"end",
"=",
"self",
".",
"end_date",
"for",
"date",
",",
"(",
"exception_type",
",",
"_",
")",
"in",
"self",
".",
"date_exceptions",
".",
"items",
"(",
")",
":",
"... | Return the range over which this ServicePeriod is valid.
The range includes exception dates that add service outside of
(start_date, end_date), but doesn't shrink the range if exception
dates take away service at the edges of the range.
Returns:
A tuple of "YYYYMMDD" strings, (start date, end date) or (None, None) if
no dates have been given. | [
"Return",
"the",
"range",
"over",
"which",
"this",
"ServicePeriod",
"is",
"valid",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L78-L104 |
225,080 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.GetCalendarFieldValuesTuple | def GetCalendarFieldValuesTuple(self):
"""Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt ."""
if self.start_date and self.end_date:
return [getattr(self, fn) for fn in self._FIELD_NAMES] | python | def GetCalendarFieldValuesTuple(self):
"""Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt ."""
if self.start_date and self.end_date:
return [getattr(self, fn) for fn in self._FIELD_NAMES] | [
"def",
"GetCalendarFieldValuesTuple",
"(",
"self",
")",
":",
"if",
"self",
".",
"start_date",
"and",
"self",
".",
"end_date",
":",
"return",
"[",
"getattr",
"(",
"self",
",",
"fn",
")",
"for",
"fn",
"in",
"self",
".",
"_FIELD_NAMES",
"]"
] | Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt . | [
"Return",
"the",
"tuple",
"of",
"calendar",
".",
"txt",
"values",
"or",
"None",
"if",
"this",
"ServicePeriod",
"should",
"not",
"be",
"in",
"calendar",
".",
"txt",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L106-L110 |
225,081 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.GenerateCalendarDatesFieldValuesTuples | def GenerateCalendarDatesFieldValuesTuples(self):
"""Generates tuples of calendar_dates.txt values. Yield zero tuples if
this ServicePeriod should not be in calendar_dates.txt ."""
for date, (exception_type, _) in self.date_exceptions.items():
yield (self.service_id, date, unicode(exception_type)) | python | def GenerateCalendarDatesFieldValuesTuples(self):
"""Generates tuples of calendar_dates.txt values. Yield zero tuples if
this ServicePeriod should not be in calendar_dates.txt ."""
for date, (exception_type, _) in self.date_exceptions.items():
yield (self.service_id, date, unicode(exception_type)) | [
"def",
"GenerateCalendarDatesFieldValuesTuples",
"(",
"self",
")",
":",
"for",
"date",
",",
"(",
"exception_type",
",",
"_",
")",
"in",
"self",
".",
"date_exceptions",
".",
"items",
"(",
")",
":",
"yield",
"(",
"self",
".",
"service_id",
",",
"date",
",",
... | Generates tuples of calendar_dates.txt values. Yield zero tuples if
this ServicePeriod should not be in calendar_dates.txt . | [
"Generates",
"tuples",
"of",
"calendar_dates",
".",
"txt",
"values",
".",
"Yield",
"zero",
"tuples",
"if",
"this",
"ServicePeriod",
"should",
"not",
"be",
"in",
"calendar_dates",
".",
"txt",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L112-L116 |
225,082 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.GetCalendarDatesFieldValuesTuples | def GetCalendarDatesFieldValuesTuples(self):
"""Return a list of date execeptions"""
result = []
for date_tuple in self.GenerateCalendarDatesFieldValuesTuples():
result.append(date_tuple)
result.sort() # helps with __eq__
return result | python | def GetCalendarDatesFieldValuesTuples(self):
"""Return a list of date execeptions"""
result = []
for date_tuple in self.GenerateCalendarDatesFieldValuesTuples():
result.append(date_tuple)
result.sort() # helps with __eq__
return result | [
"def",
"GetCalendarDatesFieldValuesTuples",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"date_tuple",
"in",
"self",
".",
"GenerateCalendarDatesFieldValuesTuples",
"(",
")",
":",
"result",
".",
"append",
"(",
"date_tuple",
")",
"result",
".",
"sort",
... | Return a list of date execeptions | [
"Return",
"a",
"list",
"of",
"date",
"execeptions"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L118-L124 |
225,083 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.HasDateExceptionOn | def HasDateExceptionOn(self, date, exception_type=_EXCEPTION_TYPE_ADD):
"""Test if this service period has a date exception of the given type.
Args:
date: a string of form "YYYYMMDD"
exception_type: the exception type the date should have. Defaults to
_EXCEPTION_TYPE_ADD
Returns:
True iff this service has service exception of specified type at date.
"""
if date in self.date_exceptions:
return exception_type == self.date_exceptions[date][0]
return False | python | def HasDateExceptionOn(self, date, exception_type=_EXCEPTION_TYPE_ADD):
"""Test if this service period has a date exception of the given type.
Args:
date: a string of form "YYYYMMDD"
exception_type: the exception type the date should have. Defaults to
_EXCEPTION_TYPE_ADD
Returns:
True iff this service has service exception of specified type at date.
"""
if date in self.date_exceptions:
return exception_type == self.date_exceptions[date][0]
return False | [
"def",
"HasDateExceptionOn",
"(",
"self",
",",
"date",
",",
"exception_type",
"=",
"_EXCEPTION_TYPE_ADD",
")",
":",
"if",
"date",
"in",
"self",
".",
"date_exceptions",
":",
"return",
"exception_type",
"==",
"self",
".",
"date_exceptions",
"[",
"date",
"]",
"["... | Test if this service period has a date exception of the given type.
Args:
date: a string of form "YYYYMMDD"
exception_type: the exception type the date should have. Defaults to
_EXCEPTION_TYPE_ADD
Returns:
True iff this service has service exception of specified type at date. | [
"Test",
"if",
"this",
"service",
"period",
"has",
"a",
"date",
"exception",
"of",
"the",
"given",
"type",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L177-L190 |
225,084 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.IsActiveOn | def IsActiveOn(self, date, date_object=None):
"""Test if this service period is active on a date.
Args:
date: a string of form "YYYYMMDD"
date_object: a date object representing the same date as date.
This parameter is optional, and present only for performance
reasons.
If the caller constructs the date string from a date object
that date object can be passed directly, thus avoiding the
costly conversion from string to date object.
Returns:
True iff this service is active on date.
"""
if date in self.date_exceptions:
exception_type, _ = self.date_exceptions[date]
if exception_type == self._EXCEPTION_TYPE_ADD:
return True
else:
return False
if (self.start_date and self.end_date and self.start_date <= date and
date <= self.end_date):
if date_object is None:
date_object = util.DateStringToDateObject(date)
return self.day_of_week[date_object.weekday()]
return False | python | def IsActiveOn(self, date, date_object=None):
"""Test if this service period is active on a date.
Args:
date: a string of form "YYYYMMDD"
date_object: a date object representing the same date as date.
This parameter is optional, and present only for performance
reasons.
If the caller constructs the date string from a date object
that date object can be passed directly, thus avoiding the
costly conversion from string to date object.
Returns:
True iff this service is active on date.
"""
if date in self.date_exceptions:
exception_type, _ = self.date_exceptions[date]
if exception_type == self._EXCEPTION_TYPE_ADD:
return True
else:
return False
if (self.start_date and self.end_date and self.start_date <= date and
date <= self.end_date):
if date_object is None:
date_object = util.DateStringToDateObject(date)
return self.day_of_week[date_object.weekday()]
return False | [
"def",
"IsActiveOn",
"(",
"self",
",",
"date",
",",
"date_object",
"=",
"None",
")",
":",
"if",
"date",
"in",
"self",
".",
"date_exceptions",
":",
"exception_type",
",",
"_",
"=",
"self",
".",
"date_exceptions",
"[",
"date",
"]",
"if",
"exception_type",
... | Test if this service period is active on a date.
Args:
date: a string of form "YYYYMMDD"
date_object: a date object representing the same date as date.
This parameter is optional, and present only for performance
reasons.
If the caller constructs the date string from a date object
that date object can be passed directly, thus avoiding the
costly conversion from string to date object.
Returns:
True iff this service is active on date. | [
"Test",
"if",
"this",
"service",
"period",
"is",
"active",
"on",
"a",
"date",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L192-L218 |
225,085 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.ActiveDates | def ActiveDates(self):
"""Return dates this service period is active as a list of "YYYYMMDD"."""
(earliest, latest) = self.GetDateRange()
if earliest is None:
return []
dates = []
date_it = util.DateStringToDateObject(earliest)
date_end = util.DateStringToDateObject(latest)
delta = datetime.timedelta(days=1)
while date_it <= date_end:
date_it_string = date_it.strftime("%Y%m%d")
if self.IsActiveOn(date_it_string, date_it):
dates.append(date_it_string)
date_it = date_it + delta
return dates | python | def ActiveDates(self):
"""Return dates this service period is active as a list of "YYYYMMDD"."""
(earliest, latest) = self.GetDateRange()
if earliest is None:
return []
dates = []
date_it = util.DateStringToDateObject(earliest)
date_end = util.DateStringToDateObject(latest)
delta = datetime.timedelta(days=1)
while date_it <= date_end:
date_it_string = date_it.strftime("%Y%m%d")
if self.IsActiveOn(date_it_string, date_it):
dates.append(date_it_string)
date_it = date_it + delta
return dates | [
"def",
"ActiveDates",
"(",
"self",
")",
":",
"(",
"earliest",
",",
"latest",
")",
"=",
"self",
".",
"GetDateRange",
"(",
")",
"if",
"earliest",
"is",
"None",
":",
"return",
"[",
"]",
"dates",
"=",
"[",
"]",
"date_it",
"=",
"util",
".",
"DateStringToD... | Return dates this service period is active as a list of "YYYYMMDD". | [
"Return",
"dates",
"this",
"service",
"period",
"is",
"active",
"as",
"a",
"list",
"of",
"YYYYMMDD",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L220-L234 |
225,086 | google/transitfeed | transitfeed/agency.py | Agency.Validate | def Validate(self, problems=default_problem_reporter):
"""Validate attribute values and this object's internal consistency.
Returns:
True iff all validation checks passed.
"""
found_problem = False
found_problem = ((not util.ValidateRequiredFieldsAreNotEmpty(
self, self._REQUIRED_FIELD_NAMES, problems))
or found_problem)
found_problem = self.ValidateAgencyUrl(problems) or found_problem
found_problem = self.ValidateAgencyLang(problems) or found_problem
found_problem = self.ValidateAgencyTimezone(problems) or found_problem
found_problem = self.ValidateAgencyFareUrl(problems) or found_problem
found_problem = self.ValidateAgencyEmail(problems) or found_problem
return not found_problem | python | def Validate(self, problems=default_problem_reporter):
"""Validate attribute values and this object's internal consistency.
Returns:
True iff all validation checks passed.
"""
found_problem = False
found_problem = ((not util.ValidateRequiredFieldsAreNotEmpty(
self, self._REQUIRED_FIELD_NAMES, problems))
or found_problem)
found_problem = self.ValidateAgencyUrl(problems) or found_problem
found_problem = self.ValidateAgencyLang(problems) or found_problem
found_problem = self.ValidateAgencyTimezone(problems) or found_problem
found_problem = self.ValidateAgencyFareUrl(problems) or found_problem
found_problem = self.ValidateAgencyEmail(problems) or found_problem
return not found_problem | [
"def",
"Validate",
"(",
"self",
",",
"problems",
"=",
"default_problem_reporter",
")",
":",
"found_problem",
"=",
"False",
"found_problem",
"=",
"(",
"(",
"not",
"util",
".",
"ValidateRequiredFieldsAreNotEmpty",
"(",
"self",
",",
"self",
".",
"_REQUIRED_FIELD_NAME... | Validate attribute values and this object's internal consistency.
Returns:
True iff all validation checks passed. | [
"Validate",
"attribute",
"values",
"and",
"this",
"object",
"s",
"internal",
"consistency",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/agency.py#L88-L104 |
225,087 | google/transitfeed | misc/import_ch_zurich.py | ConvertCH1903 | def ConvertCH1903(x, y):
"Converts coordinates from the 1903 Swiss national grid system to WGS-84."
yb = (x - 600000.0) / 1e6;
xb = (y - 200000.0) / 1e6;
lam = 2.6779094 \
+ 4.728982 * yb \
+ 0.791484 * yb * xb \
+ 0.1306 * yb * xb * xb \
- 0.0436 * yb * yb * yb
phi = 16.9023892 \
+ 3.238372 * xb \
- 0.270978 * yb * yb \
- 0.002582 * xb * xb \
- 0.0447 * yb * yb * xb \
- 0.0140 * xb * xb * xb
return (phi * 100.0 / 36.0, lam * 100.0 / 36.0) | python | def ConvertCH1903(x, y):
"Converts coordinates from the 1903 Swiss national grid system to WGS-84."
yb = (x - 600000.0) / 1e6;
xb = (y - 200000.0) / 1e6;
lam = 2.6779094 \
+ 4.728982 * yb \
+ 0.791484 * yb * xb \
+ 0.1306 * yb * xb * xb \
- 0.0436 * yb * yb * yb
phi = 16.9023892 \
+ 3.238372 * xb \
- 0.270978 * yb * yb \
- 0.002582 * xb * xb \
- 0.0447 * yb * yb * xb \
- 0.0140 * xb * xb * xb
return (phi * 100.0 / 36.0, lam * 100.0 / 36.0) | [
"def",
"ConvertCH1903",
"(",
"x",
",",
"y",
")",
":",
"yb",
"=",
"(",
"x",
"-",
"600000.0",
")",
"/",
"1e6",
"xb",
"=",
"(",
"y",
"-",
"200000.0",
")",
"/",
"1e6",
"lam",
"=",
"2.6779094",
"+",
"4.728982",
"*",
"yb",
"+",
"0.791484",
"*",
"yb",... | Converts coordinates from the 1903 Swiss national grid system to WGS-84. | [
"Converts",
"coordinates",
"from",
"the",
"1903",
"Swiss",
"national",
"grid",
"system",
"to",
"WGS",
"-",
"84",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L96-L111 |
225,088 | google/transitfeed | misc/import_ch_zurich.py | EncodeForCSV | def EncodeForCSV(x):
"Encodes one value for CSV."
k = x.encode('utf-8')
if ',' in k or '"' in k:
return '"%s"' % k.replace('"', '""')
else:
return k | python | def EncodeForCSV(x):
"Encodes one value for CSV."
k = x.encode('utf-8')
if ',' in k or '"' in k:
return '"%s"' % k.replace('"', '""')
else:
return k | [
"def",
"EncodeForCSV",
"(",
"x",
")",
":",
"k",
"=",
"x",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"','",
"in",
"k",
"or",
"'\"'",
"in",
"k",
":",
"return",
"'\"%s\"'",
"%",
"k",
".",
"replace",
"(",
"'\"'",
",",
"'\"\"'",
")",
"else",
":",
"r... | Encodes one value for CSV. | [
"Encodes",
"one",
"value",
"for",
"CSV",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L114-L120 |
225,089 | google/transitfeed | misc/import_ch_zurich.py | WriteRow | def WriteRow(stream, values):
"Writes one row of comma-separated values to stream."
stream.write(','.join([EncodeForCSV(val) for val in values]))
stream.write('\n') | python | def WriteRow(stream, values):
"Writes one row of comma-separated values to stream."
stream.write(','.join([EncodeForCSV(val) for val in values]))
stream.write('\n') | [
"def",
"WriteRow",
"(",
"stream",
",",
"values",
")",
":",
"stream",
".",
"write",
"(",
"','",
".",
"join",
"(",
"[",
"EncodeForCSV",
"(",
"val",
")",
"for",
"val",
"in",
"values",
"]",
")",
")",
"stream",
".",
"write",
"(",
"'\\n'",
")"
] | Writes one row of comma-separated values to stream. | [
"Writes",
"one",
"row",
"of",
"comma",
"-",
"separated",
"values",
"to",
"stream",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L123-L126 |
225,090 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportStations | def ImportStations(self, station_file, adv_file):
"Imports the rec_ort.mdv file."
for id, name, x, y, uic_code in \
ReadCSV(station_file, ['ORT_NR', 'ORT_NAME',
'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']):
station = Station()
station.id = id
station.position = self.coord_converter(float(x), float(y))
station.uic_code = ''
if uic_code and len(uic_code) == 7 and uic_code[:2] == '85':
station.uic_code = uic_code
station.name, station.city = self.DemangleName(name)
station.country = 'CH'
station.url = 'http://fahrplan.zvv.ch/?to.0=' + \
urllib.quote(name.encode('iso-8859-1'))
station.advertised_lines = set()
self.stations[id] = station
for station_id, line_id in ReadCSV(adv_file, ['ORT_NR', 'LI_NR']):
if station_id in self.stations:
# Line ids in this file have leading zeroes, remove.
self.stations[station_id].advertised_lines.add(line_id.lstrip("0"))
else:
print("Warning, advertised lines file references " \
"unknown station, id " + station_id) | python | def ImportStations(self, station_file, adv_file):
"Imports the rec_ort.mdv file."
for id, name, x, y, uic_code in \
ReadCSV(station_file, ['ORT_NR', 'ORT_NAME',
'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']):
station = Station()
station.id = id
station.position = self.coord_converter(float(x), float(y))
station.uic_code = ''
if uic_code and len(uic_code) == 7 and uic_code[:2] == '85':
station.uic_code = uic_code
station.name, station.city = self.DemangleName(name)
station.country = 'CH'
station.url = 'http://fahrplan.zvv.ch/?to.0=' + \
urllib.quote(name.encode('iso-8859-1'))
station.advertised_lines = set()
self.stations[id] = station
for station_id, line_id in ReadCSV(adv_file, ['ORT_NR', 'LI_NR']):
if station_id in self.stations:
# Line ids in this file have leading zeroes, remove.
self.stations[station_id].advertised_lines.add(line_id.lstrip("0"))
else:
print("Warning, advertised lines file references " \
"unknown station, id " + station_id) | [
"def",
"ImportStations",
"(",
"self",
",",
"station_file",
",",
"adv_file",
")",
":",
"for",
"id",
",",
"name",
",",
"x",
",",
"y",
",",
"uic_code",
"in",
"ReadCSV",
"(",
"station_file",
",",
"[",
"'ORT_NR'",
",",
"'ORT_NAME'",
",",
"'ORT_POS_X'",
",",
... | Imports the rec_ort.mdv file. | [
"Imports",
"the",
"rec_ort",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L207-L230 |
225,091 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportRoutes | def ImportRoutes(self, s):
"Imports the rec_lin_ber.mdv file."
# the line id is really qualified with an area_id (BEREICH_NR), but the
# table of advertised lines does not include area. Fortunately, it seems
# that line ids are unique across all areas, so we can just throw it away.
for line_id, name in \
ReadCSV(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']):
route = Route()
route.id = line_id
route.name = name
route.color = "FFFFFF"
route.color_text = "000000"
if name in TRAM_LINES:
route.type = TYPE_TRAM
route.color = TRAM_LINES[name][0]
route.color_text = TRAM_LINES[name][1]
else:
route.type = TYPE_BUS
if route.name[0:1]=="N":
route.color = "000000"
route.color_text = "FFFF00"
self.routes[route.id] = route | python | def ImportRoutes(self, s):
"Imports the rec_lin_ber.mdv file."
# the line id is really qualified with an area_id (BEREICH_NR), but the
# table of advertised lines does not include area. Fortunately, it seems
# that line ids are unique across all areas, so we can just throw it away.
for line_id, name in \
ReadCSV(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']):
route = Route()
route.id = line_id
route.name = name
route.color = "FFFFFF"
route.color_text = "000000"
if name in TRAM_LINES:
route.type = TYPE_TRAM
route.color = TRAM_LINES[name][0]
route.color_text = TRAM_LINES[name][1]
else:
route.type = TYPE_BUS
if route.name[0:1]=="N":
route.color = "000000"
route.color_text = "FFFF00"
self.routes[route.id] = route | [
"def",
"ImportRoutes",
"(",
"self",
",",
"s",
")",
":",
"# the line id is really qualified with an area_id (BEREICH_NR), but the",
"# table of advertised lines does not include area. Fortunately, it seems",
"# that line ids are unique across all areas, so we can just throw it away.",
"for",
... | Imports the rec_lin_ber.mdv file. | [
"Imports",
"the",
"rec_lin_ber",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L232-L253 |
225,092 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportPatterns | def ImportPatterns(self, s):
"Imports the lid_verlauf.mdv file."
for line, strli, direction, seq, station_id in \
ReadCSV(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']):
pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
pattern = self.patterns.get(pattern_id, None)
if not pattern:
pattern = Pattern()
pattern.id = pattern_id
pattern.stops = []
pattern.stoptimes = {}
self.patterns[pattern_id] = pattern
seq = int(seq) - 1
if len(pattern.stops) <= seq:
pattern.stops.extend([None] * (seq - len(pattern.stops) + 1))
pattern.stops[seq] = station_id | python | def ImportPatterns(self, s):
"Imports the lid_verlauf.mdv file."
for line, strli, direction, seq, station_id in \
ReadCSV(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']):
pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
pattern = self.patterns.get(pattern_id, None)
if not pattern:
pattern = Pattern()
pattern.id = pattern_id
pattern.stops = []
pattern.stoptimes = {}
self.patterns[pattern_id] = pattern
seq = int(seq) - 1
if len(pattern.stops) <= seq:
pattern.stops.extend([None] * (seq - len(pattern.stops) + 1))
pattern.stops[seq] = station_id | [
"def",
"ImportPatterns",
"(",
"self",
",",
"s",
")",
":",
"for",
"line",
",",
"strli",
",",
"direction",
",",
"seq",
",",
"station_id",
"in",
"ReadCSV",
"(",
"s",
",",
"[",
"'LI_NR'",
",",
"'STR_LI_VAR'",
",",
"'LI_RI_NR'",
",",
"'LI_LFD_NR'",
",",
"'O... | Imports the lid_verlauf.mdv file. | [
"Imports",
"the",
"lid_verlauf",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L255-L270 |
225,093 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportBoarding | def ImportBoarding(self, drop_off_file):
"Reads the bedverb.mdv file."
for trip_id, seq, code in \
ReadCSV(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']):
key = (trip_id, int(seq) - 1)
if code == 'A':
self.pickup_type[key] = '1' # '1' = no pick-up
elif code == 'E':
self.drop_off_type[key] = '1' # '1' = no drop-off
elif code == 'B' :
# 'B' just means that rider needs to push a button to have the driver
# stop. We don't encode this for now.
pass
else:
raise ValueError('Unexpected code in bedverb.mdv; '
'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) | python | def ImportBoarding(self, drop_off_file):
"Reads the bedverb.mdv file."
for trip_id, seq, code in \
ReadCSV(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']):
key = (trip_id, int(seq) - 1)
if code == 'A':
self.pickup_type[key] = '1' # '1' = no pick-up
elif code == 'E':
self.drop_off_type[key] = '1' # '1' = no drop-off
elif code == 'B' :
# 'B' just means that rider needs to push a button to have the driver
# stop. We don't encode this for now.
pass
else:
raise ValueError('Unexpected code in bedverb.mdv; '
'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) | [
"def",
"ImportBoarding",
"(",
"self",
",",
"drop_off_file",
")",
":",
"for",
"trip_id",
",",
"seq",
",",
"code",
"in",
"ReadCSV",
"(",
"drop_off_file",
",",
"[",
"'FRT_FID'",
",",
"'LI_LFD_NR'",
",",
"'BEDVERB_CODE'",
"]",
")",
":",
"key",
"=",
"(",
"tri... | Reads the bedverb.mdv file. | [
"Reads",
"the",
"bedverb",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L272-L287 |
225,094 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportTrafficRestrictions | def ImportTrafficRestrictions(self, restrictions_file):
"Reads the vb_regio.mdv file."
ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8]))
MonthNr = lambda x: int(x[:4]) * 12 + int(x[4:6])
for schedule, id, bitmask, start_date, end_date in \
ReadCSV(restrictions_file,
['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']):
id = u"VB%s.%s" % (schedule, id)
bitmask = bitmask.strip()
dates = {}
# This is ugly as hell, I know. I briefly explain what I do:
# 8 characters in the bitmask equal a month ( 8 * 4bits = 32, no month has
# more than 31 days, so it's ok).
# Then I check if the current day of the month is in the bitmask (by
# shifting the bit by x days and comparing it to the bitmask).
# If so I calculate back what year month and actual day I am in
# (very disgusting) and mark that date...
for i in range(MonthNr(end_date) - MonthNr(start_date)+1):
mask=int(bitmask[i*8:i*8+8], 16)
for d in range(32):
if 1 << d & mask:
year=int(start_date[0:4])+ ((int(start_date[4:6]) + i -1 )) / 12
month=((int(start_date[4:6]) + i-1 ) % 12) +1
day=d+1
cur_date = str(year)+("0"+str(month))[-2:]+("0"+str(day))[-2:]
dates[int(cur_date)] = 1
self.services[id] = dates.keys()
self.services[id].sort() | python | def ImportTrafficRestrictions(self, restrictions_file):
"Reads the vb_regio.mdv file."
ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8]))
MonthNr = lambda x: int(x[:4]) * 12 + int(x[4:6])
for schedule, id, bitmask, start_date, end_date in \
ReadCSV(restrictions_file,
['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']):
id = u"VB%s.%s" % (schedule, id)
bitmask = bitmask.strip()
dates = {}
# This is ugly as hell, I know. I briefly explain what I do:
# 8 characters in the bitmask equal a month ( 8 * 4bits = 32, no month has
# more than 31 days, so it's ok).
# Then I check if the current day of the month is in the bitmask (by
# shifting the bit by x days and comparing it to the bitmask).
# If so I calculate back what year month and actual day I am in
# (very disgusting) and mark that date...
for i in range(MonthNr(end_date) - MonthNr(start_date)+1):
mask=int(bitmask[i*8:i*8+8], 16)
for d in range(32):
if 1 << d & mask:
year=int(start_date[0:4])+ ((int(start_date[4:6]) + i -1 )) / 12
month=((int(start_date[4:6]) + i-1 ) % 12) +1
day=d+1
cur_date = str(year)+("0"+str(month))[-2:]+("0"+str(day))[-2:]
dates[int(cur_date)] = 1
self.services[id] = dates.keys()
self.services[id].sort() | [
"def",
"ImportTrafficRestrictions",
"(",
"self",
",",
"restrictions_file",
")",
":",
"ParseDate",
"=",
"lambda",
"x",
":",
"datetime",
".",
"date",
"(",
"int",
"(",
"x",
"[",
":",
"4",
"]",
")",
",",
"int",
"(",
"x",
"[",
"4",
":",
"6",
"]",
")",
... | Reads the vb_regio.mdv file. | [
"Reads",
"the",
"vb_regio",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L310-L338 |
225,095 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportStopTimes | def ImportStopTimes(self, stoptimes_file):
"Imports the lid_fahrzeitart.mdv file."
for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \
ReadCSV(stoptimes_file,
['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR',
'FGR_NR', 'FZT_REL', 'HZEIT']):
pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)]
stoptimes = pattern.stoptimes.setdefault(stoptime_id, [])
seq = int(seq) - 1
drive_secs = int(drive_secs)
wait_secs = int(wait_secs)
assert len(stoptimes) == seq # fails if seq not in order
stoptimes.append((drive_secs, wait_secs)) | python | def ImportStopTimes(self, stoptimes_file):
"Imports the lid_fahrzeitart.mdv file."
for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \
ReadCSV(stoptimes_file,
['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR',
'FGR_NR', 'FZT_REL', 'HZEIT']):
pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)]
stoptimes = pattern.stoptimes.setdefault(stoptime_id, [])
seq = int(seq) - 1
drive_secs = int(drive_secs)
wait_secs = int(wait_secs)
assert len(stoptimes) == seq # fails if seq not in order
stoptimes.append((drive_secs, wait_secs)) | [
"def",
"ImportStopTimes",
"(",
"self",
",",
"stoptimes_file",
")",
":",
"for",
"line",
",",
"strli",
",",
"direction",
",",
"seq",
",",
"stoptime_id",
",",
"drive_secs",
",",
"wait_secs",
"in",
"ReadCSV",
"(",
"stoptimes_file",
",",
"[",
"'LI_NR'",
",",
"'... | Imports the lid_fahrzeitart.mdv file. | [
"Imports",
"the",
"lid_fahrzeitart",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L340-L352 |
225,096 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportTrips | def ImportTrips(self, trips_file):
"Imports the rec_frt.mdv file."
for trip_id, trip_starttime, line, strli, direction, \
stoptime_id, schedule_id, daytype_id, restriction_id, \
dest_station_id, dest_stop_id, trip_type in \
ReadCSV(trips_file,
['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR',
'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB',
'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']):
if trip_type != '1':
print("skipping Trip ", trip_id, line, direction, \
dest_station_id, trip_type)
continue # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other
trip = Trip()
#The trip_id (FRT_FID) field is not unique in the vbz data, as of Dec 2009
# to prevent overwritingimported trips when we key them by trip.id
# we should make trip.id unique, by combining trip_id and line
trip.id = ("%s_%s") % (trip_id, line)
trip.starttime = int(trip_starttime)
trip.route = self.routes[line]
dest_station = self.stations[dest_station_id]
pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
trip.pattern = self.patterns[pattern_id]
trip.stoptimes = trip.pattern.stoptimes[stoptime_id]
if restriction_id:
service_id = u'VB%s.%s' % (schedule_id, restriction_id)
else:
service_id = u'C%s.%s' % (schedule_id, daytype_id)
trip.service_id = service_id
assert len(self.services[service_id]) > 0
assert not trip.id in self.trips
self.trips[trip.id] = trip | python | def ImportTrips(self, trips_file):
"Imports the rec_frt.mdv file."
for trip_id, trip_starttime, line, strli, direction, \
stoptime_id, schedule_id, daytype_id, restriction_id, \
dest_station_id, dest_stop_id, trip_type in \
ReadCSV(trips_file,
['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR',
'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB',
'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']):
if trip_type != '1':
print("skipping Trip ", trip_id, line, direction, \
dest_station_id, trip_type)
continue # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other
trip = Trip()
#The trip_id (FRT_FID) field is not unique in the vbz data, as of Dec 2009
# to prevent overwritingimported trips when we key them by trip.id
# we should make trip.id unique, by combining trip_id and line
trip.id = ("%s_%s") % (trip_id, line)
trip.starttime = int(trip_starttime)
trip.route = self.routes[line]
dest_station = self.stations[dest_station_id]
pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
trip.pattern = self.patterns[pattern_id]
trip.stoptimes = trip.pattern.stoptimes[stoptime_id]
if restriction_id:
service_id = u'VB%s.%s' % (schedule_id, restriction_id)
else:
service_id = u'C%s.%s' % (schedule_id, daytype_id)
trip.service_id = service_id
assert len(self.services[service_id]) > 0
assert not trip.id in self.trips
self.trips[trip.id] = trip | [
"def",
"ImportTrips",
"(",
"self",
",",
"trips_file",
")",
":",
"for",
"trip_id",
",",
"trip_starttime",
",",
"line",
",",
"strli",
",",
"direction",
",",
"stoptime_id",
",",
"schedule_id",
",",
"daytype_id",
",",
"restriction_id",
",",
"dest_station_id",
",",... | Imports the rec_frt.mdv file. | [
"Imports",
"the",
"rec_frt",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L354-L385 |
225,097 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.Write | def Write(self, outpath):
"Writes a .zip file in Google Transit format."
out = zipfile.ZipFile(outpath, mode="w", compression=zipfile.ZIP_DEFLATED)
for filename, func in [('agency.txt', self.WriteAgency),
('calendar.txt', self.WriteCalendar),
('calendar_dates.txt', self.WriteCalendarDates),
('routes.txt', self.WriteRoutes),
('trips.txt', self.WriteTrips),
('stops.txt', self.WriteStations),
('stop_times.txt', self.WriteStopTimes)]:
s = cStringIO.StringIO()
func(s)
out.writestr(filename, s.getvalue())
out.close() | python | def Write(self, outpath):
"Writes a .zip file in Google Transit format."
out = zipfile.ZipFile(outpath, mode="w", compression=zipfile.ZIP_DEFLATED)
for filename, func in [('agency.txt', self.WriteAgency),
('calendar.txt', self.WriteCalendar),
('calendar_dates.txt', self.WriteCalendarDates),
('routes.txt', self.WriteRoutes),
('trips.txt', self.WriteTrips),
('stops.txt', self.WriteStations),
('stop_times.txt', self.WriteStopTimes)]:
s = cStringIO.StringIO()
func(s)
out.writestr(filename, s.getvalue())
out.close() | [
"def",
"Write",
"(",
"self",
",",
"outpath",
")",
":",
"out",
"=",
"zipfile",
".",
"ZipFile",
"(",
"outpath",
",",
"mode",
"=",
"\"w\"",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"for",
"filename",
",",
"func",
"in",
"[",
"(",
"'a... | Writes a .zip file in Google Transit format. | [
"Writes",
"a",
".",
"zip",
"file",
"in",
"Google",
"Transit",
"format",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L387-L400 |
225,098 | google/transitfeed | examples/table.py | TransposeTable | def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
transposed = []
rows = len(table)
cols = max(len(row) for row in table)
for x in range(cols):
transposed.append([])
for y in range(rows):
if x < len(table[y]):
transposed[x].append(table[y][x])
else:
transposed[x].append(None)
return transposed | python | def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
transposed = []
rows = len(table)
cols = max(len(row) for row in table)
for x in range(cols):
transposed.append([])
for y in range(rows):
if x < len(table[y]):
transposed[x].append(table[y][x])
else:
transposed[x].append(None)
return transposed | [
"def",
"TransposeTable",
"(",
"table",
")",
":",
"transposed",
"=",
"[",
"]",
"rows",
"=",
"len",
"(",
"table",
")",
"cols",
"=",
"max",
"(",
"len",
"(",
"row",
")",
"for",
"row",
"in",
"table",
")",
"for",
"x",
"in",
"range",
"(",
"cols",
")",
... | Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]] | [
"Transpose",
"a",
"list",
"of",
"lists",
"using",
"None",
"to",
"extend",
"all",
"input",
"lists",
"to",
"the",
"same",
"length",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/table.py#L65-L90 |
225,099 | google/transitfeed | transitfeed/util.py | CheckVersion | def CheckVersion(problems, latest_version=None):
"""
Check if there is a newer version of transitfeed available.
Args:
problems: if a new version is available, a NewVersionAvailable problem will
be added
latest_version: if specified, override the latest version read from the
project page
"""
if not latest_version:
timeout = 20
socket.setdefaulttimeout(timeout)
request = urllib2.Request(LATEST_RELEASE_VERSION_URL)
try:
response = urllib2.urlopen(request)
content = response.read()
m = re.search(r'version=(\d+\.\d+\.\d+)', content)
if m:
latest_version = m.group(1)
except urllib2.HTTPError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server: Reason: %s [%s].' %
(e.reason, e.code))
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
except urllib2.URLError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server. Reason: %s.' % e.reason)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
if not latest_version:
description = ('During the new-version check, we had trouble parsing the '
'contents of %s.' % LATEST_RELEASE_VERSION_URL)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
newest_version = _MaxVersion([latest_version, __version__])
if __version__ != newest_version:
problems.NewVersionAvailable(newest_version) | python | def CheckVersion(problems, latest_version=None):
"""
Check if there is a newer version of transitfeed available.
Args:
problems: if a new version is available, a NewVersionAvailable problem will
be added
latest_version: if specified, override the latest version read from the
project page
"""
if not latest_version:
timeout = 20
socket.setdefaulttimeout(timeout)
request = urllib2.Request(LATEST_RELEASE_VERSION_URL)
try:
response = urllib2.urlopen(request)
content = response.read()
m = re.search(r'version=(\d+\.\d+\.\d+)', content)
if m:
latest_version = m.group(1)
except urllib2.HTTPError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server: Reason: %s [%s].' %
(e.reason, e.code))
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
except urllib2.URLError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server. Reason: %s.' % e.reason)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
if not latest_version:
description = ('During the new-version check, we had trouble parsing the '
'contents of %s.' % LATEST_RELEASE_VERSION_URL)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
newest_version = _MaxVersion([latest_version, __version__])
if __version__ != newest_version:
problems.NewVersionAvailable(newest_version) | [
"def",
"CheckVersion",
"(",
"problems",
",",
"latest_version",
"=",
"None",
")",
":",
"if",
"not",
"latest_version",
":",
"timeout",
"=",
"20",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"LATEST_R... | Check if there is a newer version of transitfeed available.
Args:
problems: if a new version is available, a NewVersionAvailable problem will
be added
latest_version: if specified, override the latest version read from the
project page | [
"Check",
"if",
"there",
"is",
"a",
"newer",
"version",
"of",
"transitfeed",
"available",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L180-L225 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.