Revision 1903

View differences:

org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/buildNumber.properties
1
#Mon Aug 28 18:11:58 CEST 2023
2
buildNumber=303
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/plugin-persistence.def
1
<?xml version="1.0"?>
2
<!--
3
Definitions of plugin persistence org.gvsig.scripting.app.mainplugin.
4
 -->
5
<definitions>
6
  <version>1.0.0</version>
7
  <classes>
8
    <class name="org.gvsig.scripting.app.mainplugin">
9
      <description>Persistence of scripting plugin</description>
10
      <fields>
11
        <field name="ComposerUseHisWindowManager" type="boolean" mandatory="true" defaultValue="true">
12
          <description>When true the composer use his window manager instead of the gvSIG Window manager.</description>
13
        </field>
14
      </fields>
15
    </class>
16
  </classes>
17
</definitions>
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/i18n/text.properties
1
_Scripting=Scripting
2
_Show_scripting_launcher=Abrir lanzador de scripts
3
_Show_scripting_composer=Abrir editor de scripts
4
_Show_scripting_jython_console=Abrir consola Jython
5

  
6
User=Usuario
7
System=Sistema
8

  
9
Accept=Aceptar
10
Cancel=Cancelar
11
Apply=Aplicar
12

  
13
Retrieving_data=Recibiendo datos...
14

  
15
File=Fichero
16
New=Nuevo
17
Close_document=Cerrar documento
18
Close_all_documents=Cerrar todos los documentos
19
Run=Ejecutar
20
Save=Guardar
21
Close=Cerrar
22
Close_current_tab=Cerrar pesta\u00f1a actual
23
Open_edition_mode=Abrir modo edici\u00f3n
24
Run_selected_script=Ejecutar script seleccionado
25
Delete_selected_script=Borrar script seleccionado
26
Refresh_directories=Actualizar carpetas
27
Move_files=Mover ficheros
28
Set_file_preferences=Editar preferencias de fichero
29

  
30

  
31
Edit=Editar
32
Cut=Cortar
33
Copy=Copiar
34
Paste=Pegar
35
Select_all=Seleccionar todo
36

  
37
Tools=Herramientas
38
Launcher=Lanzador de scripts
39
Scripting_Launcher=Lanzador de scripts
40
Scripting_Composer=Editor de scripts
41
Jython_Console=Consola Jython
42
Import_JavaDoc=Importar JavaDoc
43
JavaDoc=Ayuda de Java (JavaDoc)
44
Remove_JavaDoc=Eliminar JavaDoc
45
Help_contents=Contenido de la ayuda
46
About_scripts_editor=Acerca del editor de scripts
47
Get_help=Ayuda
48
Help=Ayuda
49
_Package_script=Empaquetar script...
50
_Package_help=Empaquetar ayuda...
51

  
52
Problems=Errores
53
Console=Consola
54

  
55
Description=Descripci\u00f3n
56
Resource=Recurso
57
Location=Ubicaci\u00f3n
58

  
59
no_line=sin l\u00ednea
60
Line=L\u00ednea
61

  
62
Welcome_message=Bienvenido al entorno de scripting
63

  
64
Error_opening_in_edition_mode_title=Error al abrir fichero
65
Error_opening_in_edition_mode=No se pudo abrir el fichero en modo edici\u00f3n
66

  
67
New_Script=Nuevo elemento
68
New_Script_Description=Crea un nuevo script, di\u00e1logo, proyecto, directorio
69

  
70
Deleting_JavaDocs_successfully_title=Operaci\u00f3n realizada con \u00e9xito
71
Deleting_JavaDocs_successfully=Eliminaci\u00f3n de los JavaDocs exitosa
72

  
73
Import_JavaDoc_title=Importar JavaDocs desde los directorios de sistema al ScriptingFramework JavaDoc
74
Remove_JavaDoc_title=Eliminar JavaDocs del ScriptingFramework JavaDoc
75

  
76
projects_modified_title=Proyectos sin guardar
77
projects_modified=Algunos proyectos han sido modificados.\u00bfSalvar cambios?
78
project_modified=ha sido modificado.\u00bfSalvar cambios?
79

  
80
Delete_all_title=Borrar el documento
81
Delete_all_message=Esta acci\u00f3n elimina el documento o el directorio con todo su contenido. \u00bf Desea continuar ?
82

  
83
About_us_title=Informaci\u00f3n de todos los contribuidores al proyecto gvSIG
84

  
85
Success=Operaci\u00f3n realizada con \u00e9xito
86
Error=Error
87
Error_renaming=Inesperado error renombrando el fichero
88
Error_moving=Inesperado error moviendo el fichero
89
Error_help=Selecciona una ayuda
90
Rename_succesfully=Renombrado del fichero realizado con \u00e9xito
91
Select_first=Debe seleccionar un fichero primero
92
help_key=No hay ayuda para el texto
93

  
94

  
95
script_filesystem=script en el \u00e1rbol de directorio
96
Move=Mover
97
move_desc=Cambia la ubicaci\u00f3n del fichero seleccionado
98
Rename=Renombrar
99
rename_desc=Cambia el nombre y otras propiedades del fichero seleccionado
100
Moving_succesfully=Reubicaci\u00f3n del fichero realizado con \u00e9xito
101

  
102
Dialog=Di\u00e1logo
103
Code=C\u00f3digo
104
Properties=Propiedades
105

  
106
current_name=Nombre actual
107
new_name=Nuevo name
108
rename_name_title=Cambiar el nombre del fichero
109
more_properties=M\u00e1s propiedades
110

  
111
Javadoc_remove=Selecciona el JavaDoc a eliminar
112
no_Javadoc_remove=No hay JavaDoc para eliminar
113

  
114
Name=Nombre
115
Version=Versi\u00f3n
116
Created_by=Creado por
117
Description=Descripci\u00f3n
118
Type=Tipo
119
Language=Lenguaje
120
Author=Autor
121
Move_from=Mover desde
122
Move_to=Destino
123
Browse=Abrir
124
Import_from=Importar desde
125

  
126
Name_blank=El nombre no puede estar en blanco
127
Name_exists=Este nombre ya existe. Debe elegir otro
128
Import_success=Los JavaDocs se han importado satisfactoriamente
129
JavaDoc_Error=Selecciona JavaDoc a importar
130

  
131
go_to_line_Xhorizontal_ellipsisX=Ir a la l\u00ednea\u2026
132
find_Xhorizontal_ellipsisX=Buscar\u2026
133
replace_Xhorizontal_ellipsisX=Reemplazar\u2026
134
_Searching_autorun_scripts_Xhorizontal_ellipsisX=Buscando scripts de autoarranque...
135
_Starting_XnameX=Iniciando {0}...
136
_The_script_XscriptnameX_is_modified=El script "{0}" ha sido modificado.
137
_Save_changes_XquestionX=\u00bf Guardar cambios ?
138
_Do_you_want_to_save_changes_XquestionX=\u00bf Desea guardar los cambios ?
139

  
140
_notice=Aviso
141
_Initializing_the_scripting_plugin_Xhorizontal_ellipsisX=Inicializando el plugin de scripting...
142
_Waiting_to_terminate=Esperando que termine.
143

  
144
_Run_main_script=Ejecutar script principal
145
_Select_main_script=Seleccionar script pricipal
146
_Main_script_is_not_selected=No hay seleccionado un script como principal.
147
_The_selected_script_is_invalid=El script seleccionado no es valido.
148
_Do_you_want_to_select_one_and_execute_it=\u00bfDesea seleccionar uno y ejecutarlo ?
149

  
150
_The_changes_in_current_file_are_not_saved=Los cambios en el fichero corriente no han sido guardados.
151
_Do_you_want_to_continue_and_discard_the_changes=\u00bf Quiere continuar y descartar los cambios ?
152

  
153
_There_was_a_problem_starting_the_application_It_is_convenient_that_you_close_it_and_start_it_again=Ha habido un problema durante el inicio de la aplicaci\u00f3n.\nEs conveniente que la cierre y vuelva a iniciarla.
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/i18n/text_en.properties
1
_Scripting=Scripting
2
_Show_scripting_launcher=Show scripting launcher
3
_Show_scripting_composer=Show scripting composer
4
_Show_scripting_jython_console=Show Jython console
5

  
6
User=User
7
System=System
8

  
9
Accept=Accept
10
Cancel=Cancel
11
Apply=Apply
12

  
13
Retrieving_data=Retrieving data...
14

  
15
File=File
16
New=New
17
Close_document=Close document
18
Close_all_documents=Cloase all documents
19
Run=Run
20
Save=Save
21
Close=Close
22
Close_current_tab=Close current tab
23
Open_edition_mode=Open edition mode
24
Run_selected_script=Run selected script
25
Delete_selected_script=Delete selected script
26
Refresh_directories=Refresh directories
27
Move_files=Move files
28
Set_file_preferences=Set file preferences
29
_Running_autorun_script_from_XnameX=Running autorun script from {0}
30

  
31
Edit=Edit
32
Cut=Cut
33
Copy=Copy
34
Paste=Paste
35
Select_all=Select all
36

  
37
Tools=Tools
38
Launcher=Scripting Launcher
39
Scripting_Launcher=Scripting Launcher
40
Scripting_Composer=Scripting Composer
41
Jython_Console=Jython console
42
Import_JavaDoc=Import JavaDoc
43
JavaDoc=Java Help (JavaDoc)
44
Remove_JavaDoc=Remove JavaDoc
45
Help_contents=Help contents
46
About_scripts_editor=About scripts editor
47
Get_help=Help
48
Help=Help
49
_Package_script=Package script...
50
_Package_help=Package help...
51

  
52
Problems=Errors
53
Console=Console
54

  
55
Description=Description
56
Resource=Resource
57
Location=Location
58

  
59
no_line=no line
60
Line=Line
61

  
62
Welcome_message=Welcome to the scripting framework
63

  
64
Error_opening_in_edition_mode_title=Error opening file in edition mode
65
Error_opening_in_edition_mode=The file can't be opened in edition mode
66

  
67
New_Script=New element
68
New_Script_Description=Create a new script, dialog, project, directory
69

  
70
Deleting_JavaDocs_successfully_title=Operation successful
71
Deleting_JavaDocs_successfully=Deleting JavaDocs successfully
72

  
73
Import_JavaDoc_title=Import JavaDocs from filesystem to ScriptingFramework JavaDoc
74
Remove_JavaDoc_title=Remove JavaDocs from ScriptingFramework JavaDoc
75

  
76
projects_modified_title=Projects without saving
77
projects_modified=Some projects have been modified. Save changes?
78
project_modified=has been modified. Save changes?
79

  
80
Delete_all_title=Delete document
81
Delete_all_message=This action removes the document or directory with all its content. Do you wish to continue ?
82

  
83
About_us_title=Information about all the gvSIG's contributors
84

  
85
Success=Operation done successfully
86
Error=Error
87
Error_renaming=Unexpected error renaming the file
88
Error_moving=Unexpected error moving the file
89
Error_help=Select help
90
Rename_succesfully=Renaming successfully
91
Select_first=Select a file first
92
help_key=There isn't any help to this text
93

  
94

  
95
script_filesystem=script filesystem
96
Move=Move
97
move_desc=Change location of selected file
98
Rename=Rename
99
rename_desc=Change the name and more properties of the selected file
100
Moving_succesfully=File moved succesfully
101

  
102
Dialog=Dialog
103
Code=Code
104
Properties=Properties
105

  
106
current_name=Current name
107
new_name=New name
108
rename_name_title=Change filename
109
more_properties=more properties
110

  
111
Javadoc_remove=Choose JavaDoc to delete
112
no_Javadoc_remove=There's no JavaDoc to delete
113

  
114
Name=Name
115
Version=Version
116
Created_by=Create by
117
Description=Description
118
Type=Type
119
Language=Language
120
Author=Author
121
Move_from=Move from
122
Move_to=Move to
123
Browse=Browse
124
Import_from=Import from
125

  
126
Name_blank=Name can't be blank
127
Name_exists=This name already exists. Choose another one
128
Import_success=JavaDocs imported successfully
129
JavaDoc_Error=Select JavaDoc to import
130

  
131

  
132
go_to_line_Xhorizontal_ellipsisX=Go To Line\u2026
133
find_Xhorizontal_ellipsisX=Find\u2026
134
replace_Xhorizontal_ellipsisX=Replace\u2026
135

  
136
_Searching_autorun_scripts_Xhorizontal_ellipsisX=Searching autorun scripts...
137
_Starting_XnameX=Starting {0}...
138
_The_script_XscriptnameX_is_modified=The script "{0}" has been modified.
139
_Save_changes_XquestionX=Save changes ?
140
_Do_you_want_to_save_changes_XquestionX=Do you want to save changes ?
141

  
142
_notice=Notice
143
_Initializing_the_scripting_plugin_Xhorizontal_ellipsisX=Initializing the scripting plugin...
144
_Waiting_to_terminate=Waiting to terminate.
145

  
146
_Run_main_script=Run main script
147
_Select_main_script=Select main script
148
_Main_script_is_not_selected=Main script is not selected.
149
_The_selected_script_is_invalid=The selected script is not valid.
150
_Do_you_want_to_select_one_and_execute_it=Do you want to select one and execute it?
151

  
152

  
153
_The_changes_in_current_file_are_not_saved=The changes in the current file are not saved.
154
_Do_you_want_to_continue_and_discard_the_changes=Do you want to continue and discard the changes?
155

  
156
_There_was_a_problem_starting_the_application_It_is_convenient_that_you_close_it_and_start_it_again=There was a problem starting the application.\nIt is convenient that you close it and start it again.
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/License_Chalkwork_icons.txt
1
----------------------------------------------
2
CHALKWORK BASIC
3
by Dave Shea
4
mezzoblue.com/icons/chalkwork/basic
5
----------------------------------------------
6
CHALKWORK COMMERCE
7
by Dave Shea
8
mezzoblue.com/icons/chalkwork/commerce
9
----------------------------------------------
10
CHALKWORK EDITING CONTROLS
11
by Dave Shea
12
mezzoblue.com/icons/chalkwork/editing-controls
13
----------------------------------------------
14
CHALKWORK INFORMATION MANAGEMENT
15
by Dave Shea
16
mezzoblue.com/icons/chalkwork/information-management
17
----------------------------------------------
18
CHALKWORK HTML (Free Version)
19
by Dave Shea
20
mezzoblue.com/icons/chalkwork/html
21
----------------------------------------------
22

  
23
Thanks for your interest in the Chalkwork Family. Please consider subscribing to the Chalkwork news feed, which will announce new releases in the family as well as inform existing users of updates if any occur.
24

  
25
	http://mezzoblue.com/icons/chalkwork/news.xml
26

  
27
- Dave Shea
28
  mezzoblue.com
29
  @mezzoblue on Twitter
30

  
31

  
32

  
33

  
34
LICENSE AGREEMENT
35
----------------------------------------------
36
By downloading this icon set, you agree to abide by the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License under which these icons are being made available for non-commercial use.
37

  
38
	Applicable Creative Commons License: http://creativecommons.org/licenses/by-nc-sa/3.0/
39
	Attribution and additional license information: http://www.mezzoblue.com/icons/license/#license-cc
40

  
41
By purchasing a Chalkwork Commercial License, you agree to abide by the Chalkwork Royalty-Free Stock Icon License Agreement under which these icons are being made available for commercial use.
42

  
43
	Chalkwork Commercial License: http://www.mezzoblue.com/icons/license/#license-cc
44

  
45
This notice must be included any time these icons are redistributed.
46

  
47

  
48

  
49

  
50
----------------------------------------------
51
ICON FOLDER INDEX
52
----------------------------------------------
53
The icon files are broken down by file format. Due to some formats resulting in higher quality results, those are considered the preferred files and are located in the folder titled 'High Quality'. This package should contain the following folders in this hierarchy:
54

  
55
High Quality
56
    ICNS (Mac)
57
    ICO (Windows)
58
    PNG
59
    TIF
60
Lower Quality
61
    BMP
62
    GIF
63

  
64
Within each of the second-level folders, you'll find 102 further folders, one for each icon and its variations. Depending on the file format, you may find multiple sizes within these folders along with any icon variations that may exist. Please note that ICO and ICNS files contain all applicable sizes within a single file, and that ICNS files do not support the 24x24 icon size.
65

  
66

  
67
----------------------------------------------
68
CHALKWORK INFORMATION MANAGEMENT ICON INDEX
69
* indicates that variations of this icon are provided within this set
70
---------------------------------------------------------------------
71

  
72
Ad
73
	- Ad (Dollars) *
74
	- Ad (Euros) *
75
	- Ad (Pounds) *
76
Address Book *
77
Announcement *
78
API
79
Archive *
80
Attachment *
81
Authenticate
82
Blog *
83
Bookmark *
84
Briefcase *
85
Category *
86
Chart (Area) *
87
Chart (Bar) *
88
Chart (Pie) *
89
Collapse
90
Colour Palette *
91
Continue
92
Control Panel
93
Conversation *
94
Create
95
Dashboard *
96
Database *
97
Dictionary *
98
Document (Area Chart) *
99
Document (Bar Chart) *
100
Document (Blank) *
101
Document (Form) *
102
Document (Photo) *
103
Document (Pie Chart) *
104
Document (Secure) *
105
Document (Shred)
106
Documents (x2) *
107
Documents (x3) *
108
Download
109
Draw
110
Entry *
111
Excerpt *
112
Expand
113
Export
114
Fax *
115
File *
116
	- File (Closed)
117
	- File (Open)
118
Filter *
119
Flag *
120
Flag (Black) *
121
Flag (Blue) *
122
Flag (Brown) *
123
Flag (Green) *
124
Flag (Light Blue) *
125
Flag (Orange) *
126
Flag (Pink) *
127
Flag (Purple) *
128
Flag (Red) *
129
Flag (White) *
130
Flag (Yellow) *
131
Formatting
132
Hierarchy *
133
Import
134
Inbox *
135
Index *
136
List *
137
Log *
138
Map *
139
Mobile Phone *
140
Moderate
141
Module *
142
News *
143
Notes *
144
Notification *
145
Office *
146
Package *
147
Password
148
Phone *
149
	- Phone (Batphone) *
150
	- Phone (Office) *
151
Plugin *
152
Preview
153
Publish
154
Read More
155
Rebuild
156
Relationship (Data) *
157
Relationship (People) *
158
Rotate Left
159
Rotate Right
160
Schedule *
161
	- Schedule (Noun)
162
	- Schedule (Verb)
163
Script *
164
Security *
165
Sign In
166
Sign Out
167
Sort Down
168
Sort Up
169
Spam *
170
Statistics *
171
Status *
172
	- Status (Green)
173
	- Status (Off)
174
	- Status (On)
175
	- Status (Red)
176
	- Status (Yellow)
177
Support *
178
Sync
179
Template *
180
Ticket *
181
Time Zone *
182
Tools *
183
Trackback
184
View (Columns)
185
View (Lists)
186
View (Thumbnails)
187
Weather *
188
Write
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/package.rst
1

  
2
This plugin provides support for scripting to gvSIG.
3
Among other things it contains:
4

  
5
- The gvSIG scripting engine
6
- The gvSIG script editor
7
- Script engines for:
8
   - Jython
9
   - Groovy
10
   - javascript
11
   - Renjin
12

  
13
- The script install module for the add-on manager.
14
- Utilities to generate packages of complements with our scripts.
15
- Python libraries as:
16
   - Six - Utilities for writing code that runs on Python 2 and 3
17
   - PyLint - Python source code analyzer
18
   - Pygments - syntax highlighting package
19
   - CSSUtils - CSS Cascading Style Sheets library
20
   - Docutils - Python Documentation Utilities
21
   - geopy - client for several popular geocoding web services
22
   - PyInliner - CSS-to-inline-styles conversion tool for HTML
23
   - Statistics - functions for calculating statistics of data
24
   - Cartodb - simple CartoDB client to perform requests against the CartoDB API
25

  
26
- Java libraries to use from scripting as:
27
   - Abeille forms deseigner
28
   - jOpenDocument
29
   - JNumeric
30
   - CSSBox
31

  
32
This plugin can be configured to be preinstalled automatically, allowing 
33
"Script" type plugins to be installed during the application installation process. 
34
To do this, the following entries must be added to the "packages.properties" 
35
of gvspks::
36

  
37
    installers=scripts
38
    installer.scripts.initializer=org.gvsig.scripting.app.extension.ScriptsInstallerInitializer
39
    installer.scripts.package.code=org.gvsig.scripting.app.mainplugin
40
    installer.scripts.factory.name=Script
41
    installer.scripts.libs=lib
42

  
43
If the "installers" entry already exists, add "scripts" to the end separating 
44
it with a space.
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib/geopy/__init__.py
1
"""
2
geopy is a Python 2 and 3 client for several popular geocoding web services.
3

  
4
geopy makes it easy for Python developers to locate the coordinates of
5
addresses, cities, countries, and landmarks across the globe using third-party
6
geocoders and other data sources.
7

  
8
geopy is tested against CPython 2.7, CPython 3.2, CPython 3.4, PyPy, and PyPy3.
9
"""
10

  
11
from geopy.point import Point
12
from geopy.location import Location
13
from geopy.geocoders import * # pylint: disable=W0401
14
from geopy.util import __version__
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib/geopy/exc.py
1
"""
2
Exceptions raised by geopy.
3
"""
4

  
5
class GeopyError(Exception):
6
    """
7
    Geopy-specific exceptions are all inherited from GeopyError.
8
    """
9

  
10
class ConfigurationError(GeopyError):
11
    """
12
    When instantiating a geocoder, the arguments given were invalid. See
13
    the documentation of each geocoder's `__init__` for more details.
14
    """
15

  
16
class GeocoderServiceError(GeopyError):
17
    """
18
    There was an exception caused when calling the remote geocoding service,
19
    and no more specific exception could be raised by geopy. When calling
20
    geocoders' `geocode` or `reverse` methods, this is the most general
21
    exception that can be raised, and any non-geopy exception will be caught
22
    and turned into this. The exception's message will be that of the
23
    original exception.
24
    """
25

  
26
class GeocoderQueryError(GeocoderServiceError):
27
    """
28
    Either geopy detected input that would cause a request to fail,
29
    or a request was made and the remote geocoding service responded
30
    that the request was bad.
31
    """
32

  
33
class GeocoderQuotaExceeded(GeocoderServiceError):
34
    """
35
    The remote geocoding service refused to fulfill the request
36
    because the client has used its quota.
37
    """
38

  
39
class GeocoderAuthenticationFailure(GeocoderServiceError):
40
    """
41
    The remote geocoding service rejects the API key or account
42
    credentials this geocoder was instantiated with.
43
    """
44

  
45
class GeocoderInsufficientPrivileges(GeocoderServiceError):
46
    """
47
    The remote geocoding service refused to fulfill a request using the
48
    account credentials given.
49
    """
50

  
51
class GeocoderTimedOut(GeocoderServiceError):
52
    """
53
    The call to the geocoding service was aborted because no response
54
    was receiving within the `timeout` argument of either the geocoding class
55
    or, if specified, the method call. Some services are just consistently
56
    slow, and a higher timeout may be needed to use them.
57
    """
58

  
59
class GeocoderUnavailable(GeocoderServiceError):
60
    """
61
    Either it was not possible to establish a connection to the remote
62
    geocoding service, or the service responded with a code indicating
63
    it was unavailable.
64
    """
65

  
66
class GeocoderParseError(GeocoderServiceError):
67
    """
68
    Geopy could not parse the service's response. This is a bug in geopy.
69
    """
70

  
71
class GeocoderNotFound(GeopyError):
72
    """
73
    Caller requested the geocoder matching a string, e.g.,
74
    "google" > GoogleV3, but no geocoder could be found.
75
    """
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib/geopy/units.py
1
"""
2
Convert units.
3
"""
4

  
5
import math
6

  
7

  
8
# Angles
9

  
10
def degrees(radians=0, arcminutes=0, arcseconds=0): # pylint: disable=W0621
11
    """
12
    TODO docs.
13
    """
14
    deg = 0.
15
    if radians:
16
        deg = math.degrees(radians)
17
    if arcminutes:
18
        deg += arcminutes / arcmin(degrees=1.)
19
    if arcseconds:
20
        deg += arcseconds / arcsec(degrees=1.)
21
    return deg
22

  
23
def radians(degrees=0, arcminutes=0, arcseconds=0): # pylint: disable=W0621
24
    """
25
    TODO docs.
26
    """
27
    if arcminutes:
28
        degrees += arcminutes / arcmin(degrees=1.)
29
    if arcseconds:
30
        degrees += arcseconds / arcsec(degrees=1.)
31
    return math.radians(degrees)
32

  
33
def arcminutes(degrees=0, radians=0, arcseconds=0): # pylint: disable=W0621
34
    """
35
    TODO docs.
36
    """
37
    if radians:
38
        degrees += math.degrees(radians)
39
    if arcseconds:
40
        degrees += arcseconds / arcsec(degrees=1.)
41
    return degrees * 60.
42

  
43
def arcseconds(degrees=0, radians=0, arcminutes=0): # pylint: disable=W0621
44
    """
45
    TODO docs.
46
    """
47
    if radians:
48
        degrees += math.degrees(radians)
49
    if arcminutes:
50
        degrees += arcminutes / arcmin(degrees=1.)
51
    return degrees * 3600.
52

  
53

  
54
# Lengths
55

  
56
def kilometers(meters=0, miles=0, feet=0, nautical=0): # pylint: disable=W0621
57
    """
58
    TODO docs.
59
    """
60
    ret = 0.
61
    if meters:
62
        ret += meters / 1000.
63
    if feet:
64
        miles += feet / ft(1.)
65
    if nautical:
66
        ret += nautical / nm(1.)
67
    ret += miles * 1.609344
68
    return ret
69

  
70
def meters(kilometers=0, miles=0, feet=0, nautical=0): # pylint: disable=W0621
71
    """
72
    TODO docs.
73
    """
74
    return (kilometers + km(nautical=nautical, miles=miles, feet=feet)) * 1000
75

  
76
def miles(kilometers=0, meters=0, feet=0, nautical=0): # pylint: disable=W0621
77
    """
78
    TODO docs.
79
    """
80
    ret = 0.
81
    if nautical:
82
        kilometers += nautical / nm(1.)
83
    if feet:
84
        ret += feet / ft(1.)
85
    if meters:
86
        kilometers += meters / 1000.
87
    ret += kilometers / 1.609344
88
    return ret
89

  
90
def feet(kilometers=0, meters=0, miles=0, nautical=0): # pylint: disable=W0621
91
    """
92
    TODO docs.
93
    """
94
    ret = 0.
95
    if nautical:
96
        kilometers += nautical / nm(1.)
97
    if meters:
98
        kilometers += meters / 1000.
99
    if kilometers:
100
        miles += mi(kilometers=kilometers)
101
    ret += miles * 5280
102
    return ret
103

  
104
def nautical(kilometers=0, meters=0, miles=0, feet=0): # pylint: disable=W0621
105
    """
106
    TODO docs.
107
    """
108
    ret = 0.
109
    if feet:
110
        miles += feet / ft(1.)
111
    if miles:
112
        kilometers += km(miles=miles)
113
    if meters:
114
        kilometers += meters / 1000.
115
    ret += kilometers / 1.852
116
    return ret
117

  
118

  
119
# Compatible names
120

  
121
rad = radians # pylint: disable=C0103
122
arcmin = arcminutes # pylint: disable=C0103
123
arcsec = arcseconds # pylint: disable=C0103
124
km = kilometers # pylint: disable=C0103
125
m = meters # pylint: disable=C0103
126
mi = miles # pylint: disable=C0103
127
ft = feet # pylint: disable=C0103
128
nm = nautical # pylint: disable=C0103
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib/geopy/compat.py
1
"""
2
Compatibility...
3
"""
4

  
5
import sys
6

  
7
py3k = sys.version_info >= (3, 0)
8

  
9
if py3k: # pragma: no cover
10
    string_compare = str
11
else: # pragma: no cover
12
    string_compare = (str, unicode)
13

  
14
# Unicode compatibility, borrowed from 'six'
15
if py3k: # pragma: no cover
16
    def u(s):
17
        """
18
        Convert to Unicode with py3k
19
        """
20
        return s
21
else: # pragma: no cover
22
    def u(s):
23
        """
24
        Convert to Unicode with unicode escaping
25
        """
26
        return unicode(s.replace(r'\\', r'\\\\'), 'unicode_escape')
27

  
28
if py3k: # pragma: no cover
29
    from urllib.parse import urlencode, quote # pylint: disable=W0611,F0401,W0611,E0611
30
    from urllib.request import (Request, urlopen, # pylint: disable=W0611,F0401,W0611,E0611
31
                                build_opener, ProxyHandler,
32
                                URLError, install_opener,
33
                                HTTPPasswordMgrWithDefaultRealm,
34
                                HTTPBasicAuthHandler)
35
    from urllib.error import HTTPError # pylint: disable=W0611,F0401,W0611,E0611
36

  
37
    def itervalues(d):
38
        """
39
        Function for iterating on values due to methods
40
        renaming between Python 2 and 3 versions
41
        For Python2
42
        """
43
        return iter(d.values())
44
    def iteritems(d):
45
        """
46
        Function for iterating on items due to methods
47
        renaming between Python 2 and 3 versions
48
        For Python2
49
        """
50
        return iter(d.items())
51

  
52
else: # pragma: no cover
53
    from urllib import urlencode as original_urlencode, quote # pylint: disable=W0611,F0401,W0611,E0611
54
    from urllib2 import (Request, HTTPError,   # pylint: disable=W0611,F0401,W0611,E0611
55
                         ProxyHandler, URLError, urlopen,
56
                         build_opener, install_opener,
57
                         HTTPPasswordMgrWithDefaultRealm,
58
                         HTTPBasicAuthHandler)
59

  
60
    def force_str(str_or_unicode):
61
        """
62
        Python2-only, ensures that a string is encoding to a str.
63
        """
64
        if isinstance(str_or_unicode, unicode):
65
            return str_or_unicode.encode('utf-8')
66
        else:
67
            return str_or_unicode
68

  
69
    def urlencode(query, doseq=0):
70
        """
71
        A version of Python's urllib.urlencode() function that can operate on
72
        unicode strings. The parameters are first cast to UTF-8 encoded strings
73
        and then encoded as per normal.
74

  
75
        Based on the urlencode from django.utils.http
76
        """
77
        if hasattr(query, 'items'):
78
            query = query.items()
79
        return original_urlencode(
80
            [(force_str(k),
81
              [force_str(i) for i in v]
82
              if isinstance(v, (list, tuple)) else force_str(v))
83
             for k, v in query],
84
            doseq)
85

  
86
    def itervalues(d):
87
        """
88
        Function for iterating on values due to methods
89
        renaming between Python 2 and 3 versions
90
        For Python3
91
        """
92
        return d.itervalues()
93
    def iteritems(d):
94
        """
95
        Function for iterating on items due to methods
96
        renaming between Python 2 and 3 versions
97
        For Python3
98
        """
99
        return d.iteritems()
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib/geopy/geocoders/baidu.py
1
"""
2
:class:`.Baidu` is the Baidu Maps geocoder.
3
"""
4

  
5
from geopy.compat import urlencode
6
from geopy.geocoders.base import Geocoder, DEFAULT_TIMEOUT
7
from geopy.exc import (
8
    GeocoderQueryError,
9
    GeocoderQuotaExceeded,
10
    GeocoderAuthenticationFailure,
11
)
12
from geopy.location import Location
13
from geopy.util import logger
14

  
15

  
16
__all__ = ("Baidu", )
17

  
18

  
19
class Baidu(Geocoder):
20
    """
21
    Geocoder using the Baidu Maps v2 API. Documentation at:
22
        http://developer.baidu.com/map/webservice-geocoding.htm
23
    """
24

  
25
    def __init__(
26
            self,
27
            api_key,
28
            scheme='http',
29
            timeout=DEFAULT_TIMEOUT,
30
            proxies=None,
31
            user_agent=None
32
        ):
33
        """
34
        Initialize a customized Baidu geocoder using the v2 API.
35

  
36
        .. versionadded:: 1.0.0
37

  
38
        :param string api_key: The API key required by Baidu Map to perform
39
            geocoding requests. API keys are managed through the Baidu APIs
40
            console (http://lbsyun.baidu.com/apiconsole/key).
41

  
42
        :param string scheme: Use 'https' or 'http' as the API URL's scheme.
43
            Default is http and only http support.
44

  
45
        :param dict proxies: If specified, routes this geocoder's requests
46
            through the specified proxy. E.g., {"https": "192.0.2.0"}. For
47
            more information, see documentation on
48
            :class:`urllib2.ProxyHandler`.
49
        """
50
        super(Baidu, self).__init__(
51
            scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent
52
        )
53
        self.api_key = api_key
54
        self.scheme = scheme
55
        self.doc = {}
56
        self.api = 'http://api.map.baidu.com/geocoder/v2/'
57

  
58

  
59
    @staticmethod
60
    def _format_components_param(components):
61
        """
62
        Format the components dict to something Baidu understands.
63
        """
64
        return "|".join(
65
            (":".join(item)
66
             for item in components.items()
67
            )
68
        )
69

  
70
    def geocode(
71
            self,
72
            query,
73
            exactly_one=True,
74
            timeout=None
75
        ):
76
        """
77
        Geocode a location query.
78

  
79
        :param string query: The address or query you wish to geocode.
80

  
81
        :param bool exactly_one: Return one result or a list of results, if
82
            available.
83

  
84
        :param int timeout: Time, in seconds, to wait for the geocoding service
85
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
86
            exception. Set this only if you wish to override, on this call
87
            only, the value set during the geocoder's initialization.
88

  
89
        """
90
        params = {
91
            'ak': self.api_key,
92
            'output': 'json',
93
            'address': self.format_string % query,
94
        }
95

  
96
        url = "?".join((self.api, urlencode(params)))
97
        logger.debug("%s.geocode: %s", self.__class__.__name__, url)
98
        return self._parse_json(
99
            self._call_geocoder(url, timeout=timeout), exactly_one=exactly_one
100
        )
101

  
102
    def reverse(self, query, timeout=None):  # pylint: disable=W0221
103
        """
104
        Given a point, find an address.
105

  
106
        :param query: The coordinates for which you wish to obtain the
107
            closest human-readable addresses.
108
        :type query: :class:`geopy.point.Point`, list or tuple of (latitude,
109
            longitude), or string as "%(latitude)s, %(longitude)s"
110

  
111
        :param int timeout: Time, in seconds, to wait for the geocoding service
112
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
113
            exception. Set this only if you wish to override, on this call
114
            only, the value set during the geocoder's initialization.
115

  
116
        """
117
        params = {
118
            'ak': self.api_key,
119
            'output': 'json',
120
            'location': self._coerce_point_to_string(query),
121
        }
122

  
123
        url = "?".join((self.api, urlencode(params)))
124

  
125
        logger.debug("%s.reverse: %s", self.__class__.__name__, url)
126
        return self._parse_reverse_json(
127
            self._call_geocoder(url, timeout=timeout)
128
        )
129

  
130

  
131
    @staticmethod
132
    def _parse_reverse_json(page):
133
        """
134
        Parses a location from a single-result reverse API call.
135
        """
136
        place = page.get('result')
137

  
138
        location = place.get('formatted_address').encode('utf-8')
139
        latitude = place['location']['lat']
140
        longitude = place['location']['lng']
141

  
142
        return Location(location, (latitude, longitude), place)
143

  
144

  
145
    def _parse_json(self, page, exactly_one=True):
146
        """
147
        Returns location, (latitude, longitude) from JSON feed.
148
        """
149

  
150
        place = page.get('result', None)
151

  
152
        if not place:
153
            self._check_status(page.get('status'))
154
            return None
155

  
156
        def parse_place(place):
157
            """
158
            Get the location, lat, lng from a single JSON place.
159
            """
160
            location = place.get('level')
161
            latitude = place['location']['lat']
162
            longitude = place['location']['lng']
163
            return Location(location, (latitude, longitude), place)
164

  
165
        if exactly_one:
166
            return parse_place(place)
167
        else:
168
            return [parse_place(item) for item in place]
169

  
170
    @staticmethod
171
    def _check_status(status):
172
        """
173
        Validates error statuses.
174
        """
175
        if status == '0':
176
            # When there are no results, just return.
177
            return
178
        if status == '1':
179
            raise GeocoderQueryError(
180
                'Internal server error.'
181
            )
182
        elif status == '2':
183
            raise GeocoderQueryError(
184
                'Invalid request.'
185
            )
186
        elif status == '3':
187
            raise GeocoderAuthenticationFailure(
188
                'Authentication failure.'
189
            )
190
        elif status == '4':
191
            raise GeocoderQuotaExceeded(
192
                'Quota validate failure.'
193
            )
194
        elif status == '5':
195
            raise GeocoderQueryError(
196
                'AK Illegal or Not Exist.'
197
            )
198
        elif status == '101':
199
            raise GeocoderQueryError(
200
                'Your request was denied.'
201
            )
202
        elif status == '102':
203
            raise GeocoderQueryError(
204
                'IP/SN/SCODE/REFERER Illegal:'
205
            )
206
        elif status == '2xx':
207
            raise GeocoderQueryError(
208
                'Has No Privilleges.'
209
            )
210
        elif status == '3xx':
211
            raise GeocoderQuotaExceeded(
212
                'Quota Error.'
213
            )
214
        else:
215
            raise GeocoderQueryError('Unknown error')
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.221/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib/geopy/geocoders/googlev3.py
1
"""
2
:class:`.GoogleV3` is the Google Maps V3 geocoder.
3
"""
4

  
5
import base64
6
import hashlib
7
import hmac
8
from geopy.compat import urlencode
9
from geopy.geocoders.base import Geocoder, DEFAULT_TIMEOUT, DEFAULT_SCHEME
10
from geopy.exc import (
11
    GeocoderQueryError,
12
    GeocoderQuotaExceeded,
13
    ConfigurationError,
14
    GeocoderParseError,
15
    GeocoderQueryError,
16
)
17
from geopy.location import Location
18
from geopy.util import logger
19

  
20
try:
21
    from pytz import timezone, UnknownTimeZoneError
22
    from calendar import timegm
23
    from datetime import datetime
24
    from numbers import Number
25
    pytz_available = True
26
except ImportError:
27
    pytz_available = False
28

  
29

  
30
__all__ = ("GoogleV3", )
31

  
32

  
33
class GoogleV3(Geocoder):  # pylint: disable=R0902
34
    """
35
    Geocoder using the Google Maps v3 API. Documentation at:
36
        https://developers.google.com/maps/documentation/geocoding/
37
    """
38

  
39
    def __init__(
40
            self,
41
            api_key=None,
42
            domain='maps.googleapis.com',
43
            scheme=DEFAULT_SCHEME,
44
            client_id=None,
45
            secret_key=None,
46
            timeout=DEFAULT_TIMEOUT,
47
            proxies=None,
48
            user_agent=None,
49
        ):  # pylint: disable=R0913
50
        """
51
        Initialize a customized Google geocoder.
52

  
53
        API authentication is only required for Google Maps Premier customers.
54

  
55
        :param string api_key: The API key required by Google to perform
56
            geocoding requests. API keys are managed through the Google APIs
57
            console (https://code.google.com/apis/console).
58

  
59
            .. versionadded:: 0.98.2
60

  
61
        :param string domain: Should be the localized Google Maps domain to
62
            connect to. The default is 'maps.googleapis.com', but if you're
63
            geocoding address in the UK (for example), you may want to set it
64
            to 'maps.google.co.uk' to properly bias results.
65

  
66
        :param string scheme: Use 'https' or 'http' as the API URL's scheme.
67
            Default is https. Note that SSL connections' certificates are not
68
            verified.
69

  
70
            .. versionadded:: 0.97
71

  
72
        :param string client_id: If using premier, the account client id.
73

  
74
        :param string secret_key: If using premier, the account secret key.
75

  
76
        :param dict proxies: If specified, routes this geocoder's requests
77
            through the specified proxy. E.g., {"https": "192.0.2.0"}. For
78
            more information, see documentation on
79
            :class:`urllib2.ProxyHandler`.
80

  
81
            .. versionadded:: 0.96
82
        """
83
        super(GoogleV3, self).__init__(
84
            scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent
85
        )
86
        if client_id and not secret_key:
87
            raise ConfigurationError('Must provide secret_key with client_id.')
88
        if secret_key and not client_id:
89
            raise ConfigurationError('Must provide client_id with secret_key.')
90

  
91
        self.api_key = api_key
92
        self.domain = domain.strip('/')
93
        self.scheme = scheme
94
        self.doc = {}
95

  
96
        if client_id and secret_key:
97
            self.premier = True
98
            self.client_id = client_id
99
            self.secret_key = secret_key
100
        else:
101
            self.premier = False
102
            self.client_id = None
103
            self.secret_key = None
104

  
105
        self.api = '%s://%s/maps/api/geocode/json' % (self.scheme, self.domain)
106
        self.tz_api = '%s://%s/maps/api/timezone/json' % (
107
            self.scheme,
108
            self.domain
109
        )
110

  
111
    def _get_signed_url(self, params):
112
        """
113
        Returns a Premier account signed url. Docs on signature:
114
            https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures
115
        """
116
        params['client'] = self.client_id
117
        path = "?".join(('/maps/api/geocode/json', urlencode(params)))
118
        signature = hmac.new(
119
            base64.urlsafe_b64decode(self.secret_key),
120
            path.encode('utf-8'),
121
            hashlib.sha1
122
        )
123
        signature = base64.urlsafe_b64encode(
124
            signature.digest()
125
        ).decode('utf-8')
126
        return '%s://%s%s&signature=%s' % (
127
            self.scheme, self.domain, path, signature
128
        )
129

  
130
    @staticmethod
131
    def _format_components_param(components):
132
        """
133
        Format the components dict to something Google understands.
134
        """
135
        return "|".join(
136
            (":".join(item)
137
             for item in components.items()
138
            )
139
        )
140

  
141
    @staticmethod
142
    def _format_bounds_param(bounds):
143
      """
144
      Format the bounds to something Google understands.
145
      """
146
      return '%f,%f|%f,%f' % (bounds[0], bounds[1], bounds[2], bounds[3])
147

  
148
    def geocode(
149
            self,
150
            query,
151
            exactly_one=True,
152
            timeout=None,
153
            bounds=None,
154
            region=None,
155
            components=None,
156
            language=None,
157
            sensor=False,
158
        ):  # pylint: disable=W0221,R0913
159
        """
160
        Geocode a location query.
161

  
162
        :param string query: The address or query you wish to geocode.
163

  
164
        :param bool exactly_one: Return one result or a list of results, if
165
            available.
166

  
167
        :param int timeout: Time, in seconds, to wait for the geocoding service
168
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
169
            exception. Set this only if you wish to override, on this call
170
            only, the value set during the geocoder's initialization.
171

  
172
            .. versionadded:: 0.97
173

  
174
        :param bounds: The bounding box of the viewport within which
175
            to bias geocode results more prominently.
176
        :type bounds: list or tuple
177

  
178
        :param string region: The region code, specified as a ccTLD
179
            ("top-level domain") two-character value.
180

  
181
        :param dict components: Restricts to an area. Can use any combination
182
            of: route, locality, administrative_area, postal_code, country.
183

  
184
            .. versionadded:: 0.97.1
185

  
186
        :param string language: The language in which to return results.
187

  
188
        :param bool sensor: Whether the geocoding request comes from a
189
            device with a location sensor.
190
        """
191
        params = {
192
            'address': self.format_string % query,
193
            'sensor': str(sensor).lower()
194
        }
195
        if self.api_key:
196
            params['key'] = self.api_key
197
        if bounds:
198
            if len(bounds) != 4:
199
                raise GeocoderQueryError(
200
                    "bounds must be a four-item iterable of lat,lon,lat,lon"
201
                )
202
            params['bounds'] = self._format_bounds_param(bounds)
203
        if region:
204
            params['region'] = region
205
        if components:
206
            params['components'] = self._format_components_param(components)
207
        if language:
208
            params['language'] = language
209

  
210
        if self.premier is False:
211
            url = "?".join((self.api, urlencode(params)))
212
        else:
213
            url = self._get_signed_url(params)
214

  
215
        logger.debug("%s.geocode: %s", self.__class__.__name__, url)
216
        return self._parse_json(
217
            self._call_geocoder(url, timeout=timeout), exactly_one
218
        )
219

  
220
    def reverse(
221
            self,
222
            query,
223
            exactly_one=False,
224
            timeout=None,
225
            language=None,
226
            sensor=False,
227
        ):  # pylint: disable=W0221,R0913
228
        """
229
        Given a point, find an address.
230

  
231
        :param query: The coordinates for which you wish to obtain the
232
            closest human-readable addresses.
233
        :type query: :class:`geopy.point.Point`, list or tuple of (latitude,
234
            longitude), or string as "%(latitude)s, %(longitude)s"
235

  
236
        :param boolean exactly_one: Return one result or a list of results, if
237
            available.
238

  
239
        :param int timeout: Time, in seconds, to wait for the geocoding service
240
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
241
            exception.
242

  
243
            .. versionadded:: 0.97
244

  
245
        :param string language: The language in which to return results.
246

  
247
        :param boolean sensor: Whether the geocoding request comes from a
248
            device with a location sensor.
249
        """
250
        params = {
251
            'latlng': self._coerce_point_to_string(query),
252
            'sensor': str(sensor).lower()
253
        }
254
        if language:
255
            params['language'] = language
256
        if self.api_key:
257
            params['key'] = self.api_key
258

  
259
        if not self.premier:
260
            url = "?".join((self.api, urlencode(params)))
261
        else:
262
            url = self._get_signed_url(params)
263

  
264
        logger.debug("%s.reverse: %s", self.__class__.__name__, url)
265
        return self._parse_json(
266
            self._call_geocoder(url, timeout=timeout), exactly_one
267
        )
268

  
269
    def timezone(self, location, at_time=None, timeout=None):
270
        """
271
        **This is an unstable API.**
272

  
273
        Finds the timezone a `location` was in for a specified `at_time`,
274
        and returns a pytz timezone object.
275

  
276
            .. versionadded:: 1.2.0
277

  
278
        :param location: The coordinates for which you want a timezone.
279
        :type location: :class:`geopy.point.Point`, list or tuple of (latitude,
280
            longitude), or string as "%(latitude)s, %(longitude)s"
281

  
282
        :param at_time: The time at which you want the timezone of this
283
            location. This is optional, and defaults to the time that the
284
            function is called in UTC.
285
        :type at_time integer, long, float, datetime:
286

  
287
        :rtype: pytz timezone
288
        """
289
        if not pytz_available:
290
            raise ImportError(
291
                'pytz must be installed in order to locate timezones. '
292
                ' Install with `pip install geopy -e ".[timezone]"`.'
293
            )
294
        location = self._coerce_point_to_string(location)
295

  
296
        if isinstance(at_time, Number):
297
            timestamp = at_time
298
        elif isinstance(at_time, datetime):
299
            timestamp = timegm(at_time.utctimetuple())
300
        elif at_time is None:
301
            timestamp = timegm(datetime.utcnow().utctimetuple())
302
        else:
303
            raise GeocoderQueryError(
304
                "`at_time` must be an epoch integer or "
305
                "datetime.datetime object"
306
            )
307

  
308
        params = {
309
            "location": location,
310
            "timestamp": timestamp,
311
        }
312
        if self.api_key:
313
            params['key'] = self.api_key
314
        url = "?".join((self.tz_api, urlencode(params)))
315

  
316
        logger.debug("%s.timezone: %s", self.__class__.__name__, url)
317
        response = self._call_geocoder(url, timeout=timeout)
318

  
319
        try:
320
            tz = timezone(response["timeZoneId"])
321
        except UnknownTimeZoneError:
322
            raise GeocoderParseError(
323
                "pytz could not parse the timezone identifier (%s) "
324
                "returned by the service." % response["timeZoneId"]
325
            )
326
        except KeyError:
327
            raise GeocoderParseError(
328
                "geopy could not find a timezone in this response: %s" %
329
                response
330
            )
331
        return tz
332

  
333
    def _parse_json(self, page, exactly_one=True):
334
        '''Returns location, (latitude, longitude) from json feed.'''
335

  
336
        places = page.get('results', [])
337
        if not len(places):
338
            self._check_status(page.get('status'))
339
            return None
340

  
341
        def parse_place(place):
342
            '''Get the location, lat, lng from a single json place.'''
343
            location = place.get('formatted_address')
344
            latitude = place['geometry']['location']['lat']
345
            longitude = place['geometry']['location']['lng']
346
            return Location(location, (latitude, longitude), place)
347

  
348
        if exactly_one:
349
            return parse_place(places[0])
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff