Installing CouchDB 2.0 on Debian Stretch
CouchDB 2.0 released on September 2016 has clustering support.
#cd /usr/src
#wget http://www-eu.apache.org/dist/couchdb/source/2.0.0/apache-couchdb-2.0.0.tar.gz
#tar xvzf apache-couchdb-2.0.0.tar.gz
#cd apache-couchdb-2.0.0
#./configure
#make release
By any chance you encounter this error,
ERROR: Unable to generate spec: read file info /usr/lib/erlang/man/man1/gcc-ar.1.gz failed
ERROR: Unexpected error: rebar_abort
generate failed while processing rebar_abort
You need to install erlang-base-hipe instead of erlang-base
#aptitude install erlang-base-hipe
#rm /usr/lib/erlang/main
#make clean
#make release
Debugging and logging in OpenResty
There is a few key point to ease the development of lua in OpenResty environment.
Turn lua code caching off
Restarting nginx everytime there is a code changes is painful. The easier way is to load external lua code using content_by_lua_file as opposed to have lua code inside nginx configuration files and then turn off the cache.
location /hello {
default_type text/html;
lua_code_cache off; #development
content_by_lua ./hello.lua;
}
Read nginx log as it is written
Set the error_log configuration directive to output log on easily accessable directory.
error_log /home/away/tmp/hello.log
And read the log interactively in a separate terminal as it been written using
tail -f /home/away/temp/hello.log
Output the log file in the terminal
Redirect all error log to the terminal where nginx is running
error_log /dev/stderr;
Log event or variable
Output debugging info using ngx.log
ngx.log(ngx.ERR, "hello world here")
References
OpenResty website
Definintely an OpenResty Guide
Nodejs gotcha on heroku
Use environment variable process.env.PORT instead of requesting for fixed port. Heroku will assign random port everytime the application bootup. This lead to some misleading error like strange Redis too many connection error and error H10.
app.listen(process.env.PORT || 5000);
Another gotcha when we upgrade the PostgreSQL to the bigger plan, yet another misleading error
error: no pg_hba.conf entry for host
The paid plan (standard-0) only accept ssl connection:
postgres://user:seckrit@pghost:5432/dbname?ssl=true
isFloat and isInteger in javascript
Found some interesting way to check isFloat and isInteger in javascript on stackoverflow
function isFloat(n) {
return n === +n && n !== (n|0);
}
function isInteger(n) {
return n === +n && n === (n|0);
}
Couchapp on Debian Stretch
I have been developing application using Qooxdoo for years. It works great so far, except when the internet very slow, which is quite common problem. It make the application behave unexpectedly weird because user will randomly click anywhere while data loading from the server.
One way to solve this problem is to design using offline first concept. That is where i get to know about PouchDB and CouchDB. Couchapp is a convinient way to develop application on CouchDB.
Installing couchapp is pretty easy,
#aptitude install python-pip
#pip install couchapp
Then creating a new project,
$couchapp generate hello
Related
Couchapp on github
Couchapp documentation
Building couchapp
Remove node_modules from remote git repo
node_modules folder in the root project directory can be very large and slow down commit.
This command will overwrite history.
$git filter-branch -f --tree-filter 'rm -rf node_modules' HEAD
$git gc --prune
$git push origin master --force
Validate malaysian phone number in javascript
My pull request just accepted by chriso author of validator.js, now you can use validator.js to validate malaysian phone number using ‘ms-MY’ locale.
Probably will take sometime before the npm and bower package updated.
You can install via npm,
$npm install --save https://github.com/chriso/validator.js.git
On nodejs,
const v = require('validator')
v.isMobilePhone('+60128747889', 'ms-MY')
On browser,
<script type="text/javascript" src="validator.min.js"></script>
<script type="text/javascript">
validator.isMobilePhone('+60128747889', 'ms-MY') //true
</script>
Btw, i wish the locale is en-MY but there is no such thing. So, i think ms-MY will do.
Update github fork from the original repo
$git remote add --track master chriso git://github.com/chriso/validator.js.git
$git fetch chriso
$git merge chriso/master
Beautify javascript code
Some of my javascript code indent contain mixed of tab and space
and only aware of the code ugly indent when i open in github.
There is a few cli program to format code and my favorite so far is js-beautify
#npm install -g js-beautify
Go to the source code do
$js-beautify -h
$js-beautify -s 2 -r *js
You can make vim to display space character on the editor by using the command
:set list
Variable in nginx configuration
Found one interesting overlook configuration in nginx.
server {
server_name ~^(www\.)?(?<domain>.+)$;
location / {
root /sites/$domain;
}
}
Some note on the matching pattern modifiers,
(none) prefix match
= match exactly
~ case sensetive regex match
~* case insensetive regex match
^~ non regular match is prefered
Related
Nginx core module configuration
Understanding server and location block selection algorithm
Install php7.0 on debian jessie
The latest PHP7.0 come with huge speed improvement. PHP7.0 debian package is available from dotdeb repository.
deb http://packages.dotdeb.org jessie all
deb-src http://packages.dotdeb.org jessie all
Then install the key
#wget https://www.dotdeb.org/dotdeb.gpg
#sudo apt-key add dotdeb.gpg
#aptitude install php7.0-fpm php7.0-pgsql php7.0-cli
Please note that some extension not yet available.
Socket.io in nodejs cluster
Running nodejs in cluster is a bit tricky. We need to make sure the same worker handle the same connection from the same client.
To make life a little bit easier, we can use Sticky Session
$npm install sticky-session
And we need to use socket.io-redis to make sure we can send message to socket handle by different workers.
$npm install socket.io-redis
Related
Sticky Session
Using multiple nodes
Node cluster socket.io
Ghost blog mail configuration using Amazon SES
Ghost is a blogging platform written in nodejs.
Edit the config.js file at the ghost root directory
mail: {
from: 'from@email.com',
transport: 'SMTP',
options: {
host: "your-amazon-host",
port: 465,
service: "SES",
auth: {
user: "your-amazon-user",
pass: "your-amazon-password"
}
}
}
Amazon SES credential can be generated from amazon control panel.
From address must be registered and verified as sender.
Related
Mail configuration on a self hosted ghost
Mail github source
Nginx and socket.io premature closed connection
It happen whenever nodejs server crashed.
Block ads using /etc/hosts in debian
We can avoid ads from loading by serving 0.0.0.0 or 127.0.0.1 for the ads domain.
There is a few website that provide such list and one of them is from mvps.org.
The installation is rather simple. Just copy and paste the list to /etc/hosts file.
#wget http://winhelp2002.mvps.org/hosts.txt
#cp /etc/hosts /etc/hosts.old
#cat hosts.txt >> /etc/hosts
The host file come from window enviroment. So there will be some extra line ugly line
ending that look like ^M in vim. To fix it
#vim /etc/hosts
Then on the vim command mode run
:%s/<CTRL-V><CTRL-M>//g
Related
Block unwanted advertisements with /etc/hosts file on Linux
Amalgamated hosts file
Compile mupdf in debian
#aptitude install libgl-dev libxcursor-dev libxrandr-dev libxinerama-dev
$git clone git@github.com:paragasu/mupdf.git
$cd mupdf
$git submodule init
$git submodule update
$make
Merge git repo as another branch
I have two local repository on my directory api-php and api-nodejs. I want to have one repo called api with two branch php and nodejs.
$cd api-php
$git remote add nodejs ../api-nodejs
$git remote update
$git checkout -b nodejs
$git rm -f *
$git merge nodejs/master
$git push -f
By the way, both php and node js implement the same api but the language is totally differnet.
It is best to put both project on separate repository.
Generate SSL certificates using letsencrypt
Letsencrypt provide free ssl certificate. The only downside is that the certificate only valid
for 3 months and then you have to renew the certificate again.
#git clone https://github.com/letsencrypt/letsencrypt
#cd letsencrypt
#./letsencrypt certonly --manual -d mydomain.com
On my debian server, The command will update packages and ask for root if you run as normal user and it will require you to put some key file in the root domain for verification.
http://mydomain.com/.well-known/acme-challenge/random-key-filename
You have to make sure the content-type is text/plain for the verification to work. The certificate will be available at /etc/letsencrypt. The latest cert will be inside the /etc/letsencrypt/live folder.
You need to update your server configuration to point to the cert file.
Https on Nodejs
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
Related
Nodejs doc
Install gin.io in Debian Jessie
Openresty is nginx with embeded lua. High performance with low memory footprint.
Gin is a small and elegant lua framework build on top of Openresty.
Install Openresty framework
#aptitude install lua-dbi-postgresql-dev
#aptitude install luajit
#aptitude install libreadline-dev libncurses5-dev libpcre3-dev libssl-dev perl make build-essential
#aptitude install libpq-dev
#cd /usr/src
#wget https://openresty.org/download/ngx_openresty-1.9.7.2.tar.gz
#cd ngx_openresty*
#./configure --with-luajit --with-http_postgres_module
Install gin framework
#aptitude install luarocks
#luarocks install --server=http://gin.io/repo gin
Related
OpenResty
Gin JSON API framework
Could not open connection to your authentication agent
eval `ssh-agent -s`
ssh-add
PostgreSQL ENUM type
To create enum type
CREATE TYPE colors AS ENUM (‘grey’, ‘skyblue’, ‘black’);
To list enum values
SELECT ENUM_RANGE(null::colors); or
SELECT UNNEST(ENUM_RANGE(null::colors)) AS colors;
To add new item on the enum list
ALTER TYPE colors ADD VALUE 'orange' AFTER 'skyblue';
To delete item from enum list
ALTER TYPE colors DROP attribute 'orange';
To drop enum type
DROP type colors
There is a more elegant way using domain to enforce value from David E. Wheeler post
CREATE DOMAIN eye_color AS TEXT
CONSTRAINT valid_eye_colors CHECK (
VALUE IN ( 'blue', 'green', 'brown' )
);
CREATE TABLE faces (
face_id SERIAL PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
eye_color eye_color NOT NULL
);
Related
Enum support function
Alter type
Enforce set of values
Hash any string to number
crc32 function will hash any string to number.
Nodemon failed to start process, possible issue with exec arguments
Nodemon will crashed with this error when the exec comman return error code 2
[Nodemon] failed to start process, possible issue with exec arguments
events.js:146
throw err;
^
Error: Uncaught, unspecified "error" event. (2)
at emit (events.js:144:17)
Error code 2 is reserved for bash. Command line tools like mocha or jshint sometimes will throw error 2. When jshint or mocha executed as argument to -x in nodemon. Nodemon crash.
A simple workaround is to put exit 1 in the -x
$nodemon --e js -w ./ -d 1 -x 'mocha ./test || exit 1'
Related
Nodemon code
JSHint integration on github
Nodejs exit code
Migration from wordpress.com to github.io in Debian
Login to wordpress and export all pages
#aptitude install ruby ruby-dev
#gem install jekyll jekyll-import hpricot open_uri_redirections
$jekyll new paragasu.github.io
$cd paragasu.github.io
$jekyll serve
git change author info
Edit the commit author and email name in github
Disable ipv6 in debian
Edit /etc/sysctl.conf and add config
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
net.ipv6.conf.eth0.disable_ipv6 = 1
#sysctl -p
Reactjs Fixed Data Table callback function onRowDoubleClick function
The callback function for onRowDoubleClick for Fixed data table.
rowClicked: function(event, rowIndex, rowData){<br />
//code here
}
Setting up nfs in debian stretch
On nfs server
#aptitude install nfs-kernel-server
Edit /etc/exports configuration file
/home/me/public 192.168.1.2(rw,no_root_squash,subtree_check)<br />
Restart nfs
#exportfs -a
#/etc/init.d/nfs-kernel-server start
On nfs client
#aptitude install nfs-common
#/etc/init.d/nfs-common start
To list available nfs
#showmount -e 192.168.1.2
To mount nfs
#mount -t nfs /home/me/public /mnt/public<br />
Docker error System error in /sys/fs/cgroup/cpu,cpuactt in debian
Basic tmux command
Ctrl+b "
- split pane horizontally.Ctrl+b %
- split pane vertically.Ctrl+b arrow key
- switch pane.- Hold
Ctrl+b
, don't release it and hold one of the arrow keys - resize pane. Ctrl+b c
- (c)reate a new window.Ctrl+b n
- move to the (n)ext window.Ctrl+b p
- move to the (p)revious window.\
Calculate distance between two point on earth in PostgreSQL
Come across nice function by Merlin Moncure posted on grokbase.
CREATE OR REPLACE
FUNCTION calculate_distance(lat1 float8, lon1 float8, lat2 float8, lon2 float8)
RETURNS float8 AS
$$
SELECT ACOS(SIN(RADIANS($1)) * SIN(RADIANS($3))
+ COS(RADIANS($1)) * COS(RADIANS($3))
* COS(RADIANS($4) - RADIANS($2))) * 6371;
$$ LANGUAGE 'sql' IMMUTABLE;
More details
Calculating distance between longitude and latitude
Calculate distance, bearing and more
Migrating from MySQL to PostgreSQL
Encounter some issue along the way
1.MySQL DATE_SUB & DATE_ADD
(DATE_ADD(NOW(), INTERVAL 30 MINUTES)
(DATE_SUB(NOW(), INTERVAL 30 MINUTES)
(NOW() - INTERVAL '30' MINUTE)
(NOW() - INTERVAL '30' MINUTE) or
(NOW() - INTERVAL '30 MINUTES') or
(NOW() - '30 MINUTES'::INTERVAL)
2.MySQL RADIANS
Need to cast to real
SELECT RADIANS(lat::real);
3.DISTINCT on json field (v9.4.5)
SELECT DISTINCT id, json_field FROM driver;
Throw could not identify an equality operator for type json error.
Converting the json field to jsonb solve the problem
Install mysql 5.6 in debian 8 jessie
The replication performance leap from MySQL 5.5 to MySQL 5.6 is more than 4x.
#wget http://dev.mysql.com/get/mysql-apt-config_0.3.5-1debian8_all.deb
#dpkg -i mysql-apt-config_0.3.5-1debian7_all.deb
#apt-get update
#apt-get install mysql-community-server
MySQL 5.6 replication performance
Install MySQL server 5.6 to debian
Firefox 40+ slow right click in Debian Linux
Just installed latest firefox on debian linux streetch.
Right click on link popup very slow.
SOLVED: [blfs-support] Firefox - slow menu and right-click response
The right click menu in Firefox is now fast again. I disabled Pulseaudio which
tried to load ConsoleKit. This did not work sine I have unstalled ConsoleKit.=== details ===
I found this:
/var/log/sys.log
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] module-console-kit.c:
GetSessionsForUnixUser() call failed:
org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.ConsoleKit
was not provided by any .service files
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] module.c: Failed to load
module "module-console-kit" (argument: ""): initialization failed.
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] main.c: Module load failed.
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] main.c: Failed to
initialize daemon.
Jan 25 09:13:47 lfs pulseaudio[2562]: [pulseaudio] main.c: Daemon startup
failed.I commented out the text below in /etc/pulse/default.pa
#.ifexists module-console-kit.so
#load-module module-console-kit
#.endifI restarted and then the problem with the Firefox menus disappeared.
The root cause is probably that I uninstalled ConsoleKit. This was
intentional, but I failed to recognize the side effects.Magnus
Qooxdoo change global application font size
setFontSize: function(size)
{
var doc = this.getRoot();
var manager = qx.theme.manager.Font.getInstance();
var defaultFont = manager.resolve(doc.getFont());
var newFont = defaultFont.clone().setSize(parseInt(size));
doc.setFont(newFont);
},
How to use genymotion emulator
Start the emulator. Then find out the genymotion assigned IP address
$ps ax | grep geny
Then connect using adb
$adb connect 192.168.1.3
ADB android over wireless connection
Connect using USB.
$adb tcpip 5555
Disconnect USB.
Reconnect using wireless connection. You can find out the IP address from wireless config
$adb connect 192.168.1.3:5555
[Genymotion] [Fatal] Cannot mix incompatible Qt library (version 0x40806) with this library (version 0x40802)
Go into genymotion installation directory
#cd /opt/genymotion
#aptitude install libxi-dev libxmu-dev
#mkdir QtLibs
#mv *Qt*.so* QtLibs
Related
Ubuntu Forums
Splash screen in nativescript
tns debug android --debug-brk in linux
The nativescript cli
$tns debug android --debug-brk
The command expect your google chrome executable name is “chrome”.
But in my debian jessie workstation. The executable name is “google-chrome”
$ln -s /usr/bin/google-chrome ~/bin/chrome
will fix the problem.
How to uninstall Cpanel from Centos 6 server
#yum erase 'centos*'
Make sure to edit the /etc/yum.conf to remove the packages listed in the exclude section
[main]
exclude= ..
Centos 6 No package php-fpm available
After installing epel and remi repository and enable remi-php56, the php packages still not available.
The issue is i just uninstall Cpanel from my Centos 6 server. Cpanel disable php packages from showing up in you.
#vim /etc/yum.conf
[main]
exclude=php* ..
Just remove php packages from the exclude section of the /etc/yum.conf.
It waste 3 hours of my time to figure this out.. :(
Powerdns unable to find backend willing to host for potential supermaster
I got this error when i setup powerdns superslave in debian using sqlite3 backend.
The condition to get the superslave working.
- The supermaster must carry a SOA record for the notified domain.
- The supermaster IP must be present in the ‘supermaster’ table.
- The set of NS records for the domain, as retrieved by the slave from the supermaster,
must include the nameserver that goes with the IP address in the supermaster table.
A very usefull command to test if the setup is working. To send the notification to the slave and
#pdns_control notify mydomain.com
To request for supermasters zone
#pdns_control retrieve mydomain.com
Related
PDNS slave operation
PostgreSQL remove not null constraints
ALTER TABLE booking ALTER nationality DROP not null;
Foundation logo align centre on small screen
<div class="row">;
<div class="small-8 small-centered large-4 large-uncentered columns">
<img src="logo.png" />
</div>
</div>
Javascript get the last value of an array
The value of the last item in a javascript array
arr.split(-1)[0]
Set ux31e LCD brightness to the minimum
Add the following line to the /etc/rc.local.
echo 0 > /sys/class/backlight/acpi_video0/brightness
Phonegap add android error
On the phonegap 3.4 running to command
$phonegap add android
Give an error like this
/bin/node_modules/q/q.js:126
throw e;
^
The problem is the android sdk still not configured properly you need to configure the environment ANDROID_HOME, ANDROID_HOME/tools and ANDROID_HOME/platform-tools add this in your ~/.bash_profile
export ANDROID_HOME=$HOME/android-sdk-linux
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
ALSA lib ctl_oss.c Cannot open device /dev/mixer
It happen recently on my debian workstation
ALSA lib ctl_oss.c:398 (_snd_ctl_oss_open) Cannot open device /dev/mixer
Cannot open mixer: No such file or directory
When you try to run alsamixer. The reason is the the module snd-pcm-oss not loaded. To fix
#modprobe snd-pcm-oss
Qooxdoo wrong icon path after migrate from 2.0 to 3.5
It must be in the form below, start by “/*” and end by “/” and in between start by “*”.
/**
* @assert(sumisi/*)
*/
Otherwise assert will not be read by JsDoc and give an error.
qx.ui.basic.Image[90-0]: Image could not be loaded: sumisi/login.png
ImageLoader: Not recognized format of external image 'sumisi/login.png'
Mssql not a valid ss_sqlsrv_stmt resource
It happen when i have a code like below
function connect()
{
return sqlsrv_connect(..);
}
..
$result = sqlsrv_query(connect(), $sql);
The error mysteriously went away when i change the code to this
$connect = connect();
$result = sqlsrv_query($connect, $sql);
nokia n9 no mobile network error
It happen when i put my DiGi simcard with the original number switch from Maxis network. Fix the problem when i swith my phone number back to Maxis.
Maybe there N9 not compatible with Mobile Number Portability implementation in Malaysia.
powerdns unexisting parameter 'bind-config'
It happen when there is two 'launch' configuration in powerdns configuration.
Delete one of it to solve the problem.
Change amazon ec2 debian AMI image hostname
$sudo -i
#hostname -b
Enable ctrl+alt+backspace to kill xorg in debian
Add this into ~/.bash_profile
setxkbmap -option terminate:ctrl_alt_bksp
nginx + php-cgi on window server 2008
php-cgi.php just hang and die on a very low load. To fix this, use spawn-php
Install
ActivePython-2.7.2.5-win64-x64.msi
pywin32-217.win-amd64-py2.7.exe
Change nginx configuration worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream php_farm {
server 127.0.0.1:9000 weight=1;
server 127.0.0.1:9001 weight=1;
server 127.0.0.1:9002 weight=1;
server 127.0.0.1:9003 weight=1;
server 127.0.0.1:9004 weight=1;
server 127.0.0.1:9005 weight=1;
server 127.0.0.1:9006 weight=1;
server 127.0.0.1:9007 weight=1;
server 127.0.0.1:9008 weight=1;
server 127.0.0.1:9009 weight=1;
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.php index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ \.php$ {
root html;
fastcgi_pass php_farm;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME c:/nginx/html/$fastcgi_script_name;
include fastcgi_params;
}
}
Change default browser
#update-alternatives --config x-www-browser
PHP linux vs window version
Come across interesting fact: In linux
echo $_SERVER['SERVER_NAME']; //somedomain.org
echo $_SERVER['HTTP_HOST']; //somedomain.org
In window
echo $_SERVER['SERVER_NAME']; //localhost
echo $_SERVER['HTTP_HOST']; //somedomain.org
Change associated array to indexed array
Sometimes i want to change this form of array
array(
'position' => array('data1', 'data2'..)
'year' => array('year1', 'year2'..)
)
to this
array(0 => array('position' =>'data1',
'year' => 'year1'),
1 => array('position' => 'data2',
'year' => 'year2')
Here is how i do it.
function array_group($data)
{
$result = array();
foreach($data as $key=>$rows)
foreach($rows as $i=>$value)
$result[$i][$key] = $value;
return $result;
}
Virtualbox look ugly
Virtualbox made with qt library. To fix the ugly win95 looking theme,
#aptitude install qt4-qtconfig
$qtconfig
and change the Gui Style to GTK+
Edit the configuration files _vimrc
set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
set smartindent
set textwidth=0
set nowrap
set number
set scrolljump=5
colorscheme koehler
set guifont=Consolas
set guioptions-=m "remove menubar
set guioptions-=T "remove toolbar
set guioptions-=r "remove scrollbar
MSSQL last insert id
Using SCOPE_IDENTITY(),
$result = sqlsrv_query($conn, 'INSERT INTO mytable(name) values ('hello world') ;
SELECT SCOPE_IDENTITY() AS ID', array(), $option);
sqlsrv_next_result();
$row = sqlsrv_fetch_object($result);
echo $row->ID; //last insert id
PHP gotcha
Some unexpected stuff
var_dump('f' == 0); //bool(true)
mssql sqlsrv_rows_affected() weirdness
The documentation says that sqlsrv_rows_affected() returned mixed values.
But it keep returning FALSE even the query executed succesfully.
From PostgreSQL to MSSQL
I love postgresql but my client request specifically for MSSQL.
1. PGSQL boolean column return 't' and 'f' for true and false
MSSQL bit column return 1 and 0 for truen and false
2. PGSQL text column is special it can be use for any size of text
MSSQL varchar column to be able to use operator in where clause and varchar(max) for long string
3. PGSQL use pg_* functions
MSSQL use sqlsrv_* driver supplied by Microsoft and this driver can only be use in windows.
4. PGSQL pg_fetch_object return string for datetime column value
MSSQL sqlsrv_fetch_object return DateTime object for datetime column value.
I have to pass 'ReturnDatesAsString' option in the connection string to turn if off.
5. Paging in PGSQL is straight forward using LIMIT .. OFFSET
In MSSQL i have to use CTE function to enable to use my existing paging library.
6. PGSQL pg_affected_rows()
MSSQL sqlsrv_rows_affected()
MSSQL paging with CTE
No LIMIT OFFSET as in PostgreSQL or MySQL.
WITH cte AS
(
SELECT ROW_NUMBER() OVER(ORDER BY country ASC) AS RowNumber
FROM company WHERE country='Malaysia'
)
SELECT * FROM cte
WHERE RowNumber > 0 AND RowNumber < 100
Sqlsrv driver return datetime colum as datetime object
MSSQL’s PHP driver sqlsrv_fetch_object return DateTime object by default.
To disable this, pass parameter ReturnDatesAsString on the connection string.
$param = array('Database' => 'db',
'UID' => 'uname',
'PWD' => 'secret',
'ReturnDatesAsStrings' => 'true');
$conn = sqlsrv_connect('localhost\sqlexpress', $param);
qooxdoo datefield value less one day
For example the user choose the date 2012-12-31 but the value submitted is 2012-12-30. It has something to do with timezone as explained
on this post
Qooxdoo disable tabview page
Here is a way to disable the tabview page. Turn it grey and unclickable.
var page = new qx.ui.tabview.Page("page");
page.set({enabled: false});
Wheezy php5-fpm and nginx
Debian wheezy version of php5-fpm (5.4.4-7) using socket instead of server running on local port 9000. Need to update nginx configuration files to point to php5-fpm socket.
location ~.\.php$ {
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
Openerp set default value of popup form from one2many field parent
class definition (shop.py), please note the magic active_id
class item(osv.osv):
_name = "shop.item"
_columns = {
"item_id": fields.many2one("shop.cart", "Cart"),
}
_defaults = {
"item_id": lambda self, cr, uid, c: c.get('item_id', False),
}
class cart(osv.osv):
_name = "shop.cart"
_columns = {
"item_ids": one2many("shop.item", "item_id", "Items"),
}
In the view definition for the one2many field (shop_view.xml)
<field name="item_ids" domain="['item_id', '=', active_id]" context="{'item_id': active_id}">
Oss4 no sound in iceweasel flash
flashplugin-nonfree only support Alsa. Thus, extra package required to support OSS4
#aptitude install flashplugin-nonfree-extrasound
#mkdir /usr/lib/oss/lib
#cd /usr/lib/oss/lib
#ln -s /usr/lib/flashplugin-nonfree-extrasound/libflashsupport.so
Restart iceweasel
Cloning object in qooxdoo
Object
var a = {};
var b = qx.lang.Object.clone(a);
Array
var a = [];
var b = a.slice();
Backend error: Database error trying to insert new slave 'domain.tld': Error while retrieving SQLite query results
Backend error: Database error trying to insert new slave 'domain.tld': Error while retrieving SQLite query results
Related to debian bug #565516
The directory and file where the sqlite3 file must be writeable by pdns
search for file that contain particular string
$grep -r "i am looking for you" /home/rogon/*php
delete file with 0 size
$find /home/paragasu/myfile -type f -size 0 -exec rm -f {} \;
qooxdoo typeerror .. is not a constructor
very tricky error. the problem lies somewhere in the defined class structure. in my case, i put the function inside the main method instead inside the members method .
Output csv from postgresql
psql> COPY (SELECT * FROM tablename) TO '/tmp/filename.csv' WITH CSV HEADER;
Qooxdoo execute callback function on this scope
rpc.callAsync(qx.lang.Function.bind(this._responseReceived, that));
Now you can refer this in _responseReceived Functions.
Global variables in qooxdoo
Declare the variables in your Application class:
qx.Class.define("custom.Application",
{
extend : qx.application.Standalone,
members :
{
/** My global variable */
bGlobal : true
main : function()
{
// access to global variable from within this class using "this"
this.bGlobal = false;
}
}
}
Then you can access that main application class using qx.core.Init.getApplication() so in some other class, you can read the global like this:
qx.Class.define("custom.SomeArbitraryClass",
{
extend : qx.core.Object,
construct : function()
{
/** Access the global variable */
if(qx.core.Init.getApplication().bGlobal)
{
alert("The global is TRUE");
}
}
}
You could also have made that global be a property of the Application class:
qx.Class.define("custom.Application",
{
extend : qx.application.Standalone,
properties :
{
/** My global variable */
global : true
...
In which case you’d reference it from the other class using the property’s getter:
qx.core.Init.getApplicaiton().getGlobal()
Install sun-java6-jdk in debian wheezy
Install sun-java6-jdk in debian wheezy
sun-java6-jdk no longer available in debian wheezy due to some licencing issues.
Download the binary called Java SE 6 Update 30 at
http://www.oracle.com/technetwork/java/javase/downloads/index.html
unpack it to /opt/jvm/
#update-alternatives --install /usr/bin/java java /opt/jvm/jdk1.6.0_30/jre/bin/java 3
#update-alternatives --config java
select the option 3 and you are done
common openerp beginner error
This code <field name="type"> form</field> produce the error below
The value " form " for the field "type" is not in the selection
make sure no space between "form"
the field(s) res_model,src_model: Invalid model name in the action definition.
if the code seem rights. restart the openerp-server.
Add menu on fbpanel
If you install binary manually eg: eclipse. Most likely you end up without entries in FBpanel the start menu. Just create a file appname.desktop in then ~/.local/share/applications
[Desktop Entry]
Type=Application
Name=Eclipse
Exec=/opt/eclipse/eclipse
Icon=/opt/eclipse/icon.xpm
NoDisplay=false
Categories=Development
Clearlooks configuration option "sunkenmenu" is not supported and will be ignored.
$android
/usr/share/themes/Taqua/gtk-2.0/gtkrc:55: Clearlooks configuration option "sunkenmenubar" is not supported and will be ignored.
/usr/share/themes/Taqua/gtk-2.0/gtkrc:56: Clearlooks configuration option "menuitemstyle" is not supported and will be ignored.
/usr/share/themes/Taqua/gtk-2.0/gtkrc:57: Clearlooks configuration option "listviewitemstyle" is not supported and will be ignored
To fix it, uncomment the sunkenmenubar, menuitemstyle and lastviewitemstyle
in the /usr/share/themes/Taqua/gtk-2.0/gtkrc
engine "clearlooks"
{
#sunkenmenubar = 0
#menuitemstyle = 0
#listviewitemstyle =0
}
e220 digi broadband in linux debian wheezy
I am using debian Wheezy
Linux 2.6.32-5-686
#aptitude install usb-modeswitch
#aptitude install wvdial
edit the /etc/wvdial.conf
[Dialer defaults]
Phone=*99#
Stupid Mode=1
Dial Command=ATDT
Modem=/dev/ttyUSB0
Baud=230400
Init2=AT+CGDCONT=1, "IP", 3gdgnet"
Init3=
Username=digi
Password=digi
AskPassword=0
ISDN=0
Compuserve=0
Force Address =0
Idle Seconds=0
Auto DNS=1
Check Def dRoute=1
plug in the Huawei E220
#wvdial
resume transfer of large ssh file
you need to install rsync on both client and server
apt-get install rsync
rsync -P -r -e ssh username@server: <serverfile> <localfile>
PHP pitfall
PCManfm Not Authorized
create a file /etc/polkit-1/localauthority/50-local.d/55-storage.pkla
with the content
[Storage Permissions]
Identity=unix-group:plugdev
Action=org.freedesktop.udisks.filesystem-mount;org.freedesktop.udisks.drive-eject;org.freedesktop.udisks.drive-detach;org.freedesktop.udisks.luks-unlock;org.freedesktop.udisks.inhibit-polling;org.freedesktop.udisks.drive-set-spindown
ResultAny=yes
ResultActive=yes
ResultInactive=no
postgresql 8.4 could not create listen socket for localhost
fixed this error by adding the
auto lo
iface lo inet loopback
in /etc/network/interfaces
©
It happen when the page is in UTF8 but the browser display in iso-8859-1.
Add this meta on the head to fix this.
install iceweasel 4 in debian squeeze
A detailed instruction
acer aspire d255e card reader driver in debian squeeze
Build in multi card reader in acer aspire one is from ENE Technology.
Here is an instruction to compile the kernel module driver
unzip to /usr/src/keucr-0.0.1
create /usr/src/keucr-0.0.1/dkms.conf file
PACKAGE_NAME="keucr"
PACKAGE_VERSION="0.0.1"
CLEAN="rm -f *.*o"
BUILT_MODULE_NAME[0]="keucr"
MAKE[0]="make -C $kernel_source_dir M=$dkms_tree/$PACKAGE_NAME/$PACKAGE_VERSION/build"
DEST_MODULE_LOCATION[0]="/extra"
AUTOINSTALL="yes"
#dkms add -m keucr -v 0.0.1
#dkms build -m keucr -v 0.0.1
#dkms install -m keucr -v 0.0.1
#cat keucr >> /etc/modules
ake: dh_testdir: Command not found
aptitude install debhelper bzip2
debian lenny and canon canoscan lide 110
Installing canoscan lide 110 scanner in debian
#cd /usr/src
#git clone git://git.debian.org/sane/sane-backends.git
#cd sane-backends
#./configure --prefix=/usr --sysconfdir=/etc/ --localstatedir=/var
#make
#make install
#adduser scanner
edit /etc/udev/rules.d/z60_libsane.rules
# Canon CanoScan Lide 110
ATTRS{idVendor}=="04a9", MODE="0664", GROUP="scanner", ATTRS{idProduct}=="1909", ENV{libsane_matched}="yes"
make sure you put the scanner to unlock mode (there is a button on the bottom) otherwise it make a loud cracking sound and it is not working.
#aptitude install xsane
debian squeeze red youtube video
solution
go to other website with flash video , right click and uncheck the video acceleration
make IE compatible with HTML5
include this script in the HTML file
mount directory over ssh
#aptitude install sshfs
#modprobe fuse
#sshfs user@server:/remote/dir /local/dir/
Error wireless request set encode 8b2a
iwconfig wlan0 set s:passphrase
It only works on WEP. WPA is not supported.
You need to install wicd or wpa_supplicant.
Edit the /etc/network/interfaces and remove any references to wlan0
#apt-get install wicd
$wicd-client
linux convert youtube to mp3
#aptitude install youtube-dl ffmpeg libmp3lame
a simple bash script called youtube
#!/bin/bash
x=/tmp/youtube-dl-$RANDOM-$RANDOM.flv
youtube-dl --output=$x --format=18 "http://www.youtube.com/watch?v=$1"
echo "convert flv to mp3"
ffmpeg -i $x -acodec libmp3lame -ac 2 -ab 128k -vn -y "/home/paragasu/mp3/youtube/$2"
rm $x
echo "done"
The fun begin
$youtube linkname fileoutput.mp3
Related
Youtube to mp3 on ubuntu linux
pdns + sqlite3: Error while retrieving SQLite query results
The directory and file where the sqlite3 database files must be belong to pdns.
burn cd
$genisoimage -vJV "name" -o isoname.iso list_folder_or_file
$wodim -v isoname.iso
set wallpaper in openbox + debian
#aptitude install feh
add the following code to /etc/xdg/openbox/autostart.sh
feh --big-scale my-wallpaper.jpg
upgrade debian etch 4.0 to lenny 5.0
Debian drop security support for etch.
Edit /etc/apt/sources.list & change all etch to lenny
#apt-get update
#apt-get install apt dpkg aptitude
#aptitude keep-all
#aptitude full-upgrade
FATAL: module fbcon not found
Recent debian upgrade cause my X server failed to start.
linux-image-2.6.32
xserver-xorg 7.5
i915 intel graphics
you can ignore the error FATAL: module fbcon not found.
the real problem might be in
$cat ~/.xsession-errors
In my case the problem is the im-switch missing default configuration files.
reinstalling im-switch solved the problem.
php anonymous object
$obj = (object) array('hello' => 'world', 'sumandak' => 'tamparuli');
echo $obj->hello; //world
creating a pdf preview
$im = new imagick('test.pdf[0]'); //1st page
$im->setImageFormat('png');
header('Content-Type: image/png');
echo $im;
more
preload images with jQuery
var photos = [ {img:'img1.jpg'}, {img: 'img2.jpg'}];
$(photos).each(function() {
(new Image()).src = this.img;
});
pdns Fatal Error: Trying to set unexisting parameter 'receiver-threads'
I got this error from syslog.
$vim /etc/powerdns/pdns.conf
comment out the receiver-threads
#receiver-threads number of receiver threads to launch
#receiver-threads=1
some people report this as bug. this one works at least for me ;)
postgresql group concat
select array_to_string(
array(select name from tbl_user), ',');
group concat in postgresql
Centos 5.4 MySQL only 480 error messages, but it should contain at least 641 error messages.
Error message file '/usr/share/mysql/english/errmsg.sys' had only 480 error messages,
but it should contain at least 641 error messages.
#yum list installed | grep mysql
In my case, the both package mysql.i386 and mysql.x86_64 is installed. So, i have to remove the mysql.i386 package (old version) and reinstall mysql.x86_64.
#yum remove mysql.i386
#yum install --enablerepo=remi mysql.x86_64
#service mysqld start
problem solved
postfix execute external command on every new email
edit /etc/postfix/master.cf
smtp inet n - - - - smtpd -o content_filter=my_scripts:
my_scripts unix - n n - - pipe
flags=Xhq user=username argv=/usr/bin/php /my_scripts.php
X - perform final delivery
h - set the domain & recipient to lowercase
q - quote white space & other special characters
more info
incoming mail and php
setup postfix to forward incoming email to php
truncate files
$cat /dev/null > filename.log
How to install PostgreSQL 8.3 into CentOS 5.4
PostgreSQL 8.1 is currently the default version in CentOS 5.4 which do not support INSERT.. RETURNING
remove PostgreSQL 8.1
#yum remove postgresql postgresql-server
# vi /etc/yum.repos.d/CentOS-Base.repo
[base]
exclude=postgresql*
[updates]
exclude=postgresql*
#wget http://yum.pgsqlrpms.org/reporpms/8.3/pgdg-centos-8.3-7.noarch.rpm
#rpm -ivh pgdg-centos-8.3-6.noarch.rpm
#yum install postgresql postgresql-server
Debian Etch pg_dumpall cron problem
Debian Etch default postgresql's superuser is postgres. And cron run as root.
Hence, pg_dumpall not working as expected in cron job. Workaround is to create user name root with superuser privilege.
postgres# create role root with superuser login
p/s: you have to create database root
backup on debian etch with s3
The current version of duplicity in Debian Etch is a bit outdated and do not support s3.
firefox flashing black fix
in the about:config
accessibillity.browsewithcaret false
debug php file_get_contents($url)
there is one special variable available $http_response_header.
the output is the header array reply by the server
$r = file_get_contents($url);
var_dump($http_response_header);
openbox print screen key binding
the original distribution configuration set the PrtScrn to gnome-screenshot.
#apt-get install gnome-utils
Openoffice how to print pps file
To edit or print the PPS file.
Rename PPS to PPT extension.
XUL close window from javascript
pref("dom.allow_scripts_to_close_windows", true);
pref("dom.allow_scripts_to_close_windows", false);
Postgresql Security
http://www.leidecker.info/pgshell/Having_Fun_With_PostgreSQL.txt
jquery how to the the value of id
supposed we have
<a href=# id="5"> hello world </a>
to get the value of id
$('a').each(function(){alert(this.id);});
//5
javascript refresh a page
/* reload every 5 minutes, in milisec */
setTimeout('location.reload(true);', 300000);
Iceweasel 3, fix high CPU usage
type about:config, and change the browser.cache.memory.enable value to false
jQuery, check if element exists
if($('#some-div').length)){ /* exists */}
postgresql dblink query across database
postgresql dblink doc
using dblink to query other postgresql database and server
google apps spf records
type TXT
value
v=spf1 a mx include:aspmx.googlemail.com include:_spf.google.com ~all
google incorrect spf records
spf checker
ckeditor - how to make simple uploader work
edit the html page where you call the ckeditor instance.
CKEDITOR.replace('editor',
{
filebrowserUploadUrl:'/path/to/upload/script.php';
});
the line above will display the upload from whenever user click on the image icon.
the upload script should return
<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(1, '<url of uploaded file>', '');</script>
ckeditor external file uploader
ckeditor image uploader problem
xfce4 enable restart and shut down for normal user
#apt-get install sudo
#visudo
add the following
your_username ALL=NOPASSWD:/usr/sbin/xfsm-shutdown-helper
enable restart and shutdown from xfce4
XUL is interesting
xul rendering gui with php
https://developer.mozilla.org/En/XUL
how to develop a firefox extension
getting started with xulrunner
multiseat system
very interesting article
http://wiki.x.org/wiki/Development/Documentation/Multiseat
how to save file into postgresql database
you need a column in a postgresql table with the type OID
create table files(
file_id serial primary key,
file oid not null
);
to insert file
INSERT INTO files(file) values(lo_import('/tmp/filename.ext');
to read the file
SELECT lo_export(file, '/tmp/filename.ext') WHERE file_id=2;
you can get the file in the /tmp/filename.ext.
store upload image postgresql
autologin with startx
edit /etc/inittab
comment out the line
#1:2345:respawn:/sbin/getty 38400 tty1
add the line
1:2345:respawn:/bin/login -f YOUR_USER_NAME tty1 /dev/tty1 2>&1
edit the .bash_profile and add
startx
autologin in debian
jquery click() doesn't work after dom update on ajax call.
<a class="clickme" href=#>clickme</a>
$('a.clickme').click(function(){ alert('hello')});
only work on DOM that already exists. it is not working.if the html above injected on existing DOM.
in this case you have to use.
$('a.clickme').live('click', function(){alert('hello')});
bug comparison in PHP
php do not be able to compare large int and float reliably.
$val1 = 0.2; $val2 = 0.2;
if($val1 < $val2){ echo 'it is true';}
one workaround for equal comparison is to cast the value to string type.
compile midlet j2me in debian linux
I can't get the ktoolbar running on my debian squeeze. Found a very good makefile from Hexist
PHP get file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
debian testing + iceweasel install flash player
#apt-get install flashplugin-nonfree
should be working. but in my debian testing it isn't. I have to manually create a symlinks
#ln -s /usr/lib/flashplugin-nonfree/libflashplayer.so /usr/lib/iceweasel/plugins/libflashplayer.so
to make it work.
jquery click li to activate a
<ul class="menu">
<li><a href="/"> Home </a></li>
</ul>
to activate the link when user click on li
$('.menu li').click(function(e){
location.href = $(this).find('a').attr('href');
});
Now, user doesn't have to click on the "Home" to activate the link.
mysql cache SQL_NO_CACHE
enable query cache (maybe default depends of the server configuration)
SELECT SQL_CACHE SUM(points) FROM account;
turn off mysql query cach
SELECT SQL_NO_CACHE SUM(points) FROM account;
javascript disable back button
add this code in the HTML head section
<script type="text/javascript">
history.forward();
</script>
php how to replace many space with one space
$str = preg_replace('/\s+/', ' ', $str); //" \n\n\n" will end up as " \n"
$str = preg_replace('/\x20+/', ' ', $str); //only space
how to detect ajax request
ajax request will send additional header
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
echo 'ajax';
The page you are looking for is temporarily unavailable. Please try again later.
server configuration php5-cgi, php5-tidy nginx, debian etch.
Tidy configuration tab-size=>0 can trigger this error. Just change the tab-size value to be greater than 0 to fix
tab-size => 1
Debian usb mouse freeze
you should have
Option "SendCoreEvents" "true"
inside the Section "Input Device", Driver "mouse"
php add leading zero
echo $num; // 1
$str = sprintf('%02d', $num, 2);
echo $str; //01
php get the number of days between two dates
$timestamp = strtotime($end_date) - strtotime($start_date);
$days = round($timestamp / 86400);
this code only works on linux box.
global distribution system (CDS)
many website like tripadvisor.com or lastminutes.com pull the information from CDS. One free provider is Kayak.com but usage is restricted to 1000 queries/day.
jquery open new window on external links
$("a:not([href^='http://www.exampleuri.com']): not([href^='#']):not([href^='/'])").attr("target","_blank");
ncftp - upload recrusive files
to upload the whole directory and subdirectory
$ncftpput -u <username> -p <password> -R <host> <remotedir> <localdir>
Bucardo - Asynchronous PostgreSQL Replication System
Bucardo is an asynchronous PostgreSQL replication system, allowing for both multi-master and multi-slave operations. It was developed at Backcountry.com by Jon Jensen and Greg Sabino Mullane of End Point Corporation, and is now in use at many other organizations.
postgresql version of mysql UNIX_TIMESTAMP()
MySQL
mysql> SELECT UNIX_TIMESTAMP();
mysql> SELECT UNIX_TIMESTAMP('1973-11-29 21:33:09');
PostgreSQL
postgres=> SELECT EXTRACT(EPOCH FROM CURRENT_TIMESTAMP(0));
postgres=> SELECT EXTRACT(EPOCH FROM TIMESTAMP '1973-11-29 21:33:09');
E319: Sorry, the command is not available in this version: syntax on
if you get this error when trying to enable syntax highlighting in vim,
#apt-get install vim
css rounded corner
.roundcorner{
border-radius:6px; /*css3 - but not supported yet*/
-webkit-border-radius: 6px; /*mozila - firefox, iceweasel */
-moz-border-radius: 6px; /*webkit - google crome, midori, safari */
}
and more
-moz-border-radius-topleft / -webkit-border-top-left-radius
postgresql add on delete cascade to foreign key
ERROR: update or delete on table "page" violates foreign key constraint "info_page_id_fkey" on table "info" DETAIL: Key (page_id)=(106) is still referenced from table "info"
you have to drop cascade and recreating the new one.
psql> \d info
psql> alter table info drop constraint info_page_id_fkey;
psql> alter table info add constraint "info_page_id_fkey" foreign key(page_id) references page on delete cascade;
chess in debian
Crafty, developed by Robert Hyatt, is a descendant of the Cray Blitz chess engine that was the World Computer Chess Champion from 1983 to 1989.
to install
#apt-get install crafty xboard
start the game with
$xboard -fcb 'crafty' -fd crafty_directory
book off -- This options disables the use of opening book for crafty.
ponder off - Crafty can't think while you are playing your move.
st 1 -- Make the maximum thinking time for Crafty just one second.
sd n -- Crafty won't think more than n moves ahead.
If you are able to beat crafty too often, you can also make it more stronger with these options:
hash nK -- Makes the hash table bigger
hashp n -- Makes the hash table for pawns as large as possible
it hard to bet.
login to SSH with keys
$ssh-gen -t rsa
$ssh-copy-id username@server
$ssh-add ~/.ssh/id_rsa
fix Firefox 3 & jquery bug
It is the problem when the $(document).ready() executed before the CSS loaded.
Make sure all CSS come before the scripts
<script type="text/javascript" src="">
<link rel="stylesheet" type="text/css" href="">
to
<link rel="stylesheet" type="text/css" href="">
<script type="text/javascript" src="">
css - remove dotted border on a active
a {
outline-style:none;
outline-width:0;
}
or
a {outline: 0 none;}
fix pidgin & yahoo messenger Error 1013
you must upgrade to pidgin 2.5.8 which is available in debian unstable (sid).
add to /etc/apt/sources.list
deb http://ftp.debian.org/debian/ sid main contrib non-free
#apt-get update
#apt-get install -t sid pidgin
change the pager server to
scsa.msg.yahoo.com
Error 1013 - just remove the @yahoo.com on your pidgin login username
how to simulate slow internet connection
#apt-get install iprelay
$iprelay -b 2500 8000:localhost:80
point the browser to localhost:8000
you can see how website look like with connection speed of 2.5Kbps.
simulate slow internet connection
debian changing eth* name
changing eth0 name to eth1 and eth2 after each reboot. it is a bug in udev package.
make all image clickable
make all image in a page to have a direct link.
$content = ''; //content of a page with <img tag
$content = preg_replace('/<img alt=".*" \/>/',
'<a href="\\1">\</a>', $content);
dns with minimum downtime
it is important to change the TTL setting of the domain to a short time (60s) before migrating to new server.
and wait for the dns record to propagate before changing the dns records.
how to check what debian version
$cat /etc/debian_version
or
$lsb_release -a
sdlmame - new game emulator for linux
sdlmame is a new alternative that replace the old xmame
not clickable link in IE
one of my client complaining to me about this problem (using IE 7). another hasLayout problem
not sure which one really fix the problem. But avoiding
<div>and <span> tags inside <a> tags might help.
find all setuid or setgid files
#find / -type f \( -perm -4000 -o -perm -2000 \) -exec ls -ld '{}' \;
wget download the whole website
$wget -r --level=1 -k -p http://websiteurl.com/
debian iceweasel chinese language support
Practically, just need it so the webpage with chinese writing in it doesn't look ugly
#apt-get install iceweasel-l10n-zh-cn
powerdns + postgresql on debian
#apt-get install pdns-server
#apt-get install pdns-backend-pgsql
install required postgresql database table.
using /usr/share/doc/pdns-backend/pgsql/pgsql.sql
edit /etc/powerdns/pdns.d/pdns.local ( /usr/share/doc/pdns-backend-pgsql/examples/pdns.local.pgsql)
gpgsql-host=localhost
gpgsql-port=5432
gpgsql-dbname=powerdns
gpgsql-user=
gpgsql-password=
edit /etc/powerdns/pdns.conf
launch=gpgsql
pdns everydns.net as secondary dns
in /etc/powerdns/pdns.conf
allow-axfr-ips=71.6.202.218,66.240.223.182
disable-axfr=no
disable-tcp=no
master=yes
make sure you insert the value 'MASTER' on the column 'type' in the domains table
add the domain with advance option "make secondary using", and specify the primary dns (server ip where you install powerdns).
the last thing to do is to modify the domain dns records to
ns1.everydns.net
ns2.everydns.net
ns3.everydns.net
ns4.everydns.net
pdns secondary dns not updated
you must update the serial number in SOA records every time you update domains records.
nginx www to non www
redirect url with www to non www. edit /etc/nginx/nginx.conf or /etc/nginx/sites-enabled/default
if ($host ~* www\.(.*)){
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1 permanent;
}
how to change timezone and UTC in debian
to change timezone
#dpkg-reconfigure tzdata
UTC time mean, you computer will display time related to GMT. To use local time instead of UTC
edit /etc/default/rcS
UTC=no
#iptables --flush to reset iptables
You must reset the iptables policies before you issue #iptables -F .
ssh - iptable rule to accept only streamyx users.
I got ssh brute force attack almost every day :p, which is almost all originated from somewhere outside malaysia (china, taiwan etc). A simple iptables rules that only allowed tcp traffic from streamyx IP range.
#iptables -P INPUT DROP
#iptables -A INPUT -p tcp --dport 80 -j ACCEPT
#iptables -A INPUT -p tcp --dport 22 -m iprange --src-range 60.0.0.0-60.255.255.255 -j ACCEPT
iptables - how to specify a range of ip address
iptables quick howto-
php-cgi process hang problem
$export PHP_FCGI_MAX_REQUESTS=1000
$spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data /usr/bin/php5-cgi
hanging of php-cgi
Fatal Error: Class 'tidy' not found
solution
#pecl install tidy
#apt-get install php5-tidy
you might have to add extension=tidy.so into php.ini
postgresql complete backup
run command under user postgres
to backup
$pg_dumpall > db.sql
to restore
$psql -f db.sql template1
lighttpd: Symbol `FamErrlist’ has different size in shared object, consider re-linking
to fix this
#apt-get install libfam0
extract date and time from timestamp column on postgresql
to extract date from coldate,
SELECT date(coldate) FROM mytable;
to extract time, doing time(coldate) will give an error instead,
SELECT "time"(coldate) FROM mytable
another way
SELECT coldate::time FROM mytable
simple cut command tutorial
cut is quite handy when we do bash script.
gobukgumuk.txt
tomulikud om tuod, tomoguang om gobuk
$cat gobukgumuk.txt | cut -d, -f2
will give "tomoguang om gobuk"
$cat gobukgumuk.txt | cut -c1-9
will give "tumolikud"
we can save the output to a variable name
name=`who am i | cut -f1 -d' '`
cut command tutorial
how to select column from a file
cut command
display battery information on fbpanel
i wrote a simple plugin to display the percentage of battery on fbpanel (i am using openbox + debian)
put this code inside ~/.config/fbpanel/default
Plugin {
type=genmon
config {
Command = echo $(acpi -b | cut -d, -f2)
PollingTime = 2
TextSize = small
TextColor = red
}
}
this is how it look like
simple iptables rule to block ip address
block an ip address
#iptables -A INPUT -s 192.168.2.3 -j DROP
block outgoing TCP traffic from the server
#iptables -A OUTPUT -p tcp -d 192.168.2.3 -j DROP
upgrade postgresql-8.1 to postgresql-8.3 in debian etch
postgresql-8.3 available for etch on backports repositories. Add to /etc/apt/sources.list
deb http://www.backports.org/debian etch-backports main contrib non-free
then install postgresql-8.3
#apt-get -t etch-backports install postgresql-8.3
#pg_dropcluster --stop 8.3 main
#pg_upgradecluster 8.1 main
#pg_dropcluster --stop 8.1 main
#apt-get remove postgresql-8.1
read more
php include vs include_once vs require vs require_once
All work the same way. But require_once is the fastest in linux.
PHP require vs. include vs. require_once vs. include_once Performance Test
Install Canon PIXMA 1880 in debian
cnijfilter-common_2.70-3_i386.deb
cnijfilter-ip1800series_2.70-3_i386.deb
extract text from ms office
Interesting program to extract text
- catdoc - extract text from ms word
- xls2cvs - extract text from ms excell
- pdftotext - extract text from pdf
- ppthtml - extract text from ms. power point
Then a simple php function can capture the output eg:
function extractWord($word_file)
{
if (file_exists($word_file)
{
// prevent malicious command execution
exec("/usr/bin/catdoc -w ' . escapeshellarg($word_file), $output);
// $output is an array corresponding to lines of output
return join("\n", $output);
}
}
css transparency
.transparent_class {
filter:alpha(opacity=50); /*IE*/
-moz-opacity:0.5; /* mozilla old version*/
-khtml-opacity: 0.5; /* safari */
opacity: 0.5; /* standard */
}
inverting value in mysql table
It is possible to invert the value in mysql table without knowing the present value. This working on mysql and may not work on postgresql.
UPDATE table_name SET column = NOT column
ps2 emulator
there is an emulator for ps2
pcsx2 project
pcsx2 on linux
pcsx2 forum thread
compiling PCSX2 from SVN
debian installer with the latest kernel
It is pain dealing with not yet supported hardware especially Ethernet card. Because it is required to continue installation on debian netinst. Using custom kernel help a lot.
Dell PowerEdge T105 - no ethernet card detected
Custom debian installer download
Etch-and-half installer
import/export csv
a very handy php function fgetcsv and fputcsv
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv; filename=document_" . date("Ymd") .".csv");
http://www.modwest.com/help/kb6-135.html
http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
develop system base on mykad
it is quite interesting to develop a software application base on mykad.
interesting topic on lowyat
free mykad SDK for testing
mykad reader
reset root password
You must have physical access to the server. On booting, append to boot
init=/bin/bash
then
#mount -o remount,rw /
#passwd
#exec init
ie6,ie7 min-height bug and margin bug fixed
I come across this stupid IE bug and it really waste a lot of my time. The worst thing is, my client use IE6 in his office computer and whenever i went to his office showing him his website. Everything look terrible.
it should look like this
Image offset to the right
Image offset to the right and the web page is too short
I am not sure it is fixed or it just a dirty workaround. But here it is
ul.innerfade li {
_margin-left:-425px; /*ie6 fix*/
*margin-left:-425px; /*ie7 fix */
}
and another one in the td (html)
style="_height:350px;"
CSS hacks
IE7 only hacks
IE bug fix
IE bug fix
1. no min-height
_height:auto !important;
2. preventing step down
float:left; display:inline;
3. haslayout
/* style for IE6 + IE5.5 + IE5.0 */
.gainlayout { height: 0; }
.gainlayout { zoom: 1; }
4. peekaboo bug fix
position: relative; /* peekaboo bug fix for IE6 */
min-width: 0; /* peekaboo bug fix for IE7 */
list of IE7 bugs
i hate IE. it took me a week just to fix a web page that works perfectly fine on other browsers even my web page is already pass w3c xhtml validation tests. I come across this a page with complete detailed of all IE7 related problem. In case you don't know how terrible IE7 browser it. read
MSIE7 bugs
display new icon based on db timestamp
this works in mysql5+. we want to display a small icon if the post_date is less than 2 days old. Unix timestamp is second. so for 2 days
60 * 60 * 24 * 2 = 172800
SQL query
SELECT IF((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(post_date)) < 172800, 1, 0) AS is_new FROM tbl_news
then the php code will be
$p = mysqli_fecth_object($sql)
$p->is_new ? echo '<img src="new.gif">' : '';
discover all domain hosted on ip address
it is a very useful and wonderful tools. You can use it to discover all website hosted on an IP address
gui wireless utility
you may try wicd as a wireless manager
debian install howto
edit /etc/apt/sources.list and add
deb http://apt.wicd.net lenny extras
then
#apt-get update
#apt-get install wicd
to start simply
#wicd-client
avoid phrising using maradns
someone wrote an howto here
booting debian in few seconds
found very interesting articles on how to make debian boot faster.
FCKEditor the easy way
fckeditor not that hard to install, but you may need some time to figure it out. Life is easier if you use FCKeditor jQuery way
alternate table row color. the easy way!
it is very simple using jQuery.
$(document).ready(function() {
$('table.zebra tr:odd').addClass('odd');
$('table.zebra tr:even').addClass('even');
});
of course you have to create two css class with the name even and odd.
print a-z
I need to create a link from a to z. I come up with a simple way to do it.
/* a-z */
$str = '';
for($i = 65; $i < 91; ++$i)
echo ''.chr($i).'';
another way
$a = range('a', 'z');
foreach($a as $chr) echo $chr;
managing source code using git
git sound strange to me. But, as i learn more, it is a very good piece of software for any programmer to manage their code.
#apt-get install git-core
starting with git with just 10 commands
Manage source code using git
Git user manual
List of proxies in malaysia
Just in case you are interested
mysql prepared statement
Prepared statement is one good way to avoid sql injection.
mysql> PREPARE stmt_name FROM "SELECT name FROM Country WHERE code = ?";
Query OK, 0 rows affected (0.09 sec)
Statement prepared
mysql> SET @test_parm = "FIN";
Query OK, 0 rows affected (0.00 sec)
mysql> EXECUTE stmt_name USING @test_parm;
+---------+
| name |
+---------+
| Finland |
+---------+
1 row in set (0.03 sec)
mysql> DEALLOCATE PREPARE stmt_name;
Query OK, 0 rows affected (0.00 sec)
copy files 100 times
Some interesting question asked on mailing list. A few interesting solutions in bash script.
$for x in $(seq -w 1 100); do cp file.jpg file${x}.jpg; done
for I in {1..100}; do cp file.jpg file$I.jpg ; done
$ seq -w 1 1 10 | xargs -i -n1 cp file.jpg file{}.jpg
how to increase website performance
Yahoo developer publish a very detailed information on this.
The best anwser is, simply Install the firebug extension YSlow.
css blueprint generator
CSS is quite simple if you only use firefox. But, thing get complicated when you considering IE.
I found a very useful css grid generator. click here
gtk project directory structure
every project share something in common. That something in common save us lazy programmer a lot of time. Here is a nice article about this
scalable webserver
i came across a blog about scalable server setup
Read here
very low memory mysql 5 my.cnf configuration
on VPS server with very limited memory it is good to tweak mysql5. In /etc/mysql/my.cnf
# Main MySQL server options
[mysqld]
port = 3306
socket = /var/run/mysqld/mysqld.sock
# No locking at all!
skip-locking
# Set internal buffers, caches and stacks very low
key_buffer = 16K
max_allowed_packet = 16K
table_cache = 1
sort_buffer_size = 16K
read_buffer_size = 16K
read_rnd_buffer_size = 1K
net_buffer_length = 1K
thread_stack = 16K
# Don't listen on a TCP/IP port at all.
# Will still work provided all access is done via localhost
skip-networking
server-id = 1
# Skip Berkley and Inno DB types
skip-bdb
skip-innodb
# Set the query cache low
query_cache_limit = 1048576
query_cache_size = 1048576
query_cache_type = 1
# Set various memory limits very low, disable memory-hogging extras
[mysqldump]
quick
max_allowed_packet = 16K
[mysql]
no-auto-rehash
[isamchk]
key_buffer = 16K
sort_buffer_size = 16K
[myisamchk]
key_buffer = 16K
sort_buffer_size = 16K
[mysqlhotcopy]
interactive-timeout
More info
HP PSC 1410 printer installation
#apt-get install hpoj hpijs
then copy the ppd files to
cp HP-PSC_1400-hpijs.ppd /usr/share/cups/model
add printer in http://localhost:631
Wireless in Linux
you have to install the package wireless-tools
#apt-get install wireless-tools
iwconfig - manipulate the basic wireless parameters
iwlist - allow to initiate scanning and list frequencies, bit-rates, encryption keys...
iwspy - allow to get per node link quality
iwpriv - allow to manipulate the Wireless Extensions specific to a driver (private)
ifrename - allow to name interfaces based on various static criteria
NEC Versa S5500 + Intel PRO/wireless 4695 AG driver
you must install the kernel 2.6.26-1-686, wpasupplicant and firmware-iwlwifi, wireless-tools to get intel pro/wireless 4695 to work.
then in /etc/network/interfaces
#auto wlan0
iface wlan0 inet dhcp
pre-up (echo ‘Modprobing iwl4965′) && /sbin/modprobe iwl4965
post-down (echo ‘Removing iwl4965′) && /sbin/modprobe -r iwl4965
wpa-ssid YOURNETNAMEAKASID
wpa-key_mgmt WPA-PSK
wpa-proto WPA
wpa-pairwise TKIP
wpa-group TKIP
wpa-psk “yourpassphrase”
wpa-driver wext
to activate the wireless driver
#ifup wlan0
NEC Versa S5500 + RT8111/8168B ethernet driver
In debian lenny, the default driver installed is r8169. It works, but sometime you will get an error
ADDRCONF(NETDEV_UP): eth1: link is not ready
you should install r8168 driver and upgrade the kernel to at least linux-image-2.6.26-1-686
How to install dig?
dig is a little program to query dns records. dig belong to the package dnsutils.
#apt-get install dnsutils
installing Internet Explorer on debian linux
i hate microsoft! but i need to install IE for web testing purpose.
#apt-get install wine cabextract
ies4linux download
IE4linux webpage
ies4linux Ubuntu install guide
opps! i changed my mind. i don't want this crap inside my notebook!
usefull x window utility
xdpyinfo - you can check resolutions
xrandr - check current screen resolution and refresh rate
lspci or lshw - check what is your graphic card
gtf - generate modeline for xorg.conf
lightweight linux workstation
doing some research on the fast and lightweight workstation, here is the package on my list
fast debian mirror
i found a fast debian mirror that can archive up to 160kBps (on peak time around 60kBps) compared to the ftp.debian.org (11kBps). I am using streamyx 1Mbps and staying in kota kinabalu.
deb http://mirror.pacific.net.au/debian lenny main contrib non-free
how to avoid ssh timeout
i always face with this problem every time i use ssh client from new installed debian system. Edit the /etc/ssh/sshd_config
ClientAliveInterval 300
ClientAliveCountMax 10
On client side, in $HOME/.ssh/config or /etc/ssh/ssh_config
ServerAliveInterval 30
ServerAliveCountMax 10
Make sure the ssh server using Protocol 2
Check man ssh_config and sshd_config for more info
howto install window codecs
You cannot play *.avi files with win32codecs. You definitely need one.
edit you /etc/apt/sources.list
deb http://ftp.tw.debian.org/debian-multimedia/ stable main
#apt-get update
#apt-get install win32codecs
you can use any mirror from debian-multimedia.org. I am using Taiwan mirror servers because it is quite fast, considering that i am in kota kinabalu.
Local dns cache with dnsmasq
local cache for faster internet browsing.
#apt-get install dnsmasq
in /etc/dnsmasq.conf
listen-address=127.0.0.1
in /etc/dhcp3/dhclient.conf
prepend domain-name-server 127.0.0.1;
in /etc/resolv.conf
nameserver 127.0.0.1
The last thing you need to do
#/etc/init.d/dnsmasq restart
#/etc/init.d/networking restart
Another interesting package that does the same thing is pdnsd. The best thing about pdnsd is, it saves the dns cache in disk which is still available even after you reboot.
Lyx - lovely word processor
I wondering why i do not find this awesome lyx before. Very well adapted into the scientific community.
Lyx is available on Windows.
tagged by sandra. something about me
i am relatively new on this blogging world. and honestly i am not really good in writing. LOL, i should write something about me supposed to be a month ago. But i am relative slow to pick up what it mean by tagged. Anyway, better late than never. so here is a 7 funny or weird fact about me.
wait. i don't even know where i should start. LOL
gnome applet tutorial
Here is a very interesting tutorial on how to create your own applet.
pwgen - password generator
from the project homepage, it says
password generator which creates password which can be easily memorized by human
#apt-get install pwgen
It does have a -y switch to include special characters in the generated password. try
$pwgen -syB
m=g_L3on
\d?7ans^
[J7\{xwo
nice!
pwgen homepage
resize photo using imagick
i use a very old laptop - VIA C3 1Ghz + 256MB memory with broken fan.
I have about 200MB photos in one folder with 1MB size each. Resizing with Gimp is not an option because it takes few minutes to even show or display the content of the folder.
I wrote simple but practical bash script resize.sh
#!/bin/bash
for i in *.JPG
do
if [-e "thumbs/$i"]; then
echo "$i exists"
else
echo "resize $i"
convert "$i" -resize 600x450 "thumbs/$i"
fi
done
echo "finish"
I simply run the script and go outside watching movie. It takes almost hours to finish
Sometime it just stop half way. Have to re-run the scripts to make the whole thumbnails.
The best solutions might be to get a new computer.
delete all gedit backup files
by default gedit will maintain a copy of files being edited with the prefix ~.
it is irritating sometimes to have this files uploaded to the server. a simple way to delete this file will be
$find . -name *~ -exec rm '{}' \;
postfix + postgresql
we can use postgresql to store postfix configuration.
#apt-get install postfix postfix-pgsql
edit the configuration /etc/postfix/main.cf
alias_maps = pgsql:/etc/postfix/pgsql-aliases.cf
then in /etc/postfix/pgsql-aliases.cf
host =
username=
password=
db_name=
query=
select_field=
table=
where_field=
additional_conditions=
more from postfix documentation
free installer for windows
Inno setup from jrsoftware.org is a free installer for window program. Another one is NSIS, and open source system to create window installer.
Wix Installer is another option. Just found out about Wix recently and it seem a very good option.
Wix Project page
Wix Tutorial page
Innosetup homepage
NullSoft scriptable install system
GtkDataBox - plotting data
GtkDatabox is a widget for the Gtk+-library designed to display large amounts of numerical data fast and easy. One or more data sets of thousands of data points (X and Y coordinate) may be displayed and updated in split seconds.
imgAreaSelect
lighttpd redirect www to non www
good SEO practice?
$HTTP["host"] =~ "^www\.(.*)" {
url.redirect = ( "^/(.*)" => "http://%1/$1" )
}
more from cyberciti
get imagemagick to work on php5 + lighttpd
somehow #apt-get install php5-imagick simply doesn't work.
The right way,
#apt-get install imagemagick
#aptitude install make php5-dev php-pear
#aptitude remove php5-imagick
#aptitude install libmagick9-dev
#pecl install imagick
lightweight dns server
one of the best open source dns server is maradns
multiple ip address on linux
debian etch
#ifconfig eth0:1 192.168.1.7
#ifconfig eth0:2 192.168.1.8
restart the networking service
#/etc/init.d/networking restart
ifup eth0 vs ifconfig eth0 up
#ifup eth0
#ifconfig eth0 up
both work the same way. ifup will configure network based on /etc/network/interfaces.
ifconfig use to configrue kernel resident network interfaces
forex exchange rate
one of my client asking me to write a software for his money changer company. The current exchange rates can
be downloaded from
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
http://www.bnm.gov.my/statistics/exchangerates.php
LibXML2 tutorial
libxml2 one of the most important c library programmer must know.
glibcurl
very interesting curl library binding using glib. It make life easier to use http in gtk program
Flickcurl c library for flickr API
Globalization support for software application
ICU is a mature, widely used set of C/C++ and Java libraries providing Unicode and Globalization support for software applications
convert video to flv
ffmpg and memcoder
hardy2@hardy2-laptop:~$ cat .bin/video-flv_png
#!/bin/bash
filename="$@"
filename=${filename%.*}
ffmpeg -sameq -i "$@" -s 640x480 -ar 44100 -r 25 $filename.flv -pass 2
ffmpeg -itsoffset -0 -i "$@" -vcodec png -vframes 1 -an -f rawvideo
-s 640x480 $filename.1.png
ffmpeg -itsoffset -0.5 -i "$@" -vcodec png -vframes 1 -an -f
rawvideo -s 640x480 $filename.2.png
ffmpeg -itsoffset -1 -i "$@" -vcodec png -vframes 1 -an -f rawvideo
-s 640x480 $filename.3.png
Vagrind
a memory error detector, a thread error detector, a cache and branch-prediction profiler, a call-graph generating cache profiler, and a heap profiler, a data race detector, and an instant memory leak detector
the magic of PHP variable function
<?php
$func = "sqrt";
if (is_callable($func)) {
print $func(49);
}
//result 7
?>
Alternatively you can use call_user_func() and call_user_func_array()
call_user_func is twice slower than direct call function and call_user_func_array is 10%-20% slower than call_user_func
how to change label font color
by using gtk_label_set_markup()
or
GdkColor color;
gdk_color_parse("red", &color);
gtk_widget_modify_fg(widget, GTK_STATE_NORMAL, &color);
Customize Openbox theme
i am a big fan of openbox window manager. Openbox is a very lightweight WM and relatively easy easy to customize.
# apt-get install gtk-chtheme
$ gtk-chtheme
wipe hard drive
DBAN
DBAN will automatically and completely delete the contents of any hard disk that it can detect
shred
shred manpage
or simply use dd
dd if=/dev/zero of=/dev/hda
new gtkimageviewer
From Dov Grobgeld
a major rewrite (using gob2 actually) where the image annotation model has been changed so that the image is provided to the user of the widget before it is drawn to the screen.
how to replace notebook page
it is quite tricky since there is not such function in gtk_notebook_*
tadeboro from gtkforums.com answer me with a good code example.
magical square root
/*
================
SquareRootFloat
================
*/
float SquareRootFloat(float number) {
long i;
float x, y;
const float f = 1.5F;
x = number * 0.5F;
y = number;
i = * ( long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( f - ( x * y * y ) );
y = y * ( f - ( x * y * y ) );
return number * y;
}
SSH filesystem
mount remote filesystem via ssh. it is develop using fuse by Miklos Szeredi
sshfs project page
fuse project page
List of filesystem develop using fuse
How to find not unique row in the table
test=*# select * from dup;
a | b
---+---
1 | 1
1 | 2
2 | 1
1 | 1
3 | 3
3 | 3
(6 rows)
test=*# select * from dup where (ctid,a,b) not in (select distinct on (a,b) ctid,* from dup);
a | b
---+---
1 | 1
3 | 3
(2 rows)
another approach:
select a,b from dup group by a,b having count(*) > 1;
libgmailer
libgmailer is a PHP library that allow you to write PHP program to access Google's free webmain service Gmail
How to display busy cursor
Interesting post on gtk-app-devel-list@gnome.org mailing list
void busy_stuff ()
{
GdkDisplay *display;
GdkCursor *cursor;
GdkWindow *window;
gint x, y;
cursor = gdk_cursor_new(GDK_WATCH);
display = gdk_display_get_default();
window = gdk_display_get_window_at_pointer(disp, &x, &y);
gdk_window_set_cursor(window, cursor);
gdk_display_sync(display);
gdk_cursor_unref(cursor);
/* do time-consuming stuff here */
gdk_window_set_cursor(window, NULL);
}
gdk_cursor_unref() prevent memory leak
More on Mailing list archive
gtk tutorial
Gtk is a very powerful GUI programming toolkits. Here is a few interesting website to look at
c basics
A Tutorial on Pointers and Arrays in C
Everything you need to know about pointers in C
Brief c tutorial
Select row within days interval
SELECT * FROM mytable WHERE mydate > DATE_SUB(now(),INTERVAL 7 DAYS)
Using g_value_get_*
Using GValue related function is quite tricky. It is not working if you do
GdaDataModel *dm;
gint i;
i = g_value_get_int ( gda_data_model_get_value_at (dm, 0, 0));
For upcomming Version 4.0 (the main difference is at GdaDataModel API)
GdaDataModel *model;
const GValue *integer;
GError *error = NULL;
integer = gda_value_new (G_TYPE_INT);
integer = gda_data_model_get_value_at (model, 0, 0, &error);
All values in a Data Model must be unmodificable then use const GValue, this will avoid compilation warnings. Or can use (gda_value_new makes this for you :-)
integer = g_new0 (GValue. 1);
g_value_init (inteteger, G_TYPE_INT);
Thanks to Daniel Espinosa
Gtk undefine reference
Header file and function on separate file should not have the static function declaration.
static void loan_new_record (gpointer data);
static void loan_display_reset ( GtkWidget *data);
to
void loan_new_record (gpointer data);
void loan_display_reset ( GtkWidget *data);
libgda INSERT SQL query example
Code example of gda_data_model_set_modification_query() and how to insert new data
How To Write Unmaintainable Code
The article come with a quote "ensure job for life".
if(a);
else;
{
int d;
d = c;
}
;
splint - tool to examine c code for bugs
Splint is a tool for statically checking C programs for security vulnerabilities and coding mistakes.
Available in debian
#apt-get install splint
Visit Splint.org
Learn the Linux Command Line
found a very interesting Linux shell tutorial
Align gtk label using gtk_misc_set_alignment()
When packing a gtk label inside gtk table. I come across one problem. All the label as aligned center.
As a result i just made one ugly form. To fix the problem, use gtk_misc_set_alignment().
See code example
#include <gtk/gtk.h>
int main (int argc, char **argv)
{
GtkWidget *window;
gtk_init( &argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GtkWidget *table = gtk_table_new( 4, 1, TRUE );
GtkWidget *label;
label = gtk_label_new("Normal label");
gtk_table_attach_defaults ( GTK_TABLE(table), label, 0, 1, 0, 1)
label = gtk_label_new( "left" );
gtk_misc_set_alignment( GTK_MISC(label), 0.0, 0.0 );
gtk_table_attach( GTK_TABLE(table), label, 0, 1, 1, 2,
GTK_EXPAND|GTK_FILL, GTK_SHRINK, 0, 0 ); /*important*/
label = gtk_label_new( "center" );
gtk_misc_set_alignment( GTK_MISC(label), 0.5, 0.0 );
gtk_table_attach_defaults( GTK_TABLE(table), label, 0, 1, 2, 3
GTK_EXPAND|GTK_FILL, GTK_SHRINK, 0, 0 ); /*important*/
label = gtk_label_new( "right" );
gtk_misc_set_alignment( GTK_MISC(label), 1.0, 0.0 );
gtk_table_attach_defaults( GTK_TABLE(table), label, 0, 1, 3, 4
GTK_EXPAND|GTK_FILL, GTK_SHRINK, 0, 0 ); /*important*/
gtk_widget_set_size_request (GTK_WIDGET (table), 200, 100);
gtk_container_add( GTK_CONTAINER (window), GTK_WIDGET(table));
gtk_widget_show_all(window);
gtk_main();
return 0;
}
Thanks to owl102 from gtkforums.com
Select row in GnomeDbRawGrid
GnomeDbRawGrid come from GtkTreeView widget. So we can select row using gtk_tree_view_selection_select_iter() and get the current selected row gtk_tree_view_get_selection().
GnomeDbRawGrid *grid;
GtkTreeView *tree_view;
tree_view = GTK_TREE_VIEW (grid);
Related
Gnome db raw grid
save image and display image from postgresql
There is several way to save image into postgresql database. Using oid, blob and bytea data types.bytea column type recommended.
To store image
gdk_pixdata_from_pixbuf(),
gdk_pixdata_serialize()
To display image
gdk_pixdata_deserialize(),
gdk_pixbuf_from_pixdata(),
gtk_image_new_from_pixbuf()
Thanks to vivien and Yann Droneaud for great help
Related
Gdk Pixbuf inline
Libgnomedb example
Malaysia Open Source IRC Channel
It is nice to know, at least there is some people out there love open source.
Channel: FreeNode
Room: #MyOSS
alternative nameserver
Just found one free domain name server run by one of malaysian open source supporter angch.
DNS IP: 202.190.85.116
It should be better than TM dns because not too many people use it or OpenDNS since it is located in malaysia.
String with dinamicaly growing buffer
String is where buffer overflow always occur. GLIB supports doing this much more easily:
/* portable asprintf() */
char *str = g_strdup_printf("string%s%d", str_variable, int_variable);
Or if you wanted a modifyable buffer:
GString *str = g_string_new(NULL);
g_string_append(str, "string");
g_string_append(str, str_variable);
g_string_sprintfa(str, "%d", int_variable); /* no g_string_append_int() */
C variable definition
extern - Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere.
static - The static data type modifier is used to create permanent storage for variables. Static variables keep their value between function calls. When used in a class, all instantiations of that class share one copy of the variable.
const - The const keyword can be used to tell the compiler that a certain variable should not be modified once it has been initialized.
Using Makefile
If you writing gtk application. You will have to use more than one source file to make the code more manage able. To compile the application you need to use make.
It is all you need to compile a c code with libgnomedb. This code will output an executable file with name ekoken. A more complicated makefiles using variable is like this
CC = gcc
LD = gcc
CFLAGS =
RM = rm -f
LDFLAGS = `pkg-config --libs gtk+-2.0`
PROG =
OBJS =
all : $(PROG)
%.o : %.c
$(CC) $(CFLAGS) -c $< -o $@
$(PROG) : $(OBJS)
$(LD) $(LDFLAGS) $(OBJS) -o $(PROG)
clean :
$(RM) $(OBJS) $(PROG)
Where PROG is the executable output and OBJS is the object file output with .o suffix.
Design pattern
Design pattern is somehow overlook in many newbie tutorial. But it is very important to know before even writing the code. I found a list of design pattern for PHP
Installing debian from running system
I am a Debian user for almost four years now. I think one very unique feature on debian system is deboostrap.
Easily install debian distro using another running system to mounted drive.
Hello world!
I think it is better to start with
<?
php echo "hello world";
?>