Tuesday, December 29, 2015

improve markdown syntax highlighting in sublime text


https://blog.mariusschulz.com/2014/12/16/how-to-set-up-sublime-text-for-a-vastly-better-markdown-writing-experience

The Markdown Extended Package

https://github.com/jonschlinkert/sublime-markdown-extended

Markdown syntax highlighter for Sublime Text, with extended support for GFM fenced code blocks, with language-specific syntax highlighting. YAML Front Matter. Works with ST2/ST3.


The Monokai Extended Package


Extends Monokai from Soda with additional syntax highlighting for Markdown, LESS, HTML, Handlebars and more. https://github.com/jonschlinkert



notes on GFM (github flavored markdown):
https://help.github.com/articles/github-flavored-markdown/



customize sublime text themes


https://github.com/buymeasoda/soda-theme/wiki/Theme-customisation


To begin customising an existing theme, create a new file in your User folder (located in the Sublime Text Packages directory) with the same name as the theme file you are extending.

For example, to customise Soda Dark, create an empty file called Soda Dark.sublime-theme (or for Sublime Text 3 create an empty file called Soda Dark 3.sublime-theme) in your User folder.

From this point, any valid theme rules you place in this file will automatically be applied by Sublime Text when the related theme is active.

Sunday, December 27, 2015

soda dark theme for sublime text

see commented-out section below for usage:

{
"color_scheme": "Packages/Tomorrow Color Schemes/Tomorrow-Night.tmTheme",
"ignored_packages":
[
"Vintage"
],
"show_full_path": true
}

// "soda_classic_tabs": true,
// "theme": "Soda Dark.sublime-theme"

Friday, December 18, 2015

de-dsstore.bat: batch file to delete-all-instances-of-ds_store-in-windows


http://awesometoast.com/delete-all-instances-of-ds_store-in-windows/

de-dsstore.bat:
e:
del /s /q /f /a .DS_STORE
del /s /q /f /a ._.*




bootstrap3 hide/show using hidden class and add/remove class




in bootstrap 3
use the hidden class instead of hide
use add/remove class instead of hide/show
jQuery ->
  if $('div.ground-school').length
    $(".previous-attempt-select").on "change", ->
      select = $(this)  #the select box from which an option was chosen
      quiz_id = select.val()
      if quiz_id > 0
        window.document.location = "/quiz_review_graded?quiz_id=#{quiz_id}"

    $(".lesson-thumbnail").on "click", ->
      link = $(this)
      lessonid = link.data('lessonid')
      # show the detail table for the selected header thumbnail
      detail_table = $(".video-thumbnail[data-videoid='#{lessonid}']").closest('table')
      detail_table_is_visible = detail_table.is(':visible')
      # if the details table isn't already visible, thumbnail is acting like an on button
      on_button_was_pressed = !detail_table_is_visible
      lesson_header = detail_table.closest('tr').prev()

      # hide everything
      $(".lesson-header").addClass('hidden')
      $(".detailtable").addClass('hidden')
      #undim header thumbnails
      $(".lesson-thumbnail").css('opacity', 1.0)
      # show reqs table for the selected lesson
      if on_button_was_pressed
        link.css('opacity', 0.7)
        detail_table.removeClass('hidden')
        lesson_header.removeClass('hidden')

Thursday, December 17, 2015

Remove iBook citations with a keyboard shortcut

save the following script
open a terminal window
run the scripts (loops until you exit it manually)


#!/usr/bin/env ruby
require 'clipboard'
loop do
  unless @clip == Clipboard.paste
    excerpt = Clipboard.paste
    puts "excerpt=#{excerpt}"
    cleaned = excerpt.match(/“([\n\w\d\s\D\W]+)”\n/)
    excerpt = cleaned.nil? ? excerpt : cleaned[1]
    puts "cleaned=#{excerpt}"
    Clipboard.copy(excerpt)
    @clip = Clipboard.paste
  end
end

sample run

the script will extract just the content between the quotes:

[smr@smr Desktop]$ ./remove-ibook-quotes.rb 

excerpt=“This rather obscure code, which you don’t need to understand in detail, arranges for precisely the behavior described above: it uses the minimum cost parameter in tests and a normal (high) cost parameter in production. (We’ll learn more about the strange ?-: notation in Section 8.4.5.)

Excerpt From: Michael Hartl. “Ruby on Rails Tutorial (3rd Ed.).” iBooks. 

cleaned=This rather obscure code, which you don’t need to understand in detail, arranges for precisely the behavior described above: it uses the minimum cost parameter in tests and a normal (high) cost parameter in production. (We’ll learn more about the strange ?-: notation in Section 8.4.5.)

notes

https://gist.github.com/iandundas/560df39f84ad00664101

prokizzle commented on Nov 7, 2015
Here's a ruby script that works for me

require 'clipboard'
loop do
  unless @clip == Clipboard.paste
    excerpt = Clipboard.paste
    cleaned = excerpt.match(/“([\n\w\d\s\D\W]+)”\n/)
    excerpt = cleaned.nil? ? excerpt : cleaned[1]
    Clipboard.copy(excerpt)
    @clip = Clipboard.paste
  end
end




use the clipboard ruby gem to copy and paste from the system clipboard

#!/usr/bin/env ruby

# require 'clipboard'
# loop do
#   unless @clip == Clipboard.paste
#     excerpt = Clipboard.paste
#     cleaned = excerpt.match(/“([\n\w\d\s\D\W]+)”\n/)
#     excerpt = cleaned.nil? ? excerpt : cleaned[1]
#     Clipboard.copy(excerpt)
#     @clip = Clipboard.paste
#   end
# end

require 'clipboard'
# loop do
#   unless @clip == Clipboard.paste
    excerpt = Clipboard.paste
    # grab everything inside the printer's quoes
    cleaned = excerpt.match(/“([\n\w\d\s\D\W]+)”\n/)
    excerpt = cleaned.nil? ? excerpt : cleaned[1]
    Clipboard.copy(excerpt)
    puts "stripped text copied to the clipboard:"
    puts excerpt

    # @clip = Clipboard.paste
#   end
# end

Saturday, December 12, 2015

python setup on osx 10.9


##################################################
# useful references
##################################################
https://dbader.org/blog/setting-up-sublime-text-for-python-development

http://outofmemoryblog.blogspot.co.uk/2012/08/python-development-with-sublime-text-2.html

https://realpython.com/blog/python/setting-up-sublime-text-3-for-full-stack-python-development/



##################################################
# system python vs python.org pkg vs homebrew python
##################################################
system:
which python
/usr/bin/python
python --version
Python 2.7.5

python.org python-3.5.0-macosx10.6.pkg:
which python3
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
python3 --version
Python 3.5.0

homebrew:
which python3
/usr/local/bin/python3
python3 --version
Python 3.5.1



configure sublime text for python syntax highlighting, autocomplete


  1. install SublimeRope using the package manager

SublimeRope gives you:
autocompletion
find defn
docs for selected fn

https://github.com/JulianEberius/SublimeRope

Thursday, December 10, 2015

compile bootstrap-3.3.6 using node and less


download source from:
http://getbootstrap.com/getting-started/#download

use homebrew to upgrade node if necessary
[smr@smr bootstrap-3.3.6]$ brew upgrade node

Error: node 5.1.1 already installed

cd bootstrap-3.3.6
npm install
grunt dist
or
grunt

see:
http://getbootstrap.com/getting-started/#grunt-commands
for details of grunt commands.


Tuesday, December 1, 2015

gotcha - if you git co a branch that uses a different rvm ruby, ruby is not switched automatically



if you forget this, you can inadvertently install stuff to the wrong ruby/gemset/etc.

easy workaround: when you switch to such a branch, close and reopen the terminal window. this will cause rvm to load the ruby listed in .ruby-version


[smr@smr pws2013 (master)]$ git co migrate-to-rails4 
Switched to branch 'migrate-to-rails4'
[smr@smr pws2013 (migrate-to-rails4)]$ ll
total 1592
drwxr-xr-x   34 smr  staff    1156 Dec  1 17:40 .
drwxr-xr-x    5 smr  staff     170 Apr 13  2013 ..
-rw-r--r--@   1 smr  staff   15364 Dec  1 10:30 .DS_Store
drwxr-xr-x   16 smr  staff     544 Dec  1 17:40 .git
-rw-r--r--    1 smr  staff     686 Dec  1 17:40 .gitignore
-rw-r--r--    1 smr  staff      14 Mar 25  2013 .rspec
-rw-r--r--    1 smr  staff       8 Dec  1 17:40 .ruby-gemset
-rw-r--r--    1 smr  staff      11 Dec  1 17:40 .ruby-version
-rw-r--r--    1 smr  staff     166 May 22  2013 Capfile
-rw-r--r--    1 smr  staff    2841 Dec  1 17:40 Gemfile
-rw-r--r--    1 smr  staff    7869 Dec  1 17:40 Gemfile.lock
-rw-r--r--    1 smr  staff    3695 Dec  1 17:40 Guardfile
-rw-r--r--    1 smr  staff    9208 Mar  7  2013 README.rdoc
-rw-r--r--    1 smr  staff     272 Mar  7  2013 Rakefile
drwxr-xr-x   10 smr  staff     340 Jun 12  2013 app
drwxr-xr-x    5 smr  staff     170 Dec  1 17:40 bin
drwxr-xr-x   16 smr  staff     544 Dec  1 17:40 config
-rw-r--r--    1 smr  staff     157 Mar  7  2013 config.ru
drwxr-xr-x  132 smr  staff    4488 Dec  1 17:40 content
drwxr-xr-x    8 smr  staff     272 Dec  1 17:40 db
drwxr-xr-x    3 smr  staff     102 Mar  7  2013 doc
-rw-r--r--    1 smr  staff  740672 Sep 30  2013 erd.pdf
drwxr-xr-x    4 smr  staff     136 Dec  1 17:40 grs_course_defns
drwxr-xr-x    7 smr  staff     238 May 25  2013 lib
drwxr-xr-x    8 smr  staff     272 Aug 16  2013 log
drwxr-xr-x    3 smr  staff     102 Jul 10 19:10 pdf
drwxr-xr-x    5 smr  staff     170 Dec  1 17:40 pdf-templates
drwxr-xr-x   12 smr  staff     408 Oct  4 14:38 public
drwxr-xr-x    5 smr  staff     170 Sep 23 11:46 script
drwxr-xr-x    8 smr  staff     272 Dec  1 17:40 smr
drwxr-xr-x   13 smr  staff     442 Dec  1 17:40 spec_old_unused
drwxr-xr-x    8 smr  staff     272 Dec  1 17:40 test
drwxr-xr-x    7 smr  staff     238 Aug  6 16:46 tmp
drwxr-xr-x    4 smr  staff     136 Mar  7  2013 vendor
[smr@smr pws2013 (migrate-to-rails4)]$ rvm current
ruby-1.9.3-p286
[smr@smr pws2013 (migrate-to-rails4)]$ rvm current
ruby-1.9.3-p286
[smr@smr pws2013 (migrate-to-rails4)]$ cd ../pws2013/
[smr@smr pws2013 (migrate-to-rails4)]$ rvm current
ruby-2.2.2@pws2013
[smr@smr pws2013 (migrate-to-rails4)]$ git co master
Switched to branch 'master'
[smr@smr pws2013 (master)]$ rvm current
ruby-2.2.2@pws2013
[smr@smr pws2013 (master)]$ cd ../pws2013/
[smr@smr pws2013 (master)]$ rvm current

ruby-1.9.3-p286



Tuesday, November 17, 2015

attempt to migrate DAT android to use AppCompat


migration worked, but getting crashes when navigating up from child activities.




tried to migrate DAT to use AppCompat.
crashing when navigating up using the toolbar (intent extras do not seem to be reserved)



https://github.com/codepath/android_guides/wiki/Migrating-to-the-AppCompat-Library


    compile 'com.android.support:appcompat-v7:23.1.1'



E/AndroidRuntime(23857): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.asa2fly.datandroid/com.asa2fly.datandroid.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

-    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">





##################################################
# search
##################################################


http://stackoverflow.com/questions/27049294/searchview-doesnt-work-since-app-compat

    <item android:id="@+id/menu_item_search"
        android:title="@string/search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always"
        app:actionViewClass="android.widget.SearchView"
        />

N.B. the app/android namespaces. since we're using appcompat we need to use app: in some cases.

imports in SFA
package com.asa2fly.datandroid;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;



##################################################
# crash
##################################################
E/AndroidRuntime(10619): FATAL EXCEPTION: main
E/AndroidRuntime(10619): Process: com.asa2fly.datandroid, PID: 10619
E/AndroidRuntime(10619): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
E/AndroidRuntime(10619): at com.asa2fly.datandroid.SearchHitListFragment.onLoadFinished(SearchHitListFragment.java:96)
E/AndroidRuntime(10619): at com.asa2fly.datandroid.SearchHitListFragment.onLoadFinished(SearchHitListFragment.java:27)
E/AndroidRuntime(10619): at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:476)
E/AndroidRuntime(10619): at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:444)
E/AndroidRuntime(10619): at android.support.v4.content.Loader.deliverResult(Loader.java:126)
E/AndroidRuntime(10619): at com.asa2fly.datandroid.SQLiteCursorLoader.deliverResult(SQLiteCursorLoader.java:32)
E/AndroidRuntime(10619): at com.asa2fly.datandroid.SQLiteCursorLoader.deliverResult(SQLiteCursorLoader.java:7)
E/AndroidRuntime(10619): at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:249)
E/AndroidRuntime(10619): at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:77)
E/AndroidRuntime(10619): at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:466)
E/AndroidRuntime(10619): at android.support.v4.content.ModernAsyncTask.access$400(ModernAsyncTask.java:48)
E/AndroidRuntime(10619): at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:483)
E/AndroidRuntime(10619): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(10619): at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(10619): at android.app.ActivityThread.main(ActivityThread.java:5254)
E/AndroidRuntime(10619): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(10619): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(10619): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)

E/AndroidRuntime(10619): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)





Sunday, November 8, 2015

enable the gradle daemon



This build could be faster, please consider using the Gradle Daemon: http://gradle.org/docs/2.4/userguide/gradle_daemon.html



[smr@smr ~]$ touch ~/.gradle/gradle.properties && echo "org.gradle.daemon=true" >> ~/.gradle/gradle.properties

https://docs.gradle.org/2.4/userguide/gradle_daemon.html


Friday, October 30, 2015

get the grs v1 site up and running on imac27




perl-mysql


##################################################
# create local mysql db
##################################################
create database groundschool;
GRANT ALL PRIVILEGES ON groundschool .* TO grs@'%' IDENTIFIED BY 'grs';
GRANT ALL PRIVILEGES ON groundschool .* TO grs@'localhost' IDENTIFIED BY 'grs';
flush privileges;
show grants for grs;


##################################################
# httpd.conf
##################################################
[smr@smr ~]$ bbedit /private/etc/apache2/httpd.conf

# Virtual hosts
Include /private/etc/apache2/extra/httpd-vhosts.conf


##################################################
# httpd-vhosts.conf
##################################################
[smr@smr ~]$ bbedit /private/etc/apache2/extra/httpd-vhosts.conf

#groundschool-alt.com.local
<VirtualHost *:80>
  <Directory /Users/smr/Sites/groundschool-alt.com/html/>
    Options +FollowSymlinks +SymLinksIfOwnerMatch
    AllowOverride All
  </Directory>
    DocumentRoot "/Users/smr/Sites/groundschool-alt.com/html/"
  ScriptAlias /cgi-bin/ "/Users/smr/Sites/groundschool-alt.com/cgi-bin/"
    ServerName groundschool-alt.local
    ErrorLog "/private/var/log/apache2/groundschool-alt.local-error_log"
    CustomLog "/private/var/log/apache2/groundschool-alt.local-access_log" common
</VirtualHost>


##################################################
# hosts
##################################################
[smr@smr ~]$ bbedit /private/etc/hosts

127.0.0.1 groundschool-alt.local


Thursday, October 29, 2015

install ruby 1.9.3 on osx 10.10. yosemite 10-29-15

awhile back i attempted this without success, but now it looks like there are some patches applied as part of the install and the install succeeds.


Last login: Mon Oct 26 17:26:44 on ttys001
[smr@macbook ~]$ rvm list

rvm rubies

   ruby-2.2.0 [ x86_64 ]
=* ruby-2.2.2 [ x86_64 ]

# => - current
# =* - current && default
#  * - default


[smr@macbook ~]$ rvm install 1.9.3
ruby-1.9.3-p551 - #removing src/ruby-1.9.3-p551..
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.10/x86_64/ruby-1.9.3-p551.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
==> Upgrading 2 outdated packages, with result:
libksba 1.3.3, openssl 1.0.2d_1
==> Upgrading libksba
==> Installing libksba dependency: libgpg-error
==> Downloading https://homebrew.bintray.com/bottles/libgpg-error-1.19.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libgpg-error-1.19.yosemite.bottle.tar.gz
🍺  /usr/local/Cellar/libgpg-error/1.19: 17 files, 352K
==> Installing libksba
==> Downloading https://homebrew.bintray.com/bottles/libksba-1.3.3.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libksba-1.3.3.yosemite.bottle.tar.gz
🍺  /usr/local/Cellar/libksba/1.3.3: 12 files, 372K
==> Upgrading openssl
==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2d_1.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring openssl-1.0.2d_1.yosemite.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺  /usr/local/Cellar/openssl/1.0.2d_1: 464 files, 18M
Certificates in '/usr/local/etc/openssl/cert.pem' are already up to date.
Requirements installation successful.
Installing Ruby from source to: /Users/smr/.rvm/rubies/ruby-1.9.3-p551, this may take a while depending on your cpu(s)...
ruby-1.9.3-p551 - #downloading ruby-1.9.3-p551, this may take a while depending on your connection...
ruby-1.9.3-p551 - #extracting ruby-1.9.3-p551 to /Users/smr/.rvm/src/ruby-1.9.3-p551....
ruby-1.9.3-p551 - #applying patch /Users/smr/.rvm/patches/ruby/GH-488.patch.
ruby-1.9.3-p551 - #applying patch /Users/smr/.rvm/patches/ruby/1.9.3/CVE-2015-1855-p484.patch.
ruby-1.9.3-p551 - #configuring...............................................
ruby-1.9.3-p551 - #post-configuration.
ruby-1.9.3-p551 - #compiling...............................................................................................|
ruby-1.9.3-p551 - #installing...........
ruby-1.9.3-p551 - #making binaries executable..
ruby-1.9.3-p551 - #downloading rubygems-2.4.8
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  437k  100  437k    0     0   226k      0  0:00:01  0:00:01 --:--:--  226k
No checksum for downloaded archive, recording checksum in user configuration.
ruby-1.9.3-p551 - #extracting rubygems-2.4.8....
ruby-1.9.3-p551 - #removing old rubygems.........
ruby-1.9.3-p551 - #installing rubygems-2.4.8......................
ruby-1.9.3-p551 - #gemset created /Users/smr/.rvm/gems/ruby-1.9.3-p551@global
ruby-1.9.3-p551 - #importing gemset /Users/smr/.rvm/gemsets/global.gems...............................................
ruby-1.9.3-p551 - #generating global wrappers........
ruby-1.9.3-p551 - #gemset created /Users/smr/.rvm/gems/ruby-1.9.3-p551
ruby-1.9.3-p551 - #importing gemsetfile /Users/smr/.rvm/gemsets/default.gems evaluated to empty gem list
ruby-1.9.3-p551 - #generating default wrappers........
ruby-1.9.3-p551 - #adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
Install of ruby-1.9.3-p551 - #complete
WARNING: Please be aware that you just installed a ruby that is no longer maintained (2014-02-23), for a list of maintained rubies visit:

    http://bugs.ruby-lang.org/projects/ruby/wiki/ReleaseEngineering

Please consider upgrading to ruby-2.2.2 which will have all of the latest security patches.
Ruby was built without documentation, to build it run: rvm docs generate-ri
[smr@macbook ~]$

extract audio from a video file using vlc on the command line; mp3






/Applications/VLC.app/Contents/MacOS/VLC -I dummy "/Users/smr/Desktop/e-dancing.m4v" --sout='#transcode{acodec=mp3,vcodec=dummyvcodec}:standard{access=file,mux=raw,dst="/Users/smr/Desktop/test2.mp3"}' vlc://quit



Wednesday, October 28, 2015

multi-line description in an advanced installer updates.txt file



;aiu;

[2016_100]
Name = Prepware 2016_100
ProductVersion = 16.1.0
URL = http://updates.prepware.com.s3.amazonaws.com/Install_Prepware_2016_100_win.exe
Size = 356235776
MD5 = 03ad573db06a698a995d13b24d052d60
ServerFileName = Install_Prepware_2016_100_win.exe
Flags = NoCache
RegistryKey = HKUD\Software\ASA\Prepware\Version
Version = 16.1.0
Description = This updater will update your installation of Prepware 2016 to version 2016_100.
Description1 = <b>Note for Prepware 2014 Users:</b> ASA provides updates for 2 years. Prepware 2014 is no longer supported with updates. If you must access the question databases represented by your old activation(s), do not do run update because it is going to remove all access to this old activation.
Feature = 10-2015 question databases
AutoCloseApplication = [APPDIR]Prepware.exe|;Prepware


Monday, October 26, 2015

add-android-metadata-to-db.pl



#!/usr/bin/perl -w
use strict;
use File::Find;
# dbs used by devices need an "android metadata table"
# sqlite> .schema
# CREATE TABLE android_metadata (locale TEXT);
use strict;
use DBI;


my $path = shift @ARGV;
die "please specify a path\n" unless $path;

find(\&wanted, $path);

sub wanted
{
if (/falcon\.db/)
{
my $filename = $_; #filename
my $full_path = $File::Find::name; #full path
my $dir = $File::Find::dir; #containing directory
print "processing $full_path\n";

my $path_to_db = $filename;
my $table_name = "android_metadata";
my $dbh = DBI->connect("dbi:SQLite:dbname=$path_to_db","","",{ AutoCommit => 0 }) or die $DBI::errstr;

#create table
$dbh->do( "drop table if exists $table_name" );
$dbh->do( "create table $table_name (locale TEXT)" );
$dbh->do( "insert into $table_name values('en_US')" );
$dbh->commit or die $dbh->errstr;
$dbh->disconnect();
}
}









python script to colorize logcat output

Thursday, October 22, 2015

pwo updates 10-2015 - verify pwo changes


these two tools are useful for verifying changes:
http://pwo-dev.prepware.com/testmaps
http://pwo-dev.prepware.com/topics_map


Turboprop (added) testmap

1.9.3-p286 :010 > y QuizDefinition.find_by_name("Turboprop (added)").testmap
---
1: 0
2: 0
3: 0
4: 8
5: 10
6: 10
7: 0
8: 0
9: 6
10: 5
11: 0
12: 0
13: 11

 => nil 

pvt chapter 11

1.9.3-p286 :008 > y Book.find_by_title("Private Pilot").chapters.find_by_chapnum(11).topics
---
- !ruby/object:Topic
  attributes:
    id: 741
    topicnum: 1
    title: Phraseology, Techniques, and Procedures
    chapter_id: 104
- !ruby/object:Topic
  attributes:
    id: 742
    topicnum: 2
    title: Airport Traffic Area Communications and Light Signals
    chapter_id: 104
- !ruby/object:Topic
  attributes:
    id: 743
    topicnum: 3
    title: Radar Assistance to VFR Aircraft
    chapter_id: 104
- !ruby/object:Topic
  attributes:
    id: 744
    topicnum: 4
    title: Transponder
    chapter_id: 104
- !ruby/object:Topic
  attributes:
    id: 745
    topicnum: 5
    title: Emergency Locator Transmitter (ELT)
    chapter_id: 104


atp chapter 5

1.9.3-p286 :009 > y Book.find_by_title("Airline Transport Pilot").chapters.find_by_chapnum(5).topics
---
- !ruby/object:Topic
  attributes:
    id: 53
    topicnum: 1
    title: Center of Gravity Computation
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 54
    topicnum: 2
    title: Stabilizer Trim Setting
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 55
    topicnum: 3
    title: Changing Loading Conditions
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 56
    topicnum: 4
    title: C208 Weight and Balance
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 57
    topicnum: 5
    title: Beech 1900 Weight and Balance
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 58
    topicnum: 6
    title: Helicopter Weight and Balance
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 59
    topicnum: 7
    title: ! 'Helicopter Weight and Balance: CG Shifts'
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 60
    topicnum: 9
    title: ! 'Helicopter Weight and Balance: Load Limits'
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 61
    topicnum: 9
    title: ! 'Helicopter Weight and Balance: Lateral CG'
    chapter_id: 49
- !ruby/object:Topic
  attributes:
    id: 62
    topicnum: 10
    title: Floor Loading Limits
    chapter_id: 49
 => nil 
1.9.3-p286 :010 > 



prepware updates 10-2015 - change Turboprop (added) testmap

falcon failed integrity checks.
cause: Turboprop (added) testmap.


old:
1.9.3-p286 :004 > y QuizDefinition.find_by_name("Turboprop (added)").testmap

1: 0
2: 1
3: 0
4: 8
5: 10
6: 10
7: 0
8: 0
9: 5
10: 5
11: 0
12: 0

13: 11

at the moment, have to do this by hand.
log onto dev.
RAILS_ENV=staging bundle exec rails console


1.9.3-p286 :010 > QuizDefinition.find_by_name("Turboprop (added)").test_map_entries.find_by_chapnum(2).update_attributes!(numq:0)
1.9.3-p286 :011 > QuizDefinition.find_by_name("Turboprop (added)").test_map_entries.find_by_chapnum(9).update_attributes!(numq:6)

new:
1.9.3-p286 :004 > y QuizDefinition.find_by_name("Turboprop (added)").testmap

1: 0
2: 0
3: 0
4: 8
5: 10
6: 10
7: 0
8: 0
9: 6
10: 5
11: 0
12: 0
13: 11

Wednesday, October 21, 2015

prepware updates 10-2015 - tweaks to fix discontiguous topic numbers


SELECT * FROM questions WHERE db_identifier='pvt' AND asachapter='11' AND topicnumber='4'

UPDATE `questions` set `topicnumber`=3 WHERE db_identifier='pvt' AND asachapter='11' AND topicnumber='4'
UPDATE `questions` set `topicnumber`=4 WHERE db_identifier='pvt' AND asachapter='11' AND topicnumber='5'
UPDATE `questions` set `topicnumber`=5 WHERE db_identifier='pvt' AND asachapter='11' AND topicnumber='6'

private chapter 11

11 1 Phraseology, Techniques, and Procedures
11 2 Airport Traffic Area Communications and Light Signals
11 3 Radar Assistance to VFR Aircraft
11 4 Transponder
11 5 Emergency Locator Transmitter (ELT)

atp chapter 5

changed my tab-delimited text (i use this to import topics into falcon) to:
5          1          Center of Gravity Computation
5          2          Stabilizer Trim Setting
5          3          Changing Loading Conditions
5          4          C208 Weight and Balance
5          5          Beech 1900 Weight and Balance
5          6          Helicopter Weight and Balance
5          7          Helicopter Weight and Balance: CG Shifts
5          8          Helicopter Weight and Balance: Load Limits
5          9          Helicopter Weight and Balance: Lateral CG
5          10        Floor Loading Limits



Friday, October 16, 2015

batch file that gets a reg key value



reg query HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ASA\Prepware /v Version
pause




Friday, October 9, 2015

create activerecord text column with size limit larger than 65k


  def self.up
    # create_table(:far_sections, :options => 'ENGINE=MyISAM DEFAULT CHARSET=utf8') do |t|
    create_table :far_sections do |t|
      t.integer :part_id
      t.integer :subpart_id
      t.string :sectiontype
      t.string :sectionnum
      t.text :title
      t.text :html, limit: 4.megabytes   #The default value of limit is 65535

      t.timestamps
    end
    execute 'CREATE FULLTEXT INDEX fulltext_far_sections ON far_sections (html)'
  end

  def self.down
    drop_table(:far_sections)
  end

end

activerecord specify tablename

http://stackoverflow.com/questions/4613574/how-do-i-explicitly-specify-a-models-table-name-mapping-in-rails
  def self.up
    create_table(:shazbat) do |t|
      t.string :name
      t.text :info

      t.timestamps
    end
    execute 'CREATE FULLTEXT INDEX fulltext_people ON shazbat (info)'
  end
class Person < ActiveRecord::Base
  self.table_name = "shazbat"
  attr_accessible :info, :name
end

Wednesday, October 7, 2015

rails 3.2.22 mysql FULLTEXT search and boolean mode


http://stackoverflow.com/questions/3923891/ruby-on-rails-migration-change-table-to-myisam

http://stackoverflow.com/questions/1039512/mysql-full-text-search-in-ruby-on-rails

http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html

class CreatePeople < ActiveRecord::Migration
  # def change
  #   create_table(:people, :options => 'ENGINE=MyISAM DEFAULT CHARSET=utf8') do |t|
  #     t.string :name
  #     t.text :info

  #     t.timestamps
  #   end
  #   # this way gives an 'without a key length' mysql error
  #   # add_index(:people, :name, type: :fulltext)

  #   # specifying an index name
  #   # execute 'CREATE FULLTEXT INDEX fulltext_person_info ON people (info)'
  #   execute 'CREATE FULLTEXT INDEX ON people (info)'
  # end

  def self.up
    create_table(:people, :options => 'ENGINE=MyISAM DEFAULT CHARSET=utf8') do |t|
      t.string :name
      t.text :info

      t.timestamps
    end
    execute 'CREATE FULLTEXT INDEX fulltext_people ON people (info)'
  end

  def self.down
    # execute 'DROP INDEX fulltext_people ON people'
    drop_table(:people)
  end

end
# index added using MySQL

# http://stackoverflow.com/questions/3923891/ruby-on-rails-migration-change-table-to-myisam
# http://stackoverflow.com/questions/1039512/mysql-full-text-search-in-ruby-on-rails


# I created a project (Rails 2.3.2, Ruby 1.9.1 MySQL 5.0) to emulate this.
# With one record in the database, I got the same results you did. When I
# added more records, the Photo.search command found the record.

# This could be because "words that are present in 50% or more of the rows are
# considered common and do not match". Ref.

# The 50% threshold does not apply in binary mode. Ref.

# IN BINARY MODE belongs inside the parentheses: AGAINST ('baceno' IN BOOLEAN
# MODE)


# 2.2.2 :013 > Person.find_by_sql("select * from people where match(info) against('Lorem' in boolean mode)")
#   Person Load (0.3ms)  select * from people where match(info) against('Lorem' in boolean mode)
#  => [#<Person id: 2, name: "fdfdfd", info: "Lorem ipsum dolor sit amet, consectetur adipisicing...", created_at: "2015-10-06 21:54:41", updated_at: "2015-10-06 21:54:41">, #<Person id: 3, name: "fdfdfd", info: "Lorem ipsum dolor sit amet, consectetur adipisicing...", created_at: "2015-10-06 21:54:41", updated_at: "2015-10-06 21:54:41">, #<Person id: 4, name: "fdfdfd", info: "Lorem ipsum dolor sit amet, consectetur adipisicing...", created_at: "2015-10-06 21:54:41", updated_at: "2015-10-06 21:54:41">, #<Person id: 5, name: "fdfdfd", info: "Lorem ipsum dolor sit amet, consectetur adipisicing...", created_at: "2015-10-06 21:54:41", updated_at: "2015-10-06 21:54:41">] 


# another approach to fix the "Mysql::Error: BLOB/TEXT column 'column-name'
# used in key specification without a key length": adjust the way the schema.rb file is generated.
# http://stackoverflow.com/questions/5147827/full-text-mysql-search-in-rails
# http://ablogaboutcode.com/2010/11/21/fulltext-index-and-spatial-index-mysql-compatible-rake-tasks/


##################################################
# boolean operators 
##################################################
# 2.2.2 :008 > Person.find_by_sql(["select * from people where match(info) against(? in boolean mode)", "+assumenda autem"]).count
#   Person Load (0.7ms)  select * from people where match(info) against('+assumenda autem' in boolean mode)
#  => 26 


Friday, October 2, 2015

ruby HoA - hash of arrays

#!/usr/bin/env ruby

items = %w(one two three one one two)
seen = {}
# step 1: init the seen hash keys
items.each { |item|
  seen[item] = []
}
# step 2: push items onto the arrays
items.each { |item|
  seen[item] << item
}

p seen

# [smr@smr Desktop]$ ./test.rb
# {"one"=>["one", "one", "one"], "two"=>["two", "two"], "three"=>["three"]}


Wednesday, September 30, 2015

rake task to delete orphan quiz records


# encoding: utf-8

namespace :db do
  desc "delete orphan quizzes"
  task delete_orphan_quizzes: :environment do
    # now = Time::now
    # Quiz.where(has_been_graded:false, mode:'quiz').each do |quiz|
    #   if quiz.expiretime.nil? || now > quiz.expiretime
    #     quiz.destroy
    #   end
    # end

    # alternate strategy, using delete (destroy instantiates ActiveRecord objects and is slow)
    # TODO: probably better to use batches here?
    # hardcoded limit of 1000 at the moment
    ids = Quiz.where("has_been_graded = ? AND mode = ? AND expiretime < ?", false, "quiz", Time::now).limit(1000).pluck :id
    puts "ids=#{ids}"
    # delete quiz and dependent objects (just ungraded questions since these quizzes have not been graded)
    Quiz.delete_all(id:ids)
    QuizQuestionMapping.delete_all(quiz_id:ids)
  end
end



ruby one-liner to print server time



ruby -e 'puts Time::now'


pwo sql to examine quizzes in progress (ungraded, unexpired)


SELECT * FROM `quizzes` WHERE (has_been_graded = 0 AND mode = 'quiz' AND expiretime > NOW())

SELECT * FROM `quizzes` WHERE (has_been_graded = 0 AND expiretime > NOW())

rails destroy vs delete_all association performance

http://stackoverflow.com/questions/2797339/rails-dependent-destroy-vs-dependent-delete-all


##################################################
# destroy
##################################################
1.9.3-p286 :004 > Quiz.last.destroy
  Quiz Load (0.3ms)  SELECT `quizzes`.* FROM `quizzes` ORDER BY `quizzes`.`id` DESC LIMIT 1
   (0.1ms)  BEGIN
  QuizQuestionMapping Load (0.4ms)  SELECT `quiz_question_mappings`.* FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`quiz_id` = 264613
  SQL (0.3ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28891
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28892
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28893
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28894
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28895
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28896
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28897
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28898
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28899
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28900
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28901
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28902
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28903
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28904
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28905
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28906
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28907
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28908
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28909
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28910
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28911
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28912
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28913
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28914
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28915
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28916
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28917
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28918
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28919
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28920
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28921
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28922
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28923
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28924
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28925
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28926
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28927
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28928
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28929
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28930
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28931
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28932
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28933
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28934
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28935
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28936
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28937
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28938
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28939
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28940
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28941
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28942
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28943
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28944
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28945
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28946
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28947
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28948
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28949
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28950
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28951
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28952
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28953
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28954
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28955
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28956
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28957
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28958
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28959
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28960
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28961
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28962
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28963
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28964
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28965
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28966
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28967
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28968
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28969
  SQL (0.2ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28970
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28971
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28972
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28973
  SQL (49.7ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28974
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28975
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28976
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28977
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28978
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28979
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28980
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28981
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28982
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28983
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28984
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28985
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28986
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28987
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28988
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28989
  SQL (0.1ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`id` = 28990
  GradedQuizQuestionMapping Load (0.2ms)  SELECT `graded_quiz_question_mappings`.* FROM `graded_quiz_question_mappings` WHERE `graded_quiz_question_mappings`.`quiz_id` = 264613
  SQL (0.2ms)  DELETE FROM `quizzes` WHERE `quizzes`.`id` = 264613
   (0.4ms)  COMMIT



##################################################
# delete_all
##################################################
1.9.3-p286 :001 > Quiz.last.destroy
  Quiz Load (0.2ms)  SELECT `quizzes`.* FROM `quizzes` ORDER BY `quizzes`.`id` DESC LIMIT 1
   (0.1ms)  BEGIN
  SQL (1.0ms)  DELETE FROM `quiz_question_mappings` WHERE `quiz_question_mappings`.`quiz_id` = 264612
  GradedQuizQuestionMapping Load (0.2ms)  SELECT `graded_quiz_question_mappings`.* FROM `graded_quiz_question_mappings` WHERE `graded_quiz_question_mappings`.`quiz_id` = 264612
  SQL (0.3ms)  DELETE FROM `quizzes` WHERE `quizzes`.`id` = 264612
   (0.6ms)  COMMIT
 => #<Quiz id: 264612, name: "Flight Instructor, Airplane", minutes_allowed: 150, mode: "quiz", has_been_graded: false, curidx: 0, starttime: "2015-09-29 18:35:38", stoptime: nil, expiretime: "2015-09-29 21:05:38", score: nil, source: "choose-quiz", is_instructor_quiz: false, template_id: 0, user_id: 1, product_id: 6, quiz_definition_id: 8, created_at: "2015-09-29 18:35:38", updated_at: "2015-09-29 18:35:39"> 

Wednesday, September 23, 2015

notes on migrating pws2013rails to rails 4.2.2

upgrade to 4.2.2


rvm gemset create pws2013
rvm use ruby-2.2.2@pws2013
echo "ruby-2.2.2" > .ruby-version
echo "pws2013" > .ruby-gemset


change gem file to be based on sample app 3e
bundle
whines about gem lock
bundle update


##################################################
# whitelist_attributes 
##################################################
Exiting
/Users/smr/.rvm/gems/ruby-2.2.2@pwo222test/gems/activerecord-4.2.2/lib/active_record/dynamic_matchers.rb:26:in `method_missing': undefined method `whitelist_attributes=' for ActiveRecord::Base:Class (NoMethodError)

https://github.com/rails/protected_attributes/issues/5

comment out:
config.active_record.whitelist_attributes = true
in /Users/smr/Desktop/pwo222test/pws2013rails/config/application.rb


##################################################
# mass_assignment_sanitizer 
##################################################
/Users/smr/.rvm/gems/ruby-2.2.2@pwo222test/gems/activerecord-4.2.2/lib/active_record/dynamic_matchers.rb:26:in `method_missing': undefined method `mass_assignment_sanitizer=' for ActiveRecord::Base:Class (NoMethodError)

coment out:
config.active_record.mass_assignment_sanitizer = :strict
in:
/Users/smr/Desktop/pwo222test/pws2013rails/config/environments/development.rb
/Users/smr/Desktop/pwo222test/pws2013rails/config/environments/test.rb


##################################################
# auto_explain_threshold_in_seconds 
##################################################
/Users/smr/.rvm/gems/ruby-2.2.2@pwo222test/gems/activerecord-4.2.2/lib/active_record/dynamic_matchers.rb:26:in `method_missing': undefined method `auto_explain_threshold_in_seconds=' for ActiveRecord::Base:Class (NoMethodError)

comment out:
config.active_record.auto_explain_threshold_in_seconds = 0.5


##################################################
# `match` method in your router 
##################################################
/Users/smr/.rvm/gems/ruby-2.2.2@pwo222test/gems/actionpack-4.2.2/lib/action_dispatch/routing/mapper.rb:238:in `add_request_method': You should not use the `match` method in your router without specifying an HTTP method. (ArgumentError)
If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.
If you want to expose your action to GET, use `get` in the router:
  Instead of: match "controller#action"
  Do: get "controller#action"

tweak routes.rb


##################################################
# Unknown key: :select 
##################################################
ArgumentError (Unknown key: :select. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type):

http://stackoverflow.com/questions/22750091/block-in-assert-valid-keys-unknown-key-order-argumenterror

change:
  has_many :instructors, :through => :followed_instructors,
           :select => "users.*, instructor_student_affiliations.pending AS pending"
to:
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many

rework like this:
  # rails 4 no likey
  # has_many :instructors, :through => :followed_instructors,
  #          :select => "users.*, instructor_student_affiliations.pending AS pending"
  has_many :instructors, 
            -> { select("users.*, instructor_student_affiliations.pending AS pending") }, 
            :through => :followed_instructors


##################################################
# undefined method `attr_accessible' 
##################################################
NoMethodError (undefined method `attr_accessible' for #<Class:0x007fd499c2a8b0>):

comment these out

***N.B. will likely have to tweak ledermann/rails-settings
class UserSettingsObject < RailsSettings::SettingObject
  # with rails 3.2
  # :var and :target need to be accessible to read values
  # if you want to change values they also need to be accessible
  # attr_accessible :var, :target, :should_send_test_completed_emails, :quiz_in_progress
  # https://github.com/ledermann/rails-settings/issues/65
end


##################################################
# compass
##################################################
File to import not found or unreadable: compass

not using this anymore. comment it out.
/Users/smr/Desktop/pwo222test/pws2013rails/app/assets/stylesheets/application.css.scss:
// @import "compass";


##################################################
# Extra .css in SCSS file 
##################################################
DEPRECATION WARNING: Extra .css in SCSS file is unnecessary.

rename these


##################################################
# @extend ".control-group" 
##################################################
Sass::SyntaxError (".field_with_errors" failed to @extend ".control-group".
The selector ".control-group" was not found.
Use "@extend .control-group !optional" if the extend should be able to fail.
):
  app/assets/stylesheets/main.scss:71
  app/views/layouts/application.html.erb:5:in `_app_views_layouts_application_html_erb__4553874112999930212_70265466688080'

https://github.com/plataformatec/simple_form


##################################################
# comment out all attr_accessible 
##################################################


##################################################
# scope needs to be callable 
##################################################
http://stackoverflow.com/questions/28951671/argument-error-the-scope-body-needs-to-be-callable

change to something like:
  scope :graded, -> { where(has_been_graded:true).order("stoptime DESC") }


##################################################
# sql error 
##################################################

ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*, instructor_student_affiliations.pending AS pending) FROM `users` INNER JOIN `' at line 1: SELECT COUNT(users.*, instructor_student_affiliations.pending AS pending) FROM `users` INNER JOIN `instructor_student_affiliations` ON `users`.`id` = `instructor_student_affiliations`.`instructor_id` WHERE `instructor_student_affiliations`.`student_id` = 1):
  app/models/user.rb:230:in `student?'
  app/models/user.rb:243:in `school_roles'
  app/views/users/show.html.erb:28:in `_app_views_users_show_html_erb__1110688672353824995_70241578162000'

not totally sure what's going on here

  def student?
    # return instructors.count > 0   #causing weird mysql error
    return instructors.length > 0
  end


##################################################
# [POST] "/init_quiz" 
##################################################
ActionController::RoutingError (No route matches [POST] "/init_quiz"):


##################################################
# none scope 
##################################################
You tried to define a scope named "none" on the model "Question", but Active Record already defined a class method with the same name.


##################################################
# multiline anchors 
##################################################
The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?

http://stackoverflow.com/questions/17759735/regular-expressions-with-validations-in-ror-4

se \A and \z rather than ^ and $ because in Ruby, ^ and $ match only a newline not start and end of string, which allows a javascript exploit to pass the test. 


##################################################
# replace modal hide 
##################################################


##################################################
# scoped 
##################################################
use User.all instead.

    else
      User.all
    end


##################################################
# ActiveModel::ForbiddenAttributesError 
##################################################
ActiveModel::ForbiddenAttributesError in UsersController#update
try to edit user
error
http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

need to:
add a private permit method to the controller
  private
    # Using a private method to encapsulate the permissible parameters
    # is just a good pattern since you'll be able to reuse the same
    # permit list between create and update. Also, you can specialize
    # this method with per-user checking of permissible attributes.
    def school_params
      params.require(:school).permit(:name, :actcode)
    end

  and do this in the update call:
    respond_to do |format|
      # if @school.update_attributes(params[:school])
      if @school.update_attributes(school_params)
        format.html { redirect_to @school, notice: 'School was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @school.errors, status: :unprocessable_entity }
      end



deal:
DEPRECATION WARNING: Passing a nested array to Active Record finder methods is deprecated and will be removed. Flatten your array before using it for 'IN' conditions. (called from search at /Users/smr/Desktop/pwo222test/pws2013rails/app/models/user.rb:294)





##################################################
# simple_form 3.2 
##################################################
https://github.com/plataformatec/simple_form

run this:
rails generate simple_form:install --bootstrap


diff --git a/config/locales/simple_form.en.yml b/config/locales/simple_form.en.yml
index 3a37025..2374383 100644
--- a/config/locales/simple_form.en.yml
+++ b/config/locales/simple_form.en.yml
@@ -10,29 +10,7 @@ en:
       # html: '<abbr title="required">*</abbr>'
     error_notification:
       default_message: "Please review the problems below:"
-    labels:
-      defaults:
-        actcode: 'Activation Code'
-      custom_question:
-        actcode: 'Activation Code'
-        answerA: 'Answer A'
-        answerB: 'Answer B'
-        answerC: 'Answer C'
-        correctChoice: 'Correct Choice'
-      school:
-        name: 'School Name'
-      score_submission:
-        mail_street_address: 'Street'
-        mail_city: 'City'
-        mail_state: 'State'
-        mail_zip: 'Zip'
-        mail_country: 'Country'
-      subscription:
-        actcode: 'Activation Code'
-
-
-
-    # Labels and hints examples
+    # Examples
     # labels:
     #   defaults:
     #     password: 'Password'
@@ -45,4 +23,9 @@ en:
     #   defaults:
     #     username: 'User name to sign in.'
     #     password: 'No special characters, please.'
-
+    # include_blanks:
+    #   defaults:
+    #     age: 'Rather not say'
+    # prompts:
+    #   defaults:
+    #     age: 'Select your age'


##################################################
# simple_form horizontal form 
##################################################
<% provide(:title, "Sign In") %>
<div class="row">
  <div>
    <h2>Sign In</h2>
    <%= simple_form_for :session, url: sessions_path, 
      html: { class: 'form-horizontal' },
      wrapper: :horizontal_form,
      wrapper_mappings: {
        check_boxes: :horizontal_radio_and_checkboxes,
        radio_buttons: :horizontal_radio_and_checkboxes,
        file: :horizontal_file_input,
        boolean: :horizontal_boolean
      } do |f| %>
      <%= f.input :email %>
      <%= f.input :password %>
      <%= f.button :submit, 'Sign In', :class => 'btn' %>
    <% end %>

    <p><%= link_to 'Forgot password?', new_password_reset_path %></p>

  </div>
</div>




##################################################
# rework test database 
##################################################
create database pws2013Test;
GRANT ALL PRIVILEGES ON pws2013Test .* TO pws2013TestUser@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON pws2013Test .* TO pws2013TestUser@'localhost' IDENTIFIED BY 'password';
show grants for pws2013TestUser;


rake db:migrate RAILS_ENV=test


##################################################
# guard doesn't seem to be running the tests 
##################################################
https://github.com/guard/guard-minitest/issues/114
spring: 'bundle exec spring rake test' works
but spring: true does not work.
It's because bin/rake doesn't exist...

https://github.com/rails/spring
bundle exec spring binstub --all


http://stackoverflow.com/questions/32215922/rails-4-guard-is-not-part-of-the-bundle-add-it-to-gemfile-gemloaderror

  gem 'guard'
  gem 'guard-minitest',     '2.4.4'

[smr@smr pws2013 (migrate-to-rails4 *%)]$ bundle exec guard
17:46:49 - INFO - Guard::Minitest 2.4.4 is running, with Minitest::Unit 5.8.0!
17:46:49 - INFO - Guard is now watching at '/Users/smr/current_projects/prepware-school-2013/pws2013'


# spec folder interferes with guard run all 
##################################################
***For some reason this issue occurs if there is spec folder along with the test one. I was migrating from rspec to minitest and I was trying to solve this issue but I gave up. Anyway, as soon as I renamed the spec folder the issue was fixed... weird.


##################################################
# spring and guard
##################################################
1. run all tests
run guard and hit return to run all the tests (since we are using all_on_start: false).


[smr@smr pws2013 (migrate-to-rails4 *%)]$ bundle exec guard
20:16:15 - INFO - Guard::Minitest 2.4.4 is running, with Minitest::Unit 5.8.0!
20:16:15 - INFO - Guard is now watching at '/Users/smr/current_projects/prepware-school-2013/pws2013'
[1] guard(main)> 
20:16:16 - INFO - Run all
20:16:16 - INFO - Running: all tests
Started

  2/2: [===================================] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.29143s
2 tests, 5 assertions, 0 failures, 0 errors, 0 skips

2. run a file's tests by saving it (see guard file fr rules on what tests get run when certain files are saved)

20:22:27 - INFO - Running: test/integration/site_layout_test.rb
Started

  1/1: [===================================] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.33901s
1 tests, 4 assertions, 0 failures, 0 errors, 0 skips




install spring stubs:
[smr@smr pws2013 (migrate-to-rails4 *%)]$ bundle exec spring binstub --all
* bin/rake: spring already present
* bin/rails: spring already present


[smr@smr pws2013 (migrate-to-rails4 *%)]$ spring status
Spring is running:

54829 spring server | pws2013 | started 2 hours ago                                                     
54830 spring app    | pws2013 | started 2 hours ago | test mode  

[smr@smr pws2013 (migrate-to-rails4 *%)]$ spring stop
Spring stopped.
[smr@smr pws2013 (migrate-to-rails4 *%)]$ spring status
Spring is not running.

can also check for spring processes using
[smr@smr pws2013 (migrate-to-rails4 *%)]$ ps aux | grep spring


##################################################
# secret_key_base 
##################################################
/Users/smr/current_projects/prepware-school-2013/pws2013/config/secrets.yml

N.B. for production server
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>