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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
238,800
django-extensions/django-extensions
django_extensions/management/commands/dumpscript.py
Script._queue_models
def _queue_models(self, models, context): """ Work an an appropriate ordering for the models. This isn't essential, but makes the script look nicer because more instances can be defined on their first try. """ model_queue = [] number_remaining_models = len(models) # Max number of cycles allowed before we call it an infinite loop. MAX_CYCLES = number_remaining_models allowed_cycles = MAX_CYCLES while number_remaining_models > 0: previous_number_remaining_models = number_remaining_models model = models.pop(0) # If the model is ready to be processed, add it to the list if check_dependencies(model, model_queue, context["__avaliable_models"]): model_class = ModelCode(model=model, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) model_queue.append(model_class) # Otherwise put the model back at the end of the list else: models.append(model) # Check for infinite loops. # This means there is a cyclic foreign key structure # That cannot be resolved by re-ordering number_remaining_models = len(models) if number_remaining_models == previous_number_remaining_models: allowed_cycles -= 1 if allowed_cycles <= 0: # Add the remaining models, but do not remove them from the model list missing_models = [ModelCode(model=m, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) for m in models] model_queue += missing_models # Replace the models with the model class objects # (sure, this is a little bit of hackery) models[:] = missing_models break else: allowed_cycles = MAX_CYCLES return model_queue
python
def _queue_models(self, models, context): model_queue = [] number_remaining_models = len(models) # Max number of cycles allowed before we call it an infinite loop. MAX_CYCLES = number_remaining_models allowed_cycles = MAX_CYCLES while number_remaining_models > 0: previous_number_remaining_models = number_remaining_models model = models.pop(0) # If the model is ready to be processed, add it to the list if check_dependencies(model, model_queue, context["__avaliable_models"]): model_class = ModelCode(model=model, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) model_queue.append(model_class) # Otherwise put the model back at the end of the list else: models.append(model) # Check for infinite loops. # This means there is a cyclic foreign key structure # That cannot be resolved by re-ordering number_remaining_models = len(models) if number_remaining_models == previous_number_remaining_models: allowed_cycles -= 1 if allowed_cycles <= 0: # Add the remaining models, but do not remove them from the model list missing_models = [ModelCode(model=m, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) for m in models] model_queue += missing_models # Replace the models with the model class objects # (sure, this is a little bit of hackery) models[:] = missing_models break else: allowed_cycles = MAX_CYCLES return model_queue
[ "def", "_queue_models", "(", "self", ",", "models", ",", "context", ")", ":", "model_queue", "=", "[", "]", "number_remaining_models", "=", "len", "(", "models", ")", "# Max number of cycles allowed before we call it an infinite loop.", "MAX_CYCLES", "=", "number_remain...
Work an an appropriate ordering for the models. This isn't essential, but makes the script look nicer because more instances can be defined on their first try.
[ "Work", "an", "an", "appropriate", "ordering", "for", "the", "models", ".", "This", "isn", "t", "essential", "but", "makes", "the", "script", "look", "nicer", "because", "more", "instances", "can", "be", "defined", "on", "their", "first", "try", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L411-L454
238,801
django-extensions/django-extensions
django_extensions/management/commands/sqldiff.py
SQLDiff.sql_to_dict
def sql_to_dict(self, query, param): """ Execute query and return a dict sql_to_dict(query, param) -> list of dicts code from snippet at http://www.djangosnippets.org/snippets/1383/ """ cursor = connection.cursor() cursor.execute(query, param) fieldnames = [name[0] for name in cursor.description] result = [] for row in cursor.fetchall(): rowset = [] for field in zip(fieldnames, row): rowset.append(field) result.append(dict(rowset)) return result
python
def sql_to_dict(self, query, param): cursor = connection.cursor() cursor.execute(query, param) fieldnames = [name[0] for name in cursor.description] result = [] for row in cursor.fetchall(): rowset = [] for field in zip(fieldnames, row): rowset.append(field) result.append(dict(rowset)) return result
[ "def", "sql_to_dict", "(", "self", ",", "query", ",", "param", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "query", ",", "param", ")", "fieldnames", "=", "[", "name", "[", "0", "]", "for", "name", ...
Execute query and return a dict sql_to_dict(query, param) -> list of dicts code from snippet at http://www.djangosnippets.org/snippets/1383/
[ "Execute", "query", "and", "return", "a", "dict" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sqldiff.py#L257-L274
238,802
django-extensions/django-extensions
django_extensions/management/commands/sqldiff.py
SQLDiff.print_diff
def print_diff(self, style=no_style()): """ Print differences to stdout """ if self.options['sql']: self.print_diff_sql(style) else: self.print_diff_text(style)
python
def print_diff(self, style=no_style()): if self.options['sql']: self.print_diff_sql(style) else: self.print_diff_text(style)
[ "def", "print_diff", "(", "self", ",", "style", "=", "no_style", "(", ")", ")", ":", "if", "self", ".", "options", "[", "'sql'", "]", ":", "self", ".", "print_diff_sql", "(", "style", ")", "else", ":", "self", ".", "print_diff_text", "(", "style", ")...
Print differences to stdout
[ "Print", "differences", "to", "stdout" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sqldiff.py#L676-L681
238,803
django-extensions/django-extensions
django_extensions/templatetags/syntax_color.py
pygments_required
def pygments_required(func): """Raise ImportError if pygments is not installed.""" def wrapper(*args, **kwargs): if not HAS_PYGMENTS: # pragma: no cover raise ImportError( "Please install 'pygments' library to use syntax_color.") rv = func(*args, **kwargs) return rv return wrapper
python
def pygments_required(func): def wrapper(*args, **kwargs): if not HAS_PYGMENTS: # pragma: no cover raise ImportError( "Please install 'pygments' library to use syntax_color.") rv = func(*args, **kwargs) return rv return wrapper
[ "def", "pygments_required", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_PYGMENTS", ":", "# pragma: no cover", "raise", "ImportError", "(", "\"Please install 'pygments' library to use syntax_color.\"...
Raise ImportError if pygments is not installed.
[ "Raise", "ImportError", "if", "pygments", "is", "not", "installed", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/templatetags/syntax_color.py#L54-L62
238,804
django-extensions/django-extensions
django_extensions/utils/dia2django.py
addparentstofks
def addparentstofks(rels, fks): """ Get a list of relations, between parents and sons and a dict of clases named in dia, and modifies the fks to add the parent as fk to get order on the output of classes and replaces the base class of the son, to put the class parent name. """ for j in rels: son = index(fks, j[1]) parent = index(fks, j[0]) fks[son][2] = fks[son][2].replace("models.Model", parent) if parent not in fks[son][0]: fks[son][0].append(parent)
python
def addparentstofks(rels, fks): for j in rels: son = index(fks, j[1]) parent = index(fks, j[0]) fks[son][2] = fks[son][2].replace("models.Model", parent) if parent not in fks[son][0]: fks[son][0].append(parent)
[ "def", "addparentstofks", "(", "rels", ",", "fks", ")", ":", "for", "j", "in", "rels", ":", "son", "=", "index", "(", "fks", ",", "j", "[", "1", "]", ")", "parent", "=", "index", "(", "fks", ",", "j", "[", "0", "]", ")", "fks", "[", "son", ...
Get a list of relations, between parents and sons and a dict of clases named in dia, and modifies the fks to add the parent as fk to get order on the output of classes and replaces the base class of the son, to put the class parent name.
[ "Get", "a", "list", "of", "relations", "between", "parents", "and", "sons", "and", "a", "dict", "of", "clases", "named", "in", "dia", "and", "modifies", "the", "fks", "to", "add", "the", "parent", "as", "fk", "to", "get", "order", "on", "the", "output"...
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/utils/dia2django.py#L57-L69
238,805
django-extensions/django-extensions
django_extensions/management/shells.py
get_app_name
def get_app_name(mod_name): """ Retrieve application name from models.py module path >>> get_app_name('testapp.models.foo') 'testapp' 'testapp' instead of 'some.testapp' for compatibility: >>> get_app_name('some.testapp.models.foo') 'testapp' >>> get_app_name('some.models.testapp.models.foo') 'testapp' >>> get_app_name('testapp.foo') 'testapp' >>> get_app_name('some.testapp.foo') 'testapp' """ rparts = list(reversed(mod_name.split('.'))) try: try: return rparts[rparts.index(MODELS_MODULE_NAME) + 1] except ValueError: # MODELS_MODULE_NAME ('models' string) is not found return rparts[1] except IndexError: # Some weird model naming scheme like in Sentry. return mod_name
python
def get_app_name(mod_name): rparts = list(reversed(mod_name.split('.'))) try: try: return rparts[rparts.index(MODELS_MODULE_NAME) + 1] except ValueError: # MODELS_MODULE_NAME ('models' string) is not found return rparts[1] except IndexError: # Some weird model naming scheme like in Sentry. return mod_name
[ "def", "get_app_name", "(", "mod_name", ")", ":", "rparts", "=", "list", "(", "reversed", "(", "mod_name", ".", "split", "(", "'.'", ")", ")", ")", "try", ":", "try", ":", "return", "rparts", "[", "rparts", ".", "index", "(", "MODELS_MODULE_NAME", ")",...
Retrieve application name from models.py module path >>> get_app_name('testapp.models.foo') 'testapp' 'testapp' instead of 'some.testapp' for compatibility: >>> get_app_name('some.testapp.models.foo') 'testapp' >>> get_app_name('some.models.testapp.models.foo') 'testapp' >>> get_app_name('testapp.foo') 'testapp' >>> get_app_name('some.testapp.foo') 'testapp'
[ "Retrieve", "application", "name", "from", "models", ".", "py", "module", "path" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/shells.py#L46-L72
238,806
django-extensions/django-extensions
django_extensions/management/commands/merge_model_instances.py
get_generic_fields
def get_generic_fields(): """Return a list of all GenericForeignKeys in all models.""" generic_fields = [] for model in apps.get_models(): for field_name, field in model.__dict__.items(): if isinstance(field, GenericForeignKey): generic_fields.append(field) return generic_fields
python
def get_generic_fields(): generic_fields = [] for model in apps.get_models(): for field_name, field in model.__dict__.items(): if isinstance(field, GenericForeignKey): generic_fields.append(field) return generic_fields
[ "def", "get_generic_fields", "(", ")", ":", "generic_fields", "=", "[", "]", "for", "model", "in", "apps", ".", "get_models", "(", ")", ":", "for", "field_name", ",", "field", "in", "model", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isinstan...
Return a list of all GenericForeignKeys in all models.
[ "Return", "a", "list", "of", "all", "GenericForeignKeys", "in", "all", "models", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/merge_model_instances.py#L78-L85
238,807
django-extensions/django-extensions
django_extensions/management/commands/merge_model_instances.py
Command.merge_model_instances
def merge_model_instances(self, primary_object, alias_objects): """ Merge several model instances into one, the `primary_object`. Use this function to merge model objects and migrate all of the related fields from the alias objects the primary object. """ generic_fields = get_generic_fields() # get related fields related_fields = list(filter( lambda x: x.is_relation is True, primary_object._meta.get_fields())) many_to_many_fields = list(filter( lambda x: x.many_to_many is True, related_fields)) related_fields = list(filter( lambda x: x.many_to_many is False, related_fields)) # Loop through all alias objects and migrate their references to the # primary object deleted_objects = [] deleted_objects_count = 0 for alias_object in alias_objects: # Migrate all foreign key references from alias object to primary # object. for many_to_many_field in many_to_many_fields: alias_varname = many_to_many_field.name related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): try: # Handle regular M2M relationships. getattr(alias_object, alias_varname).remove(obj) getattr(primary_object, alias_varname).add(obj) except AttributeError: # Handle M2M relationships with a 'through' model. # This does not delete the 'through model. # TODO: Allow the user to delete a duplicate 'through' model. through_model = getattr(alias_object, alias_varname).through kwargs = { many_to_many_field.m2m_reverse_field_name(): obj, many_to_many_field.m2m_field_name(): alias_object, } through_model_instances = through_model.objects.filter(**kwargs) for instance in through_model_instances: # Re-attach the through model to the primary_object setattr( instance, many_to_many_field.m2m_field_name(), primary_object) instance.save() # TODO: Here, try to delete duplicate instances that are # disallowed by a unique_together constraint for related_field in related_fields: if related_field.one_to_many: alias_varname = related_field.get_accessor_name() related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): field_name = related_field.field.name setattr(obj, field_name, primary_object) obj.save() elif related_field.one_to_one or related_field.many_to_one: alias_varname = related_field.name related_object = getattr(alias_object, alias_varname) primary_related_object = getattr(primary_object, alias_varname) if primary_related_object is None: setattr(primary_object, alias_varname, related_object) primary_object.save() elif related_field.one_to_one: self.stdout.write("Deleted {} with id {}\n".format( related_object, related_object.id)) related_object.delete() for field in generic_fields: filter_kwargs = {} filter_kwargs[field.fk_field] = alias_object._get_pk_val() filter_kwargs[field.ct_field] = field.get_content_type(alias_object) related_objects = field.model.objects.filter(**filter_kwargs) for generic_related_object in related_objects: setattr(generic_related_object, field.name, primary_object) generic_related_object.save() if alias_object.id: deleted_objects += [alias_object] self.stdout.write("Deleted {} with id {}\n".format( alias_object, alias_object.id)) alias_object.delete() deleted_objects_count += 1 return primary_object, deleted_objects, deleted_objects_count
python
def merge_model_instances(self, primary_object, alias_objects): generic_fields = get_generic_fields() # get related fields related_fields = list(filter( lambda x: x.is_relation is True, primary_object._meta.get_fields())) many_to_many_fields = list(filter( lambda x: x.many_to_many is True, related_fields)) related_fields = list(filter( lambda x: x.many_to_many is False, related_fields)) # Loop through all alias objects and migrate their references to the # primary object deleted_objects = [] deleted_objects_count = 0 for alias_object in alias_objects: # Migrate all foreign key references from alias object to primary # object. for many_to_many_field in many_to_many_fields: alias_varname = many_to_many_field.name related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): try: # Handle regular M2M relationships. getattr(alias_object, alias_varname).remove(obj) getattr(primary_object, alias_varname).add(obj) except AttributeError: # Handle M2M relationships with a 'through' model. # This does not delete the 'through model. # TODO: Allow the user to delete a duplicate 'through' model. through_model = getattr(alias_object, alias_varname).through kwargs = { many_to_many_field.m2m_reverse_field_name(): obj, many_to_many_field.m2m_field_name(): alias_object, } through_model_instances = through_model.objects.filter(**kwargs) for instance in through_model_instances: # Re-attach the through model to the primary_object setattr( instance, many_to_many_field.m2m_field_name(), primary_object) instance.save() # TODO: Here, try to delete duplicate instances that are # disallowed by a unique_together constraint for related_field in related_fields: if related_field.one_to_many: alias_varname = related_field.get_accessor_name() related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): field_name = related_field.field.name setattr(obj, field_name, primary_object) obj.save() elif related_field.one_to_one or related_field.many_to_one: alias_varname = related_field.name related_object = getattr(alias_object, alias_varname) primary_related_object = getattr(primary_object, alias_varname) if primary_related_object is None: setattr(primary_object, alias_varname, related_object) primary_object.save() elif related_field.one_to_one: self.stdout.write("Deleted {} with id {}\n".format( related_object, related_object.id)) related_object.delete() for field in generic_fields: filter_kwargs = {} filter_kwargs[field.fk_field] = alias_object._get_pk_val() filter_kwargs[field.ct_field] = field.get_content_type(alias_object) related_objects = field.model.objects.filter(**filter_kwargs) for generic_related_object in related_objects: setattr(generic_related_object, field.name, primary_object) generic_related_object.save() if alias_object.id: deleted_objects += [alias_object] self.stdout.write("Deleted {} with id {}\n".format( alias_object, alias_object.id)) alias_object.delete() deleted_objects_count += 1 return primary_object, deleted_objects, deleted_objects_count
[ "def", "merge_model_instances", "(", "self", ",", "primary_object", ",", "alias_objects", ")", ":", "generic_fields", "=", "get_generic_fields", "(", ")", "# get related fields", "related_fields", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "i...
Merge several model instances into one, the `primary_object`. Use this function to merge model objects and migrate all of the related fields from the alias objects the primary object.
[ "Merge", "several", "model", "instances", "into", "one", "the", "primary_object", ".", "Use", "this", "function", "to", "merge", "model", "objects", "and", "migrate", "all", "of", "the", "related", "fields", "from", "the", "alias", "objects", "the", "primary",...
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/merge_model_instances.py#L132-L222
238,808
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.add_arguments
def add_arguments(self, parser): """Unpack self.arguments for parser.add_arguments.""" parser.add_argument('app_label', nargs='*') for argument in self.arguments: parser.add_argument(*argument.split(' '), **self.arguments[argument])
python
def add_arguments(self, parser): parser.add_argument('app_label', nargs='*') for argument in self.arguments: parser.add_argument(*argument.split(' '), **self.arguments[argument])
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'app_label'", ",", "nargs", "=", "'*'", ")", "for", "argument", "in", "self", ".", "arguments", ":", "parser", ".", "add_argument", "(", "*", "argument", "...
Unpack self.arguments for parser.add_arguments.
[ "Unpack", "self", ".", "arguments", "for", "parser", ".", "add_arguments", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L169-L173
238,809
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.render_output_json
def render_output_json(self, graph_data, output_file=None): """Write model data to file or stdout in JSON format.""" if output_file: with open(output_file, 'wt') as json_output_f: json.dump(graph_data, json_output_f) else: self.stdout.write(json.dumps(graph_data))
python
def render_output_json(self, graph_data, output_file=None): if output_file: with open(output_file, 'wt') as json_output_f: json.dump(graph_data, json_output_f) else: self.stdout.write(json.dumps(graph_data))
[ "def", "render_output_json", "(", "self", ",", "graph_data", ",", "output_file", "=", "None", ")", ":", "if", "output_file", ":", "with", "open", "(", "output_file", ",", "'wt'", ")", "as", "json_output_f", ":", "json", ".", "dump", "(", "graph_data", ",",...
Write model data to file or stdout in JSON format.
[ "Write", "model", "data", "to", "file", "or", "stdout", "in", "JSON", "format", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L246-L252
238,810
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.render_output_pygraphviz
def render_output_pygraphviz(self, dotdata, **kwargs): """Render model data as image using pygraphviz""" if not HAS_PYGRAPHVIZ: raise CommandError("You need to install pygraphviz python module") version = pygraphviz.__version__.rstrip("-svn") try: if tuple(int(v) for v in version.split('.')) < (0, 36): # HACK around old/broken AGraph before version 0.36 (ubuntu ships with this old version) tmpfile = tempfile.NamedTemporaryFile() tmpfile.write(dotdata) tmpfile.seek(0) dotdata = tmpfile.name except ValueError: pass graph = pygraphviz.AGraph(dotdata) graph.layout(prog=kwargs['layout']) graph.draw(kwargs['outputfile'])
python
def render_output_pygraphviz(self, dotdata, **kwargs): if not HAS_PYGRAPHVIZ: raise CommandError("You need to install pygraphviz python module") version = pygraphviz.__version__.rstrip("-svn") try: if tuple(int(v) for v in version.split('.')) < (0, 36): # HACK around old/broken AGraph before version 0.36 (ubuntu ships with this old version) tmpfile = tempfile.NamedTemporaryFile() tmpfile.write(dotdata) tmpfile.seek(0) dotdata = tmpfile.name except ValueError: pass graph = pygraphviz.AGraph(dotdata) graph.layout(prog=kwargs['layout']) graph.draw(kwargs['outputfile'])
[ "def", "render_output_pygraphviz", "(", "self", ",", "dotdata", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_PYGRAPHVIZ", ":", "raise", "CommandError", "(", "\"You need to install pygraphviz python module\"", ")", "version", "=", "pygraphviz", ".", "__versio...
Render model data as image using pygraphviz
[ "Render", "model", "data", "as", "image", "using", "pygraphviz" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L254-L272
238,811
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.render_output_pydot
def render_output_pydot(self, dotdata, **kwargs): """Render model data as image using pydot""" if not HAS_PYDOT: raise CommandError("You need to install pydot python module") graph = pydot.graph_from_dot_data(dotdata) if not graph: raise CommandError("pydot returned an error") if isinstance(graph, (list, tuple)): if len(graph) > 1: sys.stderr.write("Found more then one graph, rendering only the first one.\n") graph = graph[0] output_file = kwargs['outputfile'] formats = [ 'bmp', 'canon', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dia', 'emf', 'em', 'fplus', 'eps', 'fig', 'gd', 'gd2', 'gif', 'gv', 'imap', 'imap_np', 'ismap', 'jpe', 'jpeg', 'jpg', 'metafile', 'pdf', 'pic', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'svg', 'svgz', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'xdot', ] ext = output_file[output_file.rfind('.') + 1:] format_ = ext if ext in formats else 'raw' graph.write(output_file, format=format_)
python
def render_output_pydot(self, dotdata, **kwargs): if not HAS_PYDOT: raise CommandError("You need to install pydot python module") graph = pydot.graph_from_dot_data(dotdata) if not graph: raise CommandError("pydot returned an error") if isinstance(graph, (list, tuple)): if len(graph) > 1: sys.stderr.write("Found more then one graph, rendering only the first one.\n") graph = graph[0] output_file = kwargs['outputfile'] formats = [ 'bmp', 'canon', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dia', 'emf', 'em', 'fplus', 'eps', 'fig', 'gd', 'gd2', 'gif', 'gv', 'imap', 'imap_np', 'ismap', 'jpe', 'jpeg', 'jpg', 'metafile', 'pdf', 'pic', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'svg', 'svgz', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'xdot', ] ext = output_file[output_file.rfind('.') + 1:] format_ = ext if ext in formats else 'raw' graph.write(output_file, format=format_)
[ "def", "render_output_pydot", "(", "self", ",", "dotdata", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_PYDOT", ":", "raise", "CommandError", "(", "\"You need to install pydot python module\"", ")", "graph", "=", "pydot", ".", "graph_from_dot_data", "(", ...
Render model data as image using pydot
[ "Render", "model", "data", "as", "image", "using", "pydot" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L274-L297
238,812
django-extensions/django-extensions
django_extensions/management/commands/show_urls.py
Command.extract_views_from_urlpatterns
def extract_views_from_urlpatterns(self, urlpatterns, base='', namespace=None): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a three-tuple: (view_func, regex, name) """ views = [] for p in urlpatterns: if isinstance(p, (URLPattern, RegexURLPattern)): try: if not p.name: name = p.name elif namespace: name = '{0}:{1}'.format(namespace, p.name) else: name = p.name pattern = describe_pattern(p) views.append((p.callback, base + pattern, name)) except ViewDoesNotExist: continue elif isinstance(p, (URLResolver, RegexURLResolver)): try: patterns = p.url_patterns except ImportError: continue if namespace and p.namespace: _namespace = '{0}:{1}'.format(namespace, p.namespace) else: _namespace = (p.namespace or namespace) pattern = describe_pattern(p) if isinstance(p, LocaleRegexURLResolver): for language in self.LANGUAGES: with translation.override(language[0]): views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) else: views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) elif hasattr(p, '_get_callback'): try: views.append((p._get_callback(), base + describe_pattern(p), p.name)) except ViewDoesNotExist: continue elif hasattr(p, 'url_patterns') or hasattr(p, '_get_url_patterns'): try: patterns = p.url_patterns except ImportError: continue views.extend(self.extract_views_from_urlpatterns(patterns, base + describe_pattern(p), namespace=namespace)) else: raise TypeError("%s does not appear to be a urlpattern object" % p) return views
python
def extract_views_from_urlpatterns(self, urlpatterns, base='', namespace=None): views = [] for p in urlpatterns: if isinstance(p, (URLPattern, RegexURLPattern)): try: if not p.name: name = p.name elif namespace: name = '{0}:{1}'.format(namespace, p.name) else: name = p.name pattern = describe_pattern(p) views.append((p.callback, base + pattern, name)) except ViewDoesNotExist: continue elif isinstance(p, (URLResolver, RegexURLResolver)): try: patterns = p.url_patterns except ImportError: continue if namespace and p.namespace: _namespace = '{0}:{1}'.format(namespace, p.namespace) else: _namespace = (p.namespace or namespace) pattern = describe_pattern(p) if isinstance(p, LocaleRegexURLResolver): for language in self.LANGUAGES: with translation.override(language[0]): views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) else: views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) elif hasattr(p, '_get_callback'): try: views.append((p._get_callback(), base + describe_pattern(p), p.name)) except ViewDoesNotExist: continue elif hasattr(p, 'url_patterns') or hasattr(p, '_get_url_patterns'): try: patterns = p.url_patterns except ImportError: continue views.extend(self.extract_views_from_urlpatterns(patterns, base + describe_pattern(p), namespace=namespace)) else: raise TypeError("%s does not appear to be a urlpattern object" % p) return views
[ "def", "extract_views_from_urlpatterns", "(", "self", ",", "urlpatterns", ",", "base", "=", "''", ",", "namespace", "=", "None", ")", ":", "views", "=", "[", "]", "for", "p", "in", "urlpatterns", ":", "if", "isinstance", "(", "p", ",", "(", "URLPattern",...
Return a list of views from a list of urlpatterns. Each object in the returned list is a three-tuple: (view_func, regex, name)
[ "Return", "a", "list", "of", "views", "from", "a", "list", "of", "urlpatterns", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/show_urls.py#L196-L245
238,813
django-extensions/django-extensions
django_extensions/admin/__init__.py
ForeignKeyAutocompleteAdminMixin.foreignkey_autocomplete
def foreignkey_autocomplete(self, request): """ Search in the fields of the given related model and returns the result as a simple string to be used by the jQuery Autocomplete plugin """ query = request.GET.get('q', None) app_label = request.GET.get('app_label', None) model_name = request.GET.get('model_name', None) search_fields = request.GET.get('search_fields', None) object_pk = request.GET.get('object_pk', None) try: to_string_function = self.related_string_functions[model_name] except KeyError: if six.PY3: to_string_function = lambda x: x.__str__() else: to_string_function = lambda x: x.__unicode__() if search_fields and app_label and model_name and (query or object_pk): def construct_search(field_name): # use different lookup methods depending on the notation if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name model = apps.get_model(app_label, model_name) queryset = model._default_manager.all() data = '' if query: for bit in query.split(): or_queries = [models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)}) for field_name in search_fields.split(',')] other_qs = QuerySet(model) other_qs.query.select_related = queryset.query.select_related other_qs = other_qs.filter(reduce(operator.or_, or_queries)) queryset = queryset & other_qs additional_filter = self.get_related_filter(model, request) if additional_filter: queryset = queryset.filter(additional_filter) if self.autocomplete_limit: queryset = queryset[:self.autocomplete_limit] data = ''.join([six.u('%s|%s\n') % (to_string_function(f), f.pk) for f in queryset]) elif object_pk: try: obj = queryset.get(pk=object_pk) except Exception: # FIXME: use stricter exception checking pass else: data = to_string_function(obj) return HttpResponse(data, content_type='text/plain') return HttpResponseNotFound()
python
def foreignkey_autocomplete(self, request): query = request.GET.get('q', None) app_label = request.GET.get('app_label', None) model_name = request.GET.get('model_name', None) search_fields = request.GET.get('search_fields', None) object_pk = request.GET.get('object_pk', None) try: to_string_function = self.related_string_functions[model_name] except KeyError: if six.PY3: to_string_function = lambda x: x.__str__() else: to_string_function = lambda x: x.__unicode__() if search_fields and app_label and model_name and (query or object_pk): def construct_search(field_name): # use different lookup methods depending on the notation if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name model = apps.get_model(app_label, model_name) queryset = model._default_manager.all() data = '' if query: for bit in query.split(): or_queries = [models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)}) for field_name in search_fields.split(',')] other_qs = QuerySet(model) other_qs.query.select_related = queryset.query.select_related other_qs = other_qs.filter(reduce(operator.or_, or_queries)) queryset = queryset & other_qs additional_filter = self.get_related_filter(model, request) if additional_filter: queryset = queryset.filter(additional_filter) if self.autocomplete_limit: queryset = queryset[:self.autocomplete_limit] data = ''.join([six.u('%s|%s\n') % (to_string_function(f), f.pk) for f in queryset]) elif object_pk: try: obj = queryset.get(pk=object_pk) except Exception: # FIXME: use stricter exception checking pass else: data = to_string_function(obj) return HttpResponse(data, content_type='text/plain') return HttpResponseNotFound()
[ "def", "foreignkey_autocomplete", "(", "self", ",", "request", ")", ":", "query", "=", "request", ".", "GET", ".", "get", "(", "'q'", ",", "None", ")", "app_label", "=", "request", ".", "GET", ".", "get", "(", "'app_label'", ",", "None", ")", "model_na...
Search in the fields of the given related model and returns the result as a simple string to be used by the jQuery Autocomplete plugin
[ "Search", "in", "the", "fields", "of", "the", "given", "related", "model", "and", "returns", "the", "result", "as", "a", "simple", "string", "to", "be", "used", "by", "the", "jQuery", "Autocomplete", "plugin" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/admin/__init__.py#L67-L126
238,814
django-extensions/django-extensions
django_extensions/admin/__init__.py
ForeignKeyAutocompleteAdminMixin.formfield_for_dbfield
def formfield_for_dbfield(self, db_field, **kwargs): """ Override the default widget for Foreignkey fields if they are specified in the related_search_fields class attribute. """ if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields: help_text = self.get_help_text(db_field.name, db_field.remote_field.model._meta.object_name) if kwargs.get('help_text'): help_text = six.u('%s %s' % (kwargs['help_text'], help_text)) kwargs['widget'] = ForeignKeySearchInput(db_field.remote_field, self.related_search_fields[db_field.name]) kwargs['help_text'] = help_text return super(ForeignKeyAutocompleteAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)
python
def formfield_for_dbfield(self, db_field, **kwargs): if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields: help_text = self.get_help_text(db_field.name, db_field.remote_field.model._meta.object_name) if kwargs.get('help_text'): help_text = six.u('%s %s' % (kwargs['help_text'], help_text)) kwargs['widget'] = ForeignKeySearchInput(db_field.remote_field, self.related_search_fields[db_field.name]) kwargs['help_text'] = help_text return super(ForeignKeyAutocompleteAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)
[ "def", "formfield_for_dbfield", "(", "self", ",", "db_field", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "db_field", ",", "models", ".", "ForeignKey", ")", "and", "db_field", ".", "name", "in", "self", ".", "related_search_fields", ":", "h...
Override the default widget for Foreignkey fields if they are specified in the related_search_fields class attribute.
[ "Override", "the", "default", "widget", "for", "Foreignkey", "fields", "if", "they", "are", "specified", "in", "the", "related_search_fields", "class", "attribute", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/admin/__init__.py#L147-L158
238,815
django-extensions/django-extensions
django_extensions/management/technical_response.py
null_technical_500_response
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Alternative function for django.views.debug.technical_500_response. Django's convert_exception_to_response() wrapper is called on each 'Middleware' object to avoid leaking exceptions. If an uncaught exception is raised, the wrapper calls technical_500_response() to create a response for django's debug view. Runserver_plus overrides the django debug view's technical_500_response() function to allow for an enhanced WSGI debugger view to be displayed. However, because Django calls convert_exception_to_response() on each object in the stack of Middleware objects, re-raising an error quickly pollutes the traceback displayed. Runserver_plus only needs needs traceback frames relevant to WSGIHandler Middleware objects, so only store the traceback if it is for a WSGIHandler. If an exception is not raised here, Django eventually throws an error for not getting a valid response object for its debug view. """ try: # Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb if isinstance(tb.tb_next.tb_frame.f_locals.get('self'), WSGIHandler): tld.wsgi_tb = tb elif tld.wsgi_tb: tb = tld.wsgi_tb except AttributeError: pass six.reraise(exc_type, exc_value, tb)
python
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500): try: # Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb if isinstance(tb.tb_next.tb_frame.f_locals.get('self'), WSGIHandler): tld.wsgi_tb = tb elif tld.wsgi_tb: tb = tld.wsgi_tb except AttributeError: pass six.reraise(exc_type, exc_value, tb)
[ "def", "null_technical_500_response", "(", "request", ",", "exc_type", ",", "exc_value", ",", "tb", ",", "status_code", "=", "500", ")", ":", "try", ":", "# Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb", "if", "isinstance", ...
Alternative function for django.views.debug.technical_500_response. Django's convert_exception_to_response() wrapper is called on each 'Middleware' object to avoid leaking exceptions. If an uncaught exception is raised, the wrapper calls technical_500_response() to create a response for django's debug view. Runserver_plus overrides the django debug view's technical_500_response() function to allow for an enhanced WSGI debugger view to be displayed. However, because Django calls convert_exception_to_response() on each object in the stack of Middleware objects, re-raising an error quickly pollutes the traceback displayed. Runserver_plus only needs needs traceback frames relevant to WSGIHandler Middleware objects, so only store the traceback if it is for a WSGIHandler. If an exception is not raised here, Django eventually throws an error for not getting a valid response object for its debug view.
[ "Alternative", "function", "for", "django", ".", "views", ".", "debug", ".", "technical_500_response", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/technical_response.py#L11-L37
238,816
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): 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
238,817
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): 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
238,818
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): 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
238,819
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): 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
238,820
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): 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
238,821
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): 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
238,822
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): # 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
238,823
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): 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
238,824
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): 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
238,825
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): # 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
238,826
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): 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
238,827
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): 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
238,828
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): 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
238,829
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): 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
238,830
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): (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
238,831
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): 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
238,832
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): 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
238,833
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): 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
238,834
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): 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
238,835
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): 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
238,836
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): 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
238,837
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): (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
238,838
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): 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
238,839
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): 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
238,840
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): 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
238,841
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): 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
238,842
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): 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
238,843
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): 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
238,844
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): 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
238,845
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): 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
238,846
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): 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
238,847
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): 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
238,848
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): 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
238,849
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): 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
238,850
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): 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
238,851
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): 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
238,852
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): 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
238,853
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): 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
238,854
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): 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
238,855
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): 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
238,856
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): 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
238,857
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): 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
238,858
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): 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
238,859
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): 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
238,860
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): 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
238,861
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): 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
238,862
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): 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
238,863
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): 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
238,864
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=""): 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
238,865
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): # 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
238,866
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): 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
238,867
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"): 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
238,868
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"): 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
238,869
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): 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
238,870
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): 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
238,871
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): 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
238,872
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): 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
238,873
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): 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
238,874
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): 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
238,875
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): 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
238,876
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): 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
238,877
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): 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
238,878
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): 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
238,879
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): 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
238,880
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): 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
238,881
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): 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
238,882
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): 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
238,883
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): 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
238,884
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): # 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
238,885
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): 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
238,886
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): 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
238,887
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): 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
238,888
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): 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
238,889
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): 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
238,890
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): 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
238,891
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): 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
238,892
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): 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
238,893
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): 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
238,894
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): 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
238,895
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): 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
238,896
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): 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
238,897
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): 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
238,898
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): 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
238,899
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): 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