2018年11月20日 星期二

Winsock 2 Windows Socket Programming

https://www.tenouk.com/Winsock/Winsock2example.html

Create empty solution
Add input to ws2_32.lib

define _WINSOCK_DEPRECATED_NO_WARNINGS


2018年11月19日 星期一

Git on Windows Shared drive

On Server:
172.16.18.77
3389
git
git
C:\git
share read write to ricky

On your desktop:
map \\172.16.18.77\git to Z:
git clone Z:\MT4Managers

2018年10月18日 星期四

Redis on Windows Visual Studio C++



https://blog.csdn.net/LG1259156776/article/details/54645745


https://github.com/MicrosoftArchive/redis
Download and extract redis-3.0.zip
Open redis-3.0\msvs\RedisServer.sln with Visual Studio Community 2017 v15.8.3
Compile hiredis and Win32_interop projects to generate hiredis.lib and Win32_Interop.lib in redis-3.0\msvs\x64\Debug
Visual Studio > New > Visual C++ > Empty Project > Project1

1. Copy hiredis.lib and Win32_Interop.lib to Project1 folder
2. Copy *.h from redis-3.0\deps\hiredis\ to Project1\deps\hiredis

async.h
dict.h
fmacros.h
hiredis.h
net.h
sds.h
win32_hiredis.h
zmalloc.h

3. Overwrite fmacros.h from redis-3.0\src\fmacros.h to Project1\deps\hiredis\fmacros.h
4. Copy *.h from redis-3.0\src\Win32_Interop\ to Project1\src\Win32_Interop\
5. Copy win32fixes.c from redis-3.0\src\Win32_Interop\win32fixes.c to Project1\win32fixes.c
6. Select x64, Project1 > Properties > C/C++ > General > Additional Include Directories > .\deps\hiredis\;.\src\;

7. create a.cpp and compile


#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <ctime>

#include "hiredis.h"
#define NO_QFORKIMPL // must add this line
#include "Win32_Interop\win32fixes.h"
#pragma comment(lib,"hiredis.lib")  
#pragma comment(lib,"Win32_Interop.lib")  

int main() {

 using namespace std;

 unsigned int j;
 redisContext *c;
 redisReply *reply;

 struct timeval timeout = { 1, 500000 }; // 1.5 seconds  
 c = redisConnectWithTimeout((char*)"127.0.0.1", 6379, timeout);
 if (c->err) {
  printf("Connection error: %s\n", c->errstr);
  exit(1);
 }

 reply = (redisReply *)redisCommand(c, "AUTH foobared");
 printf("AUTH: %s\n", reply->str);
 freeReplyObject(reply);

 clock_t begin = clock();
 for (int i = 0;i<1000; ++i) {
  reply = (redisReply *)redisCommand(c, "publish redisChat %d", i);
  //printf("publish: %s\n", reply->str);
  freeReplyObject(reply);
 }
 clock_t end = clock();
 double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
 printf("elapsed_secs = %f\n", elapsed_secs); // 0.1s for 1000 commands

 /* PING server */
 reply = (redisReply *)redisCommand(c, "PING");
 printf("PING: %s\n", reply->str);
 freeReplyObject(reply);

 /* Set a key */
 reply = (redisReply *)redisCommand(c, "SET %s %s", "foo", "hello world");
 printf("SET: %s\n", reply->str);
 freeReplyObject(reply);

 /* Set a key using binary safe API */
 /*reply = (redisReply *)redisCommand(c, "SET %b %b", "bar", 3, "hello", 5);
 printf("SET (binary API): %s\n", reply->str);
 freeReplyObject(reply);*/

 /* Try a GET and two INCR */
 reply = (redisReply *)redisCommand(c, "GET foo");
 printf("GET foo: %s\n", reply->str);
 freeReplyObject(reply);

 reply = (redisReply *)redisCommand(c, "INCR counter");
 printf("INCR counter: %lld\n", reply->integer);
 freeReplyObject(reply);
 /* again ... */
 reply = (redisReply *)redisCommand(c, "INCR counter");
 printf("INCR counter: %lld\n", reply->integer);
 freeReplyObject(reply);

 /* Create a list of numbers, from 0 to 9 */
 reply = (redisReply *)redisCommand(c, "DEL mylist");
 freeReplyObject(reply);
 for (j = 0; j < 10; j++) {
  char buf[64];

  sprintf_s(buf, 64, "%d", j);
  reply = (redisReply *)redisCommand(c, "LPUSH mylist element-%s", buf);
  freeReplyObject(reply);
 }

 /* Let's check what we have inside the list */
 reply = (redisReply *)redisCommand(c, "LRANGE mylist 0 -1");
 if (reply->type == REDIS_REPLY_ARRAY) {
  for (j = 0; j < reply->elements; j++) {
   printf("%u) %s\n", j, reply->element[j]->str);
   getchar();
  }
 }
 freeReplyObject(reply);

 return 0;

}

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,配置GOPATHGOROOT
    在打开的窗口里输入如下内容,并保存
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"
}

  其他参考:

2023 Promox on Morefine N6000 16GB 512GB

2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...