Author Archives: wudi

C++ – Initialize a two-dimensional vector in C++

1. init two-dimensional with 0 and resize

1
2
3
4
5
6
7
8
9
vector<vector<int>> c(n, vector<int>(m, 0));
 
resize:
// instantiate vector object of type std::vector<int>
std::vector<std::vector<int>> matrix;
 
// resize the vector to M elements of type std::vector<int>,
// each having size N and given default value
matrix.resize(M, std::vector<int>(N, default_value));

2. init with default value

1
2
3
4
5
6
vector<vector<int>> accounts
    {
        {1, 5},
        {7, 3},
        {3, 5}
    };

Spring – MultiValueMap and LinkedMultiValueMap

MultiValueMap is common object type in Spring Utils source code.

Here is an example of how to use it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
MultiValueMap<String, String> multiValueMaps = new LinkedMultiValueMap<String, String>();
multiValueMaps.add("Tom", "Book");
multiValueMaps.add("Tom", "Pen");
 
multiValueMaps.add("ABC", "Company");
multiValueMaps.add("ABC", "WebSite");
 
for(String key: multiValueMaps.keySet()) {
	List<String> value = multiValueMaps.get(key);
	System.out.print(key + "\t");
	for(String s: value) {
		System.out.print(s + "\t");
	}
	System.out.println();
}

Leetcode – 1553. Minimum Number of Days to Eat N Oranges

DP using hashMap

https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.HashMap;
 
public class MinimumNumberofDaystoEatNOranges_5490 {
 
	HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
	public int minDays(int n) {
 
		hashMap.put(1, 1);
		hashMap.put(2, 2);
		hashMap.put(3, 2);
 
 
 
		return foo(n);
    }
 
	public int foo(int n) {		
		if(hashMap.containsKey(n))
			return hashMap.get(n);
 
		int a=Integer.MAX_VALUE,b=Integer.MAX_VALUE,c = Integer.MAX_VALUE;
 
		if(n%3 == 0 && n%2 == 0) {
			b = foo(n/3) + 1;
			a = foo(n/2) + 1;
		} 
		else if (n%3 == 0) {
 
			b = foo(n/3) + 1;
			c = foo(n - 1) + 1;
 
 
		}
		else if(n%2 == 0) {
			a = foo(n/2) + 1;
 
			c = foo(n - 1) + 1;
		}
		else {
			c = foo(n - 1) + 1;
		}
 
		int d = Math.min(Math.min(a,  b), c);
 
		hashMap.put(n, d);
		return d;
	}
 
	public static void main(String[] args) {
		MinimumNumberofDaystoEatNOranges_5490 s = new MinimumNumberofDaystoEatNOranges_5490();
		int n = 84806671;
 
		int result = s.minDays(n);
		System.out.println(result);
	}
}

GCC – Dump all Macro defined in GCC

$ gcc -E -dM – < /dev/null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
#define __SSP_STRONG__ 3
#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 0xffff
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __GCC_IEC_559_COMPLEX 2
#define __UINT_LEAST8_TYPE__ unsigned char
#define __SIZEOF_FLOAT80__ 16
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 0xff
#define __WINT_MAX__ 0xffffffffU
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 0xffffffffffffffffUL
#define __WCHAR_MAX__ 0x7fffffff
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
....

Java – long Value Mod Integer Value

Here is a java code for long % int (long mod int)

long v = 51;
long result = v%(10^9 + 7);

what is result value. it may looks to be surprised that result is 25.

result is supported to be 51.

here is right way to go.

long v = 51;
long result = v%100000007L
int finalResult = (int) result;

Idea here is very clear that we convert long%int to be long%long and convert result to be int.

linux 0.11 kernel – __NR_write and sys_write

Linux-0.11/include/linux/sys.h

1
2
3
4
fn_ptr sys_call_table[] = { sys_setup, sys_exit, sys_fork, sys_read,
sys_write, sys_open, sys_close, sys_waitpid, sys_creat, sys_link,
sys_unlink, sys_execve, sys_chdir, sys_time, sys_mknod, sys_chmod,
sys_chown, sys_break, sys_stat, sys_lseek, sys_getpid, sys_mount, ...}

Linux-0.11/include/unistd.h

1
2
3
4
5
6
7
#define __NR_setup	0	/* used only by init, to get system going */
#define __NR_exit	1
#define __NR_fork	2
#define __NR_read	3
#define __NR_write	4
#define __NR_open	5
#define __NR_close	6

Linux-0.11/lib/open.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
__asm__("int $0x80"
		:"=a" (res)
		:"0" (__NR_open),"b" (filename),"c" (flag),
		"d" (va_arg(arg,int)));
 
#define _syscall0(type,name) \
  type name(void) \
{ \
long __res; \
__asm__ volatile ("int $0x80" \
	: "=a" (__res) \
	: "0" (__NR_##name)); \
if (__res >= 0) \
	return (type) __res; \
errno = -__res; \
return -1; \
}
 
set_system_gate(0x80,&system_call);

tomcat src – org.apache.tomcat.util.Diagnostics.java

this java file is to print out diagnostics for tomcat and jvm system information

the mainly thing is to use java.lang.management.*

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// init Bean class to dump system info
	private static final ClassLoadingMXBean classLoadingMXBean = ManagementFactory.getClassLoadingMXBean();
	private static final CompilationMXBean compilationMXBean = ManagementFactory.getCompilationMXBean();
	private static final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	private static final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
	private static final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
 
	private static final PlatformLoggingMXBean loggingMXBean = ManagementFactory
			.getPlatformMXBean(PlatformLoggingMXBean.class);
	private static final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
	private static final List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory
			.getGarbageCollectorMXBeans();
	private static final List<MemoryManagerMXBean> memoryManagerMXBeans = ManagementFactory.getMemoryManagerMXBeans();
	private static final List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();

One of examples to print out vmName and vmVersion and so on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
StringBuilder sb = new StringBuilder();
 
		synchronized (timeformat) {
			sb.append(timeformat.format(new Date()));
		}
		sb.append(CRLF);
 
		sb.append(requestedSm.getString("diagnostics.vmInfoRuntime"));
		sb.append(":" + CRLF);
		sb.append(INDENT1 + "vmName: " + runtimeMXBean.getVmName() + CRLF);
		sb.append(INDENT1 + "vmVersion: " + runtimeMXBean.getVmVersion() + CRLF);
		sb.append(INDENT1 + "vmVendor: " + runtimeMXBean.getVmVendor() + CRLF);
		sb.append(INDENT1 + "specName: " + runtimeMXBean.getSpecName() + CRLF);
		sb.append(INDENT1 + "specVersion: " + runtimeMXBean.getSpecVersion() + CRLF);
		sb.append(INDENT1 + "specVendor: " + runtimeMXBean.getSpecVendor() + CRLF);
		sb.append(INDENT1 + "managementSpecVersion: " + runtimeMXBean.getManagementSpecVersion() + CRLF);
		sb.append(INDENT1 + "name: " + runtimeMXBean.getName() + CRLF);
		sb.append(INDENT1 + "startTime: " + runtimeMXBean.getStartTime() + CRLF);
		sb.append(INDENT1 + "uptime: " + runtimeMXBean.getUptime() + CRLF);
		sb.append(INDENT1 + "isBootClassPathSupported: " + runtimeMXBean.isBootClassPathSupported() + CRLF);
		sb.append(CRLF);

Python Src – How PyMem_GetAllocator() and PyMem_SetAllocator() work

_PyMem_RawMalloc is calling ‘malloc’ to allocate memory and return pointer
so _PyMem_RawMalloc is equal to ‘malloc’

1
2
3
4
5
6
7
8
9
10
11
static void *
_PyMem_RawMalloc(void *ctx, size_t size)
{
    /* PyMem_RawMalloc(0) means malloc(1). Some systems would return NULL
       for malloc(0), which would be treated as an error. Some platforms would
       return a pointer with no memory behind it, which would break pymalloc.
       To solve these problems, allocate an extra byte. */
    if (size == 0)
        size = 1;
    return malloc(size);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
typedef struct {
    /* user context passed as the first argument to the 4 functions */
    void *ctx;
 
    /* allocate a memory block */
    void* (*malloc) (void *ctx, size_t size);
 
    /* allocate a memory block initialized by zeros */
    void* (*calloc) (void *ctx, size_t nelem, size_t elsize);
 
    /* allocate or resize a memory block */
    void* (*realloc) (void *ctx, void *ptr, size_t new_size);
 
    /* release a memory block */
    void (*free) (void *ctx, void *ptr);
} PyMemAllocatorEx;
 
#define PYRAW_FUNCS _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree // this means
//*ctx = NULL and (*malloc) = _PyMem_RawMalloc = malloc function in c
 
        PyMemAllocatorEx alloc = {NULL, PYRAW_FUNCS}; 
 
// alloc will be assigned to _PyMem_Raw, _PyMem, _PyObject
// for PyMem_GetAllocator, it will get alloc by domain name and pick up one of allocator _PyMem_Raw, _PyMem, _PyObject
        PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
        PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
        PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
void
PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
{
    switch(domain)
    {
    case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
    case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
    case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
    /* ignore unknown domain */
    }
}

There are 3 Domains that are PYMEM_DOMAIN_RAW, PYMEM_DOMAIN_MEM, PYMEM_DOMAIN_OBJ

alloc will be assigned to _PyMem_Raw, _PyMem, _PyObject based on 3 Domains.
for PyMem_GetAllocator, it will get alloc by domain name and pick up one of allocator _PyMem_Raw, _PyMem, _PyObject

Java – Runtime.getRuntime().addShutdownHook()

a useful method when program done and run last step task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
 
public class AddShutdownHookTest {
 
	static class Message extends Thread {
 
		public void run() {
			System.out.println("Bye.");
		}
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
 
			// register Message as shutdown hook
			Runtime.getRuntime().addShutdownHook(new Message());
 
			// print the state of the program
			System.out.println("Program is starting...");
 
			// cause thread to sleep for 3 seconds
			System.out.println("Waiting for 3 seconds...");
			Thread.sleep(3000);
 
			// print that the program is closing
			System.out.println("Program is closing...");
 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Nginx – reverse proxy as load-balance in ubuntu

1. install nginx in ubuntu

1
$ sudo apt install ngnix

2. print ngnix conf path

1
$ sudo ngnix -t

3. create node.conf, in nginx.conf, it would load all file matched *.conf under conf.d/

1
2
$ touch /etc/nginx/conf.d/
$ vim /etc/nginx/conf.d/node.conf

4. node.conf file context.
it is best to keep X-Real-IP and X-Forwarded-For, because in node.js app, it would record client’s ip address into log

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
upstream nodeserver {
   server localhost:3085;
}
 
server {
   listen 8080;
   server_name linode.emacslisp.com;
 
   location /test {
       proxy_pass http://nodeserver;   
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
       proxy_redirect     off;
       proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
       proxy_max_temp_file_size 0;
       proxy_connect_timeout      90;
       proxy_send_timeout         90;
       proxy_read_timeout         90;
       proxy_buffer_size          4k;
       proxy_buffers              4 32k;
       proxy_busy_buffers_size    64k;
       proxy_temp_file_write_size 64k;       
   }
}