Saturday, December 28, 2013

2013全年花费统计

房租(包水电和停车位):1500×12
DayCare: 7200
上网:700
电视:0
手机: 600
保险:1440
TTC: 3000
汽油:1000
吃饭:1000×12
衣服及日用品: 1000
其它:1500
RESP: 2500
旅游:5000

合计:54440/年 或 4536/月

Wednesday, December 25, 2013

酱牛肉

原料:牛腱子2条(金钱腱最佳)  大葱1根  姜1块  大料3颗  花椒40颗  桂皮1块  香叶2片  丁香8粒
调料:生抽10汤匙(150ml) 老抽4汤匙(60ml)欣和豆瓣酱4汤匙(60克)如果没有可以不放
做法:

1)一条牛腱子一切两半,洗净后泡入清水中浸泡30分钟,倒掉血水不要。
2)锅中倒入清水,放入牛腱子,大火煮开后,撇去浮沫,然后将牛腱子捞出,煮肉的水倒掉不要。把牛肉放入
冷水中浸泡5分钟至肉块冷却。
3)然后捞出肉,放入锅中,倒入清水煮开后,再撇去少量浮沫,然后放入葱姜和调料包(大料,花椒,桂皮,
香叶,丁香装入一次性无纺布料包),加入豆瓣酱,生抽,老抽搅匀后盖上盖子,改成中小后炖1个半小时。
4)捞出后在室温放置2个小时冷却风干。然后再放回之前的肉汤中,大火煮15分钟即可。
超级啰嗦:
**做酱牛肉要用牛腱子,金钱腱最好。金钱腱就是牛前腱,是牛小腿内1块修长而带筋的肉,肉里有筋,筋里有肉,筋肉纵横交错,层次分明,非常适合用来做酱牛肉。

**酱牛肉要经历2次冷却过程,第一次是撇沫之后,放冷水中浸泡,另一次是炖煮了1个半小时后,拿出来冷却风干2小时,这样做,酱牛肉的口感才劲道。

**酱好的牛肉,完全冷却后再切片,会比热着好切。如果觉得不好切,套上保鲜袋,放冰箱里冷藏半小时再切,会好很多。

**之前,做酱牛肉只是用生抽和老抽,但这次加了些豆瓣酱,味道更加浓郁,好吃。如果没有豆瓣酱,也可以不放。

From
http://blog.sina.com.cn/s/blog_54a625bf0102ebqp.html

已掌握或欲掌握炒菜

蚝油生菜(热锅、热油、不加盐、不用刀)
蒜蓉油菜
素炒胡萝卜丝
西红柿炒鸡蛋/韭菜鸡蛋

清炒虾仁
不腻东坡肉

To do:

清蒸鲈鱼
尖椒牛肉
泡椒猪蹄
花生米

扬州炒饭

不腻东坡肉

不腻东坡肉
1. 五花肉温水搓洗干净
2. 切成2-3cm方块,放入冷水中煮。水开后搅拌撇掉脏东西,拿出来用冷水冲洗。
3. 将葱段、姜片铺在砂锅底,肉皮朝上放入方块肉。先倒老抽少许,再倒生抽(多些),放入3、4个花椒,1、2个草果,1、2片香叶,少许冰糖,再多倒些料酒,最后加冷水盖住肉皮
冰糖加4、5小块即可
4. 大火煮开后文火炖1.5~2.5小时
5. 取出放蒸锅蒸半小时以上

Monday, December 23, 2013

素炒胡萝卜丝

1. 热锅
2. 热油
3. 加蒜末
4. 倒入胡萝卜丝和少许白菜心
5. 翻炒1~2分钟加少许水,加适量盐

关键词: 菜谱 recipe 

Thursday, December 19, 2013

Fettuccine jambalaya or Cajun jambalaya

fettuccine jambalaya:
fettuccine is a kind of pasta, which is a staple food of traditional Italian cuisine.
jambalaya is a Louisiana Creole dish of Spanish and French influence. Louisiana Creole is similar to Cajun cuisine in ingredients (such as the holy
trinity). Holy trinity is the Cajun and Louisiana Creole variant of mirepoix: onions, bell peppers, and celery in roughly equal quantities.

Wednesday, November 27, 2013

Send Email through outlook using Java

Desktop.mail can open outlook with the subject and receipt but it does not support the attachment (RFC 2368)
JMail only supports SMTP, does not support outlook (?)
JMAPI does not support 64bit
The most flexible way should by using VBA
Or use autoit as the general solution

import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URI;

public class MailService {

public static void main(String[] args) throws IOException, AWTException {
Desktop desktop = Desktop.getDesktop();
//does not support attachment
   String message = "mailto:myaccount@gmail.com?subject=New_Profile&body=seeAttachment&Attachment=C:/data/readme.txt";
   URI uri = URI.create(message);
   desktop.mail(uri);
   Robot robot =new Robot();
   robot.delay(2000);
   robot.keyPress(KeyEvent.VK_CONTROL);
   robot.keyPress(KeyEvent.VK_ENTER);
   robot.delay(2000);
   robot.keyRelease(KeyEvent.VK_ENTER);
   robot.keyRelease(KeyEvent.VK_CONTROL);
   System.exit(0);
}

}

Tuesday, November 26, 2013

I will make miracles

  Today my son borrowed a wonderful book from the library. Just copied here to help improve my English:

I will make miracles

Everyone keeps asking me,
When you get older, what will you be?

I say a plumber or pilot.
Or dance the ballet.
Though the truth is I don't really
know what to say.

But today I woke up and peeked out my left eyes.
And the sun had just started to climb to the sky.
That's when I realized it just might be fun
To spend every morning waking the sun.

Then I might stir up the waves in the ocean.
My undersea concert would
rock with commotion!

Next thing I'd do, I'd heal all the sick
With vanilla milk shakes,
creamy and thick!

I'd wake the dead, I'd wake them all,
And give them one last chance
to play ball!

What about the bad guys?
I'd help the police.

We'd send them away
and have some peace!

I'd make the world stop fighting!
I'd get it down in writing!
I'd shout it far and near.
And everyone would hear.

I'd lock the bad guys up in cages
And turn them into wise old sages.

I'll make miracles my mission
And be the number-one magician.

I'll meet everyone on Earth,
and ask about their dreams.
Because life is more,
much more than it seems.

My giant loaf of bread will cure the world of hunger,
And people who eat it will feel ten years younger!
And then for the child who has nothing to wear,
I'll sew her a dress. That will answer her prayer.

I will stamp out earthquakes, floods, and fire-
The world will stop shaking, be cooler and drier.

I will stretch out our days and our nights to feel longer
So everyone has enough time to grow stronger.

I'll fill up world with people who share,
With people who smile, with people who can share.

It might sound like God is who I want to be...
And maybe it's true. But here is the key:

To change the world from dark to bright,
First I should learn to read and write.


Wednesday, November 20, 2013

Friends S0601

chapel
vodka
hiccup
It was such a blur.
What time is your flight?
Are you asking me to have a "frienaissance"?
Where is the waitress? I'm starving.
It's a buffet, man.
How do I tell her without crushing her?
Tennis is more believable.
I can't have a mimosa with breakfast?
We're just gonna get an annulment.
You wanna play some Pai Gow?
Last night we let the dice decide.

Logback

Logback-classic module requires the presence of slf4j-api.jar and logback-core.jar in addition to logback-classic.jar on the classpath.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>
logback is divided into three modules, logback-core, logback-classic and logback-access.
To ensure that all loggers can eventually inherit a level, the root logger always has an assigned level. By default, this level is DEBUG.
the initialization steps that logback follows to try to configure itself:
Logback tries to find a file called logback.groovy in the classpath.
If no such file is found, logback tries to find a file called logback-test.xml in the classpath.
If no such file is found, it checks for the file logback.xml in the classpath..
If neither file is found, logback configures itself automatically using the BasicConfigurator which will cause logging output to be
directed to the console.

Monday, November 11, 2013

Three little pigs

Little pig, little pig, let me come in.
No, no, not by the hair on my chinny chin chin.
Then I'll huff, puff and I'll blow your house in.

Paul said that the wicked wolf was wrong to say "blow your house in", it should be "blow your house down". I didn't believe it and check the story book again. It's really "blow your house in" but "blow in" is a slang for "arrive at a place suddenly". Anyway, it shows that Paul's English is excellent now.

The hair on one's chin is one's beard. In folklore, the beard was always considered special, or magical, or sacred, and taking an oath by one's beard was a standard practice. Notice, by the way, how in Act 4, Scene 1 of Shakespeare's Two Gentleman of Verona the Third Outlaw says (in response to the Second Outlaw's statement that they will listen to Valentine):
Ay, by my beard, will we, for he's a proper man.

Pigs do not have beards, of course, but they may have stray hairs on their chin that can at least serve the purpose for taking an oath.

Blow in: to arrive at a place suddenly, or surprisingly, or with a casual air.

Wednesday, October 2, 2013

The subway mouse

He found an empty corner and built a snug hideout.
Nib loved to come home, wash up and fall asleep surrounded by his colorful treasures.
They scratched, stretched and scampered off.
A train pounded into the station in a cloud of dust.
Another noisy, dirty, dull, grey day.
A gust of wind snatched up the pieces of Nib's ruined nest.
"Goodbye!" He trotted past his cousins.
The next train drowned out their laughter.
Nib curled in a crack to sleep.
Nib saw a jellybean and pounced.
"Drop it!" A big mouse blocked their path. Two others stepped out from behind him.
"Run!" Lola squeaked.
Dodging and darting, they ran the length of the station, with the gang snapping at their tails.
As they plodded along another unending curve, the last train roared past.
"I'm worn thin! ..."
She plucked a feather from under the rail.
"Finders keepers!"
A tiny, far-off note echoed through the tunnel. Nib's fur stood on end. What was that?
As they rounded the corner, a light breeze brushed their whiskers.



Thursday, September 26, 2013

Asset Control Java API samples

Asset Control Java API samples
The sample is based on the official asset control document but it can compile and run with the actual result.
1. Runnable Java sample to get the result for ado query and ado browse query.
package section3;

import java.util.ArrayList;
import java.util.List;

import com.ac.api.data.model.AdoId;
import com.ac.api.data.model.AttributeObjectId;
import com.ac.api.data.model.UserId;
import com.ac.api.data.statics.Ado;
import com.ac.api.data.statics.StaticAttributeValue;
import com.ac.api.error.LogonException;
import com.ac.api.error.RemoteException;
import com.ac.api.error.ServerException;
import com.ac.api.factory.ApiFactory;
import com.ac.api.factory.ApiMetaFactory;
import com.ac.api.factory.DefaultApiMetaFactory;
import com.ac.api.query.AdoBrowseQuery;
import com.ac.api.query.AdoBrowseResult;
import com.ac.api.query.AdoQuery;
import com.ac.api.query.AdoQueryOptions;
import com.ac.api.query.AdoResult;
import com.ac.api.query.QueryFactory;
import com.ac.api.server.ConnectionInfo;
import com.ac.api.server.Installation;
import com.ac.api.server.Installations;
import com.ac.api.server.RemoteServer;
import com.ac.api.server.ServerInterface;

public class ConnExample {

static final String HOST = "cpacnvb01";
static final String INSTANCE = "INSTANCE";
static final String USER = "USER";
static final String PASSWD = "PASSWD";
static final String ADO_ID = "ADO_ID";
static final String SYMBOL = "SYMBOL%";
static final Integer TIMEOUT = 120;
private QueryFactory queryFactory;
private ServerInterface serverInterface;
//also use createTimeSeriesQuery,createListQuery

public static void main(String[] args) throws ServerException {
// new ConnExample().adosQuery();
new ConnExample().browseQuery();
}

private void browseQuery() throws ServerException{
AdoBrowseQuery adoBrowseQuery = queryFactory.createAdoBrowseQuery("symbol like '"+SYMBOL+"'", true, true, false);
AdoBrowseResult adoBrowseResult = serverInterface.adoBrowseQuery(adoBrowseQuery);
for(Ado ado:adoBrowseResult){
System.out.println(ado.getId().getValue()+","+ado.getName());
}
}

private void adosQuery() throws ServerException {
AdoQuery adoQuery = queryFactory.createAdoQuery(AdoId.create(ADO_ID),
new ArrayList<AttributeObjectId>(), AdoQueryOptions.AS_OF_NOW, null,
AdoQueryOptions.CodeOptions.NO_CODES);
AdoResult adoResult = serverInterface.adoQuery(adoQuery);
List<StaticAttributeValue> attributeValues = adoResult.getAdo().getAttributeValues();
for (StaticAttributeValue sav : attributeValues){
System.out.println(sav.getAttributeId().getValue()+","+sav.getValue().toString());
}
}

public ConnExample() throws LogonException, RemoteException {
queryFactory = ApiFactory.getInstance().getQueryFactory();
serverInterface = getServerInterface();
}

private static ServerInterface getServerInterface() throws RemoteException,
LogonException {
final ApiMetaFactory apiFactory = DefaultApiMetaFactory.getInstance();
final RemoteServer remoteServer = apiFactory.getServerFactory()
.createRemoteServer();
final Installations installations = remoteServer.getInstallations(HOST,
null);
final Installation installation = installations
.getInstallation(INSTANCE);
final ConnectionInfo connectionInfo = ConnectionInfo.create(TIMEOUT);
final UserId userId = UserId.create(USER);
remoteServer.connect(installation, userId, PASSWD, connectionInfo);
ServerInterface serverInterface = remoteServer.getServerInterface();
return serverInterface;
}

}

2. Runnable Java sample to get the xml result based on the xml query file for ado query and ado browse
package xml;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;

import com.ac.api.data.model.UserId;
import com.ac.api.error.LogonException;
import com.ac.api.error.RemoteException;
import com.ac.api.error.ServerException;
import com.ac.api.factory.ApiFactory;
import com.ac.api.factory.ApiMetaFactory;
import com.ac.api.factory.DefaultApiMetaFactory;
import com.ac.api.query.QueryResult;
import com.ac.api.query.QuerySpec;
import com.ac.api.server.ConnectionInfo;
import com.ac.api.server.Installation;
import com.ac.api.server.Installations;
import com.ac.api.server.RemoteServer;
import com.ac.api.server.ServerInterface;
import com.ac.api.xml.XmlApiConsumer;
import com.ac.api.xml.XmlApiFormatter;
import com.ac.api.xml.XmlException;

public class XMLExample {

private static final ApiFactory apiFactory = ApiFactory.getInstance();
static final String HOST = "HOST";
static final String INSTANCE = "INSTANCE";
static final String USER = "USER";
static final String PASSWD = "PASSWD";
static final Integer TIMEOUT = 120;
static final String queryFilename = "AdoQuery.xml";
static final String queryBrowseFilename = "AdoBrowseQuery.xml";
static final String queryResultFile = "AdoQueryResult.xml";

public static void main(String[] args) throws XmlException, IOException,
ServerException {
String xmlQuerySpec = getXMLString(new File(queryBrowseFilename));
writeXML(xmlQuerySpec);
}

private static void writeXML(String xmlQuery) throws XmlException,
ServerException, IOException {
StringReader sbReader = new StringReader(xmlQuery);
final XmlApiConsumer consumer = apiFactory.getXmlConsumer();
final QuerySpec querySpec = consumer.getQuerySpec(sbReader);
ServerInterface serverInterface = getServerInterface();
final QueryResult queryResult = querySpec.execute(serverInterface);
final Writer xmlWriter = new FileWriter(queryResultFile);
final XmlApiFormatter xmlFormatter = apiFactory
.getXmlFormatter(xmlWriter);
xmlFormatter.addQueryResult(queryResult);
xmlWriter.close();
}

private static String getXMLString(File file) throws XmlException,
IOException {
final String xmlQuerySpec;
String line = null;
final StringBuffer stringBuffer = new StringBuffer();
final BufferedReader reader = new BufferedReader(new FileReader(
file));
while ((line = reader.readLine()) != null) {
stringBuffer.append(line).append(
System.getProperty("line.separator"));
}
xmlQuerySpec = stringBuffer.toString();
return xmlQuerySpec;
}

private static ServerInterface getServerInterface() throws RemoteException,
LogonException {
final ApiMetaFactory apiFactory = DefaultApiMetaFactory.getInstance();
final RemoteServer remoteServer = apiFactory.getServerFactory()
.createRemoteServer();
final Installations installations = remoteServer.getInstallations(HOST,
null);
final Installation installation = installations
.getInstallation(INSTANCE);
final ConnectionInfo connectionInfo = ConnectionInfo.create(TIMEOUT);
final UserId userId = UserId.create(USER);
remoteServer.connect(installation, userId, PASSWD, connectionInfo);
ServerInterface serverInterface = remoteServer.getServerInterface();
return serverInterface;
}

}

AdoQuery.xml
<?xml version="1.0"?>
<ado-query xmlns="http://www.asset-control.com/xml/api/3.1">
<ado id="ADO.SAMPLEID" />
<attributes default="true" />
<as-of-date timestamp="0" />
<link-options />
</ado-query>

AdoBrowseQuery.xml
<?xml version="1.0"?>
<ado-browse-query xmlns="http://www.asset-control.com/xml/api/3.1">
<query>symbol like 'SYMBOL%'</query>
<options use-inheritance="false" return-name="true" return-details="true" />
</ado-browse-query>

Wednesday, September 25, 2013

disable scientific notation in Java

disable scientific notation in Java
To print the number without scientific notation (keep all numbers and without additional 0), although it's ugly, maybe the best way is to
double d = -0.0000000000000000001;
System.out.println(new BigDecimal(Double.toString(d)).stripTrailingZeros().toPlainString());
---0.0000000000000000001
To disable scientific notation globally, can use AOP or dynamic proxy to intercept Number/Decimal 's toString
On Swing JTable, it's controlled by NumberRenderer/DoubleRenderer, can provide custom render or convert it from database side:
Oracle pl/sql
FUNCTION get_orig_value(pi_value IN NUMBER)
RETURN VARCHAR2
IS
BEGIN
  if pi_value = 0 then
    RETURN '0';
  end if;
  if abs(pi_value) < 1 then
    RETURN TO_CHAR(pi_value,'FM0D9999999999999999999999999999999999999999999999999999999999999');
  else
    RETURN TO_CHAR(pi_value,'TM');
  end if;
END get_orig_value;

Sunday, September 22, 2013

English from my son

ribbit
platypus

Emily tigers:
The little girl has a problem with her temper.
Emily pouted.
Emily growled
...she gave her loudest tiger ROAR!
"Not again!" Mom groaned.
"Come here, you rascal!"
Emily bounded around the room, and bounced out of the window.
"Me!" squealed Emily.
Emily stamped her foot and gave a huge ...
Emily snapped, and swishing her long, curly tail.
"Hello, I'm here!" sang Granny as she pranced through the door.
"Gollygumdrops, it looks like a zoo in here. What's been going on?"
"No need to e scared, pumpkin"
That night, Emily dreamt about being a tiger with Granny.
Granny leapt right over the moon.
Emily didn't dare follow her the.re.
You'll learn.
Emily spotted Dylan Jones making a fort.
"Can I help?" asked Emily.
"Hey, give it back!" shouted Emily, and she crouched down, ready to pounce.
Then she glimpsed over at Granny.
"Yippee!" Dylan whooped as he pedaled past. Emily ignored him.
Emily helped Dylan pick himself up.
"Are you OK?"
Granny grinned and gave Emily a big thumbs-up.
She helped Dad wash up, and she brushed her teeth without even the slightest growl.
She showed Emily how to soar over hedges, scale walls and climb trees.


Friday, September 13, 2013

mvn test

maven test
The test scope is different with JUnit (in Eclipse)
The default includes for maven test will be (from http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html)
<includes>
 <include>**/Test*.java</include>
 <include>**/*Test.java</include>
 <include>**/*TestCase.java</include>
</includes>

Another option is to add the configuration in build plugins like:
            <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.16</version>
        <configuration>
          <excludes>
            <exclude>**/Test*.java</exclude>          
          </excludes>
        </configuration>
      </plugin>

Thursday, September 12, 2013

F6 S01E15

So much bigger than the cubicle. Oh, this is a cube.
Yes indeedy! With a beautiful view of...
I put a roof over your head! If that means nothing....

http://www.hjenglish.com/new/p528572/

Tuesday, August 27, 2013

Oracle 11g new features

select /*+ result_cache */ state_code,count(*) ...
In PL/SQL:
return sales_tax_rate.tax_rate%type  
result_cache
relies_on (sales_tax_rate, customers)
is
l_ret   sales_tax_rate.tax_rate%type;
begin
Notice the clause "relies on" in the function code. It tells the function that the cache depends on those two tables: customers and tax_rate.
If the data in those tables change, the cache needs to be refreshed. The refresh happens automatically without your intervention. If the data
does not change, the cache continues to provide the cached values as quickly as possible. (In Oracle Database 11g Release 2, the function
knows the tables it gets the data from and automatically checks for the data change in them; the RELIES_ON clause is not necessary. The syntax
still allows the table name but it is redundant.)
The cache is for a database instance; not for a session. This ability to make caching in one session available in all others is very
different from using package variables that hold the value in memory, which are visible in a session only.
Furthermore, the package variables have no idea about the underlying table being changed. You have to manually refresh them when the data
changes; otherwise the apps will get stale data. Both SQL Result Cache and PL/SQL Function Cache automatically refresh the cache when the
underlying table data changes; no user intervention is required.

Dynamic SQL:

DBMS_SQL.PARSE(v_cursor, v_plsql, DBMS_SQL.NATIVE);
DBMS_SQL.BIND_VARIABLE(v_cursor, 'jobs', v_jobs);
DBMS_SQL.BIND_VARIABLE(v_cursor, 'empnos', v_empnos);
v_execute := DBMS_SQL.EXECUTE(v_cursor);

pivot and unpivot
SELECT deptno
FROM   emp
PIVOT (SUM(sal)
FOR    deptno IN (10,20,30,40));

PL/SQL note

An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record
—even if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins,
depending on which table's rows are retained (left, right, or both).
A left outer join returns all the values from an inner join plus all values in the left table that do not match to the right table.
This allows us to find an employee's department, but still shows the employee(s) even when they have not been assigned to a department
SELECT *
FROM employee, department
WHERE employee.DepartmentID = department.DepartmentID(+)

Merge Row:
SELECT DepartmentID,
  listagg(LastName, ', ') WITHIN GROUP (ORDER BY LastName) AS LastNames
FROM employee
GROUP BY DepartmentID;

Explain plan is the SQL command that you may use to get Oracle to tell you what the query plan for a given SQL query would be if you
executed it right now in your current environment. The way to read this plan is to turning it into a graph of sorts-an evaluation tree.
From left to right, down to top. Using SQL_TRACE, you can capture the actual plan used at runtime.
AUTOTRACE gives you a look at how much work it actually took to perform your query, providing some important statistics regarding its
actual execution.
TKPROF is real and more powerful.

Currently, there are three transaction isolation levels supported by the Oracle database.  There is a fourth transition isolation level, read uncommitted, that is not supported by Oracle.
 These transaction isolation levels are:
Read Committed
Serializable
Read Only
The read committed transaction isolation level is the Oracle default. With this setting, each query can see only data committed before before the query (not the transaction) began.
Any transaction that executes a given query more than once can experience non-repeatable reads or phantoms.
Unlike the read committed level transactions, serializable isolation level transactions will not experience non-repeatable reads or phantoms.
All queries in an Oracle serializable transaction see the database as of a single point in time
With the Read Only transaction isolation level, only data that was committed at the start of the transaction can be accessed by a query.  No modification to the data is allowed.

Friday, August 23, 2013

Use Nologging tom improve the loading performance

Nologging is designed to handle bulk inserts of data which is reproducable.
Nologging has no effect on update, delete and insert statements.
Nologging can be applied on table or table space

(For Oracle 11g, use APPEND_VALUES instead of APPEND hint to bypass the redo log)

Nologging is active when performing one of the following commands:

direct load (SQL*Loader)
direct load INSERT (using APPEND hint)
CREATE TABLE … AS SELECT
CREATE INDEX
ALTER TABLE MOVE
ALTER TABLE … MOVE PARTITION
ALTER TABLE … SPLIT PARTITION
ALTER TABLE MERGE PARTITION
ALTER TABLE MODIFY PARTITION ADD SUBPARTITON
ALTER TABLE MODIFY PARTITION COALESCE SUBPARTITON
ALTER INDEX … SPLIT PARTITION
ALTER INDEX … REBUILD
ALTER INDEX … REBUILD PARTITION

The test on OIS shows that nologging has no meaning on the runtime:
--nolog1,23-AUG-13 02.27.45.000000000 PM to 23-AUG-13 02.53.10.000000000 PM
--nolog2,23-AUG-13 02.57.04.000000000 PM to 23-AUG-13 03.22.14.000000000 PM
--log,   23-AUG-13 03.31.00.000000000 PM to 23-AUG-13 03.51.56.000000000 PM

create table to hold all weekday for further computation

create table to hold all weekday for further computation
--create table weekday (valuation_date date)
--alter table weekday add primary key (valuation_date);
set serveroutput on
declare
lv_start_date date := trim(to_date('20080201','yyyymmdd'));
lv_date date;
lv_week pls_integer;
begin
  select trim(current_date) into lv_date from dual;
  while lv_start_date <= lv_date loop
    lv_week := to_number(to_char (lv_start_date, 'D')) - 1;
    if lv_week>=1 and lv_week<=5 then
      dbms_output.put_line(lv_start_date);
      insert into weekday values(lv_start_date);
    end if;
    select trim(lv_start_date+1) into lv_start_date from dual;
  end loop;
  commit;
end;
/

JavaFX table is much powerful than Java Swing JTable

JavaFX table is much powerful than Java Swing JTable, for example, to support nested column in the table,
JTable needs to implement by the developer itself (or use the third party more powerful table).
http://www.esus.com/docs/GetQuestionPage.jsp?uid=1272

In JavaFX table, it's very natural:
TableColumn firstEmailCol = new TableColumn("Primary");
TableColumn secondEmailCol = new TableColumn("Secondary");
emailCol.getColumns().addAll(firstEmailCol, secondEmailCol);

http://docs.oracle.com/javafx/2/ui_controls/table-view.htm

Wednesday, August 21, 2013

LinkedHashMap and TreeMap

LinkedHashMap
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
It's used to compare/merge the currency pair list for FX
While TreeMap
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a
Comparator provided at map creation time, depending on which constructor is used.

Tuesday, August 20, 2013

Deploy Java Swing GUI application through JNLP (Java Web Start)

Deploy Java Swing GUI application through JNLP (Java Web Start)
1. Export runnable jar from Eclipse
The image source file may not in the jar. Put them into the jar if they are missing
2. Create keystore and sign the jar
keytool -genkey -keystore midasKeys -alias pengp2
jarsigner -keystore midasKeys midas.jar pengp2
3. Copy the signed jar to Tomcat folder.
4. Check "Keep temporary files on my computer" if there's Found unsigned entry in resource error.

Tuesday, July 30, 2013

Note: How to write SQL injection proof PL/SQL

Use const
Use compile-time-fixed SQL statement text unless you cannotUse compile-time-fixed SQL statement text unless you cannot
Use sql syntax template that constructs run-time-created sql statement text.
Expose the database to clients only via a pl/sql api. Control priviledges so that the client has no direct access to the application's objects of other kinds -- especially tables and views.


check/limit the variable
expose minimal pl/sql api
expose minimal previledge

The & syntax device denotes what we will call a value placeholder; and the &&
syntax device9
 denotes what we will call a simple SQL name placeholder

Note: Doing SQL from PL/SQL: Best and Worst Practices

A must read document for all Oracle PL/SQL developers.
1.
PL/SQL supports three methods for issuing SQL: Embedded SQL, native dynamic sql and dbms_sql api.
alter session is not supported by embedded sql. So use execute immediated 'alter session ...'

2. Use the constant keyword in the declaration of any variable that is not changed after its initialization.
(reduces the surface area of attack for SQL injection)

3. Always specify the authid property explicitly in every PL/SQL unit. definer's or invoker's
procedure p(Input in varchar2) authid Current_User is...

4. To avoid sql injection
Stmt constant varchar2(200) := Replace(
 Template, '&&t',
 Sys.DBMS_Assert.Simple_Sql_Name(The_Table));

5. When the sql statement text cannot be fixed at compile time, strive to sue a fixed syntax template and limit the run-

time variation to the provision of names.

6. Native dynamic sql was introduced as an improvement on the dbms_sql API (it is easier to write and executes faster):
open_cursor(), parse(), define_column(), bind_variable(), execute_and_fetch() and close_cursor()

7. when a PL/SQL subprogram executes a
SQL statement there is at least one, and possibly many, so-called context
switches from the PL/SQL virtual machine, to the SQL virtual machine, and
back to the PL/SQL virtual machine

8.
When many rows are to be selected, and the result set may be arbitrarily big,
process them in batches by using fetch... bulk collect into with the limit clause
inside an infinite loop.

9.
When you have an “upsert” requirement, use merge rather than implementing
update... set row... and providing an exception handler for Dup_Val_On_Index
that implements the corresponding insert.

Friday, July 26, 2013

Oracle PL/SQL interview note

Object type is "known and visible" to Oracle SQL engine AND PL/SQL engine.
Record Type is "known and visible" to PL/SQL engine only.
Left join and right join
Exception
e_integration exception;
pragma exception_init(e_integration,-2291);

raise_application_error(-20001,'The employee has no complementary!');
1) Indexed TABLE
DECLARE
TYPE ename_table_type IS TABLE OF emp.ename%TYPE
   INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
BEGIN
SELECT ename INTO ename_table(-1) FROM emp WHERE empno = 7788;
DBMS_OUTPUT.PUT_LINE('The name is:'||ename_table(-1));
END;
/   
2) Nested table
declare
type ename_table_type is table of emp.ename%type;
ename_table ename_table_type;
begin
ename_table:=ename_table_type('MARY','MARY','MARY');
select ename into ename_table(2) from emp where empno = &no;
dbms_output.put_line('The employee name: '||ename_table(2));
end;
/
3) VARRAY
CREATE TYPE article_type AS OBJECT (
title VARCHAR2(30), pubdate DATE
);
CREATE TYPE article_array IS VARRAY(20) OF article_type;
CREATE TABLE author(
id NUMBER(6),name VARCHAR2(10),article article_array
);


UNION, INTERSECT and MINUS are ordered by the first column while UNION ALL is not ordered.


select the N element order asc:
select * from (select t.*,dense_rank() over (PARTITION BY deptno order by sal) rank from employee t) where rank = N;


Most complicated sql query:


B*Tree index is used mostly (one key to one row/range) while Bitmap index is used for low cardinality data (Y,N and null).

dynamic sql

Oracle PL/SQL note

Oralce PL/SQL
11g new features:
Compound Triggers: define statement triggers and row triggers at the same time
Ordered Triggers: specify "follows ..." to define the order (dependency)
disabled triggers
virtual column
result cache
continue support
straight sequence

The names for exceptions can be referenced in only two ways:
In a RAISE statement in the execution section of the program (to raise the exception),
as in:
RAISE invalid_company_id;
In the WHEN clauses of the exception section (to handle the raised exception), as
in:
WHEN invalid_company_id THEN

You can raise an exception of your own or a system exception. The RAISE
statement can take one of three forms:
RAISE exception_name;
RAISE package_name.exception_name;
RAISE; --Use this form when you want to re-raise (or propagate out) the same exception from within an exception handler
EXCEPTION
WHEN NO_DATA_FOUND
THEN
-- Use common package to record all the "context" information,
-- such as error code, program name, etc.
errlog.putline (company_id_in);
-- And now propagate NO_DATA_FOUND unhandled to the enclosing block.
RAISE;

The advantage to using RAISE_APPLICATION_ERROR instead of RAISE (which can
also raise an application-specific, explicitly declared exception) is that you can associate
an error message with the exception.

When this procedure is run, execution of the current PL/SQL block halts immediately,
and any changes made to OUT or IN OUT arguments (if present and without the
NOCOPY hint) will be reversed. Changes made to global data structures, such as
packaged variables, and to database objects (by executing an INSERT, UPDATE,
MERGE, or DELETE) will not be rolled back. You must execute an explicit ROLLBACK
to reverse the effect of DML operations.
The maximum length string that SQLERRM will return is 512 bytes (in some earlier
versions of Oracle, only 255 bytes). Because of this restriction, Oracle Corporation
recommends that you instead call DBMS_UTILITY.FORMAT_ERROR_STACK
to ensure that you see the full error message string (this built-in will not truncate
until 2,000 bytes).
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE --see the error line number
You should call the DBMS_UTILITY.FORMAT_ERROR_BACKTRACE function in
your exception handler.

In the PL/SQL language, errors of any kind are treated as exceptions—situations that
should not occur—in your program. When an error occurs in PL/SQL, whether it’s a system error or an application error,
an exception is raised. The processing in the current PL/SQL block’s execution section
halts, and control is transferred to the separate exception section of the current block,
if one exists, to handle the exception. You cannot return to that block after you finish
handling the exception. Instead, control is passed to the enclosing block, if any.
There are, in general, two types of exceptions:
System exception
An exception that is defined by Oracle and is usually raised by the PL/SQL runtime
engine when it detects an error condition. Some system exceptions have names,
such as NO_DATA_FOUND, while many others simply have numbers and
descriptions.
Programmer-defined exception
An exception that is defined by the programmer and is therefore specific to the
application at hand. You can associate exception names with specific Oracle errors
using the EXCEPTION_INIT pragma (a compiler directive, requesting a specific
behavior), or you can assign a number and description to that error using
RAISE_APPLICATION_ERROR.

Raise
Stops execution of the current PL/SQL block by notifying the runtime engine of
an error. The database itself can raise exceptions, or your own code can raise an
exception with either the RAISE or RAISE_APPLICATION_ERROR command.
Unhandled exception
An exception is said to go “unhandled” when it propagates without being handled
out of the outermost PL/SQL block. Control then passes back to the host execution
environment, at which point that environment/program determines how to respond
to the exception (roll back the transaction, display an error, ignore it, etc.).
Un-named or anonymous exception
An exception that has an error code and a description associated with it, but does
not have a name that can be used in a RAISE statement or in an exception handler
WHEN clause.
Named exception
An exception that has been given a name, either by Oracle in one of its built-in
packages or by a developer. You can also associate a name with this exception
through the use of the EXCEPTION_INIT pragma, or leave it defined only by its
name (which can be used to both raise and handle the exception).
You declare an exception by listing the name of the exception you want
to raise in your program followed by the keyword EXCEPTION:
exception_name EXCEPTION;



Associative arrays:
like hash table
Nested tables:
unbounded
become sparse through deletions
no inherent order to the elements
PL/SQL and database
varrays:
must specify the max number of elements
never sparse
element order is preserved
PL/SQL and database

Programming Interviews Exposed note

Programming.Interviews.Exposed.2nd.Edition.Apr.2007
If someone is sufficiently impressed by your résumé to want to talk to you, the next step is one or more screening interviews,
usually followed by an on-site interview.
Your performance in on-site interviews is the biggest factor in determining whether you get an offer.
If you make a negative impression at lunch, you may lose your offer. Be polite, and avoid alcohol and messy foods like ribs.
a suit is de rigueur when interviewing at a bank or brokerage, unless of course you’re interviewing on the West Coast.
A standard technical interviewing outfit for men consists of nondenim cotton pants, a collared shirt, and loafers (no sneakers or sandals).
their job is to get you to sign with their company as quickly as possible for as little money as possible.
This shouldn’t be a snap decision - never accept an offer on the spot. Always spend at least a day thinking about important decisions like this;
it’s surprising how much can change in a day.
Don’t let this bullying rush your decision.
In the worst case, the company refuses to change the offer and you’re no worse off than before you tried to negotiate.
Pigs get fat, but hogs get slaughtered.
I’m very pleased to have received the offer, but I’m having a hard time accepting it because it’s not competitive with my other offers.
I keep all my offers confidential, including yours, and feel that it’s unprofessional to give out that sort of information.
I want to thank you again for extending me the offer. I was very impressed with your company, but I’ve decided it’s not the best choice for me right now.
Thank you again, and I appreciate your confidence in me.
Describe the better way to solve the problem, but solve the question as it was asked. For example, if you are asked to solve a certain problem with a hash table,
you might say, “This would be easy with a binary search tree because it’s much easier to extract the largest element, but let’s see how I can solve this with
a hash table …”
Even when you immediately know the answer to a problem, because it’s something you’ve already done before, don’t just blurt it out. Break the answer down into
discrete steps and explain the thought processes behind each step.
Make sure you check your code for all error and special cases, especially boundary conditions.

I guess you’re off the hook!”

java concurrency in practice note

In the absence of synchronization, the compiler, hardware, and runtime are allowed to take substantial liberties with the timing and ordering of actions, such as caching variables in registers or processor-local caches where they are temporarily (or even permanently) invisible to other threads.

Every Java application uses threads. When the JVM starts, it creates threads for JVM housekeeping tasks (garbage collection, finalization) and a main thread for running the main method.

If a TimerTask accesses data that is also accessed by other application threads, then not only must the TimerTask do so in a thread-safe manner, but so must any other classes that access that data. Often the easiest way to achieve this is to ensure that objects accessed by the TimerTask are themselves thread-safe, thus encapsulating the thread safety within the shared objects.

Like servlets, RMI objects should be prepared for multiple simultaneous calls and must provide their own thread safety.

Swing components, such as JTable, are not thread-safe. Instead, Swing programs achieve their thread safety by confining all access to GUI components to the event thread. If an application wants to manipulate the GUI from outside the event thread, it must cause the code that will manipulate the GUI to run in the event thread instead.

Perhaps surprisingly, concurrent programming isn't so much about threads or locks, Writing thread-safe code is, at its core, about managing access to state, and in particular to shared, mutable state. By shared, we mean that a variable could be accessed by multiple threads; by mutable, we mean that its value could change during its lifetime. Whenever more than one thread accesses a given state variable, and one of them might write to it, they all must coordinate their access to it using synchronization. The primary mechanism for synchronization in Java is the synchronized keyword, which provides exclusive locking, but the term "synchronization" also includes the use of volatile variables, explicit locks, and atomic variables.

A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
Thread-safe classes encapsulate any needed synchronization so that clients need not provide their own.

The transient state for a particular computation exists solely in local variables that are stored on the thread's stack and are accessible only to the executing thread. One thread accessing a StatelessFactorizer cannot influence the result of another thread accessing the same StatelessFactorizer; because the two threads do not share state, it is as if they were accessing different instances. Since the actions of a thread accessing a stateless object cannot affect the correctness of operations in other threads, stateless objects are thread-safe.

A race condition occurs when the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime; in other words, when getting the right answer relies on lucky timing. The most common type of race condition is check-then-act, where a potentially stale observation is used to make a decision on what to do next.

To ensure thread safety, check-then-act operations (like lazy initialization) and read-modify-write operations (like increment) must always be atomic. We refer collectively to check-then-act and read-modify-write sequences as compound actions.

When a single element of state is added to a stateless class, the resulting class will be thread-safe if the state is entirely managed by a thread-safe object.

A synchronized block has two parts: a reference to an object that will serve as the lock, and a block of code to be guarded by that lock. A synchronized method is a shorthand for a synchronized block that spans an entire method body, and whose lock is the object on which the method is being invoked. (Static synchronized methods use the Class object for the lock.)
Every Java object can implicitly act as a lock for purposes of synchronization; these built-in locks are called intrinsic locks or monitor locks. The lock is automatically acquired by the executing thread before entering a synchronized block and automatically released when control exits the synchronized block, whether by the normal control path or by throwing an exception out of the block.

Intrinsic locks in Java act as mutexes (or mutual exclusion locks), which means that at most one thread may own the lock. When thread A attempts to acquire a lock held by thread B, A must wait, or block, until B releases it. If B never releases the lock, A waits forever.

When a thread requests a lock that is already held by another thread, the requesting thread blocks. But because intrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds. Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held. In this case, we say that the variable is guarded by that lock.

A common locking convention is to encapsulate all mutable state within an object and to protect it from concurrent access by synchronizing any code path that accesses mutable state using the object's intrinsic lock. This pattern is used by many thread-safe classes, such as Vector and other synchronized collection classes. In such cases, all the variables in an object's state are guarded by the object's intrinsic lock.

Code auditing tools like FindBugs can identify when a variable is frequently but not always accessed with a lock held, which may indicate a bug.

In order to ensure visibility of memory writes across threads, you must use synchronization.
Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread.
Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility.
When an object creates a thread from its constructor, it almost always shares its this reference with the new thread, either explicitly (by passing it to the constructor) or implicitly (because the Thread or Runnable is an inner class of the owning object

If data is only accessed from a single thread, no synchronization is needed. This technique, thread confinement, is one of the simplest ways to achieve thread safety. Swing uses thread confinement extensively. The Swing visual components and data model objects are not thread safe; instead, safety is achieved by confining them to the Swing event dispatch thread. To use Swing properly, code running in threads other than the event thread should not access these objects. (To make this easier, Swing provides the invokeLater mechanism to schedule a Runnable for execution in the event thread.)

Final fields can't be modified (although the objects they refer to can be modified if they are mutable),
Barriers are similar to latches in that they block a group of threads until some event has occurred. The key difference is that with a barrier, all the threads must come together at a barrier point at the same time in order to proceed.

The primary abstraction for task execution in the Java class libraries is not Thread, but Executor

However, Timer has some drawbacks, and ScheduledThreadPoolExecutor should be thought of as its replacement. there is little reason to use Timer in Java 5.0 or later.

single-threaded event queue model: a dedicated thread fetches events off a queue and dispatches them to applicationdefined event handlers.
Single-threaded GUI frameworks achieve thread safety via thread confinement; all GUI objects, including visual components and data models, are accessed exclusively from the event thread. Of course, this just pushes some of the thread safety burden back onto the application developer, who must make sure these objects are properly confined.

The Swing single-thread rule: Swing components and models should be created, modified, and queried only from the event-dispatching thread.













Java OSGI note

OSGi container implementations such as Knopflerfish, Equinox, and Apache Felix allow you to break your application into multiple modules
and thus more easily manage cross-dependencies between them.
Similar to the Java Servlet and EJB specifications, the OSGi specification defines two things: a set of services that an OSGi container
must implement and a contract between the container and
your application. Developing on the OSGi platform means first building your application using OSGi APIs, then deploying it in an OSGi container.
very Eclipse plug-in is essentially an OSGi bundle with some additional Eclipse-specific code.
The OSGi container creates a different class loader for every bundle.

Java Spring note

http://www.tutorialspoint.com/spring/index.htm

Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods.
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.

Java Swing Thread note

A Swing programmer deals with the following kinds of threads:
•Initial threads, the threads that execute initial application code.
•The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
•Worker threads, also known as background threads, where time-consuming background tasks are executed.
The programmer does not need to provide code that explicitly creates these threads: they are provided by the runtime or the Swing framework. The programmer's
job is to utilize these threads to create a responsive, maintainable Swing program.

An initial thread schedules the GUI creation task by invoking javax.swing.SwingUtilities.invokeLater or javax.swing.SwingUtilities.invokeAndWait .
Both of these methods take a single argument: the Runnable that defines the new task. Their only difference is indicated by their names:
invokeLater simply schedules the task and returns; invokeAndWait waits for the task to finish before returning.
You can see examples of this throughout the Swing tutorial:
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        createAndShowGUI();
    }
});

Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must
run on the event dispatch thread.

Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on
this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread
interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification;
these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread.

It's useful to think of the code running on the event dispatch thread as a series of short tasks.Tasks on the event dispatch thread must finish quickly;
if they don't, unhandled events back up and the user interface becomes unresponsive.

If you need to determine whether your code is running on the event dispatch thread, invoke javax.swing.SwingUtilities.isEventDispatchThread.

SwingWorker provides a number of communication and control features:
•The SwingWorker subclass can define a method, done, which is automatically invoked on the event dispatch thread when the background task is finished.
•SwingWorker implements java.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread. Other methods in this interface allow cancellation of the background task and discovering whether the background task has finished or been cancelled.
•The background task can provide intermediate results by invoking SwingWorker.publish, causing SwingWorker.process to be invoked from the event dispatch thread.
•The background task can define bound properties. Changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread.

When writing a multi-threaded application using Swing, there are two constraints to keep in mind:
Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.
Swing components should be accessed on the Event Dispatch Thread only.

Don't invoke get without arguments unless you are confident that the background task is complete or close to completion.

a single cell renderer is generally used to draw all of the cells that contain the same type of data. When the user starts to edit a cell's data, a cell editor takes over the cell, controlling the cell's editing behavior.
To choose the renderer that displays the cells in a column, a table first determines whether you specified a renderer for that particular column. If you did not, then the table invokes the table model's getColumnClass method, which gets the data type of the column's cells. Next, the table compares the column's data type with a list of data types for which cell renderers are registered. This list is initialized by the table, but you can add to it or change it. Currently, tables put the following types of data in the list:

•Boolean — rendered with a check box.
•Number — rendered by a right-aligned label.
•Double, Float — same as Number, but the object-to-text translation is performed by a NumberFormat instance (using the default number format for the current locale).
•Date — rendered by a label, with the object-to-text translation performed by a DateFormat instance (using a short style for the date and time).
•ImageIcon, Icon — rendered by a centered label.
•Object — rendered by a label that displays the object's string value.
Cell editors are chosen using a similar algorithm.

asks described by Callable can throw checked and unchecked exceptions





Java Swing note

Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet
•Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI.
The menu bar is by convention positioned within the top-level container, but outside the content pane.
Although JInternalFrame mimics JFrame, internal frames aren't actually top-level containers.
With the exception of top-level containers, all Swing components whose names begin with "J" descend from the JComponent class.
An opaque component fills its background with its background color.
The z-order determines the order that components are painted. The component with the highest z-order paints first and the component with the lowest z-order paints last. Where components overlap, the component with the lower z-order paints over the component with the higher z-order.
repaint(): Request that all or part of the component be repainted.
void revalidate(): Request that the component and its affected containers be laid out again. You should not generally need to invoke this method unless you explicitly change a component's size/alignment hints after it's visible or change a containment hierarchy after it is visible. Always invoke repaint after revalidate.
void paintComponent(Graphics) Paint the component. Override this method to implement painting for custom components.

Unix shell VI note

Ctrl+a : Moves the cursor to the line start (equivalent to the key
Ctrl+e : (end) moves the cursor to the line end (equivalent to the key
Ctrl+l : Clears the screen content
Ctrl+x Ctrl+e : Edits the current line in the $EDITOR program, or vi if undefined.
CTRL+R in BASH for searching/activating previously executed commands (the contents of ~/.bash_history).

man 7 ascii
cd - Change to the previous working directory

Monday, July 8, 2013

no ads (ads free) merriam webster

import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Robot;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;

import com.sun.glass.events.KeyEvent;

public class MWDict {

private static final boolean AUTO_CLOSE = true;
    public static void main(String[] args) throws Exception {
    String word = "sumo";
    display(word);
    playAudio(word);
    System.exit(0);
    }
   
    public static void display(String word) throws IOException{
    String text = Jsoup.connect("http://www.merriam-webster.com/dictionary/"+word.trim()).get().getElementsByClass("d").outerHtml();
    List<String> lines = new ArrayList<String>();
    lines.add("<html>");
    lines.add(text);
    lines.add("</html>");
    FileUtils.write(new File("test.html"), lines);
    Desktop.getDesktop().browse(new File("test.html").toURI());
    }
   
    public static String getAudioURL(String word) throws IOException{
    String text = Jsoup.connect("http://www.merriam-webster.com/dictionary/"+word).get().getElementsByClass("au").outerHtml();
    String[] elements = text.substring(text.indexOf("(")+1,text.indexOf(")")).replaceAll("'","").split(",");
    String url = "http://www.merriam-webster.com/audio.php?file="+elements[0].trim()+"&word="+elements[1].trim();
    System.out.println("url: "+url);
    return url;
    }
   
    public static void playAudio(String word) throws IOException, URISyntaxException, AWTException, InterruptedException{
    Desktop.getDesktop().browse(new URI(getAudioURL(word)));
    //close
    if(AUTO_CLOSE){
        Thread.sleep(2000);
        Robot robot = new Robot();
        robot.setAutoDelay(200);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_W);
        robot.keyRelease(KeyEvent.VK_W);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }
    }
}

Tuesday, June 25, 2013

How to catch JVM crash

Problem:
 A scheduled task will invoke 3rd party library and sometimes JVM crashes and it cannot be recovered.
Solution:
 Use ProcessBuilder to invoke the possible-crash application. (It works on JRE7, not on JRE6)
public
class CrashExample {
@SuppressWarnings("restriction")
public static void main(String[] args) {
System.
out.println("Hello, I will crash!");
new sun.dc.pr.PathDasher(null);
}
}

import
java.io.IOException;
import
java.util.concurrent.Executors;
import
java.util.concurrent.TimeUnit;
 
public
class FixedTest {
public static void main(String[] args) {
Executors.newScheduledThreadPool(10).scheduleAtFixedRate(
new Runnable() {
volatile int cnt = 0;
volatile boolean is_normal;
@Override
public void run() {
cnt++;
if(is_normal||cnt<5){
System.
out.println("Running..."+cnt);
}
else{
String separator = System.getProperty(
"file.separator");
String classpath = System.getProperty(
"java.class.path");
String path = System.getProperty(
"java.home")
+ separator +
"bin" + separator + "java";
System.
out.println("path="+path);
ProcessBuilder processBuilder =
new ProcessBuilder(path, "-cp",
classpath,
CrashExample.
class.getName());
// processBuilder.inheritIO();
try {
Process process = processBuilder.start();
process.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.
out.println("Running "+cnt);
is_normal = true;
}
}
}, 100, 1000, TimeUnit.
MILLISECONDS);
}
}