2018年12月29日 星期六
node.js java 連用(g8 王)
const net = require("net");
const host = '127.0.0.1';
const port = 8082;
let count = 0;
http.createServer(function (req, res) {
debugger;
count++;
req.on('data', function(){
debugger;
});
req.on('end', async function () {
debugger;
console.log('count(%d)', count);
let data;
data = await getJavaData(count);
res.writeHead(200, { 'Content-Type': 'text/html' });
let content = `<p>${data}</p>`;
res.end(content);
});
}).listen(3000);
//======================================
function getJavaData(count) {
return new Promise(function (res, rej) {
let data = '';
let time = 0;
const client = net.connect(port, host, function () {
console.log('java connect...');
});
client.on('data', function (_data) {
if (time++ == 0) {
data = _data.toString();
console.log('java count(%s) data(%s) data.length', count, data, data.length);
}
});
client.on('end', function () {
console.log('java end...');
res(data);
});
});
}
//////////////////////////////////////////////////////////////////////////////////////
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test_5;
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import static java.lang.System.out;
/**
*
* @author xman
*/
public class Socket_1 {
ServerSocket ss;
Socket socket;
static int port = 8082;
public Socket_1() throws Exception {
ss = new ServerSocket(port);
while(true){
socket = ss.accept();
out.println("connect");
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("i am java");
ps.close();
socket.close();
out.println("disconnect");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
new Socket_1();
}catch(Exception e){
out.println(e.toString());
}
}
}
2018年12月22日 星期六
java promise
http://ifeve.com/promise-future-callback/
https://github.com/hprose/hprose-java/wiki/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E2%80%94%E2%80%94Promise
https://juejin.im/post/5b126065e51d4506bd72b7cc
https://www.infoq.cn/article/design-patterns-promise https://www.cnkirito.moe/future-and-promise/
interface Closure<E, T> {
public T callback(E in);
public void error(Error err);
}
public class Promise<E> {
protected int status = 0;
protected ArrayList<Closure> jobList = new ArrayList<>();
protected Closure<Promise, Void> job;
protected E data;
public Promise(Closure job){
this.job = job;
// 暴露 resolve, reject
this.job.callback(this);
}
private Promise() {
}
public void resolve(E e){
}
public void reject(String err){
}
protected void reject(Error err){
}
public Promise done(Closure c){
return (new Promise<E>());
}
public Promise error(Closure c){
return (new Promise<E>());
}
}
2018年12月21日 星期五
java 非同步做法
// in: 回傳的資料
public void back(T in);
// 錯誤時要做的事
// err 錯誤訊息
public void error(E err);
}
//----------------------------------------
public class Server_1 {
public Thread asyncGetData(Callback callback) {
out.println("server start");
Thread th_1 = new Thread(() -> {
int time = (int) (Math.random() * 5000);
out.printf("server thread start(%s)\n", time);
try {
Thread.sleep(time);
// 回傳資料
callback.back(time);
out.printf("server thread end(%s)\n", time);
} catch (InterruptedException ex) {
callback.error(ex);
}
});
th_1.start();
return th_1;
}
}
//----------------------------------------
public class Client_1 {
// 資料交換用
int switchData_int;
public void getData(){
out.println("client.getData()");
Server_1 server_1 = new Server_1();
int gg;
Thread th_1 = server_1.asyncGetData(new Callback<Integer, Error>() {
@Override
public void back(Integer in) {
out.println("callback.back");
// 閉包只適用於套嵌的 class
Client_1.this.switchData_int = in;
}
@Override
public void error(Error err) {
}
});
try {
th_1.join();
} catch (InterruptedException ex) {
out.println(ex);
}
out.printf("result(%s)\n------------\n", this.switchData_int);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Client_1 cl = new Client_1();
cl.getData();
cl.getData();
}
}
2018年12月18日 星期二
javascript 另一種模板編組
const evalExpr = /<%=(.+?)%>/g;
const expr = /<%([\s\S]+?)%>/g;
template = template.replace(evalExpr, '`); \n echo( $1 ); \n echo(`');
template = template.replace(expr, '`); \n $1 \n echo(`');
template = 'echo(`' + template + '`);';
console.log(template);
let script =
`let output = "";
function echo(html){
output += html;
}
${template}
return output;`;
return new Function(script);
}
let content = "<ul>\
<% for(let i=0; i < 4; i++){ %>\
<li><%= i %>--${i*2}</li>\
<% } %>\
</ul>";
let res = compile(content);
console.log(res());
console.log('--------------------');
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
https://johnresig.com/blog/javascript-micro-templating/
function compile(template) {
let functionStr = compile_1(template);
functionStr = "data = data || {};\n\
for(let k in data){\n\
let command = 'var '+ k + '= data[\"'+k+'\"];';\n\
eval(command);\n\
}\n\
" + functionStr;
console.log(functionStr);
let fun = new Function('print', 'data', functionStr);
function print(html) {
return html;
}
return (fun).bind(null, print);
}
function compile_1(template) {
const expr = /([\s\S]*?)<%([\s\S]+?)%>/g;
const evalExpr = /([\s\S]*?)<%=([\s\S]+?)%>/g;
reg_1 = /<%[^=-][\s\S]+?%>/;
reg_2 = /<%=[\s\S]+?%>/;
reg_3 = /<%-[^-][\s\S]+?%>/;
let reg = [];
reg.push("(" + reg_1.source + ")");
reg.push("(" + reg_2.source + ")");
reg.push("(" + reg_3.source + ")");
reg = reg.join("|");
reg = `([\\s\\S]*?)(?:${reg})`;
console.log(reg);
reg = RegExp(reg, 'g');
let source = "let source = [];\n";
template = template.replace(reg, function (m, g1, g2, g3, g4) {
debugger;
if (g1) {
source += `source.push(\`${g1}\`);\n`;
}
if (g2) {
// <% %>
g2 = g2.replace(/%>$/, '').replace(/^<%/, '');
source += `\n${g2}\n`;
} else if (g3) {
// <%= %>
g3 = g3.replace(/%>$/, '').replace(/^<%=/, '');
source += `source.push(print(${g3}));\n`;
} else if (g4) {
// <%- %>
g4 = g4.replace(/%>$/, '').replace(/^<%-/, '');
source += `source.push(print(${g4}));\n`;
}
return '';
});
if (template) {
source += `source.push(\`${template}\`);\n`;
}
source += 'return (source.join(""));\n';
return source;
}
let content = "<ul>\
<% for(let i=0; i < a.length; i++){ %>\
<li><%= i*2 %>--${a[i]*2}</li>\
<% } %>\
</ul>";
let res = compile(content);
console.dir(res);
2018年11月21日 星期三
json deepCopy
module.exports = deepCopy;
let jobList = [];
// for test
// 與 JSON.stringify() 對比速度用
function deepCopy(value) {
// debugger;
let dataSet = new DataSet(value);
jobList.push(dataSet);
let index = 0;
while ((dataSet = jobList[index++]) != null) {
// debugger;
let _value = dataSet.originalValue;
if (Array.isArray(_value)) {
for (let i = 0; i < _value.length; i++) {
let v = _value[i];
let ds = new DataSet(v, dataSet, i);
jobList.push(ds);
}
} else if (typeof (_value) == "object") {
for (let k in _value) {
let v = _value[k];
let ds = new DataSet(v, dataSet, k);
jobList.push(ds);
}
} else {
continue;
}
}
//-----------------------
let res;
let d;
while ((d = jobList.pop()) != null) {
res = d;
d.solve();
}
return res.value;
}
//======================================
function DataSet(v, p, k) {
this.parent; // DataSet
this.parentKey;
this.value;
this.originalValue;
this.__construct(v, p, k);
}
(function () {
this.__construct = function (v, p, k) {
this.originalValue = v;
if (p) {
this.parent = p;
this.parentKey = k;
}
this._makeValue();
};
//--------------------------------------
this._makeValue = function () {
if (Array.isArray(this.originalValue)) {
this.value = [];
} else if (typeof (this.originalValue) == "object") {
this.value = {};
} else {
this.value = this.originalValue;
}
};
//--------------------------------------
this.solve = function () {
if (this.parent == null) {
return;
}
let data = this.parent.value;
data[this.parentKey] = this.value;
this._destory();
};
//--------------------------------------
this._destory = function () {
this.parent = undefined;
this.parentKey = undefined;
this.value = undefined;
this.originalValue = undefined;
};
}).call(DataSet.prototype);
2018年11月15日 星期四
2018年11月13日 星期二
java 從網址取得 json data 並解析
package test_4;
import org.json.*;
import java.net.*;
import java.io.*;
import static java.lang.System.out;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author xman
*/
public class T_1 {
public static String getURLContent(String urlPath) throws MalformedURLException, IOException {
String content = "";
HttpURLConnection connection = null;
BufferedReader in;
URL url = null;
url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
} else {
System.out.println("请输入 URL 地址");
return content;
}
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String current;
while ((current = in.readLine()) != null) {
content += current;
}
return content;
}
public static void main(String[] args) throws Exception {
String htmlContent = getURLContent("http://localhost:8081/test_1/JSON/t_1.php");
// out.println(htmlContent);
JSONObject j;
j = new JSONObject(htmlContent);
Iterator<String> it = j.keys();;
while (it.hasNext()) {
String key = it.next();
Object o_1 = j.get(key);
out.printf("(%s)=>(%s)\n", key, o_1.toString());
}
}
}
java 閉包 範例
import static java.lang.System.out;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author xman
*/
public class T_2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int a = 5;
T2_Closure t = (new T2_Closure<Object, Void>() {
@Override
public Void callback(Object in) {
// 引用 a
out.printf("callback(%s)\n", a);
return null;
}
});
t.callback(null);
//------------------------------------
T2_Query q = new T2_Query();
q.query(new T2_Closure<T2_Query, Void>() {
@Override
public Void callback(T2_Query in) {
String res = in.name + " : " + a;
out.println(res);
return null;
}
});
}
}
//--------------------------------------
// 閉包
interface T2_Closure<T, E> {
public E callback(T in);
}
//--------------------------------------
class T2_Query {
String name = "xyz";
void query(T2_Closure closure) {
Thread th = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
out.println(e);
}
closure.callback(T2_Query.this);
});
th.start();
out.println("thread start");
}
}
2018年11月10日 星期六
java callback
/**
*
* @author xman
*/
public class Tt {
String name = "......";
void query(Tool t) {
t.set(this);
}
public static void main(String[] args) {
Tt tt = new Tt();
tt.query(new Tool<Tt>() {
public void set(Tt o) {
out.println(o.name);
}
});
tt.query((o) -> {
// error
out.println(o.name);
});
}
}
interface Tool<T> {
public void set(T in);
}
java 非同步呼叫 callback
public class Ajax_1 {
Callback callback;
String name;
void query(Callback callback) {
this.callback = callback;
// 非同步
Thread t = new Thread(() -> {
// 取得查詢
String name = (new SyncSqlQuery()).query();
Ajax_1.this.name = name;
Ajax_1.this.callback.callback();
});
t.start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Ajax_1 a = new Ajax_1();
int x = 5;
a.query(() -> {
// 及時命令
out.println(a.name);
});
a.query(new Callback(){
public void callback(){
// 及時命令
out.println(a.name);
}
});
}
}
//-------------------------------------------------------
public interface Callback {
void callback();
}
//-------------------------------------------------------
public class SyncSqlQuery {
public static int id = 0;
String query(){
return "SyncSqlQuery_" + id++;
}
}
//////////////////////////////////////////////////////////////////////////
/**
*
* @author xman
*/
public class Ajax_1 {
String name;
void query(Callback callback) {
Thread t = new Thread(() -> {
// 取得查詢
String name = (new SyncSqlQuery()).query();
Ajax_1.this.name = name;
});
t.start();
try {
t.join();
} catch (InterruptedException ex) {
out.println(ex);
}
callback.callback();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Ajax_1 a = new Ajax_1();
int x = 5;
a.query(() -> {
out.println(a.name);
});
a.query(new Callback(){
public void callback(){
out.println(a.name);
}
});
}
}
java inner-class 閉包
public class T_4 {
String name;
String getName() {
return name;
}
//----------------------------
class A {
public void setName(String name) {
T_4.this.name = name;
}
}
//----------------------------
public static void main(String[] args) {
T_4 t = new T_4();
T_4.A a = t.new A();
a.setName("Xman");
out.println(t.getName());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// 運用 lambda
// 比較方便偷懶
interface Callback {
// callback 內容隨你寫....讚
public void callback(String name);
}
//-------------------------------------------
public class T_4 {
String name;
String getName() {
return name;
}
// 送出一個 callback
// 來設定 name
Callback getCallback() {
// lambda 生成一個 匿名 class implements Callback
return ((name) -> {
T_4.this.name = name;
});
}
// ----------------------------
public static void main(String[] args) {
T_4 t = new T_4();
// 藉由 callback 設定 t
t.getCallback().callback("Xyz");
out.println(t.getName());
}
}
2018年11月9日 星期五
java繼承 與變數型態 間的問題
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
T_1_B b = new T_1_B();
b.showName();
T_1_A a = b;
a.showName();
try {
a.getName(); // error
} catch (Exception e) {
out.println(e);
}
}
}
//--------------------------------
class T_1_A {
String name = "G";
void showName() {
out.printf("A(%s)\n", name);
}
}
//--------------------------------
class T_1_B extends T_1_A {
void showName() {
String _name = this.getName();
out.printf("B(%s)\n", name);
}
String getName() {
return name;
}
}
2018年11月3日 星期六
Java中對象的類型判斷
instanceof
判斷一個對象是否是一個類的實例,用Java中自帶的關鍵字instanceof似乎可以做到(僅從關鍵字名稱上可以猜測出),如下面的代碼:
public static void main(String args[]) {
Object i = new Integer(7);
if (i instanceof Number) {
System.out.println("Integer i is a Number");
} else {
System.out.println("Integer i isn't a Number");
}
if (i instanceof Serializable) {
System.out.println("Integer i is a Serializable");
} else {
System.out.println("Integer i isn't a Serializable");
}
if (i instanceof Integer) {
System.out.println("Integer i is an Integer");
} else {
System.out.println("Integer i isn't an Integer");
}
if (i instanceof Float) {
System.out.println("Integer i is a Float");
} else {
System.out.println("Integer i isn't a Float");
}
}
類定義部分為:
public abstract class Number implements java.io.Serializable {}
public final class Integer extends Number implements Comparable<Integer> {}
運行結果:
Console Output :
Integer i is a Number
Integer i is a Serializable
Integer i is an Integer
Integer i isn't a Float
然而好像和預期的不太一樣,能看出,使用該關鍵字不僅可以判斷對象是否是某個類的實例,甚至連該類繼承的基類和實現的接口也都能夠被識別為true,雖然這樣在邏輯上沒有任何問題,是可以把Integer當做一個Number來看來用,也當做一個Serializable來看來用,但是這樣返回的結果就沒有針對性了,太過於模糊,我們如果僅僅需要i instanceof Integer為true該怎麼做呢?
Class.equals
還好在Java有一個叫做Class的類,這是一個用來描述類信息的類,我們如果要精確判斷一個對象是否是具體的一個類的實例,可以這麼做:
public static void main(String args[]) {
Object i = new Integer(7);
if (i.getClass().equals(Number.class)) {
System.out.println("Integer i is a Number");
} else {
System.out.println("Integer i isn't a Number");
}
if (i.getClass().equals(Serializable.class)) {
System.out.println("Integer i is a Serializable");
} else {
System.out.println("Integer i isn't a Serializable");
}
if (i.getClass().equals(Integer.class)) {
System.out.println("Integer i is an Integer");
} else {
System.out.println("Integer i isn't an Integer");
}
if (i.getClass().equals(Float.class)) {
System.out.println("Integer i is a Float");
} else {
System.out.println("Integer i isn't a Float");
}
}
2018年11月2日 星期五
java 區域變數的問題
int[] t = new int[1];
int y; // 會有問題
for (int i = 0; i < d.length; i++) {
t[0] = d[i];
y = d[i];
}
System.out.println("(%d, %d)",t[0], y);
2018年10月25日 星期四
java String, char 間的轉換
char[] bm;
// String 轉 char[]
bm = str.toCharArray();
// char[] 轉 String
str = String.valueOf(bm);
簡化 java System.out.print.*
package com.xyz.util;
import java.io.*;
/**
*
* @author xman
*/
public class Out {
public static void println(Object obj) {
System.out.println(obj);
}
//--------------------------------------------------------------------------
// 换行输出
public static void println() {
System.out.println();
}
//--------------------------------------------------------------------------
// 不换行输出,
public static void print(Object obj) {
System.out.print(obj);
}
//--------------------------------------------------------------------------
public static void printf(String format, Object... args) {
System.out.printf(format, args);
}
}
2018年10月17日 星期三
visual studio code debbuger
// 使用 IntelliSense 以得知可用的屬性。
// 暫留以檢視現有屬性的描述。
// 如需詳細資訊,請瀏覽: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "java Debug (Launch)",
"request": "launch",
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"stopOnEntry": false,
"mainClass": "",
"args": ""
},
{
"name": "nodejs Launch Program",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/app.js"
},
{
"name": "nodejs: Current File",
"type": "node",
"request": "launch",
"program": "${file}"
},
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
},
{
"name": "Python: Attach",
"type": "python",
"request": "attach",
"port": 5678,
"host": "localhost"
},
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"console": "integratedTerminal",
"args": [
"runserver",
"--noreload",
"--nothreading"
],
"django": true
},
{
"name": "Python: Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "app.py"
},
"args": [
"run",
"--no-debugger",
"--no-reload"
],
"jinja": true
},
{
"name": "Python: Current File (External Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "externalTerminal"
}
]
}
2018年10月2日 星期二
jquery 靜態工具
cleanData: 清除 $.data() 資料
cssHooks: css 設定提取所需要的特殊處理
cssNumber: 哪些 css 是數值類
attrHooks: 處理頑疾 attr
support: 檢測瀏覽器的支援
valHooks: 針對 table value
contains(context, elem): context 是否包含 elem
easing: 動畫用的運動函式
$.css:
$.style:
parseHTML(內文, context, option): context 通常指 document, option 若內文含 script 是否要執行
2018年9月26日 星期三
jq 偌多個組件需要統一使用 queue
const queue_1 = {
name: "queue"
};
function t_1() {
$(queue_1).queue(function (next) {
$("#box_1").animate({
left: "+=5%"
}, {
duration: 1000,
queue: false,
complete: function () {
next();
}
})
});
}
2018年9月20日 星期四
2018年8月29日 星期三
php 正則易碰到的問題
printf('<p>%s</p>', $s);
var_dump($s);
$res = preg_replace('/\//', '@', $s);
printf('<p>%s</p><hr>', $res);
//----------------------------
$s = '\\a\\b';
printf('<p>%s</p>', $s);
var_dump($s);
$res = preg_replace('/\\\\/', '@', $s);
printf('<p>%s</p><hr>', $res);
//----------------------------
$s = '\a\b';
printf('<p>%s</p>', $s);
var_dump($s);
$res = preg_replace('/\\\\/', '@', $s);
printf('<p>%s</p><hr>', $res);
----------------------------------------------------------
'/\\\\/' => php string = /\\/ => reg = /\/(匹配 '\')
'///' => php string = /// => reg = error
'/\//' => php string = /\// => reg = ///(匹配 '/')
----------------------------------------------------------
對 php preg來說 (/) 也屬於保留字
----------------------------------------------------------
PHP的跳脫字元
對 "" 來說,對''無用
\$ 顯示金錢符號 $
\" 顯示雙引號符號 "
\' 顯示單引號符號 '
\\ 顯示倒斜線符號 \
\b Backspace鍵
\n 換行符號<br>
\r Return 歸位字元
\t Tab鍵
\000 ~ \377 以16進位表示某一個字元
\x00 ~ \xFF 以8進位表示某一個字元
單引號 ' ' 是連跳脫字元都不處理,也就是 \n 會當成 \ 和 n ,而不是換行!這點要特別注意!很多 bug 就是由此而來,例如 str_replace \n 沒有作用之類的。
附帶一提,雖然單引號 ' ' 裡面不處理跳脫字元,但在單引號 ' ' 裡面要寫 (') 或 (\) 還是要記得跳脫一下,不然 PHP 會無法判斷字串結尾︰
<?php echo '\''; // 會印 ' echo '\\'; // 會印 \ ?>
PHP preg_quote() 函數
PHP 正則表達式(PCRE)preg_last_error 函數用於轉義正則表達式字符。
語法
string preg_quote ( string $str [, string $delimiter = NULL ] ) preg_quote() 需要參數 str 並向其中 每個正則表達式語法中的字符前增加一個反斜線。 這通常用於你有一些運行時字符串 需要作為正則表達式進行匹配的時候。正則表達式特殊字符有: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
參數說明:
- $str: 輸入字符串。
- $delimiter: 如果指定了可選參數 delimiter,它也會被轉義。這通常用於 轉義 PCRE 函數使用的分隔符。 / 是最通用的分隔符。
返回值
返回轉義後的字符串。實例
實例 1
返回 \$40 for a g3\/400
將文本中的單詞替換為斜體
This book is <i>*very*</i> difficult to find.
2018年8月21日 星期二
php 一些取得 object 資訊的 API
get_class(): 取得物件的 className
get_parent_class(): 取得物件繼承者的 className
get_object_vars(): 返回類中所有的非靜態屬性
get_class_methods(): 函數的作用是返回由類的方法名組成的數組
2018年7月25日 星期三
php 讓 container 注入模組的方式
public $name = 'a';
public $age = 19;
public $load;
public function __construct() {
$this->load = new Loader($this);
}
public function getName() {
printf('<p>%s</p>', $this->name);
}
}
// 注入模組
class Loader {
public $container;
public function __construct($container) {
$this->container = $container;
}
public function __get($name) {
if (isset($this->container->$name)) {
return $this->container->$name;
}
}
}
$a = new Container();
$load = $a->load;
var_dump($load->name);
2018年7月20日 星期五
php 取得最上層的 className
$res = $o;
while (TRUE) {
$ref = new ReflectionClass($res);
$r = $ref->getParentClass();
if ($r) {
$ref = $r;
} else {
break;
}
// className
$res = $ref->getName();
}
return $res;
}
2018年6月30日 星期六
php &fn
<?php
function &_copy(){
// 函數(&)的目的
static $data = array();
return $data;
}
// 呼叫函數還是需要&
$a = &_copy();
$a[] = 5;
// 呼叫函數還是需要&
$b = &_copy();
var_dump($a);
var_dump($b);
------------------------------------------------
Example2>>
function &xyz(Array &$d){
return $d;
}
$data_1 = array(5, 1, 6);
$data_2 = &xyz($data_1);
//----------------------------
var_dump($data_2);
//----------------------------
sort($data_1);
var_dump($data_2);
2018年6月13日 星期三
gseries.js
return new Promise(function (res, rej) {
let it = fn();
job(data);
//----------------------------
function job(d) {
// 主要要不斷重複的步驟
let g = it.next(d);
let p = g.value;
// p.then(...)
if (g.done) {
res(p);
} else if (p instanceof Promise) {
p.then(function (d) {
job(d);
}, function (err) {
rej(err);
});
}else{
job(p);
}
}
});
}
java extend 的問題
String name = "A";
public void a(){
System.out.println("i am " + name);
}
public void getName(){
System.out.println(name);
}
}
//=====================================
public class B extends A {
String name = "B";
public void b(){
System.out.println("i am " + name);
}
public void getName(){
System.out.println("extend " + name);
}
}
//=====================================
public static void main(String[] args) {
A a = new B();
a.a(); // i am A
a.getName(); // extend B
//----------------------------
B b = (B)a;
b.a(); // 容易出問題 => i am A
b.getName(); // extend B
b.b(); // i am B
}
2018年6月5日 星期二
讓 js.generator 不斷往下執行
function asynce(index) {
return new Promise(function (res, rej) {
console.log('index(%s) start', index);
setTimeout(function () {
console.log('index(%s) end', index);
res(index);
}, 3000);
});
}
function* main() {
yield asynce(0);
yield asynce(1);
return asynce(2);
}
let p = gseries(main);
--------------------------------------------------------
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
module.exports = gseries;
function gseries(fn, data) {
return new Promise(function (res, rej) {
let it = fn();
job(data);
//----------------------------
function job(d) {
// 主要要不斷重複的步驟
let g = it.next(d);
let p = g.value;
// p.then(...)
if (g.done) {
res(p);
} else if (p instanceof Promise) {
p.then(function (d) {
job(d);
}, function (err) {
rej(err);
});
}else{
job(p);
}
}
});
}
2018年6月2日 星期六
php 檔案鎖定(檔案同步)
PHP flock() 函數
定義和用法
flock() 函數鎖定或釋放文件。若成功,則返回 true。若失敗,則返回 false。
語法
flock(file,lock,block)
| 參數 | 描述 |
|---|---|
| file | 必需。規定要鎖定或釋放的已打開的文件。 |
| lock | 必需。規定要使用哪種鎖定類型。 |
| block | 可選。若設置為 1 或 true,則當進行鎖定時阻擋其他進程。 |
說明
flock() 操作的 file 必須是一個已經打開的文件指針。lock 參數可以是以下值之一:
- 要取得共享鎖定(讀取的程序),將 lock 設為 LOCK_SH(PHP 4.0.1 以前的版本設置為 1)。
- 要取得獨佔鎖定(寫入的程序),將 lock 設為 LOCK_EX(PHP 4.0.1 以前的版本中設置為 2)。
- 要釋放鎖定(無論共享或獨佔),將 lock 設為 LOCK_UN(PHP 4.0.1 以前的版本中設置為 3)。
- 如果不希望 flock() 在鎖定時堵塞,則給 lock 加上 LOCK_NB(PHP 4.0.1 以前的版本中設置為 4)。
提示和註釋
-----------------------------------------------------------
例子
a_1.php>>
<?php
ob_start();
$filename = "a1.txt";
$file = fopen($filename, "r+");
$res = '';
// 排它性的锁定
if (flock($file, LOCK_EX)) {
sleep(15);
while(!feof($file)){
$res .= fgets($file);
}
flock($file, LOCK_UN);
} else {
echo "Error locking file!";
}
fclose($file);
printf('<p>finish(%s)</p>', $res);
-----------------------------------------------------------
a_2.php>>
<?php
ob_start();
$filename = "a1.txt";
$file = fopen($filename, "r+");
$res = '';
// 排它性的锁定
if (flock($file, LOCK_EX)) {
while(!feof($file)){
$res .= fgets($file);
}
flock($file, LOCK_UN);
} else {
echo "Error locking file!";
}
fclose($file);
printf('<p>finish(%s)</p>', $res);
2018年5月31日 星期四
2018年5月29日 星期二
TinyMCE
https://www.tinymce.com/
TinyMCE
http://blog.pulipuli.info/2017/08/htmltinymce-online-html-editor.html
https://ckeditor.com/ckeditor-4/
(html5)
http://xing.github.io/wysihtml5/
(html5)
https://archive.codeplex.com/?p=jhtmlarea
https://github.com/crpietschmann/jHtmlArea
(html5)
http://www.nicedit.com/
https://kevinroth.com/rte/
https://kevinroth.com/rte/demo.htm
http://www.freetextbox.com
http://www.unverse.net
http://markitup.jaysalvat.com/home/
http://www.themaninblue.com/experiment/widgEditor/
http://www.freetextbox.com
http://www.wymeditor.org/demo/
http://www.openwebware.com
http://www.xstandard.com
http://www.nicedit.com/index.php
2018年5月25日 星期五
netbeans 8.0.1 修改行间距
https://svenspruijt.nl/themebuilder/
C:\Users\{Administrator}\AppData\Roaming\NetBeans\8.0\config\Editors\Preferences 目录下
C:\Users\allen\AppData\Roaming\NetBeans\12.0\config\Editors\Preferences\org-netbeans-modules-editor-settings-CustomPreferences.xml
-------------------------------------------------------
org-netbeans-modules-editor-settings-CustomPreferences.xml 文件
<editor-preferences>
//原来的代码
/** 添加的代码 -- 开始 */
<entry javaType="java.lang.Float" name="line-height-correction" xml:space="preserve">
<value><![CDATA[1.20]]></value> //间距数值
</entry>
/** 添加的代码 -- 结束*/
</editor-preferences>
重启netbeans 查看效果
-------------------------------------------------------
更改系統字型大小 >>
....Netbeans/etc/netbeans.conf
netbeans_default_options="....... --fontsize 17"
-------------------------------------------------------
Open netbeans.conf file (etc folder) and add "--fontsize 28" to netbeans_default_options value.
Example:
netbeans_default_options="--fontsize 28 -J-XX:+UseStringDeduplication -J-Xss2m -J-
baidutemplate
<% for(var i = 0; i < 5; i++){ %>\
<% if(i<3){ %>\
<p>111111</p>\
<% _template_fun_array.push(x()); %>\
<% }else{ %>\
<p>222222</p>\
<% } %>\
<% } %>'
紅色的地方可化為 echo (x());
2018年5月16日 星期三
矩陣相乘
a(11)......a(1n)
.
.
a(m1)......a(mn)
--------------------------------------
B(n*p) =
b(11)......b(1p)
.
.
b(n1)......b(np)
--------------------------------------
C(n*p) =
c(11)......c(1p)
.
.
c(n1)......c(np)
--------------------------------------
A*B = C
--------------------------------------
c(11) = a(11)*b(11) + ........+ a(1n)b(n1)
.....
c(1p) = a(11)*b(1p) + ........+ a(1n)b(np)
.....
c(mp) = a(m1)*b(1p) + ........+ a(mn)b(np)
2018年5月11日 星期五
php 另一種引入其他 php檔的方法(處理模板,標籤命令的起手)
<?php
$d = 'hi.........';
$content = sprintf('?>%s', file_get_contents('b.php'));
// 解析,並執行 b.php 裡的內容
$s = eval($content);
// 備用,萬一執行裡面沒有 <?php ?>標籤
echo $s;
-----------------------------------------------------------------------------
b.php>>
printf('<h1>d = %s</h1>', @$d);
java eval()
I could advise you to use Exp4j. It is easy to understand as you can see from the following example code:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
------------------------------------------------------------------------
------------------------------------------------------------------------
------------------------------------------------------------------------
package core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public abstract class FunctionSolver {
public static double solveNumericExpression (String expression) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return solve(expression, new HashMap<>());
}
public static double solveByX (String function, double value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
HashMap<String, Double> values = new HashMap<>();
values.put("x", value);
return solveComplexFunction(function, function, values);
}
public static double solve (String function, HashMap<String,Double> values) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return solveComplexFunction(function, function, values);
}
private static double solveComplexFunction (String function, String motherFunction, HashMap<String, Double> values) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
int position = 0;
while(position < function.length()) {
if (alphabetic.contains(""+function.charAt(position))) {
if (position == 0 || !alphabetic.contains(""+function.charAt(position-1))) {
int endIndex = -1;
for (int j = position ; j < function.length()-1 ; j++) {
if (alphabetic.contains(""+function.charAt(j))
&& !alphabetic.contains(""+function.charAt(j+1))) {
endIndex = j;
break;
}
}
if (endIndex == -1 & alphabetic.contains(""+function.charAt(function.length()-1))) {
endIndex = function.length()-1;
}
if (endIndex != -1) {
String alphabeticElement = function.substring(position, endIndex+1);
if (Arrays.asList(usableMathMethods()).contains(alphabeticElement)) {
//Start analyzing a Math function
int closeParenthesisIndex = -1;
int openedParenthesisquantity = 0;
int commaIndex = -1;
for (int j = endIndex+1 ; j < function.length() ; j++) {
if (function.substring(j,j+1).equals("(")) {
openedParenthesisquantity++;
}else if (function.substring(j,j+1).equals(")")) {
openedParenthesisquantity--;
if (openedParenthesisquantity == 0) {
closeParenthesisIndex = j;
break;
}
}else if (function.substring(j,j+1).equals(",") & openedParenthesisquantity == 0) {
if (commaIndex == -1) {
commaIndex = j;
}else{
throw new IllegalArgumentException("The argument of math function (which is "+alphabeticElement+") has too many commas");
}
}
}
if (closeParenthesisIndex == -1) {
throw new IllegalArgumentException("The argument of a Math function (which is "+alphabeticElement+") hasn't got the closing bracket )");
}
String functionArgument = function.substring(endIndex+2,closeParenthesisIndex);
if (commaIndex != -1) {
double firstParameter = solveComplexFunction(functionArgument.substring(0,commaIndex),motherFunction,values);
double secondParameter = solveComplexFunction(functionArgument.substring(commaIndex+1),motherFunction,values);
Method mathMethod = Math.class.getDeclaredMethod(alphabeticElement, new Class<?>[] {double.class, double.class});
mathMethod.setAccessible(true);
String newKey = getNewKey(values);
values.put(newKey, (Double) mathMethod.invoke(null, firstParameter, secondParameter));
function = function.substring(0, position)+newKey
+((closeParenthesisIndex == function.length()-1)?(""):(function.substring(closeParenthesisIndex+1)));
}else {
double firstParameter = solveComplexFunction(functionArgument, motherFunction, values);
Method mathMethod = Math.class.getDeclaredMethod(alphabeticElement, new Class<?>[] {double.class});
mathMethod.setAccessible(true);
String newKey = getNewKey(values);
values.put(newKey, (Double) mathMethod.invoke(null, firstParameter));
function = function.substring(0, position)+newKey
+((closeParenthesisIndex == function.length()-1)?(""):(function.substring(closeParenthesisIndex+1)));
}
}else if (!values.containsKey(alphabeticElement)) {
throw new IllegalArgumentException("Found a group of letters ("+alphabeticElement+") which is neither a variable nor a Math function: ");
}
}
}
}
position++;
}
return solveBracketsFunction(function,motherFunction,values);
}
private static double solveBracketsFunction (String function,String motherFunction,HashMap<String, Double> values) throws IllegalArgumentException{
function = function.replace(" ", "");
String openingBrackets = "([{";
String closingBrackets = ")]}";
int parenthesisIndex = 0;
do {
int position = 0;
int openParenthesisBlockIndex = -1;
String currentOpeningBracket = openingBrackets.charAt(parenthesisIndex)+"";
String currentClosingBracket = closingBrackets.charAt(parenthesisIndex)+"";
if (contOccouranceIn(currentOpeningBracket,function) != contOccouranceIn(currentClosingBracket,function)) {
throw new IllegalArgumentException("Error: brackets are misused in the function "+function);
}
while (position < function.length()) {
if (function.substring(position,position+1).equals(currentOpeningBracket)) {
if (position != 0 && !operators.contains(function.substring(position-1,position))) {
throw new IllegalArgumentException("Error in function: there must be an operator following a "+currentClosingBracket+" breacket");
}
openParenthesisBlockIndex = position;
}else if (function.substring(position,position+1).equals(currentClosingBracket)) {
if (position != function.length()-1 && !operators.contains(function.substring(position+1,position+2))) {
throw new IllegalArgumentException("Error in function: there must be an operator before a "+currentClosingBracket+" breacket");
}
String newKey = getNewKey(values);
values.put(newKey, solveBracketsFunction(function.substring(openParenthesisBlockIndex+1,position),motherFunction, values));
function = function.substring(0,openParenthesisBlockIndex)+newKey
+((position == function.length()-1)?(""):(function.substring(position+1)));
position = -1;
}
position++;
}
parenthesisIndex++;
}while (parenthesisIndex < openingBrackets.length());
return solveBasicFunction(function,motherFunction, values);
}
private static double solveBasicFunction (String function, String motherFunction, HashMap<String, Double> values) throws IllegalArgumentException{
if (!firstContainsOnlySecond(function, alphanumeric+operators)) {
throw new IllegalArgumentException("The function "+function+" is not a basic function");
}
if (function.contains("**") |
function.contains("//") |
function.contains("--") |
function.contains("+*") |
function.contains("+/") |
function.contains("-*") |
function.contains("-/")) {
/*
* ( -+ , +- , *- , *+ , /- , /+ )> Those values are admitted
*/
throw new IllegalArgumentException("Operators are misused in the function");
}
function = function.replace(" ", "");
int position;
int operatorIndex = 0;
String currentOperator;
do {
currentOperator = operators.substring(operatorIndex,operatorIndex+1);
if (currentOperator.equals("*")) {
currentOperator+="/";
operatorIndex++;
}else if (currentOperator.equals("+")) {
currentOperator+="-";
operatorIndex++;
}
operatorIndex++;
position = 0;
while (position < function.length()) {
if ((position == 0 && !(""+function.charAt(position)).equals("-") && !(""+function.charAt(position)).equals("+") && operators.contains(""+function.charAt(position))) ||
(position == function.length()-1 && operators.contains(""+function.charAt(position)))){
throw new IllegalArgumentException("Operators are misused in the function");
}
if (currentOperator.contains(function.substring(position, position+1)) & position != 0) {
int firstTermBeginIndex = position;
while (firstTermBeginIndex > 0) {
if ((alphanumeric.contains(""+function.charAt(firstTermBeginIndex))) & (operators.contains(""+function.charAt(firstTermBeginIndex-1)))){
break;
}
firstTermBeginIndex--;
}
if (firstTermBeginIndex != 0 && (function.charAt(firstTermBeginIndex-1) == '-' | function.charAt(firstTermBeginIndex-1) == '+')) {
if (firstTermBeginIndex == 1) {
firstTermBeginIndex--;
}else if (operators.contains(""+(function.charAt(firstTermBeginIndex-2)))){
firstTermBeginIndex--;
}
}
String firstTerm = function.substring(firstTermBeginIndex,position);
int secondTermLastIndex = position;
while (secondTermLastIndex < function.length()-1) {
if ((alphanumeric.contains(""+function.charAt(secondTermLastIndex))) & (operators.contains(""+function.charAt(secondTermLastIndex+1)))) {
break;
}
secondTermLastIndex++;
}
String secondTerm = function.substring(position+1,secondTermLastIndex+1);
double result;
switch (function.substring(position,position+1)) {
case "*": result = solveSingleValue(firstTerm,values)*solveSingleValue(secondTerm,values); break;
case "/": result = solveSingleValue(firstTerm,values)/solveSingleValue(secondTerm,values); break;
case "+": result = solveSingleValue(firstTerm,values)+solveSingleValue(secondTerm,values); break;
case "-": result = solveSingleValue(firstTerm,values)-solveSingleValue(secondTerm,values); break;
case "^": result = Math.pow(solveSingleValue(firstTerm,values),solveSingleValue(secondTerm,values)); break;
default: throw new IllegalArgumentException("Unknown operator: "+currentOperator);
}
String newAttribute = getNewKey(values);
values.put(newAttribute, result);
function = function.substring(0,firstTermBeginIndex)+newAttribute+function.substring(secondTermLastIndex+1,function.length());
deleteValueIfPossible(firstTerm, values, motherFunction);
deleteValueIfPossible(secondTerm, values, motherFunction);
position = -1;
}
position++;
}
}while (operatorIndex < operators.length());
return solveSingleValue(function, values);
}
private static double solveSingleValue (String singleValue, HashMap<String, Double> values) throws IllegalArgumentException{
if (isDouble(singleValue)) {
return Double.parseDouble(singleValue);
}else if (firstContainsOnlySecond(singleValue, alphabetic)){
return getValueFromVariable(singleValue, values);
}else if (firstContainsOnlySecond(singleValue, alphanumeric+"-+")) {
String[] composition = splitByLettersAndNumbers(singleValue);
if (composition.length != 2) {
throw new IllegalArgumentException("Wrong expression: "+singleValue);
}else {
if (composition[0].equals("-")) {
composition[0] = "-1";
}else if (composition[1].equals("-")) {
composition[1] = "-1";
}else if (composition[0].equals("+")) {
composition[0] = "+1";
}else if (composition[1].equals("+")) {
composition[1] = "+1";
}
if (isDouble(composition[0])) {
return Double.parseDouble(composition[0])*getValueFromVariable(composition[1], values);
}else if (isDouble(composition[1])){
return Double.parseDouble(composition[1])*getValueFromVariable(composition[0], values);
}else {
throw new IllegalArgumentException("Wrong expression: "+singleValue);
}
}
}else {
throw new IllegalArgumentException("Wrong expression: "+singleValue);
}
}
private static double getValueFromVariable (String variable, HashMap<String, Double> values) throws IllegalArgumentException{
Double val = values.get(variable);
if (val == null) {
throw new IllegalArgumentException("Unknown variable: "+variable);
}else {
return val;
}
}
/*
* FunctionSolver help tools:
*
*/
private static final String alphabetic = "abcdefghilmnopqrstuvzwykxy";
private static final String numeric = "0123456789.";
private static final String alphanumeric = alphabetic+numeric;
private static final String operators = "^*/+-"; //--> Operators order in important!
private static boolean firstContainsOnlySecond(String firstString, String secondString) {
for (int j = 0 ; j < firstString.length() ; j++) {
if (!secondString.contains(firstString.substring(j, j+1))) {
return false;
}
}
return true;
}
private static String getNewKey (HashMap<String, Double> hashMap) {
String alpha = "abcdefghilmnopqrstuvzyjkx";
for (int j = 0 ; j < alpha.length() ; j++) {
String k = alpha.substring(j,j+1);
if (!hashMap.containsKey(k) & !Arrays.asList(usableMathMethods()).contains(k)) {
return k;
}
}
for (int j = 0 ; j < alpha.length() ; j++) {
for (int i = 0 ; i < alpha.length() ; i++) {
String k = alpha.substring(j,j+1)+alpha.substring(i,i+1);
if (!hashMap.containsKey(k) & !Arrays.asList(usableMathMethods()).contains(k)) {
return k;
}
}
}
throw new NullPointerException();
}
public static String[] usableMathMethods () {
/*
* Only methods that:
* return a double type
* present one or two parameters (which are double type)
*/
Method[] mathMethods = Math.class.getDeclaredMethods();
ArrayList<String> usableMethodsNames = new ArrayList<>();
for (Method method : mathMethods) {
boolean usable = true;
int argumentsCounter = 0;
Class<?>[] methodParametersTypes = method.getParameterTypes();
for (Class<?> parameter : methodParametersTypes) {
if (!parameter.getSimpleName().equalsIgnoreCase("double")) {
usable = false;
break;
}else {
argumentsCounter++;
}
}
if (!method.getReturnType().getSimpleName().toLowerCase().equals("double")) {
usable = false;
}
if (usable & argumentsCounter<=2) {
usableMethodsNames.add(method.getName());
}
}
return usableMethodsNames.toArray(new String[usableMethodsNames.size()]);
}
private static boolean isDouble (String number) {
try {
Double.parseDouble(number);
return true;
}catch (Exception ex) {
return false;
}
}
private static String[] splitByLettersAndNumbers (String val) {
if (!firstContainsOnlySecond(val, alphanumeric+"+-")) {
throw new IllegalArgumentException("Wrong passed value: <<"+val+">>");
}
ArrayList<String> response = new ArrayList<>();
String searchingFor;
int lastIndex = 0;
if (firstContainsOnlySecond(""+val.charAt(0), numeric+"+-")) {
searchingFor = alphabetic;
}else {
searchingFor = numeric+"+-";
}
for (int j = 0 ; j < val.length() ; j++) {
if (searchingFor.contains(val.charAt(j)+"")) {
response.add(val.substring(lastIndex, j));
lastIndex = j;
if (searchingFor.equals(numeric+"+-")) {
searchingFor = alphabetic;
}else {
searchingFor = numeric+"+-";
}
}
}
response.add(val.substring(lastIndex,val.length()));
return response.toArray(new String[response.size()]);
}
private static void deleteValueIfPossible (String val, HashMap<String, Double> values, String function) {
if (values.get(val) != null & function != null) {
if (!function.contains(val)) {
values.remove(val);
}
}
}
private static int contOccouranceIn (String howManyOfThatString, String inThatString) {
return inThatString.length() - inThatString.replace(howManyOfThatString, "").length();
}
}




