TextMate 2: uses spaces instead of tabs and set tab size








  • Edit ~/.tm_properties and put:
    tabSize = 2
    softTabs = true
    softWrap = true
    
    [ source.java ]
    tabSize = 4
    softTabs = true
    
    [ source.python ]
    tabSize = 4
    softTabs = true
    
    [ source.tcl ]
    tabSize = 4
    softTabs = true
    



Uploading Multiple Files to Google Drive with Google App Script








  • Form.html Note: Replace rootFolderId with the id of destination folder on your Google Drive.


  • Code.gs



Enable livepatch on Ubuntu Linux 16.04 LTS








  1. Install snapd:
    sudo apt-get install snapd
  2. Install the canonical-livepatch snap:
    sudo snap install canonical-livepatch
  3. Go to https://ubuntu.com/livepatch and retrieve your livepatch token
  4. Enable the service with your token:
    sudo /snap/bin/canonical-livepatch enable [TOKEN]
  5. You can check the status at any time using:
    sudo /snap/bin/canonical-livepatch status --verbose



See also




xargs argument position








echo "foo" | xargs -i echo {} "bar"
produces:
foo bar



xargs with multiple commands








  • Example 1:
    find "/Users/wilson/Documents" -type f -print0 | xargs -0 -i bash -c 'grep -L "{}" /tmp/document-list.csv || echo "{}"'
  • Example 2:
    cat a.txt | xargs -I % sh -c 'echo %; ls %'






see also




JSON to POJO








http://www.jsonschema2pojo.org


SFC Game: Contra III - The Alien Wars Cheats & Codes








Passwords

Here are some passwords for the stages, across the various difficulty settings. (Note: The game ends after Level 3 on easy.)
Easy:
Level 2 - HMH4
Level 3 - HMRK

Normal:
Level 2 - MDMG
Level 3 - MDWC
Level 4 - 1ZKC
Level 5 - M2P5

Hard:
Level 2 - J3YS
Level 3 - JJ34
Level 4 - NCR1
Level 5 - JKCG

Maniac: Level 2 - G43Q
Level 3 - G4SM
Level 4 - K31Y
Level 5 - GPM2


Infinite Lives - B32R

Skip Stage - H2F2 - Now while playing, press START to skip to the next stage.

Play Stage 4 on Easy - 21LN
70条命:标题画面按2P手柄(CBA右左)三次。
选关:标题画面按2P手柄(左右ABC)三次。
加满武器:游戏中1P暂停,按(上上下下A上上下下B上上下下C)。

注意,这里的标题画面是指一开始,有‘魂斗罗’字样,可以选择1P和2P 的那个标题画面。
如果秘技输入成功,会有一个男性的声音叫一声‘呀’的声效。



Mac OS X: install lxml








  • Install xcode first
  • Run the command:
    xcode-select --install



Shell scripting: get the last argument









for last; do true; done
echo $last




Install MyTardis on Ubuntu Linux 16.04








  1. Create a service user account for running MyTardis:
    useradd -m -d /opt/mytardis -s /bin/bash tardis
  2. Check out MyTardis from github:
    cd /opt
    sudo git clone -b master https://github.com/mytardis/mytardis.git
    sudo chown tardis:tardis /opt/mytardis
  3. Install required ubuntu packages:
    sudo bash /opt/mytardis/install-ubuntu-requirements.sh
  4. Setup virtualenv for tardis account:
    sudo su tardis
    source /usr/share/virtualenvwrapper/virtualenvwrapper.sh
    mkvirtualenv --system-site-packages mytardis
    pip install -U pip
    echo "source /usr/share/virtualenvwrapper/virtualenvwrapper.sh" >> ~/.bashrc
    echo "workon mytardis" >> ~/.bashrc
    source ~/.bashrc
  5. (As user 'tardis',) To work around this bleach bug, set html5lib version by adding line below to requirements.txt:
    html5lib==0.9999999
  6. remove billiard from requirements.txt or after installing the required packages, re-install celery package to downgrade billiard to 3.3.0.23. This is because the installed billiard 3.5.0.0 is installed and it causes celery failed to process any task. (Thread ResultHandler crashed: TypeError ...)
  7. (As user 'tardis',) Install required Python packages:
    cd /opt/mytardis
    pip install -U -r requirements.txt
  8. (As user 'tardis',) Initialize tardis/settings.py (as user 'tardis'):
    cd /opt/mytardis
    mv tardis/settings_changeme.py tardis/settings.py
    add the following lines:
    DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
    DATABASES['default']['NAME'] = 'tardis_db'
    
  9. (As user 'tardis',) Generate SECRET_KEY and save to tardis/settings.py:
    echo "SECRET_KEY='`python mytardis.py generate_secret_key`'" >> tardis/settings.py
    or to re-generate:
    python -c "import os; from random import choice; key_line = '%sSECRET_KEY=\"%s\"  # generated from build.sh\n' % ('from tardis.default_settings import * \n\n' if not os.path.isfile('tardis/settings.py') else '', ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789\\!@#$%^&*(-_=+)') for i in range(50)])); f=open('tardis/settings.py', 'a+'); f.write(key_line); f.close()"
  10. (As user 'tardis',) Initialize database:
    python mytardis.py migrate
  11. (As user 'tardis',) Create cache tables:
    python mytardis.py createcachetable default_cache
    python mytardis.py createcachetable celery_lock_cache
  12. (As user 'tardis',) Collect static files and save to static/ directory under /opt/mytardis:
    python mytardis.py collectstatic
  13. (As user 'tardis',) Create superuser (as user 'tardis'):
    python mytardis.py createsuperuser
  14. (As user 'tardis',) Create var/store directory:
    mkdir -p var/store
  15. (As user 'tardis',) Start mytardis server:
    python mytardis.py celeryd &
    python mytardis.py runserver 0.0.0.0:8000
    Note: 1) celeryd has to be started manually prior mytardis; 2) append 0.0.0.0:8000 to runserver command will make the server serve other hosts rather than only localhost:8000
  16. Supervisor can be installed to auto-start celeryd and webserver...



Setup XNAT on Ubuntu 16.04








  1. Create user xnat to run Tomcat service:
    sudo useradd -u 6667 -d /opt/xnat -s /bin/bash xnat
  2. Install PostgreSQL:
    sudo apt-get install postgresql
    then edit /etc/postgresql/9.5/main/postgresql.conf file:
    standard_conforming_strings=off
    , and restart PostgreSQL server:
    sudo /etc/init.d/postgresql restart
  3. Install Java 7
    Current XNAT (v1.6.5) requires Java 7. Java 8 will NOT work. Type the commands below to install Java 7:
    sudo add-apt-repository ppa:webupd8team/java
    sudo apt-get update
    sudo apt-get install oracle-java7-installer oracle-java7-set-default
  4. Install Tomcat 7
    Current XNAT v1.6.5 requires Tomcat7. However, DO NOT install tomcat7 from Ubuntu Repository. It was compiled with Java 8 and will cause this problem. Instead, you should download from offical Tomcat web site. Type the command below to install tomcat:
    cd /opt
    sudo wget http://apache.mirror.serversaustralia.com.au/tomcat/tomcat-7/v7.0.70/bin/apache-tomcat-7.0.70.tar.gz
    sudo tar zxvf apache-tomcat-7.0.70.tar.gz
    sudo ln -s /opt/apache-tomcat-7.0.70 /opt/tomcat7
    sudo chown -R xnat:xnat /opt/apache-tomcat-7.0.70
    sudo chown -R xnat:xnat /opt/tomcat7
    then set startup scripts permissions:
    sudo chmod +x /opt/tomcat7/bin/startup.sh
    sudo chmod +x /opt/tomcat7/bin/shutdown.sh
    and you need to set JAVA_OPTS in /opt/tomcat7/bin/catalina.sh and insert the following line at the start:
    JAVA_OPTS="-XX:MaxPermSize=1024m -Xmx8192m"
    NOTE: you need to set MaxPermSize and MaxHeapSize(Xmx) in JAVA_OPTS. Otherwise, OutOfMemoryError will occur when you load XNAT web app.
  5. Install Maven:
    sudo apt-get install maven
  6. Download and extract XNAT 1.6.5:
    cd /opt
    sudo wget ftp://ftp.nrg.wustl.edu/pub/xnat/xnat-1.6.5.tar.gz
    sudo tar zxvf xnat-1.6.5.tar.gz
    sudo chown -R xnat:xnat /opt/xnat
  7. Prepare XNAT directories:
    sudo mkdir /data/xnat/archive
    sudo mkdir /data/xnat/prearchive
    sudo mkdir /data/xnat/ftp
    sudo mkdir /data/xnat/cache
    sudo mkdir /data/xnat/build
    NOTE: '/data/xnat' should be the mount point for large storage for XNAT.
  8. Set up environment variables for xnat user, by editting .bashrc file:
    sudo su xnat
    vi ~/.bashrc
    add the following:
    # JAVA
    export JAVA_HOME=/usr/lib/jvm/java-7-oracle
    export PATH=$JAVA_HOME/bin:$PATH
    
    # Tomcat
    export TOMCAT_HOME=/opt/tomcat7
    export PATH=$PATH:$TOMCAT_HOME/bin
    
    # XNAT
    export XNAT_HOME=/opt/xnat
    export PATH=$PATH:$XNAT_HOME/bin
  9. Create XNAT database user xnat01:
    sudo su postgres
    createuser -U postgres -S -D -R -P xnat01
    Note: set and remember the password for db user xnat01, you will need it in the XNAT build.properties file.
  10. Create XNAT database:
    sudo su postgres
    createdb -U postgres -O xnat01 xnat
  11. Edit /opt/xnat/build.properties:
    su xnat
    cd /opt/xnat
    cp build.properties.sample build.properties
    vi build.properties
    and the content should be like below:
    maven.appserver.home = /opt/tomcat7
    
    xnat.site.title=XNAT
    xdat.project.name=xnat
    xdat.project.db.name=xnat
    xdat.project.db.driver=org.postgresql.Driver
    xdat.project.db.connection.string=jdbc:postgresql://localhost/xnat
    xdat.project.db.user=xnat01
    xdat.project.db.password=XXXXXXX
    xdat.archive.location=/data/xnat/archive
    xdat.prearchive.location=/data/xnat/prearchive
    xdat.cache.location=/data/xnat/cache
    xdat.ftp.location=/data/xnat/ftp
    xdat.build.location=/data/xnat/build
    xdat.mail.server=mail.yourdomain.org
    xdat.mail.port=25
    xdat.mail.protocol=smtp
    xdat.mail.username=
    xdat.mail.password=
    xdat.mail.admin=xnat-admin@yourdomain.org
    xdat.url=http://192.168.100.12:8080/xnat
    xdat.require_login=true
    xdat.enable_new_registrations=false
    xdat.security.channel=any
    xdat.enable_csrf_token=true
    Note: xdat.url need to be set to the public ip or address instead of localhost if you want the XNAT server to be accessed from other computers.
  12. Edit project.properties file. and replace the 'maven.repo.remote' line with
    maven.repo.remote=https://nrgxnat.artifactoryonline.com/nrgxnat/xnat-maven1

    NOTE: You need to do this because the offical XNAT maven repository is down.
  13. Run setup.sh script to build:
    sudo su xnat
    cd /opt/xnat
    bin/setup.sh
  14. Create Database tables & views:
    cd /opt/xnat
    psql xnat01 -h localhost -d xnat -f deployments/xnat/sql/xnat.sql
    Note: you need supply the password for db user xnat01.
  15. Store initial security settings:
    sudo su xnat
    cd /opt/xnat/deployments/xnat
    StoreXML -project xnat -l security/security.xml -allowDataDeletion true
  16. Store Example Custom Variable Sets:
    sudo su xnat
    cd /opt/xnat/deployments/xnat
    StoreXML -dir ./work/field_groups -u admin -p admin -allowDataDeletion true
  17. Deploy the web app
    sudo su xnat
    cd /opt/xnat
    bin/update.sh -Ddeploy=true
  18. Now start Tomcat7 server:
    sudo su xnat
    /opt/tomcat7/bin/startup.sh
  19. When open the xnat web page in browser the first name, it will take a very long time to load as it is loading the XNAT web app in Tomcat.


Key points

  • Install JAVA 7. Java 8 does not work.
  • Download Tomcat 7 binary from offical Tomcat web site. DO NOT install from Ubuntu Repository.
  • Set Java MaxPermSize and Xmx(MaxHeapSize) in JAVA_OPTS for Tomcat7 startup script catalina.sh. Missing this step will cause OutOfMemoryError when load XNAT web app
  • Official XNAT maven repository site is down. Edit project.properties to replace it with https://nrgxnat.artifactoryonline.com/nrgxnat/xnat-maven1
  • Tomat7 server is run as xnat user.



Get human readable file size in GWT











Convert file size to human readable string in Java











Hotmail (Outlook) denied POP3 access from Gmail








Recently, my Gmail failed to access my hotmail via POP3:
Server denied POP3 access for the given username and password.
Please contact Microsoft's Support Team for more information on POP access.
Server returned error: "Authentication failure: unknown user name or bad password. [Error="ProxyNotAuthenticated" AuthResult=0 Proxy=KL1PR0201MB1655.apcprd02.prod.outlook.com:1995:SSL]"

It was working fine for a few years. Suddenly stopped working. I searched and found the reason: Microsoft turned off POP3 access on my account without any notification. So turning it back on solved the problem:
For more details, see here


Mount CIFS/SMB (Windows) Share on Linux








Install CIFS/Samba client

sudo apt-get install cifs-utils

Manual mount

  • sudo mount -t cifs -o domain=yourdomain,username=yourusername //your-cifs-server.your-domain.org/yourshare /mnt/yourshare

Auto mount

  • Create a credentials file at /etc/cifs-credentials
    domain=yourdomain
    username=yourusername
    password=yourpassword
      
  • Edit /etc/fstab as root (or sudo)
    //your-cifs-server.your-domain.org/yourshare /mnt/yourshare cifs credentials=/etc/cifs-credentials  0 0
      
  • sudo mount -a







See also




OMERO systemd units








  • Systemd unit for OMERO.server:
    cat /lib/systemd/system/omero.service
    [Unit]
    Description=OMERO Server
    Wants=remote-fs.target postgresql.service
    After=remote-fs.target postgresql.service
       
    [Service]
    Type=forking
    ExecStart=/etc/init.d/omero start
    ExecStop=/etc/init.d/omero stop
    
    [Install]
    WantedBy=multi-user.target
    
  • Systemd unit for OMERO.web:
    cat /lib/systemd/system/omero-web.service
    [Unit]
    Description=OMERO web
    Wants=nginx.service omero.service
    After=nginx.service omero.service
       
    [Service]
    Type=forking
    ExecStart=/etc/init.d/omero-web start
    ExecStop=/etc/init.d/omero-web stop
    
    [Install]
    WantedBy=multi-user.target
    



OMERO.web startup script /etc/init.d/omero-web











OMERO.server startup script /etc/init.d/omero











Mediaflux startup script to run the server as non-root user








  • The configuration file should be saved to /etc/mediaflux:
    export MFLUX_HOME=/opt/mediaflux
    export MFLUX_DOMAIN=system
    export MFLUX_USER=manager
    export MFLUX_TRANSPORT=https
    export MFLUX_PORT=8443
    export MFLUX_UMASK=0007
    export MFLUX_ADMIN=mflux
    
  • The startup script modified from $MFLUX_HOME/bin/unix/mediaflux should be saved to /etc/init.d/mediaflux
    • sudo cp $MFLUX_HOME/bin/unix/mediaflux /etc/init.d/mediaflux
    • sudo vi /etc/init.d/mediaflux
      • Note: the following changes is required by systemd on Ubuntu Linux 16.04:
        #!/bin/bash
        # Required-Start:    $remote_fs $syslog
        # Required-Stop:     $remote_fs $syslog
        # Default-Start:  2 3 4 5
        # Default-Stop: 0 1 6
        
      • Note: the following changes is to run the sevice as user mflux rather than root:
        start-stop-daemon --start --background --umask $MFLUX_UMASK -c $MFLUX_ADMIN --exec "${JAVA}" -- -jar $MFLUX_HOME/bin/aserver.jar application.home=$MFLUX_HOME nogui $DEBUG >> $MFLUX_HOME/volatile/logs/unix_start.log&

see also




Start Mediaflux server on system reboot using systemd on Ubuntu Linux 16.04








  1. Modify mediaflux script file from $MFLUX_HOME/bin/unix/mediaflux and install it to /etc/init.d/mediaflux.
  2. create systemd unit file at /lib/systemd/system/mediaflux.service
    [Unit]
    Description=Mediaflux Server
    After=remote-fs.target
       
    [Service]
    Type=forking
    ExecStart=/etc/init.d/mediaflux start
    ExecStop=/etc/init.d/mediaflux force-stop
    
    [Install]
    WantedBy=multi-user.target
    
  3. Enable the systemd unit (so that it is called on reboot)
    sudo systemctl enable mediaflux.service
  4. Start the service manually(without reboot)
    sudo systemctl start mediaflux.service

see also




Ubuntu Linux 16.04 systemd unit file for Mediaflux server








[Unit]
Description=Mediaflux Server
After=remote-fs.target
   
[Service]
Type=forking
ExecStart=/etc/init.d/mediaflux start
ExecStop=/etc/init.d/mediaflux force-stop

[Install]
# IMPORTANT: The following line is to insert the service to the dependency tree. Otherwise, it will not be called on system reboot.
WantedBy=multi-user.target

see also




Mac OS X: extra output message when exiting Terminal








After upgrade to Mac OS X El Captain, when exiting from Terminal, I see the following message: According to this, it is not to be worried.


趙傳 - 我是一隻小小鳥











赵传 - 我很丑,可是我很温柔











趙傳 - 我終於失去了你











rsync: specify SSH identity file (private key)








rsync -Pavx -e 'ssh -i /path/to/id_rsa' /local/file user@server:/remote/dir



Bash: check if number is odd or even








n=12
if [[ $((n % 2)) -eq 0 ]]; then
   echo "even"
else
   echo "odd"
fi



Bash: loop through file names with spaces








#!/bin/bash

IFS_BAK=$IFS
IFS=$(echo -en "\n\b")
for f in $(ls)
do
  echo "$f"
done
IFS=$IFS_BAK



bash: remove leading zeros








s="00012"
n=$(expr $s + 0)
echo $n



find without recursion








find . -maxdepth 1
find . -maxdepth 1 -type d



sed: delete all characters before matching word








echo "    1234567890abcdef" | sed 's/^*.abc/abc/'



sed: replace formatted numbers








Example remove date string:
s="1234 2007-12-21 11:22:30 1.txt"
s=$(echo $s | sed 's/[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\s*//')
echo $s
# 1234 1.txt



Shell script: execute a string as command








eval is what we need:
string="echo \"Shell scripting is cool.\""
eval $string



Shell script: set delimiter and read line from file








while IFS=$'\t' read col1 col2; do
    echo "column 1: ${col1}"
done < /path/to/input.txt
The above code read from tab delimited text file.


Shell script: loop through lines from file or command output








You can pipe command output to a while loop
echo /path/to/1.txt | while IFS=$'\t' read a b; do
   echo "${b}, ${a}"
done

Or loop through a text file:
while IFS=$'\t' read a b; do
   echo "${b}, ${a}"
done < /path/to/1.txt



awk: re-order columns using printf








echo 1.txt | awk 'BEGIN{FS="\t"} {printf "%s\t%s\n", $2, $1}'



Shell script: get file size








stat -c %s /path/to/file
or
#!/bin/bash

path=/path/to/file
size=$(stat -c %s ${path})
if [[ $size -eq 0 ]]; then
    echo "${path} is a zero-size file."
fi
Note: If path directs to a directory, it will not fail nor return 0. It returns the block size associated with the directory. See this for more details.


Shell script: remove leading and trailing character








s="\"Shell scripting is interesting.\""
echo $s

# ${s%\"} will remove the suffix " (escaped with a backslash to prevent shell interpretation)
s=${s%\"}

# ${s#\"} will remove the prefix " (escaped with a backslash to prevent shell interpretation)
s=${s#\"}
echo $s



Sed: multiple substitutes in one sed command








Delimit commands with semicolon:
echo "John like apples." | sed 's/apple/pear/;s/John/David/'
Another example, remove leading and trailing quotes:
echo "'Sed is cool.'" | sed 's/^'//;s/'$//'



A shell script to check files in SWIFT object storage











sed: delete matching lines








sed -i.bak '/pattern/d' input.txt



Shell scripting: remove .DS_Store and ._* files recursively on Linux or Mac








find . -name ".DS_Store" -print0 | xargs -0 rm -rf
find . -name "._*" -print0 | xargs -0 rm -rf
find . -name ".DS_Store" -delete
find . -name "._*" -delete
find . \( -name '.DS_Store' -or -name '._*' \) -delete



Shell scripting: Removing repeating empty lines








cat -s 1.txt > 1.txt; mv 1.txt.tmp 1.txt



Shell scripting: enclose all lines with quotes








  • Using awk:
    awk '{print "\""$0"\""}' input.txt
    
    or if ignore empty lines:
    awk 'NF {print "\""$0"\""}' input.txt
    
  • Or using sed:
    sed -i.bak 's/^/"/; s/$/"/' input.txt
    
    or if ignore empty lines:
    sed -i.bak 's/^..*$/"&"/' input.txt
    



Shell Scripting: delete blank lines from a text file using sed








Delete empty lines using sed:
sed -i.bak '/^\s*$/d' 1.txt



Java: Stream Handler for Logger








        Logger logger = Logger.getLogger("daris-download");
        logger.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
        /*
         * file handler
         */
        FileHandler fileHandler = new FileHandler(
                "%h/.daris/daris-download.%g.log", 5000000, 2);
        fileHandler.setLevel(Level.ALL);
        fileHandler.setFormatter(new Formatter() {

            @Override
            public String format(LogRecord record) {
                StringBuilder sb = new StringBuilder();
                sb.append(new Date(record.getMillis())).append(" ");
                sb.append("[thread: ").append(record.getThreadID())
                        .append("] ");
                sb.append(record.getLevel().getName()).append(" ");
                sb.append(record.getMessage());
                sb.append("\n");
                return sb.toString();
            }
        });
        logger.addHandler(fileHandler);
        /*
         * console handler
         */
        StreamHandler consoleHandler = new StreamHandler(System.out,
                new Formatter() {
                    @Override
                    public String format(LogRecord record) {
                        return record.getMessage() + "\n";
                    }
                }) {
            @Override
            public synchronized void publish(LogRecord record) {
                super.publish(record);
                super.flush();
            }
        };
        consoleHandler.setLevel(Level.INFO);
        logger.addHandler(consoleHandler);



几个中文影视直播APK











Shell script: Java arguments contains spaces








java -jar myapp.jar ${1+"$@"}

See also




Java: low level logging messages not showing








FINE level logging message is not shown even if the handler.setLevel(Level.FINE).

Reason

java.util.logging has a root logger that defaults to Level.INFO, and a ConsoleHandler attached to it that also defaults to Level.INFO. Level.FINE is lower than Level.INFO, so fine messages are not displayed by default.

Solution

    Logger logger = Logger.getLogger("my-logger");
    logger.setLevel(Level.ALL);
    logger.setUseParentHandlers(false);
    /*
     * file handler
     */
    FileHandler fileHandler = new FileHandler(
                "%h/.my-app.%g.log", 5000000, 2);
    fileHandler.setLevel(Level.ALL);
    logger.addHandler(fileHandler);
    /*
     * console handler
     */
    ConsoleHandler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.INFO);
    logger.addHandler(consoleHandler);



Java: Consume InputStream by Null OutputStream








OutputStream nullOutputStream = new OutputStream() { 
    @Override
    public void write(int b) {
    }
};

See also




Java: Remove illegal character 0x0 from string








Unicode 0x0 is illegal in XML.
str.replaceAll("[\\000]+", "")



海外看中超亚冠直播的几个网站








2017年3月更新

  • 乐视由于欠费,失去2017亚冠中超直播权。2017亚冠中超网上直播有PPTV。央视也开始直播亚冠中超。
飞流直播 目前最好的看2017亚冠,中超直播站。【推荐】
http://goatd.net/ 速度比较快,画质一般,无中文解说。中超亚冠都有直播。【不再推荐,因为此网站被google提示有安全问题,其实是弹窗广告安装流氓软件】
央视体育频道(CCTV 5, CCTV 5+)
可在电脑上安装Bluestacks模拟器和电视家观看
中文解说,画质较好,经常有停滞和音画不同步。央视2017直播亚冠中超。



Java synchronized block in static method








class Test {


    public static Test() {
        synchronized(Test.class) {
            ... ...
        }
    }

}



JavaFX WebView shows blank page when the web site ssl certificate is not trusted ( or self-signed)








JavaFX WebView shows blank page when the web site ssl certificate is not trusted (or self-signed). There is not errors/exceptions that you can see unless you set up a listener before you load the web site in WebView: The following code will show the error:
    WebView web = new WebView();
    web.getEngine().load("https://www.your-org.org");
    web.getEngine().getLoadWorker().stateProperty()
            .addListener((ov, oldState, newState) -> {
                System.err.println(web.getEngine().getLoadWorker()
                         .exceptionProperty());
            });
The error is like below:
java.lang.Throwable: SSL handshake failed
To resolve the error, if you trust the web site, you can ignore the error by adding following code before you start the WebView:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { 
    new X509TrustManager() {     
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            return null;
        } 
        public void checkClientTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
            } 
        public void checkServerTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    } 
}; 

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL"); 
    sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}

WebView web = new WebView();
web.getEngine().load("https://www.your-org.org");
NOTE: After executing the above code, your application will trust all https web sites. To have a more secure solution, you may maintain a local key store to add the trusted certificates, see this for more detail.

See also




openssl command to check web site ssl certificate








openssl s_client -showcerts -connect www.google.com:443



Coolpad 8297W remove News Stream








  1. Root the phone
  2. Install System App Remover from Google Play Store.
  3. Uninstall News Stream in System Application Remover



Telstra ZTE MF60 WIFI modem: change APN settings








  • You have to insert a Telstra SIM card (otherwise you will not be able to set the new profile as default.)
  • Power on the modem, can connect to the WIFI from your computer.
  • Open http://192.168.0.1 in your browser.(Default username: admin password: admin)
  • 3G Settings -> APN Settings
  • Click 'Add' button to add a new profile,  edit the APN, then click 'Set default' button.

See also




Telstra ZTE MF60 WIFI modem: reset WIFI password








Hold the WPS button and the POWER button at the same time for about 5-10 secs it will re-start the modem back to the default factory settings.

The original password is printed under the battery in the modem.

See also




Free Piano Lessons for Kids








Huffman Academy Free Piano Lession for Kids




VIM: tidy up HTML








First enable filetype indent then set filetype to html, then enable smartident:
:filetype indent on
:set filetype=html
:set smartindent
Then re-format the file using the following commands:
1G      # go to the beginning of file
gg=G    # reformat the file from the beginning



CSS: image auto resize and centered inside a div








<div style="width:600px; height:400px;">
<div style="vertical-align:middle; text-align:center; width:100%; height:100%;">
    <img style="max-width:100%; max-height:100%; width:auto; height:100%;" src="http://your-domain.org/your-img.png"/>
</div>
</div>

see also




CSS: fit textarea to its parent div








textarea {
    height: 100%;
    width: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
Example HTML code:
<div style="width:600px; height:400px;">
<textarea style="height:100%; width:100%; box-sizing: border-box;" readonly>
This is a textarea.
</textarea>
</div>
Run the Example:



Enable Mac OS X Integration library (com.apple.eawt.*) in Eclipse Java 8 Project








  1. Right click the project, select 'Build Path' then 'Configure Build Path...'
  2. Activate 'Libraries' tab, then open 'JRE System Library', then select Access Rules...
  3. Click 'Edit...' button, then click 'Add' button and type the rules:
    • Resolution: 'Accessible'
    • Rule Pattern: 'com/apple/eawt/**'



Install XNAT on Ubuntu 14.04








  1. Install and configure postgresql
    • Install postgresql:
      sudo apt-get install postgresql
    • Edit /etc/postgresql/9.3/postgresql.conf, and set:
      standard_conforming_strings=off
    • Restart postgresql:
      sudo /etc/init.d/postgresql restart
  2. Install Java 7
    • Run the following commands to install Java 7 SDK:
      sudo add-apt-repository ppa:webupd8team/java
      sudo apt-get update
      sudo apt-get install oracle-java7-installer
      sudo echo "export JAVA_HOME=/usr/lib/jvm/java-7-oracle" >> /etc/bash.bashrc
      
    • Run the following command to set Java 7 as default(java):
      sudo apt-get install oracle-java7-set-default
  3. Install Tomcat 7:
    export JAVA_HOME=/usr/lib/jvm/java-7-oracle; sudo apt-get install tomcat7
    
  4. Install Maven:
    cd /opt/; sudo wget http://apache.mirror.serversaustralia.com.au/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz
    sudo tar zxvf apache-maven-3.3.9-bin.tar.gz
    sudo ln -s /opt/apache-maven-3.3.9/ /opt/maven
  5. Download and extract XNAT source:
    cd /opt
    sudo wget ftp://ftp.nrg.wustl.edu/pub/xnat/xnat-1.6.5.tar.gz
    sudo tar zxvf xnat-1.6.5.tar.gz
  6. Create XNAT unix user:
    sudo useradd -u 6667 -d /opt/xnat -s /bin/bash xnat
    sudo usermod -a -G tomcat7 xnat
    sudo chown -R xnat:xnat /opt/xnat
  7. Prepare XNAT directories:
    sudo mkdir /data/xnat/archive
    sudo mkdir /data/xnat/prearchive
    sudo mkdir /data/xnat/ftp
    sudo mkdir /data/xnat/cache
    sudo mkdir /data/xnat/build
    Note: /data/xnat should be the mount point for large storage for XNAT.
  8. Set up environment variables for xnat user, by editting .bashrc file:
    sudo su xnat
    vi ~/.bashrc
    add the following:
    # JAVA
    export JAVA_HOME=/usr/lib/jvm/java-8-oracle
    export PATH=$JAVA_HOME/bin:$PATH
    
    
    # Maven
    export MAVEN_HOME=/opt/maven
    export PATH=$PATH:$MAVEN_HOME/bin
    
    # Tomcat
    export TOMCAT_HOME=/opt/tomcat
    export PATH=$PATH:$TOMCAT_HOME/bin
    
    # XNAT
    export XNAT_HOME=/opt/xnat
    export PATH=$PATH:$XNAT_HOME/bin
  9. Create XNAT database user xnat01:
    sudo su postgres
    createuser -U postgres -S -D -R -P xnat01
    Note: set and remember the password for db user xnat01, you will need it in the XNAT build.properties file.
  10. Create XNAT database:
    sudo su postgres
    createdb -U postgres -O xnat01 xnat
  11. Edit build.properties:
    su xnat
    cd /opt/xnat
    cp build.properties.sample build.properties
    vi build.properties
    and the content should be like below:
    maven.appserver.home = /var/lib/tomcat7
    
    xnat.site.title=XNAT
    xdat.project.name=xnat
    xdat.project.db.name=xnat
    xdat.project.db.driver=org.postgresql.Driver
    xdat.project.db.connection.string=jdbc:postgresql://localhost/xnat
    xdat.project.db.user=xnat01
    xdat.project.db.password=XXXXXXX
    xdat.archive.location=/data/xnat/archive
    xdat.prearchive.location=/data/xnat/prearchive
    xdat.cache.location=/data/xnat/cache
    xdat.ftp.location=/data/xnat/ftp
    xdat.build.location=/data/xnat/build
    xdat.mail.server=mail.yourdomain.org
    xdat.mail.port=25
    xdat.mail.protocol=smtp
    xdat.mail.username=
    xdat.mail.password=
    xdat.mail.admin=admin@xnat.yourdomain.org
    xdat.url=http://192.168.100.12:8080/xnat
    xdat.require_login=true
    xdat.enable_new_registrations=false
    xdat.security.channel=any
    xdat.enable_csrf_token=true
    Note: xdat.url need to be set to the public ip or address instead of localhost if you want the XNAT server to be accessed from other computers.
  12. Edit project.properties file. and replace the 'maven.repo.remote' line with
    maven.repo.remote=https://nrgxnat.artifactoryonline.com/nrgxnat/xnat-maven1
  13. Run setup.sh script
    sudo su xnat
    cd /opt/xnat
    bin/setup.sh
  14. Create Database tables & views:
    cd /opt/xnat
    psql xnat01 -h localhost -d xnat -f deployments/xnat/sql/xnat.sql
    
    Note: you need supply the password for db user xnat01.
  15. Store initial security settings:
    sudo su xnat; cd /opt/xnat/deployments/xnat
    StoreXML -project xnat -l security/security.xml -allowDataDeletion true
  16. Store Example Custom Variable Sets:
    sudo su xnat; cd /opt/xnat/deployments/xnat
    StoreXML -dir ./work/field_groups -u admin -p admin -allowDataDeletion true
  17. Deploy the web app
    sudo su xnat; cd /opt/xnat
    bin/update.sh -Ddeploy=true
  18. Set the ownership of web app directory:
    sudo su chown -R tomcat7:tomcat7 /var/lib/tomcat7/webapps/xnat



Coolpad F1 8297W: How to install custom recovery?








  1. You need to root your 8297W mobile phone first.
  2. After rooting, install Mobile Uncle(YDSS) MTK tools from Google play store.
  3. You can install CWM or TWRP.
  4. Extract the downloaded CWM or TWRP package, copy recovery.img file to your 8297W SD card's root directory.
  5. Open MobileUncle Tools (in your mobile) to install recovery update







see also




Coolpad F1 8297W: How to enter fastboot mode?








How to enter Fastboot Mode

  1. Turn off the mobile.
  2. Hold Volume Up, Volume Down and Power buttons until system starts.







see also




Coolpad F1 8297W: How to enter recovery mode?








How to enter Recovery Mode

  1. Turn off the mobile.
  2. Hold Volume Up and Power buttons until phone starts.
  3. It should display a little Android Icon with message "No command."
  4. Press Power button again to enter Recovery Mode.
  5. Use Volume Down button to move the cursor and use Volume Up button to enter the selected item.







see also




Coolpad F1 8297W: How to root?








Method 1: Use Baidu Root tool. You can try either PC version or Android version:


Method 2: Manual root

  1. Download Official_root.zip and copy it to the phone's SD card.
  2. Turn off the phone.
  3. Hold Volume Up and Power buttons to start the phone and enter Recovery Mode, until see the Android icon with message "No command". Press Power button again to see the menu.
  4. Use Volume Down button to move cursor to "Apply software update from SD card", press Volume Up to select it.
  5. Select Official_root.zip then press Volume Up to install it
  6. After installation, restart the phone. You should see a app named SU.








see also




Coolpad F1 8297W: ROM Update Guide








  1. First, you need to root your coolpad F1 8297W mobile phone.
  2. Install Custom Recovery. You can install eitherCWM or TWRP.
  3. Copy the ROM zip file to your 8297W mobile's SD card.
  4. Turn off the phone.
  5. Hold Volume Up and Power buttons to get into recovery mode.
  6. In the main menu of the recovery mode, select "wipe data/factory reset" to clear all user data.
  7. In the main menu of the recovery mode, select "wipe cache partition" to clear cache.
  8. In the main menu of the recovery mode, select "install zip from sdcard" then select the ROM zip file from SD card to install.
  9. Complete flashing. First reboot may take a while.







see also




rsync script to mirror files/directories








#!/bin/bash

rsync -avx --progress -e ssh "$@"




Python: calculate crc32 checksum for a file








def crc32(path):
    from zlib import crc32
    with open(path, 'r') as f:
        crc = crc32('')
        while True:
            data = f.read(BUFFER_SIZE)
            if not data:
                break
            crc = crc32(data, crc)
    return crc

def main():
    csum = crc32('/tmp/123.dat')
    print(str(hex(csum)))

if __name__ == '__main__'
    main()



Flash Chess Game












Generate a self-signed multiple domain (UCC) SSL certificate








  • Option 1: using openssl
    • Find openssl.cnf
      sudo find / | grep openssl.cnf
      • On Mac OS X, it is /System/Library/OpenSSL/openssl.cnf
      • On Ubuntu Linux, it is /usr/lib/ssl/openssl.cnf
    • Make a copy of openssl.cnf to /tmp/openssl.cnf
      cp /usr/lib/ssl/openssl.cnf /tmp/openssl.cnf
    • Edit /tmp/openssl.cnf and append following line in [v3_ca] section:
      [v3_ca]
      ... ... ...
      subjectAltName = @alternate_names
      
      then append [alternate_names] section:
      [alternate_names]
      DNS.1 = mediaflux.localhost
      DNS.2 = daris.localhost
      
      Also, modify
      copy_extensions = copy
      
      It ensures the SANs are copied into the certificate.
    • Generate private key:
      openssl genrsa -out private.key 3072 -nodes openssl req -new -x509 -key private.key -sha256 -config /tmp/openssl.cnf -out public.crt -days 730 -subj "/C=AU/ST=Victoria/L=Melbourne/O=W/OU=WL/CN=localhost"
  • Option 2: using Java keytool
    • keytool -selfcert -genkeypair -keystore /tmp/certs -alias mflux -storepass password -keyalg "RSA" -validity 3650 -dname "cn=localhost, ou=WL, o=W, l=Melbourne, st=Victoria, c=AU" -ext san=dns:daris.localhost,dns:mediaflux.localhost

see also