Git Product home page Git Product logo

google-visualization-python's Introduction

Google Visualization API

This project is a helper python library for providers who want to implement a data source for visualizations built on the Google Visualization API.

  • Documentation - See the API documentation for details about how to use this library.
  • Installation - pip install gviz_api
  • Samples - You can see sample code illustrating how to use the library here.
(Please note that the dynamic example is not a full html page example but rather is an actual data source url that you can plug into a google.visualization.Query. See documentation at: http://code.google.com/apis/visualization/documentation/queries.html)

License

Copyright (C) 2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

google-visualization-python's People

Contributors

mishas avatar perimosocordiae avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-visualization-python's Issues

ToJSCode method is too slow

ToJSCode method uses a very inefficient way of concatenating strings: it uses += operator. For "toy" strings this is ok, but when strings get very large, this method takes an excruciatingly long amount of time (hours) to complete. Fortunately, it is easily fixable: put all sub-strings into a list and return a join of them at the end of the function.

Python uses C-style strings: concatenating them with + operator is extremely inefficient since it takes time just to find the end of the string (\0 character) where the concatenation should take place. This is why ''.join(some_list) is much (orders of magnitude) faster than concatenating with + operator.

If possible, please implement this quick fix.

in ToCsv, use standard CSV separator instead of " ,"

Should just change the default value of ToCsv() separator param to ',' 

http://tools.ietf.org/html/rfc4180


   4.  Within the header and each record, there may be one or more
       fields, separated by commas.  Each line should contain the same
       number of fields throughout the file.  Spaces are considered part
       of a field and should not be ignored.  The last field in the
       record must not be followed by a comma.  For example:

       aaa,bbb,ccc

Original issue reported on code.google.com by [email protected] on 18 Mar 2011 at 10:02

Error TimeOfDay milliseconds between 00:00:00.000 and 00:59:59.999

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

.........................

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback (drawChart);

function drawChart ()
{
var data = new google.visualization.DataTable ();
data.addColumn('timeofday', 'Time');
data.addColumn('number', 'Data');
data.addRows
([
[[00,00,00,001],5], // Error: chart shows 00:00:00..999
[[00,59,59,999],10], // Error: chart shows 00:59:59..001
[[01,00,00,001],6], // Good: chart shows 01:00:00.001
]);
var options =
{
backgroundColor: 'white'
};

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw (data, options);
}

.........................

Thanks!

Weird testing pattern.

While it's nice to have the `test` command directly available, I would much 
prefer to have test available as an option with possible dependencies such as 
`nosetest` and `coverage`. Overwriting method with `pass` as is currently the 
case is not best practice.

Regarding the tests themselves: unit tests should test individual methods and 
functions in isolation where possible with additional tests for different code 
paths. Currently _InnerAppendData has no test coverage and AppendData contains 
not only tests for different code paths into the method but also for detecting 
exceptions that will be raised by _InnerAppendData. I will submit a patch both 
for testing and for the setup.

Original issue reported on code.google.com by [email protected] on 6 May 2012 at 9:21

Add support for decimal.Decimal

What
Allow the developer to add not only int, long, float values but also 
decimal.Decimal values.

Why
When writing your own data source, you often pull data from a MySQL database. 
Any aggregation in the database (like AVG() or SUM()) returns a 
decimal.Decimal. It's bothersome to have to cast to int, long, or float and you 
have to take care of None values separately. It would be better if you could 
add any numbers from the database to a DataTable without having to know what 
SQL generated it.

Original issue reported on code.google.com by [email protected] on 18 Apr 2012 at 6:46

Missing __init__.py file

What steps will reproduce the problem?
1. Add the trunk of this project to mine using svn:externals
2. Try to import gviz_api.py
3. Missing __init__.py causes fail

Checking in an __init__.py at the top-level trunk directory would be really 
cool.

Original issue reported on code.google.com by [email protected] on 24 Nov 2009 at 5:20

User specified precision for float values

I am sometimes sending a lot of float values over the wire however most of the 
time I am only interested in a the first 3 or 4 digits after the comma. 
However right now (even when the float is rounded) all digits are transmitted 
which increases the payload size significantly. 

It would be helpful to have a method that allows the user to specify the 
precision of the float. 

Right now I monkeypatched the ToString(value) method to return a float with 
precision 2 (hardcoded)

"%.2f" % value instead of just str(value).lower()

It would be nice if we could configure the precision somehow (maybe by column 
proprerties)?

Original issue reported on code.google.com by [email protected] on 3 Oct 2012 at 12:35

Timeline: When only having id, Start, End, if added a column with special role, this column will be ignored

My use case is in Timeline chart.
For example, now there are only 3 columns in the dataTable, which is id, Start, and End, and I want to format the color of each data row, so I added a column, specifying {'role': 'style'}, the conversion from python code to js will be successful, but this column will be ignored.
I will have to add another data column, and then this 'style' column will be recognized.
I find it a little confusing, because in the documentation, only three columns are mandatory.

Example bug code:
description = {"id": ("string", "id"), "style": ("string", "style", {'role': 'style'}), "Start": ("datetime", "Start"), "End": ("datetime", "End")}
data = [{"id": "001", "style": 'opacity: 0.5', "Start": datetime(2018, 2, 2, 8, 0, 0), "End": datetime(2018, 2, 2, 8, 30, 0)}, {"id": "001", "style": 'color: #0000cf', "Start": datetime(2018, 2, 2, 8, 30, 0), "End": datetime(2018, 2, 2, 9, 30, 0)}, {"id": "001", "style": 'color: #603913', "Start": datetime(2018, 2, 2, 10, 30, 0), "End": datetime(2018, 2, 2, 11, 30, 0)}, {"id": "002", "style": 'color: #cbb69d', "Start": datetime(2018, 2, 2, 9, 0, 0), "End": datetime(2018, 2, 2, 9, 30, 0)}, {"id": "002", "style": 'color: #603913', "Start": datetime(2018, 2, 2, 11, 30, 0), "End": datetime(2018, 2, 2, 12, 30, 0)}]
This will not work, I will have to add another column in the dataTable.
description = {"id": ("string", "id"), "State": ("string", "State"), "style": ("string", "style", {'role': 'style'}), "Start": ("datetime", "Start"), "End": ("datetime", "End")}

data = [{"id": "001", "State": "Completed", "style": 'opacity: 0.5', "Start": datetime(2018, 2, 2, 8, 0, 0), "End": datetime(2018, 2, 2, 8, 30, 0)}, {"id": "001", "State": "Completed", "style": 'color: #0000cf', "Start": datetime(2018, 2, 2, 8, 30, 0), "End": datetime(2018, 2, 2, 9, 30, 0)}, {"id": "001", "State": "Incompleted", "style": 'color: #603913', "Start": datetime(2018, 2, 2, 10, 30, 0), "End": datetime(2018, 2, 2, 11, 30, 0)}, {"id": "002", "State": "Completed", "style": 'color: #cbb69d', "Start": datetime(2018, 2, 2, 9, 0, 0), "End": datetime(2018, 2, 2, 9, 30, 0)}, {"id": "002", "State": "Incompleted", "style": 'color: #603913', "Start": datetime(2018, 2, 2, 11, 30, 0), "End": datetime(2018, 2, 2, 12, 30, 0)}]

as reqID is required parameter default of 0 is unhelpful

What steps will reproduce the problem?
Adding a second visualization to a page fails if reqID=0
The supplied example will fail this test

What is the expected output? What do you see instead?
It would be nice to see the example improved to use reqID as per the 0.6 
standard.

What version of the product are you using? On what operating system?
1.7.0  for protocol ver 0.6

Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 21 Nov 2011 at 7:47

ToCsv() generates JavaScript dates instead of spreadsheet-readable dates

What steps will reproduce the problem?

Let's say you want to build a data source showing your ice cream consumption 
per day. Users should be able to download the data in CSV format, so they can 
import it into their own spreadsheets. Let's say you ate one ice cream on Jan 1 
and two ice creams on Jan 2. Start the Python interpreter and run the following 
code:
------------------------------
import datetime
import gviz_api
data = []
row = {}
row['date'] = datetime.date(2011,1,1)
row['icecreams'] = 1
data.append(row)
row = {}
row['date'] = datetime.date(2011,1,2)
row['icecreams'] = 2
data.append(row)
description = {}
description["date"] = ("date", "Date")
description["icecreams"] = ("number", "Ice creams eaten")
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
print data_table.ToCsv()
------------------------------


What is the expected output? What do you see instead?

I expected this output:
"Date", "Ice creams eaten"
"2011-01-01", 1
"2011-01-02", 2

Instead I got this output:
"Date", "Ice creams eaten"
"new Date(2011,0,1)", 1
"new Date(2011,0,2)", 2

JavaScript formatting of dates makes sense in JSON output. In CSV output it 
doesn't. ISO-formatting, YYYY-MM-DD, would make more sense as it can be read by 
spreadsheet software.


What version of the product are you using? On what operating system?

gviz_api_py-1.7.0.tar.gz
Python 2.6.5
MacOS 10.5

Original issue reported on code.google.com by [email protected] on 30 Aug 2011 at 8:19

traceback if argument tqx ends semicolon in function toResponse

DataTable.ToResponse

In certain cases the argument tqx end with a Semicolon causing the the 
following traceback

Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/cherrypy/_cprequest.py", line 645, in respond
    response.body = self.handler()
  File "/usr/lib/python2.6/site-packages/cherrypy/lib/encoding.py", line 188, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "/usr/lib/python2.6/site-packages/cherrypy/_cpdispatch.py", line 29, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "/opt/sandbox/IDIPYT/trunk/src/py/_RECVIEW/Ajax.py", line 101, in timeLine
    return table.ToResponse(tqx = tqx)
  File "/usr/local/lib/python2.6/site-packages/gviz_api.py", line 1041, in ToResponse
    tqx_dict = dict(opt.split(":") for opt in tqx.split(";"))
ValueError: dictionary update sequence element #1 has length 1; 2 is required

adding at line 1033 solves the issue
if tqx.endswith(";") :
    tqx = tqx[:-1]

Original issue reported on code.google.com by [email protected] on 17 Oct 2011 at 11:15

Import error for json with Python <2.6

What steps will reproduce the problem?
1. Use library in Python <2.6
2. Get import error for "json"

What is the expected output? What do you see instead?
  Working module, import error.

What version of the product are you using? On what operating system?
  Python <2.6

Please provide any additional information below.
  Add import check against json and if failure, import simplejson.

Original issue reported on code.google.com by [email protected] on 22 Feb 2012 at 3:09

Project not available in PyPI

As the project already contains the setup.py file, it should be fairly easy to 
add it to PyPI. This would ease automatic installation, uninstallation, 
dependency management etc. for the users of google-visualization-python.

http://pypi.python.org/

Original issue reported on code.google.com by [email protected] on 15 Apr 2011 at 10:44

Feature Request: AddRow() method

While I very much appreciate this module I found it extremely counterintuitive 
to use. Allowing different constructors not only for the description but 
depending on their structure for adding data doesn't make sense to me. Surely, 
the two should be decoupled?

Be that as it may. One thing I found I wanted to use but found lacking was an 
AppendRow() method as AppendData() works row by row anyway.

  def AppendRow(self, row, custom_properties):
    self._InnerAppendData(({}, custom_properties), row, 0)

Original issue reported on code.google.com by [email protected] on 6 May 2012 at 12:08

convert nan and inf into JSON "null" or CSV ''

NaN and +-Inf numbers are not allowed in JSON.  
They should be represented as "null" in JSON output.  
In CSV output, it's less clear since there is no standard, but empty string 
would work for me.

see http://tools.ietf.org/html/rfc4627 about NaN

see http://en.wikipedia.org/wiki/IEEE_754-2008 about JSON numbers
2.4.  Numbers
...
Numeric values that cannot be represented as sequences of digits
   (such as Infinity and NaN) are not permitted.


Original issue reported on code.google.com by [email protected] on 18 Mar 2011 at 10:29

sdist package not installable - fixes are simple

What steps will reproduce the problem?
1. python setup.py sdist
2. copy tarball elsewhere
3. try and install via easy_install

What is the expected output? What do you see instead?
I copied the sdist to our webserver, and then try to install it:
easy_install --find-links http://ooici.net/packages gviz_api.py

Searching for gviz-api.py
Reading http://ooici.net/packages
Best match: gviz-api.py 1.7.0
Downloading http://ooici.net/packages/gviz_api.py-1.7.0.tar.gz
Processing gviz_api.py-1.7.0.tar.gz
Running gviz_api.py-1.7.0/setup.py -q bdist_egg --dist-dir 
/var/folders/Sw/SwEOWKQ7FdihT03Yr5CBOU+++TI/-Tmp-/easy_install-IQGY_h/gviz_api.p
y-1.7.0/egg-dist-tmp-DH3Ktj
Traceback (most recent call last):
  File "/Users/hubbard/code/ve/junk/bin/easy_install", line 8, in <module>
    load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()
  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in <lambda>

  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/core.py", line 152, in setup
    dist.run_commands()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands
    self.run_command(cmd)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/dist.py", line 995, in run_command
    cmd_obj.run()
  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup

  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup
  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run
  File "/Users/hubbard/code/ve/junk/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in <lambda>
  File "setup.py", line 23, in <module>
ImportError: No module named gviz_api_test

The fix:
- Add gviz_api_test.py to MANIFEST
- Change py_modules stanza in setup.py to:

    py_modules=["gviz_api", 'gviz_api_test'],

Now works.

Original issue reported on code.google.com by [email protected] on 18 Aug 2010 at 4:58

Unable to get google-visualization-python working with google app-engine

What steps will reproduce the problem?
1. Setup App Engine & Install google-visualization-python
2. Run the sample.py in the google App Enging
3.

What is the expected output? What do you see instead?
Google App Engine unable to find gviz_app libraries

What version of the product are you using? On what operating system?


Please provide any additional information below.

ERROR    2008-12-08 19:28:53,910 dev_appserver.py] Encountered error 
loading mod
ule "src.viz": <type 'exceptions.ImportError'>: Could not find module 
src.viz
Traceback (most recent call last):

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1607, in LoadTargetModule
    module_code = import_hook.get_code(module_fullname)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 847, in decorate
    return func(self, *args, **kwargs)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1470, in get_code
    full_path, search_path, submodule = self.GetModuleInfo(fullname)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 847, in decorate
    return func(self, *args, **kwargs)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1422, in GetModuleInfo
    submodule, search_path = self.GetParentSearchPath(fullname)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 847, in decorate
    return func(self, *args, **kwargs)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1401, in GetParentSearchPath
    parent_package = self.GetParentPackage(fullname)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 847, in decorate
    return func(self, *args, **kwargs)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1378, in GetParentPackage
    raise ImportError('Could not find module %s' % fullname)
ImportError: Could not find module src.viz
WARNING  2008-12-08 19:28:53,926 dev_appserver.py] Missing package 
initializatio
n files: C:\Users\Michael\workspace\helloworld\src\__init__.py
ERROR    2008-12-08 19:28:53,953 dev_appserver.py] Exception encountered 
handlin
g request
Traceback (most recent call last):

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 2443, in _HandleRequest
    base_env_dict=env_dict)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 353, in Dispatch
    base_env_dict=base_env_dict)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1869, in Dispatch
    self._module_dict)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1787, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)

File "C:\Users\Michael\DevTools\google_appengine\google\appengine\tools\dev
_ap
pserver.py", line 1683, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "C:\Users\Michael\workspace\helloworld\src/viz.py", line 1, in 
<module>
    import gviz_api
ImportError: No module named gviz_api

Original issue reported on code.google.com by [email protected] on 8 Dec 2008 at 7:33

Query Existing Google Sheet

Hi guys,

I just wanted to know if it is possible to query an existing Google Sheet using this package? I have seen that this is possible with JavaScript as shown below,

var query = new google.visualization.Query(DATA_SOURCE_URL);
query.setQuery('select dept, sum(salary) group by dept');
query.send(handleQueryResponse);

https://developers.google.com/chart/interactive/docs/querylanguage#top_of_page

Is it possible to do something similar either through this package or something else?

Uncaught TypeError: Ei is not a function

Hello,

Since few weeks I decided to localize my website based on the the browser culture and since that decision i start to face the following error. Uncaught TypeError: Ei is not a function.

The weird thing is that when i change the language of my chrome(Version 47.0.2526.106 m) to English US and i set up the APIversion to 1 (google.load('visualization', '1', { packages: ['controls'], callback: createCpuRamChart });) my charts are shown.

When i change the browser language to Danish i am getting the error i mentioned before.

I have tried also to use the API version 1.1. The result was that with the browser language set up to English US, the charts are not shown but when i change to Danish the chart works..

I have even changed the way how i load the data like:

var cpuData = new google.visualization.DataTable();

             cpuData.addColumn('date', 'Date');
             cpuData.addColumn('number', 'CPU');
             cpuData.addRow([new Date(1252152000000),4])
             cpuData.addRow([new Date(1252152000123),5])
             cpuData.addRow([new Date(1252152000456),6])

But unfortunate I am getting the same error....

My code looks like:

google.load('visualization', '1.1', { packages: ['controls'], callback: createCpuRamChart });

function createCpuRamChart() {

    // A. Create new instance of DataTable to add our data to
    var cpuData = new google.visualization.DataTable();

    cpuData.addColumn('date', 'Date');
    cpuData.addColumn('number', '@Resources.Administration.ServerStatistics_CPU_ChartLabel');

    @if (Model.cpuUsage != null)
    {
        DateTime d1 = new DateTime(1970, 1, 1);
        foreach (var item in Model.cpuUsage)
        {
            var dateTime = (DateTime)item.GetValue(0); 
            DateTime d2 = dateTime.ToUniversalTime();
            TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
            @: cpuData.addRow([new Date(@ts.TotalMilliseconds),@item.GetValue(1).ToString().Replace(",", ".")])
                }
    };

    //B. RAM data instance

    var ramData = new google.visualization.DataTable();

    // B. Create three columns with DataTable.addColumn(type, label)
    ramData.addColumn('date', 'Date');
    ramData.addColumn('number', '@Resources.Administration.ServerStatistics_RAM_ChartLabel');

    @if (Model.memUsage != null)
    {
        DateTime d1 = new DateTime(1970, 1, 1);
        foreach (var item in Model.memUsage)
        {
            var dateTime = (DateTime)item.GetValue(0);
            DateTime d2 = dateTime.ToUniversalTime();
            TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
            @: ramData.addRow([new Date(@ts.TotalMilliseconds),@item.GetValue(1).ToString().Replace(",", ".")])
        }
    };


    // Create the main Chart
    var cpuChart = new google.visualization.ChartWrapper({
        chartType: 'LineChart',
        containerId: 'cpuUsageLineChart',
        options: {
            hAxis: {
                title: 'Period'
            },
            vAxis: {
                title: 'Percentage'
            },
            width: 800,
            height: 400,
            chartArea: { left: 70, top: 20, bottom: 30, width: "80%", height: "80%" }
        }
    });


    var ramChart = new google.visualization.ChartWrapper({
        'chartType': 'LineChart',
        'containerId': 'ramUsageLineChart',
        options: {
            //legend:'none',
            hAxis: {
                title: 'Period'
            },
            vAxis: {
                title: 'GB'
            },
            width: 800,
            height: 400,
            chartArea: { left: 70, top: 20, bottom: 30, width: "80%", height: "80%" },
        }
    });

    // Create a date range slider
    var cpuDateSlider = new google.visualization.ControlWrapper({
        'controlType': 'ChartRangeFilter',
        'containerId': 'cpuUsageDateRange',
        'options': {

            height: 150,
            // Filter by the date axis.
            filterColumnLabel: 'Date',
            backgroundColor: '#f1f8e9',
            ui: {
                //minRangeSize: 1800000,//not needed. You can set the range under the master dashboard
                chartOptions: {
                    chartArea: { width: '95%', height: '100' },
                },
            }
        },

    });

    var ramDateSlider = new google.visualization.ControlWrapper({
        'controlType': 'ChartRangeFilter',
        'containerId': 'ramUsageDateRange',
        'options': {
            // Filter by the date axis.
            filterColumnLabel: 'Date',
            backgroundColor: '#f1f8e9',
            ui: {
                //minRangeSize: 1800000, //not needed. You can set the range under the master dashboard
                chartOptions: {
                    chartArea: { width: '95%', height: '100' },
                },
            }
        },

    });
    var formatDate = new google.visualization.DateFormat(
       { prefix: 'Time: ', pattern: "dd MMM HH:mm", });
        //{ prefix: 'Time: ', formatType: 'medium', });

    formatDate.format(cpuData, 0);
    formatDate.format(ramData, 0);
    // Create a dashboard.
    var dash_container = new google.visualization.Dashboard(document.getElementById('dashboard'));
    dash_container.bind(cpuDateSlider, cpuChart);

    var dash_container2 = new google.visualization.Dashboard(document.getElementById('dashboard2'));
    dash_container2.bind(ramDateSlider, ramChart);

    dash_container.draw(cpuData);
    dash_container2.draw(ramData);

    // create the master control
    var controlMaster = new google.visualization.ControlWrapper({
        controlType: 'ChartRangeFilter',
        containerId: 'control_master2',
        dataTable: cpuData,
        options: {

            // Filter by the date axis.
            filterColumnLabel: 'Date',
            backgroundColor: '#f1f8e9',
            ui: {
                // 1 day in milliseconds = 24 * 60 * 60 * 1000 = 86,400,000
                minRangeSize: 1800000,// 30 min
                //chartView: {columns: [0, 1]},
                chartOptions: {
                    chartArea: { width: '95%', height: '80' },
                },
            }
        },
    });
    google.visualization.events.addListener(controlMaster, 'statechange', function () {
        var state = controlMaster.getState();
        cpuDateSlider.setState(state);
        ramDateSlider.setState(state);
        dash_container.draw(cpuData);
        dash_container2.draw(ramData);
    });

    controlMaster.draw();
}

Add support for a 'unixepoch' form of Date (patch included)

Please consider adding support for a Unix Epoch form of Date (unixepoch), as 
used by sqlite3. This is very handy for sysadmin-type stuff, and I'm already 
using a modified version of the Python library supporting it.

Here is a context diff showing how to implement it:

*** google-visualization-python/gviz_api.py      Thu Oct  8 06:00:05 2009
--- with-unixepoch-support/gviz_api.py     Mon Oct 18 17:08:11 2010
***************
*** 185,192 ****

      Args:
        value: The value which should be converted
!       value_type: One of "string", "number", "boolean", "date", "datetime" or
!                   "timeofday".
        escape_func: The function to use for escaping strings.

      Returns:
--- 185,192 ----

      Args:
        value: The value which should be converted
!       value_type: One of "string", "number", "boolean", "date", "datetime",
!                   "timeofday" or "unixepoch".
        escape_func: The function to use for escaping strings.

      Returns:
***************
*** 264,269 ****
--- 264,274 ----
          raise DataTableException("Wrong type %s when expected time" % t_value)
        return "[%d,%d,%d]" % (value.hour, value.minute, value.second)

+     elif value_type == "unixepoch":
+       if not isinstance(value, (int, long)):
+         raise DataTableException("Wrong type %s when expected seconds since 
unix epoch" % t_value)
+       return "new Date(%d)" % (value*1000)
+
      elif value_type == "datetime":
        if not isinstance(value, datetime.datetime):
          raise DataTableException("Wrong type %s when expected datetime" %
***************
*** 335,341 ****
            if len(description) > 4:
              raise DataTableException("Description error: tuple of length > 4")
      if desc_dict["type"] not in ["string", "number", "boolean",
!                                  "date", "datetime", "timeofday"]:
        raise DataTableException(
            "Description error: unsupported type '%s'" % desc_dict["type"])
      return desc_dict
--- 340,346 ----
            if len(description) > 4:
              raise DataTableException("Description error: tuple of length > 4")
      if desc_dict["type"] not in ["string", "number", "boolean",
!                                  "date", "datetime", "timeofday", 
"unixepoch"]:
        raise DataTableException(
            "Description error: unsupported type '%s'" % desc_dict["type"])
      return desc_dict

Original issue reported on code.google.com by [email protected] on 20 Oct 2010 at 2:52

Table error when only TWO columns under dictionary structure

What steps will reproduce the problem?
1. Create following code:
#In subclass of "webapp.RequestHandler"
cols = {('Col1', 'String'): {'Col2': 'string'}}
    rows = {'row1': {'Col2': 'Col2, row1'}, 
            'row2': {'Col2': 'Col2, row2'}}
    colOrder = ['Col1', 'Col2']
    data_table = gviz_api.DataTable(cols)
    data_table.AppendData(rows)
self.response.out.write(data_table.ToJSonResponse(columns_order=colOrder,order_b
y=colOrder[0]))

2. Make a simple JS embeded HTML to access this response:
<html xmlns="http://www.w3.org/1999/xhtml"> 
  <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <title> 
      Google Visualization API Sample
    </title> 
    <script type="text/javascript" src="http://www.google.com/jsapi"></script> 
    <script type="text/javascript"> 
    google.load('visualization', '1', {packages: ['table']});
    </script> 
    <script type="text/javascript"> 
    var visualization;

    function drawVisualization() {
      var query = new google.visualization.Query(
          'http://localhost:8080/query?name=gdp&dims=all&dfmt=%Y.%m');

      // Send the query with a callback function.
      query.send(handleQueryResponse);
    }

    function handleQueryResponse(response) {
      if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
      }

      var data = response.getDataTable();
      visualization = new google.visualization.Table(document.getElementById('mytable'));
      visualization.draw(data, null);
    }

    google.setOnLoadCallback(drawVisualization);
    </script> 
  </head> 
  <body style="font-family: Arial;border: 0 none;"> 
    <div id="mytable" style="height: 400px; width: 800px;"></div> 
  </body> 
</html> 

What is the expected output? What do you see instead?
Expected: The column2 value in row1 and row2 are "Col2, row1" and "Col2, row2"
Instead: The column2 value in row1 and row2 are "Col2", which is column2's name!

What version of the product are you using? On what operating system?
Version: gviz_api_py-1.1.0.tar
OS: WinXP

Please provide any additional information below.
If I simple add a non-value Col3 as following:

cols = {('Col1', 'String'): {'Col2': 'string', 'Col3': 'string'}}
rows = {'row1': {'Col2': 'Col2, row1'}, 
            'row2': {'Col2': 'Col2, row2'}}
colOrder = ['Col1', 'Col2', 'Col3']

The result shown will be correct.


Original issue reported on code.google.com by Feng.W.QIN on 15 Mar 2009 at 7:08

Attachments:

bad Time resolution in DataTable

DataTable.SingleValueToJS (version 1.7)
Using "datetime" as input the time resolution is limited to 1 second.
datetime.resolution is 1 microseconds and the javascript Date() allows also 
higher resolution (at least millisecs).

return statement of SingleValuetoToJS

millisecs = int(round(value.microsecond/1000.0, 0))
return "new Date(%d,%d,%d,%d,%d,%d,%d,%d)" % (value.year,
                                                 value.month - 1,
                                                 value.day,
                                                 value.hour,
                                                 value.minute,
                                                 value.second,
                                                 millisecs
                                               )

Original issue reported on code.google.com by [email protected] on 17 Oct 2011 at 11:06

ToJSon does not generate valid JSON

ToJSon returns valid syntax for a JavaScript object, but it is not parseable 
with many JSON implementations 
because it uses syntax that is not within the subset defined by the JSON 
standard.

The simplest solution is probably to rename this function or at least document 
that it doesn't really return 
JSON, but expects to be executed by a full JS interpreter.

For example, the result will not parse with Python 2.6's json package:
>>> d = gviz_api.DataTable(('a', 'string'), ['foo'])
>>> d.ToJSon()
"{cols: [{id:'a',label:'a',type:'string'}],rows: [{c:[{v:'foo'}]}]}"
>>> json.loads(d.ToJSon())
Traceback (most recent call last):
...
ValueError: Expecting property name: line 1 column 1 (char 1)

Some more basic issues are:
- JSON strings must use double-quotes
- JSON keys must be quoted following the string syntax
e.g. {"key": "value"}, not {key: 'value'}

Python's default unicode escaping is also not compatible with JSON strings.  
For example, it will use \x hex 
escape codes which do happen to work in JavaScript, but JSON only allows \u 
4-digit hex escapes, e.g.
Wrong:
>>> json.loads('"\\xfc"')
Traceback (most recent call last):
...
ValueError: Invalid \escape: line 1 column 1 (char 1)

Right:
>>> json.loads('"\\u00fc"')
u'\xfc'

Also, JSON does not define any syntax for Date types, so the "new Date()" 
syntax is not supported by most 
non-JS-native JSON parsers.

Since this data structure is primarily designed for consumption by the JS viz 
API, I don't have a problem with 
the syntax remaining as it is, just please don't misrepresent it as "JSON", 
which could cause confusion if 
people try to parse it with a JSON library.

Original issue reported on code.google.com by [email protected] on 20 Jul 2009 at 10:05

Python3 support ?

Collecting https://github.com/google/google-visualization-python/zipball/master (from -r requirements.txt (line 9))
Downloading https://github.com/google/google-visualization-python/zipball/master
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/private/var/folders/94/_b72550n6x9bbrdcdw7w694m0000gn/T/pip-xi2ugjee-build/setup.py", line 23, in
import gviz_api_test
File "/private/var/folders/94/_b72550n6x9bbrdcdw7w694m0000gn/T/pip-xi2ugjee-build/gviz_api_test.py", line 30, in
from gviz_api import DataTable
File "/private/var/folders/94/_b72550n6x9bbrdcdw7w694m0000gn/T/pip-xi2ugjee-build/gviz_api.py", line 30, in
import cStringIO
ModuleNotFoundError: No module named 'cStringIO'

[PATCH] add support for "warnings" and "errors" fields in JSON responses

This is a patch that adds support for warnings and errors in JSON responses.

It includes new unittests to test added functionality. The results were tested 
against Google's javascript library and they come through correctly.

No old unittests needed fixing, since the change is 100% backwards compatible.

Original issue reported on code.google.com by [email protected] on 20 Aug 2010 at 5:43

Attachments:

datetime timezone not applied correctly to js date object

Currently if a python datetime object is given, an appropriate javascript
date object will be created as follows:
new Date(%d,%d,%d,%d,%d,%d)" % (value.year, value.month ....

Please note that this will be local time for the js date, which may not
match the python datetime object. I'd suggest converting to a
unix-timestamp and creating the js date from the timestamp instead. e.g.:
new Date(1252152000000)


Original issue reported on code.google.com by [email protected] on 5 Sep 2009 at 1:33

Constants for supported value types

I'm using the strings that indicate the supported value types in my own application code:

  • One of "string", "number", "boolean", "date", "datetime" or "timeofday"

It would be nice if these strings could be imported as constants from this library to make the application code more clear.

dynamic exammple on project homepage is broken?

What steps will reproduce the problem?
1. visit http://code.google.com/p/google-visualization-python/
2. click http://google-visualization.appspot.com/python/dynamic_example


What is the expected output? What do you see instead?
some graph is expected, instead, I am looking at the following message:

google.visualization.Query.setResponse({'version':'0.5', 'reqId':'0', 
'status':'OK', 'table': {cols: 
[{id:'name',label:'Name',type:'string'},{id:'salary',label:'Salary',type:'n
umber'},{id:'full_time',label:'Full Time Employee',type:'boolean'}],rows: 
[{c:[{v:'Jim'},{v:800,f:'$800'},{v:false}]},{c:[{v:'Bob'},{v:7000,f:'$7,000
'},{v:true}]},{c:[{v:'Mike'},{v:10000,f:'$10,000'},{v:true}]},{c:[{v:'Alice
'},{v:12500,f:'$12,500'},{v:true}]}]}});

What version of the product are you using? On what operating system?
windows xp, chrome

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 2 May 2009 at 6:14

Cell-level custom properties

If I understand correctly Google Visualizations supports custom properties at the cell level. However, this package seems to only provide APIs for setting them at the level of the entire column or the entire row.

Did I miss a way to cell-level properties or they are indeed not supported at the moment?

At the very least, this issue should be documented and if the capability to set cell-level custom properties is not available right now it should definitely be added...

super() call in DataTableJSONEncoder

In the class DataTableJSONEncoder (line 62), the line

    return super(DataTableJSONEncoder, self).default(self, o)

should read:

    return super(DataTableJSONEncoder, self).default(o)

Example session:

>>> import gviz_api
>>> encoder = gviz_api.DataTableJSONEncoder()
>>> encoder.default(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "gviz_api.py", line 62, in default
    return super(DataTableJSONEncoder, self).default(self, o)
TypeError: default() takes exactly 2 arguments (3 given)

Original issue reported on code.google.com by [email protected] on 24 Apr 2012 at 9:10

Can't create a table with one column using dictionaries.

To reproduce the problem:
>>> dt = gviz_api.DataTable({"c1": ("string", "column 1")})
>>> dt.LoadData({"c1": "blah"})

Problem is, the case of one column is ambiguous with a different description 
case.

Original issue reported on code.google.com by misha.seltzer on 29 Sep 2009 at 2:01

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.