zoukankan      html  css  js  c++  java
  • 各种小结

    Implement wget in Java

    URL gotoUrl = new URL(url);
    InputStreamReader isr = new InputStreamReader(gotoUrl.openStream());
    BufferedReader in = new BufferedReader(isr);
    
    FileWriter fw = new FileWriter(filename);
    while ((text = in.readLine()) != null) {
        fw.append(text + "\n");
    }
                
    fw.close();
    in.close();

    Extends std library containers?

    template<typename T>
    class Vector : public std::vector<T>

    That said, you should not extend the standard library containers via inheritance, if for no other reason then because they do not have virtual destructors and it is therefore inherently unsafe.

    If you want to "enhance" std::vector, do so using composition (i.e., with a member variable of std::vector type) or use non-member functions to provide your additional functionality.

    netstat -tulnp 查看监听端口

    sudo apt-get install openssh-server 安装服务器端SSH
     
    删除所有.svn目录
    find . -type d -name ".svn"|xargs rm -rf
     
    adb shell
    su
    ------
    lsmod
    insmod
    rmmod

    提高STL效率

    程序中如果大量使用stl,效率低下,可以在项目预处理宏里面添加

    _HAS_ITERATOR_DEBUGGING=0

    _SECURE_SCL=0

    Gprof使用步骤

    1)加参数进行编译,g++ -pg test.cpp

    2)执行./a.out,会产生gmon.out文件

    3)用gprof命令将结果输出到指定文件,gprof a.out gmon.out> performance.txt

    C语言标准库常用函数

    sizeof(array)以及输出十六进制
    int i[10] = {2, 3,4, 5,0};
    printf("%032X\n", sizeof(i));

     XADD(80486+)

    .global xadd_func /* wrapper function of the xadd instruction */
    xadd_func
    : movl 8(%esp), %eax /* Save the second parameter in eax */ movl 4(%esp), %ecx /* Save the first parameter in ecx */ xadd %eax, (%ecx) /* Exchange and add */ ret

    ARM Code

    while (a <= b) {
        if (a < b)
            b = b - c;
        else
            a = a + c;
    }
    
      ||
      \/
    
    loop:
        CMP          r0, r1
        SUBLT        r1, r1, r2
        ADDEQ        r0, r0, r2
        BLE          loop

    Interrupt

    When an interrupt is sent by the PIC, the PIC will not send another interrupt from that same source until it gets acknowledged through an I/O port. This is because interrupt handlers usually manipulate critical data structures and would not withstand being interrupted by new invocations of themselves (i.e. they are not reentrant). In particular, an interrupt handler must never block on anything. Most interrupt handlers simply make a note of work that must be done as a result of the interrupt, clear the interrupt, then terminate, leaving the work to be done at a more convenient time. Note that it may be possible for one interrupt handler to be interrupted by a different interrupt handler, so long as they do not share data structures.

    Interrupt handler在执行前,会保存之前系统状态,执行完后,会恢复之前的状态。当一个interrupt handler A被interrupt handler B 打断以后,B执行完以后,A就继续执行,只有当handler执行完以后,才会执行之前的被打断的user-level instruction.

    tar命令不包含某个文件进行压缩

    tar cvzf data.tar.gz --exclude=/data/web/aaa --exclude=/data/web/bbb /data/web/
    
    另一种方法,先建立一个文件excludefile,里面写好
    /data/web/aaa
    /data/web/bbb
    
    
    然后tar命令这样:
    tar cvzf data.tar.gz --exclude-from /data/excludefile  /data/web/

     Re-entrant & Interrput handler & Thread-safe

    malloc and printf usually use global structures, and employ lock-based synchronization internally. That's why they're not reentrant.
    
    The malloc function could either be thread-safe or thread-unsafe. Both are not reentrant:
    
    Any thread-unsafe function is not reentrant (reentrant functions are thread-safe by definition). Malloc operates on a global heap, and it's possible that two different invocations of malloc that happen at the same time, return the same memory block. (The 2nd malloc call should happen before an address of the chunkis fetched, but the chunk is not marked as unavailable). This violates the postcondition of malloc, so this implementation would not be re-entrant.
    
    To prevent this effect, a thread-safe implementation of malloc would use lock-based synchronization. However, if malloc is called from signal handler, the following situation may happen:
    
    malloc();            //initial call
      lock(memory_lock); //acquire lock inside malloc implementation
    signal_handler();    //interrupt and process signal
    malloc();            //call malloc() inside signal handler
      lock(memory_lock); //try to acquire lock in malloc implementation
      // DEADLOCK!  We wait for release of memory_lock, but 
      // it won't be released because the original malloc call is interrupted
    This situation won't happen when malloc is simply called from different threads. Indeed, the reentrancy concept goes beyond thread-safety and also requires  functions to work properly even if one of its invocation never terminates. That's basically the reasoning why any function with locks would be not re-entrant.
    
    The printf function also operated on global data. Any output stream usually employs a global buffer attached to the resource data are sent to (a buffer for  terminal, or for a file). The print process is usually a sequence of copying data to buffer and flushing the buffer afterwards. This buffer should be protected by locks in the same way malloc does. Therefore, printf is also non-reentrant.

     malloc size 0

    When void *ptr = malloc(size), size == 0, malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

     MySQL常用命令:

    show databases; /* 显示当前所有数据库 */
    create database test; /* 创建新数据库test */
    use test;           /* 开始使用test */
    create table user (name varchar(20), sex char(1)); /* 创建表格 */
    show tables;   /* 显示test数据库里面的表格 */
    drop table user; /* 删除表格user */
    describe user;    /* 显示fields */
    select * from user /* 显示表内容 */

      max_allowed_packet=500M /* 存大量byte */
      net stop mysql & net start mysql /* windows下重启mysql (管理员权限)*/

    
    增删查改如果嫌麻烦,直接用mysql-front

     Caller save & callee save registers

    %eax, %edx, %ecx
    Caller saves prior to call if values are used later
    
    %eax
    also used to return integer value
    
    %ebx, %esi, %edi
    Callee saves if wants to use them
    
    %esp, %ebp
    special form of callee save
    Restored to original values upon exit from procedure

     Create a file

    When you want to create a file, it is better to use open(pathname, O_RDWR | O_CREAT | O_TRUNC, mode). ~ APUE P63

     char* 与char[]的区别

     char *name1 = "andrew";
     char name2[] = "andrew";
     name1的"andrew"不可变的,企图改变的话,则会产生"segmentation fault"
     name2则可以任意改变

     创建临时文件(mkstemp()函数与unlink()函数)

     Reference: http://www.thegeekstuff.com/2012/06/c-temporary-files/

    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    #include<string.h>
    #include<errno.h>
    
    int main()
    {
        // buffer to hold the temporary file name
        char nameBuff[32];
        // buffer to hold data to be written/read to/from temporary file
        char buffer[24];
        int filedes = -1,count=0;
    
        // memset the buffers to 0
        memset(nameBuff,0,sizeof(nameBuff));
        memset(buffer,0,sizeof(buffer));
    
        // Copy the relevant information in the buffers
        strncpy(nameBuff,"/tmp/myTmpFile-XXXXXX",21);
        strncpy(buffer,"Hello World",11);
    
        errno = 0;
        // Create the temporary file, this function will replace the 'X's
        filedes = mkstemp(nameBuff);
    
        // Call unlink so that whenever the file is closed or the program exits
        // the temporary file is deleted
        unlink(nameBuff);
        if(filedes<1) {
            printf("\n Creation of temp file failed with error [%s]\n",strerror(errno));
            return 1;
        } else {
            printf("\n Temporary file [%s] created\n", nameBuff);
        }
        errno = 0;
        // Write some data to the temporary file
        if(-1 == write(filedes,buffer,sizeof(buffer))) {
            printf("\n write failed with error [%s]\n",strerror(errno));
            return 1;
        }
    
        printf("\n Data written to temporary file is [%s]\n",buffer);
    
        // reset the buffer as it will be used in read operation now
        memset(buffer,0,sizeof(buffer));
        errno = 0;
        // rewind the stream pointer to the start of temporary file
        if(-1 == lseek(filedes,0,SEEK_SET)) {
            printf("\n lseek failed with error [%s]\n",strerror(errno));
            return 1;
        }
        errno=0;
        // read the data from temporary file
        if( (count =read(filedes,buffer,11)) < 11 ) {
            printf("\n read failed with error [%s]\n",strerror(errno));
            return 1;
        }
        // Show whatever is read
        printf("\n Data read back from temporary file is [%s]\n",buffer);
        return 0;
    }

     xxd命令可以查看当前文件的ascii码构成

     FILE *file = fopen(path, "w")直接把原来的文件内容都清空了;char str[100] = {0},初始化为0.

     Debug Log File

    logfile = fopen("cloudfs.log", "w");
    setvbuf(logfile, NULL, _IOLBF, 0); /* To ensure that a log of content is not buffered */
    
    void debug_msg(const char *format, ...) {
        va_list ap;
        va_start(ap, format);
    
        vfprintf(logFile, format, ap);
    }

    C++ LinkedHashMap

    unordered_map < string, list< pair<string, node> >::iterator > mymap;
    list< pair<string, node> > mylist;

    C++ Virtual Destructor & operator overloading

    #include <iostream>
    using namespace std;
    
    class A {
    public:
        A(){}
        virtual ~A() {cout<<"A destructor"<<endl;}
    bool operator > (A &a); };
    class B : public A { public: B(){} ~B() {cout<<"B destructor"<<endl;} }; int main() { B *b = new B(); A *a = b; delete a; return 0; }

     本地排序:只需要定量的额外空间或者不需要额外的空间    稳定排序:若两个元素相等,则其相对位置不变

    Big Endian vs. Little Endian

    Carry out vs. overflow

    The rules for detecting overflow in a two's complement sum are simple:

    1. If the sum of two positive numbers yields a negative result, the sum has overflowed.
    2. If the sum of two negative numbers yields a positive result, the sum has overflowed.
    3. Otherwise, the sum has not overflowed.

    It is important to note the overflow and carry out can each occur without the other.  In unsigned numbers, carry out is equivalent to overflow. In two's complement, carry out tells you nothing about overflow.

    http://sandbox.mc.edu/~bennet/cs110/tc/add.html

    Whether two dateranges are overlapped

    Let ConditionA Mean DateRange A Completely After DateRange B (True if StartA > EndB)
    Let ConditionB Mean DateRange A Completely Before DateRange B (True if EndA < StartB)
    Then Overlap exists if Neither A Nor B is true ( If one range is neither completely after the other, nor completely before the other, then they must overlap)
    Now deMorgan's law says that:
    Not (A Or B) <=> Not A And Not B
    Which means (StartA <= EndB) and (EndA >= StartB)
    NOTE: This includes conditions where the edges overlap exactly. If you wish to exclude that, change the >= operators to >, and <= to <

    Race condition
    - outcome depends on the particular order in which the operations take place

    Deadlock

    s1 = 1 s2=1, deadlock

    p(s1)     p(s2)
    p(s2)     p(s1)
     
    v(s2)     v(s1)
    v(s1)     v(s2)
     
    -123/10 = -12
    -123%10 = -3
     
    一直是用笔记本外接一个大显示器工作,主要工作都在大的显示器操作,笔记本的屏幕太小了。在使用VirtualBox虚拟机的时候发现只要一选择全屏模式,VirtualBox会自动切换到笔记本的小显示器上,用起来很不爽。记得曾经看到过在哪个地方可以修改,找来找去原来不是修改VirtualBox的设置,而是在Guest系统上操作,就在这里:
  • 相关阅读:
    求斐波那契数列的第n项
    八大经典排序算法
    [BZOJ 3083] 遥远的国度
    [BZOJ 3306] 树
    [SCOI 2010] 序列操作
    [AHOI 2013] 差异
    [USACO2006 DEC] Milk Patterns
    [JSOI 2007] 字符加密
    [BZOJ 2588] Count on a tree
    [NOIP 2018 Day1] 简要题解
  • 原文地址:https://www.cnblogs.com/null00/p/2731894.html
Copyright © 2011-2022 走看看