Esempio n. 1
0
 def test_row_map(self):
     """
     Test map a function to rows, or a subset of fields
     """
     t = TableFu(self.table)
     result = [s.lower() for s in t.values('Style')]
     self.assertEqual(result, t.map(lambda row: row['Style'].value.lower()))
Esempio n. 2
0
 def test_sort_option_int(self):
     "Sorting the table by an int field, Number of Pages"
     t = TableFu(self.csv_file)
     pages = t.values('Number of Pages')
     pages = sorted(pages, reverse=True)
     t.sort('Number of Pages', reverse=True)
     self.assertEqual(t.values('Number of Pages'), pages)
Esempio n. 3
0
    def test_transpose(self):
        t = TableFu(self.table)
        result = [[
            'Author', 'Samuel Beckett', 'James Joyce', 'Nicholson Baker',
            'Vladimir Sorokin', 'Ayn Rand'
        ],
                  [
                      'Best Book', 'Malone Muert', 'Ulysses', 'Mezannine',
                      'The Queue', 'Atlas Shrugged'
                  ], ['Number of Pages', '120', '644', '150', '263', '1088'],
                  [
                      'Style', 'Modernism', 'Modernism', 'Minimalism',
                      'Satire', 'Science fiction'
                  ]]

        transposed = t.transpose()
        self.assertEqual(transposed.table, result[1:])
        self.assertEqual(transposed.columns, [
            'Author',
            'Samuel Beckett',
            'James Joyce',
            'Nicholson Baker',
            'Vladimir Sorokin',
            'Ayn Rand',
        ])
Esempio n. 4
0
 def test_sort(self):
     "Sort a table in place"
     t = TableFu(self.csv_file)
     self.table.pop(0)
     self.table.sort(key=lambda row: row[0])
     t.sort('Author')
     self.assertEqual(t[0].cells, self.table[0])
Esempio n. 5
0
 def test_map_values(self):
     """
     Test mapping a function to specific column values
     """
     t = TableFu(self.table)
     result = [s.lower() for s in t.values('Style')]
     self.assertEqual(result, t.map(str.lower, 'Style'))
Esempio n. 6
0
 def test_row_map(self):
     """
     Test map a function to rows, or a subset of fields
     """
     t = TableFu(self.table)
     result = [s.lower() for s in t.values('Style')]
     self.assertEqual(result, t.map(lambda row: row['Style'].value.lower()))
Esempio n. 7
0
 def test_map_values(self):
     """
     Test mapping a function to specific column values
     """
     t = TableFu(self.table)
     result = [s.lower() for s in t.values('Style')]
     self.assertEqual(result, t.map(str.lower, 'Style'))
Esempio n. 8
0
 def test_map_many_values(self):
     """
     Test mapping a function to multiple columns
     """
     t = TableFu(self.table)
     result = [[s.lower() for s in t.values(value)]
               for value in ['Best Book', 'Style']]
     self.assertEqual(result, t.map(str.lower, 'Best Book', 'Style'))
Esempio n. 9
0
 def test_limit_columns(self):
     "Column definitions are passed to rows"
     t = TableFu(self.csv_file)
     t.columns = ['Author', 'Style']
     self.assertEqual(
         str(t[0]),
         'Samuel Beckett, Modernism'
         )
Esempio n. 10
0
 def test_limit_columns(self):
     "Column definitions are passed to rows"
     t = TableFu(self.csv_file)
     t.columns = ['Author', 'Style']
     self.assertEqual(
         str(t[0]),
         'Samuel Beckett, Modernism'
         )
Esempio n. 11
0
    def test_cell_format(self):
        "Format a cell"
        t = TableFu(self.csv_file)
        t.formatting = {'Name': {'filter': 'link', 'args': ['URL']}}

        self.assertEqual(
            str(t[0]['Name']),
            '<a href="http://www.chrisamico.com" title="ChrisAmico.com">ChrisAmico.com</a>'
        )
Esempio n. 12
0
 def test_facet(self):
     "Facet tables based on shared column values"
     t = TableFu(self.csv_file)
     tables = t.facet_by('Style')
     style_row = self.table[4]
     self.assertEqual(
         style_row,
         tables[2][0].cells
     )
Esempio n. 13
0
 def test_transform_to_int(self):
     """
     Convert the Number of Pages field to integers
     """
     t = TableFu(self.csv_file)
     pages = t.values('Number of Pages')
     t.transform('Number of Pages', int)
     for s, i in zip(pages, t.values('Number of Pages')):
         self.assertEqual(int(s), i)
Esempio n. 14
0
 def testFacets(self):
     table = Table(self.yml)
     options = self.parsed['table']['column_options']
     url = "http://spreadsheets.google.com/pub?key=tcSL0eqrj3yb5d6ljak4Dcw&output=csv"
     response = urllib2.urlopen(url)
     tf = TableFu(response, **options)
     tables = tf.facet_by('State')
     for i, t in enumerate(tables):
         self.assertEqual(t.table, table.data[i].table)
Esempio n. 15
0
 def test_facet(self):
     "Facet tables based on shared column values"
     t = TableFu(self.csv_file)
     tables = t.facet_by('Style')
     style_row = self.table[4]
     self.assertEqual(
         style_row,
         tables[2][0].cells
     )
Esempio n. 16
0
    def test_cell_format(self):
        "Format a cell"
        t = TableFu(self.csv_file)
        t.formatting = {'Name': {'filter': 'link', 'args': ['URL']}}

        self.assertEqual(
            str(t[0]['Name']),
            '<a href="http://www.chrisamico.com" title="ChrisAmico.com">ChrisAmico.com</a>'
        )
Esempio n. 17
0
 def test_sort(self):
     "Sort a table in place"
     t = TableFu(self.csv_file)
     self.table.pop(0)
     self.table.sort(key=lambda row: row[0])
     t.sort('Author')
     self.assertEqual(
         t[0].cells,
         self.table[0]
     )
Esempio n. 18
0
 def test_map_many_values(self):
     """
     Test mapping a function to multiple columns
     """
     t = TableFu(self.table)
     result = [
         [s.lower() for s in t.values(value)]
         for value in ['Best Book', 'Style']
     ]
     self.assertEqual(result, t.map(str.lower, 'Best Book', 'Style'))
Esempio n. 19
0
 def _open(self):
     if self.url:
         f = urllib2.urlopen(self.url)
     elif self.filename:
         f = open(self.filename, 'rb')
     else: # there's neither a url nor a file
         raise TableError("You must specify a google_key, URL or local file containing CSV data")
     
     t = TableFu(f, **self.options.get('column_options', {}))
     if self.options.get('faceting', False):
         return t.facet_by(self.options['faceting']['facet_by'])
     return t
Esempio n. 20
0
    def test_json(self):
        try:
            import json
        except ImportError:
            try:
                import simplejson as json
            except ImportError:
                return

        t = TableFu(self.csv_file)
        self.csv_file.seek(0)
        reader = csv.DictReader(self.csv_file)
        jsoned = json.dumps([row for row in reader])
        self.assertEqual(t.json(), jsoned)
Esempio n. 21
0
 def test_json(self):
     try:
         import json
     except ImportError:
         try:
             import simplejson as json
         except ImportError:
             return
     
     t = TableFu(self.csv_file)
     self.csv_file.seek(0)
     reader = csv.DictReader(self.csv_file)
     jsoned = json.dumps([row for row in reader])
     self.assertEqual(t.json(), jsoned)
Esempio n. 22
0
 def test_header_th_style(self):
     t = TableFu(self.csv_file, style={'Author': 'text-align:left;'})
     hed = t.headers[0]
     self.assertEqual(
         hed.as_th(),
         '<th style="text-align:left;" class="header">Author</th>'
     )
Esempio n. 23
0
 def test_datum_values(self):
     "Ensure every cell has the right value"
     t = TableFu(self.csv_file)
     columns = self.table.pop(0)
     for i, row in enumerate(t.rows):
         for index, column in enumerate(columns):
             self.assertEqual(self.table[i][index], str(row[column]))
Esempio n. 24
0
 def test_datum_td_style(self):
     t = TableFu(self.csv_file, style={'Author': 'text-align:left;'})
     beckett = t[0]['Author']
     self.assertEqual(
         beckett.as_td(),
         '<td style="text-align:left;" class="datum">Samuel Beckett</td>'
     )
Esempio n. 25
0
 def test_from_url(self):
     if not os.getenv('TEST_REMOTE'):
         return True
     url = "http://spreadsheets.google.com/pub?key=thJa_BvqQuNdaFfFJMMII0Q&output=csv"
     t1 = TableFu.from_url(url)
     t2 = TableFu(urllib2.urlopen(url))
     self.assertEqual(t1.table, t2.table)
Esempio n. 26
0
 def get_tablefu(self):
     """
     Trick the data out with TableFu.
     """
     path = os.path.join(settings.CSV_DIR, self.csv_name)
     data = open(path, 'r')
     return TableFu(data, **self.get_tablefu_opts())
Esempio n. 27
0
def csvviresult():
    global table
    # data = request.form['text']
    # table = TableFu.from_file('app/vi-csv.csv')
    table = TableFu.from_file('app/vi-csv.csv')
    # return render_template('vi-template.html', table=table)
    return render_template('vi-template.html', table=table)
Esempio n. 28
0
 def test_items(self):
     "Get key-value pairs for a row"
     t = TableFu(self.csv_file)
     modernism = t[0]
     self.assertEqual(
         modernism.items(),
         zip(modernism.keys(), modernism.values())
     )
Esempio n. 29
0
 def test_list_row(self):
     "Convert a row back to a list"
     t = TableFu(self.csv_file)
     modernism = t[0]
     self.assertEqual(
         list(modernism),
         modernism.values()
     )
Esempio n. 30
0
 def test_datum_td(self):
     "Output a cell as a <td> element"
     t = TableFu(self.csv_file)
     beckett = t[0]['Author']
     self.assertEqual(
         beckett.as_td(),
         '<td style="" class="datum">Samuel Beckett</td>'
     )
Esempio n. 31
0
 def test_row_tr(self):
     "Output a row as a <tr> element"
     t = TableFu(self.csv_file)
     row = t[0]
     self.assertEqual(
         row.as_tr(),
         '<tr id="row0" class="row even"><td style="" class="datum">Samuel Beckett</td><td style="" class="datum">Malone Muert</td><td style="" class="datum">120</td><td style="" class="datum">Modernism</td></tr>'
     )
Esempio n. 32
0
 def test_transpose(self):
     t = TableFu(self.table)
     result = [
         ['Author', 'Samuel Beckett', 'James Joyce', 'Nicholson Baker', 'Vladimir Sorokin'],
         ['Best Book', 'Malone Muert', 'Ulysses', 'Mezannine', 'The Queue'],
         ['Number of Pages', '120', '644', '150', '263'],
         ['Style', 'Modernism', 'Modernism', 'Minimalism', 'Satire']
     ]
     
     transposed = t.transpose()
     self.assertEqual(transposed.table, result[1:])
     self.assertEqual(transposed.columns, [
         'Author',
         'Samuel Beckett',
         'James Joyce',
         'Nicholson Baker',
         'Vladimir Sorokin'
     ])
Esempio n. 33
0
 def test_bad_key(self):
     "Non-existent columns raise a KeyError"
     t = TableFu(self.csv_file)
     for row in t.rows:
         self.assertRaises(
             KeyError,
             row.__getitem__,
             'not-a-key'
         )
Esempio n. 34
0
 def test_check_row(self):
     "Check that row numbers are assigned correctly"
     t = TableFu(self.csv_file)
     self.table.pop(0)
     for i, row in enumerate(self.table):
         self.assertEqual(
             t[i].cells,
             self.table[i]
         )
Esempio n. 35
0
 def test_use_url(self):
     "Use a response from urllib2.urlopen as our base file"
     url = "http://spreadsheets.google.com/pub?key=thJa_BvqQuNdaFfFJMMII0Q&output=csv"
     response1 = urllib2.urlopen(url)
     response2 = urllib2.urlopen(url)
     reader = csv.reader(response1)
     columns = reader.next()
     t = TableFu(response2)
     self.assertEqual(columns, t.columns)
Esempio n. 36
0
    def test_set_columns(self):
        arra = TableFu.from_file(self.filename)
        arra.columns = ["State", "County", "Urban Area"]

        tabled = Table(
            title="That Stimulus", added_by=self.user, file=File(self.file), columns=["State", "County", "Urban Area"]
        )
        tabled.save()

        self.assertEqual(arra.columns, tabled.data.columns)
Esempio n. 37
0
 def data(self):
     """Return a TableFu instance with data for this model"""
     if hasattr(self, '_data') and self._data is not None:
         return self._data
     
     if self.file:
         # this gets wrapped in a with block for cleanliness
         d = TableFu.from_file(self.file.path)
     
     elif self.url:
         d = TableFu.from_url(self.url)
     
     else:
         return None
             
     if self.columns:
         d.columns = self.columns
     
     self._data = d
     return self._data
Esempio n. 38
0
 def test_update_values(self):
     "Update multiple cell values for a given row"
     t = TableFu(self.csv_file)
     modernism = t[0]
     kerouac = {
         'Author': 'Jack Kerouac',
         'Best Book': 'On the Road',
         'Number of Pages': '320',
         'Style': 'Beat'
     }
     modernism.update(kerouac)
     self.assertEqual(set(kerouac.values()), set(modernism.cells))
Esempio n. 39
0
def virtualissueautomate():
    
    myDOIs = str(request.form["text"]).split('\r\n')
    
 
     # run python process
    createVI(myDOIs)

    global table
    # data = request.form['text']
    table = TableFu.from_file('vi-csv.csv')
    return render_template('vi-template.html', table=table, results=results)
Esempio n. 40
0
 def test_sort_option_int(self):
     "Sorting the table by an int field, Number of Pages"
     t = TableFu(self.csv_file)
     pages = t.values('Number of Pages')
     pages = sorted(pages, reverse=True)
     t.sort('Number of Pages', reverse=True)
     self.assertEqual(t.values('Number of Pages'), pages)
Esempio n. 41
0
def podcastupload():
    if request.method == 'POST':
        # Get the name of uploaded file
        file = request.files['file']
        # Check if the file is an allowed extension
        if file and allowed_file(file.filename):
            # Make the filename safe - remove unsupported characters
            filename = secure_filename(file.filename)
            # # Move the file from the temp folder to the upload folder
            file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
            # Use tablefu to template out the uploaded CSV file
            global table
            table = TableFu.from_file('app/static/uploads/' + filename)
            return render_template('podcastresults.html', table=table)
Esempio n. 42
0
def podcastupload():
    if request.method == 'POST':
    # Get the name of uploaded file
        file = request.files['file']
        # Check if the file is an allowed extension
        if file and allowed_file(file.filename):
            # Make the filename safe - remove unsupported characters
            filename = secure_filename(file.filename)
            # # Move the file from the temp folder to the upload folder
            file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
            # Use tablefu to template out the uploaded CSV file
            global table
            table = TableFu.from_file('app/static/uploads/' + filename)
            return render_template('podcastresults.html', table=table)
Esempio n. 43
0
 def test_transform_to_int(self):
     """
     Convert the Number of Pages field to integers
     """
     t = TableFu(self.csv_file)
     pages = t.values('Number of Pages')
     t.transform('Number of Pages', int)
     for s, i in zip(pages, t.values('Number of Pages')):
         self.assertEqual(int(s), i)
Esempio n. 44
0
def data_import(generator, content=None):
    if not content:
        # Then it's a page, not an article
        #pdb.set_trace()
        contents = getattr(generator, 'pages')
    else:
        # An article, so content is only one element
        # To make it work with pages (where content is an array)
        # we need to create an array
        contents = [content]

    for content_obj in contents:
        if hasattr(content_obj, 'data') and len(content_obj.data) > 0:
            # if isinstance(content.data, (str, basestring)): # make string into 1-item list
            # 	data = [content.data]
            # else:
            # 	data = content.data
            data = content_obj.data.split('|')
            #print data
            datatables = []
            for d in data:
                logger.debug("Loading data <%s> for article %s" %
                             (d, content_obj.slug))
                #logger.debug(os.getcwd())
                #pdb.set_trace()
                filepath = os.path.join(os.getcwd(),
                                        generator.settings['PATH'],
                                        generator.settings['DATA_PATH'], d)

                try:
                    _data = TableFu.from_file(filepath)
                    datatables.append(_data)
                    #setattr(content, 'datatable', data)
                except:
                    #raise
                    logger.warn("Could not load data file for %s: %s" %
                                (content_obj.slug, filepath))
                setattr(content_obj, 'datatables', datatables)

        elif hasattr(content_obj, 'mapdata') and len(content_obj.mapdata) > 0:
            # If mapdata but no data, add empty datatables object so that
            # figure titles and captions will work
            datatable = {'rows': [], 'columns': []}
            setattr(content_obj, 'datatables', [datatable])
Esempio n. 45
0
def facet(starter, *facets):
    table = TableFu.from_file(starter)
    out_dir = os.path.dirname(starter)
    files = []
    for f in facets:
        try:
            tables = table.facet_by(f)
        except KeyError:
            sys.stderr.write('Bad column name: %s\n' % f)
            sys.stderr.write('Available columns: %s\n\n' % ', '.join(table.columns))
            continue

        for t in tables:
            out = open(os.path.join(out_dir, '%s.csv' % t.faceted_on), 'wb')
            out.write(t.csv().getvalue())
            out.close()
            files.append(out.name)
    
    return files
Esempio n. 46
0
 def test_set_columns(self):
     "Set new columns for a table"
     t = TableFu(self.csv_file)
     columns = ['Style', 'Author']
     t.columns = columns
     self.assertEqual(t.columns, columns)
Esempio n. 47
0
 def test_big_filter(self):
     arra = open('tests/arra.csv')
     t = TableFu(arra)
     f = t.filter(State='ALABAMA', County='COLBERT')
     self.assertEqual(f.count(), 5)
Esempio n. 48
0
 def test_multi_filter(self):
     "Filter by multiple keywords"
     t = TableFu(self.csv_file)
     f = t.filter(Style='Modernism', Author='Samuel Beckett')
     self.assertEqual(f[0].cells, self.table[1])
Esempio n. 49
0
 def test_simple_filter(self):
     "Filter by keyword args"
     t = TableFu(self.csv_file)
     f = t.filter(Author='Samuel Beckett')
     self.assertEqual(f[0].cells, self.table[1])
Esempio n. 50
0
 def test_filter(self):
     "Filtering returns a new TableFu instance"
     t = TableFu(self.csv_file)
     f = t.filter(Author='Samuel Beckett')
     self.assertEqual(type(t), type(f))
     self.assertEqual(t.columns, f.columns)
Esempio n. 51
0
 def test_count(self):
     "Count is like len()"
     t = TableFu(self.csv_file)
     self.assertEqual(len(t), t.count())
Esempio n. 52
0
 def test_totals(self):
     "Total values for a table across rows"
     t = TableFu(self.csv_file)
     self.table.pop(0)
     pages = sum([float(row[2]) for row in self.table])
     self.assertEqual(pages, t.total('Number of Pages'))
Esempio n. 53
0
 def test_values(self):
     "Return one column's values for all rows"
     t = TableFu(self.csv_file)
     self.table.pop(0)
     authors = [row[0] for row in self.table]
     self.assertEqual(authors, t.values('Author'))
Esempio n. 54
0
 def test_count_rows(self):
     "Count rows, not including headings"
     t = TableFu(self.csv_file)
     self.table.pop(0)
     self.assertEqual(len(list(t.rows)), len(self.table))
     self.assertEqual(len(t), len(self.table))
Esempio n. 55
0
def podcastresult():
    global table
    table = TableFu.from_file('app/chembio.csv')
    return render_template('podcastresultsnano.html', table=table)
Esempio n. 56
0
 def test_from_file(self):
     t1 = TableFu.from_file('tests/arra.csv')
     t2 = TableFu(open('tests/arra.csv'))
     self.assertEqual(t1.table, t2.table)
Esempio n. 57
0
 def test_from_url(self):
     url = "http://spreadsheets.google.com/pub?key=thJa_BvqQuNdaFfFJMMII0Q&output=csv"
     t1 = TableFu.from_url(url)
     t2 = TableFu(urllib2.urlopen(url))
     self.assertEqual(t1.table, t2.table)
Esempio n. 58
0
 def test_get_headers(self):
     "Get the table's headers"
     t = TableFu(self.csv_file)
     self.assertEqual(t.headers, self.table[0])
Esempio n. 59
0
 def test_get_row(self):
     "Get one row by slicing the table"
     t = TableFu(self.csv_file)
     self.assertEqual(t[1], list(t.rows)[1])
Esempio n. 60
0
 def test_from_file(self):
     t1 = TableFu.from_file('tests/arra.csv')
     t2 = TableFu(open('tests/arra.csv'))
     self.assertEqual(t1.table, t2.table)