web2py genericIndexJoe.html & layoutJoe.html

genericIndexJoe.html

{{extend 'layoutJoe.html'}}
{{response.menu}} {{# uncommented, makes the menu appear }}
{{ #=BEAUTIFY(response._vars) }}
{{ =response._vars['message'] }}

layoutJoe.html

<!DOCTYPE html>
<!-- copied from ordersarrive >> layoutJoe.html which may be crappy -->

<!--[if (gt IE 9)|!(IE)]><!--> <html class="no-js" lang="{{=T.accepted_language or 'en'}}"> <!--<![endif]-->
  <head>
    <meta charset="utf-8">
    <!-- www.phpied.com/conditional-comments-block-downloads/ -->
    <!-- Always force latest IE rendering engine
         (even in intranet) & Chrome Frame
         Remove this if you use the .htaccess -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge{{=not request.is_local and ',chrome=1' or ''}}">
    <!--  Mobile Viewport Fix
          j.mp/mobileviewport & davidbcalhoun.com/2010/viewport-metatag
          device-width: Occupy full width of the screen in its current orientation
          initial-scale = 1.0 retains dimensions instead of zooming out if page height > device height
          user-scalable = yes allows the user to zoom in -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{=response.title or request.application}}</title>
    <!-- http://dev.w3.org/html5/markup/meta.name.html -->
    <meta name="application-name" content="{{=request.application}}">
    <!-- Speaking of Google, don't forget to set your site up:
         http://google.com/webmasters -->
    <meta name="google-site-verification" content="">
    <!-- include stylesheets -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="{{=URL('static','css/bootstrap.min.css')}}"/>
    <link rel="stylesheet" href="{{=URL('static','css/web2py-bootstrap4.css')}}"/>
    <link rel="shortcut icon" href="{{=URL('static','images/favicon.ico')}}" type="image/x-icon">
    <link rel="apple-touch-icon" href="{{=URL('static','images/favicon.png')}}">
    <!-- All JavaScript at the bottom, except for Modernizr which enables
         HTML5 elements & feature detects -->
    <a href="http://=URL('static','js/modernizr-2.8.3.min.js')">http://=URL('static','js/modernizr-2.8.3.min.js')</a>
    <!-- Favicons -->
    {{include 'web2py_ajax.html'}} <!-- this includes jquery.js, calendar.js/.css and web2py.js -->
    {{block head}}{{end}}
  </head>
  <body>
    <div class="w2p_flash alert alert-dismissable">{{=response.flash or ''}}</div>
    <!-- Navbar ======================================= -->
    <nav class="navbar navbar-light navbar-expand-md bg-faded bg-dark navbar-dark justify-content-center">
<!--        <a href="http://web2py.com" class="navbar-brand d-flex w-50 mr-auto">web2py</a> -->
        <a href="http://JoeCodeswell.com" class="navbar-brand d-flex w-50 mr-auto">JoeCodeswell.com</a> 
       <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
         <span class="navbar-toggler-icon"></span>
       </button>
       <div class="navbar-collapse collapse w-100" id="navbarNavDropdown">
         <ul class="navbar-nav w-100 justify-content-center">
          {{for _item in response.menu or []:}}
          {{if len(_item)<4 or not _item[3]:}}
          <li class="nav-item {{if _item[1]:}}active{{pass}}">
            <a class="nav-link" href="{{=_item[2]}}">{{=_item[0]}}</a>
          </li>
          {{else:}}
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="{{=_item[2]}}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{=_item[0]}}</a>
            <div class="dropdown-menu">
              {{for _subitem in _item[3]:}}
              <a class="dropdown-item" href="{{=_subitem[2]}}">{{=_subitem[0]}}</a>
              {{pass}}
            </div>
          </li>
          {{pass}}
          {{pass}}
        </ul>
         <form class="form-inline my-2 my-lg-0">
             <input class="form-control mr-sm-2" type="text" placeholder="Search">
         </form>
        {{if 'auth' in globals():}}
        <ul class="nav navbar-nav ml-auto w-100 justify-content-end">
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              {{if auth.user:}}{{=auth.user.first_name}}{{else:}}LOGIN{{pass}}
            </a>
            <div class="dropdown-menu dropdown-menu-right">
              {{if auth.user:}}
              <a class="dropdown-item" href="{{=URL('default','user/profile')}}">{{=T('Profile')}}</a>
              {{if 'change_password' not in auth.settings.actions_disabled:}}
              <a class="dropdown-item" href="{{=URL('default','user/change_password')}}">{{=T('Change Password')}}</a>
              {{pass}}
              <a class="dropdown-item" href="{{=URL('default','user/logout')}}">{{=T('Logout')}}</a>
              {{else:}}
              <a class="dropdown-item" href="{{=URL('default','user/login')}}">{{=T('Login')}}</a>
              {{if 'register' not in auth.settings.actions_disabled:}}
              <a class="dropdown-item" href="{{=URL('default','user/register')}}">{{=T('Sign up')}}</a>
              {{pass}}
              {{if 'retrieve_password' not in auth.settings.actions_disabled:}}
              <a class="dropdown-item" href="{{=URL('default','user/retrieve_password')}}">{{=T('Lost Password')}}</a>
              {{pass}}
              {{pass}}
            </div>
          </li>
        </ul>
        {{pass}}
      </div>
    </nav>

    <!-- Masthead ===================================== -->
    {{block header}}
    {{end}}
    <!-- Main ========================================= -->
    <!-- Begin page content -->
    <div class="container-fluid main-container">
      {{include}}
      {{=response.toolbar() if response.show_toolbar else ''}} 
    </div>

    {{block footer}} <!-- this is default footer -->
    <footer class="footer container-fluid">
      <div class="row">
        <div class="col-md-12">
          <div class="copyright pull-left">{{=T('Copyright ')}} © {{=request.now.year}} Joseph P. Dorocak, Sacramento, CA. All rights reserved.</div>
          <div id="poweredBy" class="pull-right">
            {{=T('Powered by')}}
            <a href="http://www.web2py.com/">web2py</a>
          </div>
        </div>
      </div>
    </footer>
    {{end}}
    <!-- The javascript =============================== -->
    <a href="http://=URL('static','js/bootstrap.bundle.min.js')">http://=URL('static','js/bootstrap.bundle.min.js')</a>
    <a href="http://=URL('static','js/web2py-bootstrap4.js')">http://=URL('static','js/web2py-bootstrap4.js')</a>
    {{block page_js}}{{end page_js}}
    {{if response.google_analytics_id:}}
    <!-- Analytics ==================================== -->
    <a href="http://=URL('static','js/analytics.min.js')">http://=URL('static','js/analytics.min.js')</a>
    <script type="text/javascript">
      analytics.initialize({
      'Google Analytics':{trackingId:'{{=response.google_analytics_id}}'}
      });
    </script>
    {{pass}}
  </body>
</html>





<!-- original stuff below here -->
{{#extend 'layout.html'}}
<!-- <h1>This is the layoutJoe.html template</h1> -->
{{#=BEAUTIFY(response._vars)}}

#markdown, #web2py

web2py Markdown Usage Example

web2py Markdown Usage Example

from gluon.contrib.markdown import WIKI as markdown
def index():
    """ ##
      [see](web2py.com/examples/static/sphinx/gluon/gluon.contrib.markdown.html)
      [Markdown see](https://groups.google.com/g/web2py/c/om9aXi3xg3Y/m/jE4t-KwpBQAJ)

    """
    # response.view = 'genericIndexJoe.html'
    response.flash = T("Welcome!")

    my_md = '''## Welcome to the cov19cty App!
### To generate County Comparison Charts:
1. Click Menu >> Gen Chart >> Multi-County Input Form
  1. Add Your Counties to compare (state, county, typeOfData)
  2. Define Your Time Series
2. Click Menu >> Gen Chart >> Show Multi-County Chart
    '''
    my_html = markdown(my_md)

    # return dict( message=my_html )  
    return my_html

#markdown, #web2py

react post from wp-admin editor text tab


/**
 *  File: App.js
 *  "React State Example-1: Update state using 2 select elements."
 *  by Joe Dorocak (JoeCodeswell.com) 
 *  Demonstrates changing state with 2 select elements 
 * 
 *  Source Code Link: https://joecodeswell.wordpress.com/2018/09/25/react-state-example-1-update-state-using-2-select-elements/
 * 
 * MIT License
 * 
 * Copyright (c) [2018] [Joseph P. Dorocak]
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 *  https://en.forums.wordpress.com/topic/posting-javascript-markdown-does-not-show/
 * 
 *  
 */

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

let programmerList =  ["Admiral Grace Hopper","Ada Lovelace","Donald Knuth","James Gosling","Guido van Rossum","Linus Torvalds"];

class App extends Component {
  constructor() {
    super();
    this.state = {
      counter: 0,
      programmer_list: programmerList,
      fmSelFrom: programmerList[0],
      fmSelTo:programmerList[0]
    };
  }
  handleFromChange = (event) => {
    this.setState({ 
      fmSelFrom: event.target.value     
    });
  }
  handleToChange = (event) => {
    this.setState({ 
      fmSelTo: event.target.value    
    });
  }
  render() {
    // inside class App -> render(){ before return(
    return (

      /* begin out of the box jsx */
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        {/* end out of the box jsx */}
        {/* begin non out of the box jsx */}
        <div id="show-programmer-list">
          <p>Programmer List</p>
            {this.state.programmer_list.map(  (itm,ix) => <p key={ix} value={itm} >ix:{ix}->itm:{itm}</p> )   }          
        </div>

        <div id="select-programmer-from-to">
        <label>
            Pick your FROM Programmer:        
            <select id="select-from"  value={this.value} onChange={this.handleFromChange} >
              {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={ix+":"+itm} >{itm}</option> )   }  
            </select>
        </label>
        <label>
          Pick your TO Programmer:         
          <select id="select-to" value={this.key} onChange={this.handleToChange} >
            {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={itm} >{itm}</option> )   }
          </select>
        </label>

        <p>this.state.fmSelFrom: {this.state.fmSelFrom}</p>
        <p>this.state.fmSelTo: {this.state.fmSelTo}</p>

        </div>
        {/* end non out of the box jsx */}
     
      </div> 
      /* end of <div className="App"> */

      // inside class App -> render(){ ->return( -> after <div className="App"></div>

    ); // end render -> return
  } // end render () code
}

export default App;
App.js.txt
Displaying App.js.txt.

Help with publishing code on WordPress.com

Here is a link to a WordPress.com support request of mine regarding publishing code on WordPress.com, posting “` javascript markdown DOES NOT show ”.

The folks were a GREAT HELP.

Thanks again to  @melancholia.

Love and peace,

Joe

React State Example-1: Update state using 2 select elements.

Based on Out of the box src for create-react-app -V 1.5.2


/**
 *  File: App.js
 *  "React State Example-1: Update state using 2 select elements."
 *  by Joe Dorocak (JoeCodeswell.com) 
 *  Demonstrates changing state with 2 select elements 
 * 
 *  Source Code Link: https://joecodeswell.wordpress.com/2018/09/25/react-state-example-1-update-state-using-2-select-elements/
 * 
 * MIT License
 * 
 * Copyright (c) [2018] [Joseph P. Dorocak]
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 *  https://en.forums.wordpress.com/topic/posting-javascript-markdown-does-not-show/
 * 
 *  
 */

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

let programmerList =  ["Admiral Grace Hopper","Ada Lovelace","Donald Knuth","James Gosling","Guido van Rossum","Linus Torvalds"];

class App extends Component {
  constructor() {
    super();
    this.state = {
      counter: 0,
      programmer_list: programmerList,
      fmSelFrom: programmerList[0],
      fmSelTo:programmerList[0]
    };
  }
  handleFromChange = (event) => {
    this.setState({ 
      fmSelFrom: event.target.value     
    });
  }
  handleToChange = (event) => {
    this.setState({ 
      fmSelTo: event.target.value    
    });
  }
  render() {
    // inside class App -> render(){ before return(
    return (

      /* begin out of the box jsx */
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        {/* end out of the box jsx */}
        {/* begin non out of the box jsx */}
        <div id="show-programmer-list">
          <p>Programmer List</p>
            {this.state.programmer_list.map(  (itm,ix) => <p key={ix} value={itm} >ix:{ix}->itm:{itm}</p> )   }          
        </div>

        <div id="select-programmer-from-to">
        <label>
            Pick your FROM Programmer:        
            <select id="select-from"  value={this.value} onChange={this.handleFromChange} >
              {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={ix+":"+itm} >{itm}</option> )   }  
            </select>
        </label>
        <label>
          Pick your TO Programmer:         
          <select id="select-to" value={this.key} onChange={this.handleToChange} >
            {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={itm} >{itm}</option> )   }
          </select>
        </label>

        <p>this.state.fmSelFrom: {this.state.fmSelFrom}</p>
        <p>this.state.fmSelTo: {this.state.fmSelTo}</p>

        </div>
        {/* end non out of the box jsx */}
     
      </div> 
      /* end of <div className="App"> */

      // inside class App -> render(){ ->return( -> after <div className="App"></div>

    ); // end render -> return
  } // end render () code
}

// App.js.txt
// Displaying App.js.txt.

export default App;

Out of the box src for create-react-app -V 1.5.2

App.js out of the box

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div>
        <header>
          <img src="{logo}" alt="logo" />
          <h1>Welcome to React</h1>
        </header>

          To get started, edit <code>src/App.js</code> and save to reload.

      </div>
    );
  }
}

export default App;

App.css out of the box

.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 80px;
}

.App-header {
  background-color: #222;
  height: 150px;
  padding: 20px;
  color: white;
}

.App-title {
  font-size: 1.5em;
}

.App-intro {
  font-size: large;
}

@keyframes App-logo-spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

App.test.js out of the box

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

index.css out of the box

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

index.js out of the box

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

registerServiceWorker.js out of the box

<br />// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Lets check if a service worker still exists or not.
        checkValidServiceWorker(swUrl);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://goo.gl/SC7cgQ'
          );
        });
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl);
      }
    });
  }
}

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      if (
        response.status === 404 ||
        response.headers.get('content-type').indexOf('javascript') === -1
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

logo.svg out of the box

NOT shown due to WordPress.com markdown limitations!

#222

gDocInsertDateTime Google Docs add-on

For my own use & that of others, I just wrote gDocInsertDateTime. It is a Google Docs add-on that inserts a date-time stamp at the position of the cursor.

Please use the comments below for feedback. Thanks.

Shortlink: https://wp.me/p1zI3Z-uZ

I just installed P2 and…

FINALLY, I AM HAPPY! 🙂

My Travails

BUMMER: I just installed P2 and the links to my pages (menu?) at the top of the site disappeared! I am going to go back to Truly Minimal theme and see if they HOPEFULLY re appear!

ANOTHER BUMMER: wordpress says you can’t revert to an old theme.

ANOTHER BIG BIG BUMMER: Markdown gets replaced by [X]HTML in posts. Find Markdown onP2 by Automattic

ANOTHER BUMMER: STILL can’t get P2 to display links to my pages.
See P2 User Guide

Fixing Menu to Pages

  1. My sites > JoeCodeswell > Themes [Customize button]
  2. Menus Tab
  3. Create New Menu [Named “Pages” N.B. name does not show]
  4. Menu Location: Where do you want this menu to appear? (If you plan to use a menu widget (opens in a new window), skip this step.) [X] Primary Menu (Current: Pages) N.B. I clicked [X] on this item.
  5. Click “+ Add Items” button RESULT Menu of links appears on right. Including as JSON: [Search menu items…, Pages: [Home,ES6 Notes, Django Notes, Python Notes, Web2py Notes, My Resume (SCROLL DOWN TO SEE!)], Posts, Categories, Tags, Format ]
  6. I clicked + on all the Page Items to add them to the menu

RESULT: Pages Menu APPEARS ACROSS TOP WITHOUT “Pages” title. Thanks be to God. Amen.

Python code creates a database from .csv

Content

  1. Documentation
  2. Code

1. Documentation

csv2sqliteDB.py:
1. Creates an sqlite Database (from SQLITE_FILEPATH) then
2. Creates and Loads TABLE_NAME (adding id INTEGER PRIMARY KEY )
FROM CSV_FILEPATH (with header, NO id field necessary)
INTO DATABASE_FILEPATH
CREATING DATABASE_FILEPATH if it doesn’t exist.

Usage:   csv2sqliteDB.py TABLE_NAME CSV_FILEPATH  SQLITE_FILEPATH
Example: csv2sqliteDB.py contacts   contacts2.csv contactsDB2id.db

2. Code


#!/usr/bin/python
#! python3
#! python2
# -*- coding: utf-8 -*-
"""csv2sqliteDB.py Creates and Loads TABLE_NAME (adding id INTEGER PRIMARY KEY )
      from CSV_FILEPATH (with header, NO id field necessary)
      into DATABASE_FILEPATH
          creating DATABASE_FILEPATH if it doesn't exist

Usage:   csv2sqliteDB.py TABLE_NAME CSV_FILEPATH  SQLITE_FILEPATH
Example: csv2sqliteDB.py contacts   contacts2.csv contactsDB2id.db
"""

# see:
    # Importing a CSV file into a sqlite3 - http://stackoverflow.com/a/2888042/601770
    # csv file using python with headers intact - http://stackoverflow.com/a/3428633/601770

import os, sys, csv, sqlite3

def csv2sqliteDB(table_name, csv_filepath, database_filepath):
    conn, cursor = createDatabaseIfNotExist(database_filepath)
    nlines = sum(1 for line in open(csv_filepath)) # http://stackoverflow.com/a/36973958/601770
    with open(csv_filepath, 'r') as f:
        reader = csv.reader(f)
        headerL = reader.__next__()

        createTable(table_name, conn, cursor, headerL)

        loadTable(table_name, conn, cursor, headerL, reader, nlines)
    conn.close()

def createDatabaseIfNotExist(database_filepath):
    # if we error, we rollback automatically, else commit!
    with sqlite3.connect(database_filepath) as conn:
        cursor = conn.cursor()
        cursor.execute('SELECT SQLITE_VERSION()')
        data = cursor.fetchone()
        print('SQLite version:', data)
        return conn, cursor

def createTable(table_name, conn, cursor,  headerL):
    """
    :param table_name:
    :param conn:
    :param cursor:
    :param header:
    :return:
    """
    # http://stackoverflow.com/a/12432311/601770
    # http: // stackoverflow.com / a / 19730169 / 601770

    textL = len(headerL)*'TEXT'.split()
    def_str = ', '.join( ['id INTEGER PRIMARY KEY'] + [i[0]+' '+i[1] for i in list(zip(headerL, textL))] )
    script_str = """DROP TABLE IF EXISTS %s;
        CREATE TABLE %s (%s);
    """%(table_name, table_name, def_str) # checks to see if table exists and makes a fresh table.

    cursor.executescript(script_str)


def loadTable(table_name, conn, cursor, headerL, reader, nlines):
    insert_str_model = "INSERT INTO {table_name} ({col_names}) VALUES({q_marks});"
    col_names = ','.join(headerL)
    q_marks = ','.join(len(headerL)*'?'.split())

    insert_str = insert_str_model.format(table_name=table_name, col_names=col_names, q_marks=q_marks)

    # DO THE INSERTS
    line_count = 0
    for row in reader:
        line_count += 1
        if line_count%10 == 1: print('line %s of %s'%(line_count, nlines))
        cursor.execute(insert_str, row)
        conn.commit()


NUM_ARGS = 3
def main():
    args = sys.argv[1:]
    if len(args) != NUM_ARGS or "-h" in args or "--help" in args:
        print (__doc__)
        sys.exit(2)
    csv2sqliteDB(args[0], args[1], args[2])

if __name__ == '__main__':
    main()

#code, #csv, #database, #python, #sqlite

Teach Kids Coding – Turtle, Python, IDLE

Advantage – Immediate Feedback

As the student repeatedly presses the Debug Control’s “Over” button, she will be able to see the Turtle execute the commands she has given it.

Content

  • Summary
  • Video Link
  • Technique Steps
  • Code

Summary

This post will demonstrate a technique for teaching kids (or anyone) coding, using Turtle Graphics, Python, Python IDLE, Python IDLE’s Debug Control and Statement Execution Stepping.

This technique should work for Windows, Mac, and Linux (e.g. Raspberry Pi).

Video Link

Here is a link to a YouTube Video for this post.

Technique Steps

  1. Open your File Manager
    • “File Explorer” in Windows
    • “Finder” in Mac
    • “File Manager” in Raspberry Pi
  2. Navigate to the folder [CodeFolderPath] in which you have your code to be used. Most File Managers let you copy the path to a command line.
  3. Open a Command Line Window
    • “Command Prompt” in Windows
    • “Terminal” in Mac and Raspberry Pi
  4. At the Command Line, change directory to [CodeFolderPath], whatever that is.
    • example:
    • $ cd ~/pythonPjs/MasonPjs
  5. At the Command Line, run IDLE.
    • $ idle
    • This will bring up the IDLE Shell Window.
  6. In the IDLE Shell Window’s menu bar, click File Open and open the appropriate code file.
    • This will bring up the IDLE Code Window.
  7. In the IDLE Shell Window’s menu bar, click Debug/Debugger.
    • This will bring up the IDLE Debug Control Window.
  8. In the Debug Control Window:
    • UnTick the Stack Checkbox.
    • Tick the Source Checkbox.
  9. Minimize the IDLE Shell, File Manager and Command Line Windows. We want the student to focus on the important windows.
    • IDLE Debug Control
    • IDLE Code
    • Turtle Graphics
  10. Position the Debug Control & IDLE Code windows so you’ll be able to see them AND the Turtle Graphics Window SIMULTANEOUSLY. I plan on Turtle Graphics Window to be on the RIGHT of the screen. So I put:
    • Debug Contol – Top Left of the screen.
    • IDLE Code – Bottom Left of the screen. I make it about the same WIDTH as the Debug Control Window.
  11. In the IDLE Code window click on File/Run/Run Module
    • RESIZE it to be above the IDLE Code Window.
    • ALSO Minimize the IDLE Shell Window that (annoyingly 🙂 ) popped up again.
  12. Click on Debug Control Window’s “Over” button until the Turtle Graphics window appears. NOTICE with each click of “Over”.
    • NOTICE with each click, A NEW LINE in the Code Window is highlighted.
    • NOTICE when forward() or left() commands are executed, the Turtle Graphics Window responds with the appropriate action.
    • NOTICE after the line A1pos = pos(); A2abs_pos = abs(pos()) has been executed, the Debug Control Window contains 2 lines under the “Locals”
    • A1pos – (200.00,0.00) or something like this value
    • A2abs_pos – 200.00 or something like this value
      • Keeping track of the current values of these items.
    • NOTICE that after we execute the if abs(pos()) &lt; 1: statement, we loop back to just under the while True: statement.
  13. Click on "Over" for about 30 more times. NOTICE the Turtle Graphics window cooking along, OBEYING the commands in the Code Window. 🙂
  14. Right Click on the break Line & select "Set Breakpoint".
    • NOTICE the yellow background.
  15. In the Debug Control Window Click on the "Go" button. This will run until just before we execute the breakpoint line.
    • WATCH the Trutle Graphics window do its thing.
  16. Click "Over".
    • NOTICE we exit the while True: loop.
  17. Click "Over".
    • NOTICE the end_fill() statement colors the star yellow.
  18. Click "Over" one last time.
    • NOTICE we are DONE. 🙂

Code

Here is the code we used in the video.

from turtle import *
setup (width=500, height=500, startx=500)
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    A1pos = pos(); A2abs_pos = abs(pos()) 
    if abs(pos()) < 1:
        break
end_fill()
done()

#coding, #debug-statement-execution, #education, #linux, #mac, #python, #python-idle, #raspberry-pi, #turtle-graphics, #windows