2018年10月18日 星期四

Design Data Structure in Redis


Redis Setup
https://redislabs.com/blog/redis-on-windows-10/
Install Ubuntu on Windows by "Windows Feature" GUI or by command line:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

> sudo apt-get update
> sudo apt-get upgrade
> sudo apt-get install redis-server
> redis-cli -v

> $ sudo vi /etc/redis/redis.conf
requirepass foobared

> sudo service redis-server restart

127.0.0.1:6379> get foo
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth foobared
OK
127.0.0.1:6379> get foo
"bar"


Data Structure

class Summary : public Item {
double orders;
double buyVolume;
double buyPrice;
double sellVolume;
double sellPrice;
double profit;
};
class Quote : public Item {

double bid;
double ask;
};

std::unordered_map<std::string, Summary> items;
std::unordered_map<std::string, Quote> items;

Redis Hashes
https://www.tutorialspoint.com/redis/redis_data_types.htm
Redis hashes are key-value pairs.
redis 127.0.0.1:6379> HMSET user:1 username tutorialspoint password 
tutorialspoint points 200 
OK 
redis 127.0.0.1:6379> HGETALL user:1  
1) "username" 
2) "tutorialspoint" 
3) "password" 
4) "tutorialspoint" 
5) "points" 
6) "200"

The above represents

class User {
std::string username;
std::string password;
int points;
};
std::unordered_map<std::string, User> users;
users["1"] = User{"name", "password", 200};


Python get set

import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0, password='foobared')
r.set('foo', 'bar')
print(r.get('foo'))


Python subscribe to Redis
import redis

def main():
    try:
        r = redis.StrictRedis(host='localhost', port=6379, db=0, password='foobared')
        p = r.pubsub()
        p.subscribe('redisChat')
        done = False
        while not done:
            message = p.get_message()
            if message:
                data = message['data']
                if isinstance(data, bytes):
                    print(data)
    except Exception as e:
        print(e)

if __name__=='__main__':
    main()



The End

2018年10月11日 星期四

Event schedule in MySQL 8.0



https://dev.mysql.com/doc/refman/5.7/en/create-event.html

1. Create a sample database

use usersdb;
create table users (id int, name varchar(32), time datetime);
insert into users values (1, "a", NOW());
select * from users;






2. Create event

delimiter |
create event if not exists FiveSeconds on schedule EVERY 5 second
COMMENT 'Saves total number of sessions then clears the table each day'
do
begin
insert into users values (2, "a", NOW());
insert into users values (3, "a", NOW());
set @id = 4;
insert into users values (@id, "a", NOW());
set @id = 5;
insert into users values (@id, "a", NOW());
END |
delimiter ;





































The End


2018年10月1日 星期一

Multiple RDP Sessions on Windows 10 Hyper-V

Hyper V
=======

Hyper V
Version 2 (New)
win10 pro
4096MB
No Check Point
Install from DVD

RDPWrap
=======

https://github.com/stascorp/rdpwrap/releases
RDPWrap-v1.6.2.zip
admin cmd.exe > install.bat

net user
========

net user /add user01 Passw0rd
net localgroup administrators user01 /add
net localgroup "Remote Desktop Users" user01 /add

net user /add user02 Passw0rd
net localgroup administrators user02 /add
net localgroup "Remote Desktop Users" user02 /add

net user /add user03 Passw0rd
net localgroup administrators user03 /add
net localgroup "Remote Desktop Users" user03 /add

net user /add user04 Passw0rd
net localgroup administrators user04 /add
net localgroup "Remote Desktop Users" user04 /add

net user /add user05 Passw0rd
net localgroup administrators user05 /add
net localgroup "Remote Desktop Users" user05 /add

2018年9月27日 星期四

C# Nancy Simple Web Application


https://dotblogs.com.tw/ricochen/2016/12/22/220117


Visual Studio 2017 > New Project > Windows Desktop > .NET Framework Console Application

Install-Package Nancy.Hosting.Self


Program.cs

using Nancy;
using Nancy.Hosting.Self;
using Nancy.ModelBinding;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace ConsoleApp1
{
    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public bool IsAdmin { get; set; }
    }

    public class TestModule : NancyModule
    {
        public TestModule()
        {
            Get["/"] = _ => "Hello Nancy from Get request";

            Post["/"] = _ => "Hello Nancy from Post request";

            Get["/Home"] = Post["/Home"] = parameters =>
            {
                var usersmodel = new List<User>();
                usersmodel.Add(new User { Name = "rico" });
                usersmodel.Add(new User { Name = "sherry" });

                this.ViewBag.data = "From Nancy";

                return View["index.sshtml", usersmodel];
            };

            Get["/User/{Name}"] = p =>
            {
                if (p.Name == "rico")
                    return $"Admini user #{p.Name}!";

                else
                    return $"Normal user #{p.Name}!";
            };

            Post["/RequestBody"] = _ =>
            {
                byte[] data = new byte[this.Request.Body.Length];
                this.Request.Body.Read(data, 0, (int)this.Request.Body.Length);
                string body = System.Text.Encoding.Default.GetString(data);
                User user = JsonConvert.DeserializeObject<User>(body);//Install-Package Nancy.Serialization.JsonNet
                return $"Name:{user.Name} Age:{user.Age} IsAdmin:{user.IsAdmin}";
            };

            Post["/Bind"] = _ =>
            {
                var requestPOCO = this.Bind<User>();
                return $"Name:{requestPOCO.Name}";
            };
        }
    }

    public class ClockModule : NancyModule
    {
        public ClockModule()
        {
            Get["/clock"] = (args) => {
                return new Response
                {
                    ContentType = "text/event-stream",
                    Contents = (Stream stream) =>
                    {
                        var data = Encoding.UTF8.GetBytes("retry: 1000\ndata: " + DateTime.Now.ToString() + "\n\n");
                        stream.Write(data, 0, data.Length);
                        stream.Flush();
                    }
                };
            };
        }
    }

    class Program
    {
        public Program()
        {
            Uri uri = new Uri("http://localhost:9487/");
            HostConfiguration hostConfigs = new HostConfiguration
            {
                UrlReservations = new UrlReservations() { CreateAutomatically = true }
            };
            NancyHost host = new NancyHost(hostConfigs, uri);
            host.Start();
            System.Diagnostics.Process.Start(uri.ToString()+"sse.html");
            Console.WriteLine(uri);
        }

        static void Main(string[] args)
        {
            try
            {
                new Program();
                Console.ReadKey();
            } catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}


views/index.html

<html>
<body>
<h4>@ViewBag.data</h4>
@Each
<p>Name:@Current.Name</p>
@EndEach

<div id="clock">1970-01-01</div>
<script>
new EventSource("/clock").onmessage = function(event) {
    document.getElementById("clock").innerHTML = event.data;
};
</script>

</body>
</html>


Test URL

http://127.0.0.1:9487/
http://127.0.0.1:9487/Home
http://127.0.0.1:9487/User/rico
http://127.0.0.1:9487/User/apple

Postman.exe x64

POST http://127.0.0.1:9487/RequestBody > Body > raw:
{"Name":"Rico","Age":"35","IsAdmin":"true"}

POST http://127.0.0.1:9487/Bind > Body < raw + JSON(application/json)
{"Name":"Rico","Age":"35","IsAdmin":"true"}


Server Sent Event
http://127.0.0.1:9487/clock


End

2018年9月11日 星期二

My SQL locks exceeds the lock table size




Error Code: 1206. The total number of locks exceeds the lock table size


show variables like 'innodb_buffer_pool_size';

innodb_buffer_pool_size 8388608


set global innodb_buffer_pool_size=4g;
Access Denied;


"C:\Program Files\MySQL\MySQL Router 8.0\bin\mysqlrouter.exe" -c "C:\ProgramData\MySQL\MySQL Router\mysqlrouter.conf" --service

C:\ProgramData\MySQL\MySQL Router\mysqlrouter.conf
innodb_buffer_pool_size=8M
innodb_buffer_pool_size=4G

2018年8月10日 星期五

Sublime Text for Golang




Install Sublime Text 3

https://packagecontrol.io/installation#st3
Copy text
import urllib.request,os,hashlib; h = '6f4c264a24d933ce70df5dedcf1dcaee' + 'ebe013ee18cced0ef93d5f746d80ef60'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)


  1. Sublime Text > Ctrl+` 调出控制台, 执行上面网页中的 python代码安装 Package Control
  2. 在sublime中,按住快捷键 shift + ctrl + p,在弹出框中输入install package,并按下回车
  3. 接着,输入gosublime,并按下回车(可能需要稍微等待下,可以看sublime最下面的状态)
  4. gosublime安装完成后,点击菜单项Preferences -> package settings -> GoSublime -> Settings - Uesrs,配置GOPATH,GOROOT
  5. cmd.exe > go env
  6. set GOPATH=C:\Users\ricky\go
  7. set GOROOT=C:\Go
  8. gosublime安装完成后,点击菜单项Preferences -> package settings -> GoSublime -> Settings - Uesrs,配置GOPATH,GOROOT 在打开的窗口里输入如下内容,并保存

{
    "env": {
        "GOPATH": "C:/Users/ricky/go",
        "GOROOT": "C:/Go"
    }
}

配置(可选),点击菜单项Tools->Build System->New Build System,在打开的窗口里输入如下内容,并保存GoNewBuildSystem

{
  "cmd": ["go", "run", "$file_name"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "working_dir": "$file_path",
    "selector": "source.go"
}



https://www.cnblogs.com/simplelovecs/p/5311899.html

安装Golang

go语言主页:
go语言安装下载:
环境变量设置:
  GOROOT:
    GOROOT变量设置go安装的根目录,windows下,通常是 c:\go
  GOPATH:
    GOPATH变量设置go源代码存放的根目录

安装 Sublime Text3

首先,安装 Sublime Text 3:

接着,安装 Sublime Text 3 的 Package Control:

  运行sublime text 3,按下快捷键 ctrl+` 调出控制台,执行上面网页中的 python代码安装 Package Control,然后重启sublime text 3。

最后,安装插件 GoSublime:

  1)在sublime中,按住快捷键 shift + ctrl + p,在弹出框中输入install package,并按下回车
  2)接着,输入gosublime,并按下回车(可能需要稍微等待下,可以看sublime最下面的状态)
  3)gosublime安装完成后,点击菜单项Preferences -> package settings -> GoSublime -> Settings - Uesrs,配置GOPATH,GOROOT
    在打开的窗口里输入如下内容,并保存
1
2
3
4
5
6
{
    "env": {
        "GOPATH": "c:/go",
        "GOROOT": "d:/GoWorkspace"
    }
}
  4)配置(可选),点击菜单项Tools->Build System->New Build System,在打开的窗口里输入如下内容,并保存
1
2
3
4
5
6
{
  "cmd": ["go", "run", "$file_name"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "working_dir": "$file_path",
    "selector": "source.go"
}

  其他参考:

2018年7月31日 星期二

MT4 Leverage, Margin, Balance, Equity, Free Margin

Screenshot Explain
==================

May refer to
https://www.luckscout.com/leverage-margin-balance-equity-free-margin-and-margin-level-in-forex-trading/

Initially I had $200,000.

In trade tab,
I opened buy 1 lot (100 ounces) of GOLD at $1,223.26 (ask price) and I should need to pay $122,326 for GOLD with $77,674 USD left.
At this moment my total balance of all assets is still $200,000 whatever what I bought.

Few days later, bid ask prices are $1,211.94 and $1,222.44.
If I had to sell I would need to sell at bid price, and so my GOLD asset has value of $1,221.94.
Trade tab shows my profit -$132.00 which is ($1,221.94 - $1223.26) x 100 ounces.
Also I need to pay the swap of -$55.31 and so my total profit is -$187.31.

MT4 calculates the equity = $200,000 - $187.31 = $199,812.69
As the marginis fixed at $1000, the Free margin is $198,812.69 / $1,000 * 100% = 19881.27%
MT4 pumping mode publishes the margin level with balance $200,000, equity $199,812, volume 100, margin 1000.
MT4 derives margin free and margin level from equity and margin.




Golden Formula
==============

For each trade, calculate profit by difference of open price and market price, add

-----

In MT4 the profit is a derived value not a stored value.
Profit is derived from Margin where Margin contains equity and balance.

In MT4 ReportAPI ReportSegregated.cpp
Pnl = MarginLevel.equity - MarginLevel.balance
Equity is calculated by UserRecord.balance + UserRecord.Credit + PnL.PnL

2007 to 2023 HP and Dell Servers Comparison

  HP Gen5 to Gen11  using ChatGPT HP ProLiant Gen Active Years CPU Socket Popular HP CPUs Cores Base Clock Max RAM Capacity Comparable Dell ...