Thinking beyond source code

Recording my throughs


  • 首页

  • 关于

  • 归档

  • 标签

Max Flow Min Cut Algorithm.

发表于 2014-05-16 | 分类于 Algorithm

这些算法都是基于Ford-Fulkerson 方法,

这个方法基本上是这样的一个循环:

Cap = 0;
while find Augmenting Path != NIL
Cap += decrease capacity of the Augmenting path

return Cap;

就是循环的寻找Augmenting Path(增广路径), 然后再在图上的边的Capacity(容量)上减去这个值, 这样一直找, 知道找不到增广路径位置。

首先是一个基于BFS(广度有限搜索)的算法, 名字叫做: Edwinds-Karp alg:

下面是一个C++实现:

#include <vector>
#include <unordered_set>
#include <queue>
#include <cmath>
#include <climits>
#include <cstring>

using namespace std;

vector< vector<int> > matrix;
vector< vector<int> > capacity;

int bfs(int source, int size,  int sink) {
    queue<int> q;
    q.push(source);
    int from[size];
    bool visited[size];

    memset(from, -1, sizeof(from));
    memset(visited, false, sizeof(visited));

    visited[source] = true;
    // use bfs find the route to the sink.
    while(!q.empty()) {
        bool found_sink = false;
        int where = q.front();
        q.pop();

        // for each vertex next adjancent to where.
        for (auto next = matrix[where].begin(); next != matrix[where].end(); next++) {
            int val = *next;
            if (visited[val] == true)
                continue;
            if (capacity[where][val] > 0) {
                q.push(val);
                visited[val] = true;
                from[val] = where;
                if (val == sink) {
                    found_sink = true;
                    break;
                }
            }
        }
        if (found_sink)
            break;
    }

    //  then compute the path capacity.
    // Find the critical path from the sink back to source.
    // find the minimal path capacity of the path.
    int where = sink, prev, path_cap = INT_MAX;
    while (from[where] > -1) {
        prev = from[where];
        path_cap = min(path_cap, capacity[prev][where]);
        where = prev;
    }

    // then update the residual network, if no path is found the while loop will not be enter.

    // Then - augment.
    where = sink;
    while (from[where] > -1) {
        prev = from[where];
        capacity[prev][where] -= path_cap;
        capacity[where][prev] += path_cap;
        where = prev;
    }

    // if no path is found, path_cap is infinity.
    // and return the augmenting capacity.
    if (path_cap == INT_MAX)
        return 0;
    else
        return path_cap;
}

int max_flow()
{
    int result = 0, path_cap ;
    while (true) {
        path_cap = bfs(1, 8, 7);
        if (path_cap == 0)
            break;
        else
            result += path_cap;
    }
    return result;
}

这个实现的是基于BFS的。

BFS 里面的循环基本就是一个标准的BFS遍历方法, 检测条件的时候增加了一个路径的Capacity(容量)必须大于0, 这样就不会找到已经满了路径了。顺着source一直走到sink以后, 记录下路径。

然后通过sink反着找到Capacity最小的一条边, 记录这个值。

最后在路径上对于正方向, 减去这个指, 对于反方向, 增加这个值。并且返回这个数值。

这个实现的算法复杂度是O(VE²), 因为BFS的负责读是O(E), 而其他每一次找增广路径的计算的复杂度是O(V)。

 

Notes on Mattt Thompson: Postgres & Rails 4: NoSQL in your SQL Database

发表于 2014-05-16 | 分类于 Rails

Video: https://www.youtube.com/watch?v=HXEb5-9Nt20

记录一些要点,

Postgres 9.2:

- hstore, 在Sql 数据库中加入NoSQL的元素。Rails 4 可以直接使用 t.hstore , 初始化的时候就像Dict一样assign。 非Rails4可以使用这个Gem, activerecord-postgres-hstore。 (create extension hstore)
- Full Text Index: 对于English Native 更加有用吧。
- plv8: Buildin Javascript: node.js的风刮到这里了。可以直接在postgres里面执行javascript, 会让更多的人把应用逻辑写到数据库里把。 当然这样的效率肯定很高。缺点嘛, 就是Vendor Lock了。
- JSON: 直接放进Postgres里面, 可以index等, Postgres有一个Cool Feature。

Rails4:
- hstore, 上面说过了。
- Buildin 高级的Type:
* INET: ipv4, ipv6的类型, 比用string提供更多的功能。
* CIDR: Sub Net 专用类型
* MACADDR: 专用的Mac Address的类型
* UUID: UUID 的类型, 比String的好处在于: 对于支持Buildin UUID 的Database, 这个可以直接BuindIn
* ARRAY: 这个大赞, 比如 这个migration, t.string :tags, array: true 这样就可以存在tags里面存多个值, 如果没有,我通常得新建一张表。

回顾一下, 最赞的地方莫过于hstore & ARRAY

Finally Fix ia32-libs depends error

发表于 2013-06-28 | 分类于 未分类

I'm using Ubuntu 12.04 at work, the laptop is a intel + nvidia video card, so I have tried a lot of solution to fix the 3D issue, but I finally found it introduce a lot of other issue like ia32-libs depends issue.

The log is like this:

/var@jasozhang-nv $ sudo apt-get install ia32-libs
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 ia32-libs : Depends: ia32-libs-multiarch
E: Unable to correct problems, you have held broken packages.

After tried every method on google, all failed.

So I remember I have add lots of ppa which maybe related to this issue.

I tried this:

1. in Update Manager -> Software Sources -> Other Software
Enable *ALL* ppa you have ever installed, what even currently it was disable or not, enable them all.

2. Then, install y-ppa-manager, (method can be search on google).
*Purge* Every ppa you have.

After did this, the package relationship become a normal.

In the end, I think this is a lesson that install ppa, specially big ppa, like xorg-edgers, kubuntu-ppa are very risky. Be caution when you install such ppa.

C++: Disallow evil constructors.

发表于 2013-01-29 | 分类于 C++

I have not write C++ code for years, recently because some reason, also because c++11, have start touch c++.

Today found a very funny macro in google's android c++ code, it maybe very populary in c++ world, but I still want to write some about this.

The macro is like this:

// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) 
  TypeName(const TypeName&);               
  void operator=(const TypeName&)

// An older, deprecated, politically incorrect name for the above.
// NOTE: The usage of this macro was baned from our code base, but some
// third_party libraries are yet using it.
// TODO(tfarina): Figure out how to fix the usage of this macro in the
// third_party libraries and get rid of it.
#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName)

From the comment, you can see this macro declear the copy constructor and assign operator.

If you want to disabllow these two "help" function generated by c++ complier, you can do the macro the private, like this:

class Foo {
public:
  int bar();
private:
DISALLOW_EVIL_CONSTRUCTORS(Foo);
};

This macro will do this for you, generally, you want do this in all you c++ class, except you really need it.

This macro was in many project, like chromium, regex-re2, skia, srec, webrtc, android.

 

Handy One-liners for AWK

发表于 2012-12-22 | 分类于 未分类

This post copy a very handy text about awk, for I can reference in further.
The copyright belongs to the origin auther: Eric Pement.

HANDY ONE-LINERS FOR AWK                                  22 July 2003
compiled by Eric Pement <pemente@northpark.edu>           version 0.22
   Latest version of this file is usually at:
   http://www.student.northpark.edu/pemente/awk/awk1line.txt

USAGE:

    Unix:  awk '/pattern/ {print "$1"}'    # standard Unix shells
 DOS/Win:  awk '/pattern/ {print "$1"}'    # okay for DJGPP compiled
           awk "/pattern/ {print "$1"}"  # required for Mingw32

Most of my experience comes from version of GNU awk (gawk) compiled for
Win32. Note in particular that DJGPP compilations permit the awk script
to follow Unix quoting syntax '/like/ {"this"}'. However, the user must
know that single quotes under DOS/Windows do not protect the redirection
arrows (<, >) nor do they protect pipes (|). Both are special symbols
for the DOS/CMD command shell and their special meaning is ignored only
if they are placed within "double quotes." Likewise, DOS/Win users must
remember that the percent sign (%) is used to mark DOS/Win environment
variables, so it must be doubled (%%) to yield a single percent sign
visible to awk.

If I am sure that a script will NOT need to be quoted in Unix, DOS, or
CMD, then I normally omit the quote marks. If an example is peculiar to
GNU awk, the command 'gawk' will be used. Please notify me if you find
errors or new commands to add to this list (total length under 65
characters). I usually try to put the shortest script first.

FILE SPACING:

 # double space a file
 awk '1;{print ""}'
 awk 'BEGIN{ORS="nn"};1'

 # double space a file which already has blank lines in it. Output file
 # should contain no more than one blank line between lines of text.
 # NOTE: On Unix systems, DOS lines which have only CRLF (rn) are
 # often treated as non-blank, and thus 'NF' alone will return TRUE.
 awk 'NF{print $0 "n"}'

 # triple space a file
 awk '1;{print "n"}'

NUMBERING AND CALCULATIONS:

 # precede each line by its line number FOR THAT FILE (left alignment).
 # Using a tab (t) instead of space will preserve margins.
 awk '{print FNR "t" $0}' files*

 # precede each line by its line number FOR ALL FILES TOGETHER, with tab.
 awk '{print NR "t" $0}' files*

 # number each line of a file (number on left, right-aligned)
 # Double the percent signs if typing from the DOS command prompt.
 awk '{printf("%5d : %sn", NR,$0)}'

 # number each line of file, but only print numbers if line is not blank
 # Remember caveats about Unix treatment of r (mentioned above)
 awk 'NF{$0=++a " :" $0};{print}'
 awk '{print (NF? ++a " :" :"") $0}'

 # count lines (emulates "wc -l")
 awk 'END{print NR}'

 # print the sums of the fields of every line
 awk '{s=0; for (i=1; i<=NF; i++) s=s+$i; print s}'

 # add all fields in all lines and print the sum
 awk '{for (i=1; i<=NF; i++) s=s+$i}; END{print s}'

 # print every line after replacing each field with its absolute value
 awk '{for (i=1; i<=NF; i++) if ($i < 0) $i = -$i; print }'
 awk '{for (i=1; i<=NF; i++) $i = ($i < 0) ? -$i : $i; print }'

 # print the total number of fields ("words") in all lines
 awk '{ total = total + NF }; END {print total}' file

 # print the total number of lines that contain "Beth"
 awk '/Beth/{n++}; END {print n+0}' file

 # print the largest first field and the line that contains it
 # Intended for finding the longest string in field #1
 awk '$1 > max {max=$1; maxline=$0}; END{ print max, maxline}'

 # print the number of fields in each line, fol]+$/,lowed by the line
 awk '{ print NF ":" $0 } '

 # print the last field of each line
 awk '{ print $NF }'

 # print the last field of the last line
 awk '{ field = $NF }; END{ print field }'

 # print every line with more than 4 fields
 awk 'NF > 4'

 # print every line where the value of the last field is > 4
 awk '$NF > 4'

TEXT CONVERSION AND SUBSTITUTION:

 # IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
 awk '{sub(/r$/,"");print}'   # assumes EACH line ends with Ctrl-M

 # IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format
 awk '{sub(/$/,"r");print}'

 # IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format
 awk 1

 # IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
 # Cannot be done with DOS versions of awk, other than gawk:
 gawk -v BINMODE="w" '1' infile >outfile

 # Use "tr" instead.
 tr -d r <infile >outfile            # GNU tr version 1.22 or higher

 # delete leading whitespace (spaces, tabs) from front of each line
 # aligns all text flush left
 awk '{sub(/^[ t]+/, ""); print}'

 # delete trailing whitespace (spaces, tabs) from end of each line
 awk '{sub(/[ t]+$/, "");print}'

 # delete BOTH leading and trailing whitespace from each line
 awk '{gsub(/^[ t]+|[ t]+$/,"");print}'
 awk '{$1=$1;print}'           # also removes extra space between fields

 # insert 5 blank spaces at beginning of each line (make page offset)
 awk '{sub(/^/, "     ");print}'

 # align all text flush right on a 79-column width
 awk '{printf "%79sn", $0}' file*

 # center all text on a 79-character width
 awk '{l=length();s=int((79-l)/2); printf "%"(s+l)"sn",$0}' file*

 # substitute (find and replace) "foo" with "bar" on each line
 awk '{sub(/foo/,"bar");print}'           # replaces only 1st instance
 gawk '{$0=gensub(/foo/,"bar",4);print}'  # replaces only 4th instance
 awk '{gsub(/foo/,"bar");print}'          # replaces ALL instances in a line

 # substitute "foo" with "bar" ONLY for lines which contain "baz"
 awk '/baz/{gsub(/foo/, "bar")};{print}'

 # substitute "foo" with "bar" EXCEPT for lines which contain "baz"
 awk '!/baz/{gsub(/foo/, "bar")};{print}'

 # change "scarlet" or "ruby" or "puce" to "red"
 awk '{gsub(/scarlet|ruby|puce/, "red"); print}'

 # reverse order of lines (emulates "tac")
 awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*

 # if a line ends with a backslash, append the next line to it
 # (fails if there are multiple lines ending with backslash...)
 awk '/$/ {sub(/$/,""); getline t; print $0 t; next}; 1' file*

 # print and sort the login names of all users
 awk -F ":" '{ print $1 | "sort" }' /etc/passwd

 # print the first 2 fields, in opposite order, of every line
 awk '{print $2, $1}' file

 # switch the first 2 fields of every line
 awk '{temp = $1; $1 = $2; $2 = temp}' file

 # print every line, deleting the second field of that line
 awk '{ $2 = ""; print }'

 # print in reverse order the fields of every line
 awk '{for (i=NF; i>0; i--) printf("%s ",i);printf ("n")}' file

 # remove duplicate, consecutive lines (emulates "uniq")
 awk 'a !~ $0; {a=$0}'

 # remove duplicate, nonconsecutive lines
 awk '! a[$0]++'                     # most concise script
 awk '!($0 in a) {a[$0];print}'      # most efficient script

 # concatenate every 5 lines of input, using a comma separator
 # between fields
 awk 'ORS=%NR%5?",":"n"' file

SELECTIVE PRINTING OF CERTAIN LINES:

 # print first 10 lines of file (emulates behavior of "head")
 awk 'NR < 11'

 # print first line of file (emulates "head -1")
 awk 'NR>1{exit};1'

  # print the last 2 lines of a file (emulates "tail -2")
 awk '{y=x "n" $0; x=$0};END{print y}'

 # print the last line of a file (emulates "tail -1")
 awk 'END{print}'

 # print only lines which match regular expression (emulates "grep")
 awk '/regex/'

 # print only lines which do NOT match regex (emulates "grep -v")
 awk '!/regex/'

 # print the line immediately before a regex, but not the line
 # containing the regex
 awk '/regex/{print x};{x=$0}'
 awk '/regex/{print (x=="" ? "match on line 1" : x)};{x=$0}'

 # print the line immediately after a regex, but not the line
 # containing the regex
 awk '/regex/{getline;print}'

 # grep for AAA and BBB and CCC (in any order)
 awk '/AAA/; /BBB/; /CCC/'

 # grep for AAA and BBB and CCC (in that order)
 awk '/AAA.*BBB.*CCC/'

 # print only lines of 65 characters or longer
 awk 'length > 64'

 # print only lines of less than 65 characters
 awk 'length < 64'

 # print section of file from regular expression to end of file
 awk '/regex/,0'
 awk '/regex/,EOF'

 # print section of file based on line numbers (lines 8-12, inclusive)
 awk 'NR==8,NR==12'

 # print line number 52
 awk 'NR==52'
 awk 'NR==52 {print;exit}'          # more efficient on large files

 # print section of file between two regular expressions (inclusive)
 awk '/Iowa/,/Montana/'             # case sensitive

SELECTIVE DELETION OF CERTAIN LINES:

 # delete ALL blank lines from a file (same as "grep '.' ")
 awk NF
 awk '/./'

CREDITS AND THANKS:

Special thanks to Peter S. Tillier for helping me with the first release
of this FAQ file.

For additional syntax instructions, including the way to apply editing
commands from a disk file instead of the command line, consult:

"sed & awk, 2nd Edition," by Dale Dougherty and Arnold Robbins
  O'Reilly, 1997
"UNIX Text Processing," by Dale Dougherty and Tim O'Reilly
  Hayden Books, 1987
"Effective awk Programming, 3rd Edition." by Arnold Robbins
  O'Reilly, 2001

To fully exploit the power of awk, one must understand "regular
expressions." For detailed discussion of regular expressions, see
"Mastering Regular Expressions, 2d edition" by Jeffrey Friedl
   (O'Reilly, 2002).

The manual ("man") pages on Unix systems may be helpful (try "man awk",
"man nawk", "man regexp", or the section on regular expressions in "man
ed"), but man pages are notoriously difficult. They are not written to
teach awk use or regexps to first-time users, but as a reference text
for those already acquainted with these tools.

USE OF 't' IN awk SCRIPTS: For clarity in documentation, we have used
the expression 't' to indicate a tab character (0x09) in the scripts.
All versions of awk, even the UNIX System 7 version should recognize
the 't' abbreviation.

#---end of file---

 

 

最近Google搜索打不开?看这里

发表于 2012-12-06 | 分类于 未分类

最近由于一些总所周知的原因,大陆地区的Google的搜索结果打不开(或者说很难打开)了。 原因是因为DNS污染之类的, 详见: http://www.williamlong.info/archives/2263.html

解决办法倒是有一些的,针对不同的浏览器, 下载不同的插件去掉Google搜索结果打开需要的Google Forward 的URL即可:

Chrome: 这里:https://chrome.google.com/webstore/detail/remove-google-redirects/ccenmflbeofaceccfhhggbagkblihpoh

Opera: https://addons.opera.com/en/extensions/details/remove-google-redirects/

Safari: 无。我已经提交了一个插件,希望能够尽快出现

Firefox: 无, 这个有时间也弄一个。

这个插件的原理就是去掉Gogole Forward的URL, 让你直接打开你搜索到的结果, 这样没有被墙的内容还是可以打开的。

Rails: Dynamic Finders

发表于 2012-12-01 | 分类于 Rails

 

 

Rails's ActiveRecord can use a dymatic way to finder

Like this model class in rails:

class Article < ActiveRecord::Base
  attr_accessible :body, :excerpt, :location, :published_at, :title
  validates :title, :presence => true
  validates :body, :presence => true
end

It don't have much query function, but you can use query function like:

Article.find_by_title('Hello')
=>; #<;article id:1,="" title:="" "hello",="" ...="">;

It because it use Ruby’s method_missing functionality to automatically create methods that don’t exist until runtime. Using dynamic finders, you can include the attribute you’re looking for directly in the method name.

There are several variations of dynamic finders, which are summarized in the Table:

 
Finder Example
find_by_*(cond) find_by_title('Hello') #=>; Article
find_all_by_*(cond) find_all_by_title('Hello') #=>; Array
find_by_*_and_*(cond1, cond2) find_by_title_and_published_on('Hello', '2012-03-12') #=>;Articlelike creating a record. You can update attributes one at a time and
then save the result, or you can update attributes in one fell swoop. When you update a
record, a SQL UPDATE statement is constructed behind the scenes. First, you use a find
operation to retrieve the record you
find_all_by_*_and_*(cond1, cond2) find_all_by_title_and_published_on('Hello', '2012-03-12') #=>;Array

Amazing...

 

ARM V6 和V6+架构中的原子指令

发表于 2012-11-26 | 分类于 CPU , 未分类

ARM V6

ARM V6中原子指令是:

SWP 指令

该指令可以实现寄存器和内存之间的原子交换, 但是由于该指令要lock住BUS, 所以会影响系统性能.
例子:
sem_wati:MOV R1,#0
LDR R0,=SEM
SWP R1,R1,[R0] ;取出信号量,并设置其为0
CMP R1,#0 ;判断是否有信号
BEQ sem_wait ;若没有信号,则等待
所以在内核中, V6以前的架构, atomic_add/sub 之类的指令都是用
raw_local_irq_save(flags)
val = v->counter;
v->counter = val += 1;
raw_local_irq_restore(flags)
来实现的.

ARM V6 以后, V7, V8中

提供LDREX和STREX来替换SWP指令, 实现对原子的内存操作.
LDREX <Rt>,[Rn]STREX <Rd>,<Rt>,[Rn] ;STREX成功,Rd置0
所以Linux内核就可以利用这个指令来做原子操作, 内核中的atomic_add 实现就是
 static inline void atomic_add(int i, atomic_t *v)
static inline void atomic_add(int i, atomic_t *v)
{
     unsigned long tmp;
     int result;

     __asm__ __volatile__("@ atomic_addn"
"1:     ldrex     %0, [%3]n"    // 先读入counter
"     add     %0, %0, %4n"     // 再把counter+i
"     strex     %1, %0, [%3]n"  // 把counter再写到result的地址, 并且放返回值到tmp里面.
"     teq     %1, #0n"                // 检查tmp和0相等否
"     bne     1b"                          // 如果不相等, 再重新来一次. 防止被其他的CPU或者其他的竞争条件.
     : "=&r" (result), "=&r" (tmp), "+Qo" (v->counter)
     : "r" (&v->counter), "Ir" (i)
     : "cc");
}
下面是一些ARM V6+架构对该指令的内部实现,(参考:http://www.keil.com/support/man/docs/armasmref/armasmref_Cihbghef.htm)

LDREX loads data from memory.If the physical address has the Shared TLB attribute, LDREX tags the physical address as exclusive access for the current processor, and clears any exclusive access tag for this processor for any other physical address.

Otherwise, it tags the fact that the executing processor has an outstanding tagged physical address.

(如果物理地址在TLB中, 那么LDREX就标识该地址为当前CORE的排他使用(exclusive access), 而且清楚掉该Core对其他的地址的exclusive access.
如果不在TLB中, 那么就标志当前CPU有一个outstanding tagged 物理地址, 我想应该是一个特殊的物理地址访问的意思.)

STREX performs a conditional store to memory. The conditions are as follows:If the physical address does not have the Shared TLB attribute, and the executing processor has an outstanding tagged physical address, the store takes place, the tag is cleared, and the value 0 is returned in Rd.

(如果该物理地址没有share TBL 属性, 也就是没有load到TLB中, 当前执行的CPU有一个"outstanding tagged physical address", 那么存储会直接存进去, 清除tag, 然后再Rd里面返回0)

    If the physical address does not have the Shared TLB attribute, and the executing processor does not have an outstanding tagged physical address, the store does not take place, and the value 1 is returned in Rd. (如果物理地址没有在TBL中, 而且当前执行CPU没有一个outstanding tagged physical address, 那么这次store不发生, 并且返回1在Rd中).If the physical address has the Shared TLB attribute, and the physical address is tagged as exclusive access for the executing processor, the store takes place, the tag is cleared, and the value 0 is returned in Rd.

(如果物理地址已经有一个TLB的属性, 而且该物理地址已经被标识为exclusive access, 那么存储发生, 并且清掉TAG, 在Rd中返回0)

If the physical address has the Shared TLB attribute, and the physical address is not tagged as exclusive access for the executing processor, the store does not take place, and the value 1 is returned in Rd.
(如果该地址已经有TLB的属性, 但是物理地址没有tag成exclusive access, 存储不发生, 并且在Rd中返回0.

Time Machine Eat My HD...

发表于 2012-07-20 | 分类于 未分类

今天忽然发现自己的MBP上面的320G的硬盘用完了, 慢的叫个没话说。
可是东西感觉没安多少, 基本上就是iTune U上面下了很多视频, 但是也不至于把硬盘全部用完把。
所以还是先到根目录下面找找是什么占了内存了:
  

cd /
sudo find . -size +200M 2&>/dev/null
惊讶的发现删掉的很多视频竟然出现在 /.MbileBackups 里面。
计算了一下大小:
sudo du -sh /.MobileBackups.trash/
发现竟然有48G, My God, 必须回收回来。。
Google了一会发现原来发现这个目录是Time Machine用来做本地备份的,
Apple considered to implement a new "feature" to Lion that no one seems to be aware of: Local Backups if your Time Machine Drive is not connected to you computer. It seems to affect only Mac Laptops, not the desktop Macs. So every time your Time Machine backup starts without the destination drive it will copy all data in a secure folder on your local startup volume called ".MobileBackups".
已经有很多天备份了, 而且已经把Music目录排除出去了,估计这些文件是在很早以前下载的。 于是查到了通过这个命令关掉这些本地备份, 重启以后就会全部删掉。
sudo tmutil disablelocal
sudo reboot
然后发现重启以后就多了48G空间
不过Time Machine还是有必要的,于是又重新打开
sudo tmutil enablelocal
sudo reboot

adb & gdbserver: remote gdb debugging under android

发表于 2012-07-14 | 分类于 未分类

 



Most of operations are reference from this link, but with some more refine, and detail.

http://www.kandroid.org/online-pdk/guide/debugging_native.html

This page show how to use gdb in android env, it will use adb to forward tcp to gbd port, so no network needed, and also show how to load the symbol information from an android build dir, also use sshfs to mapping the build env in server to local PC.

first, the commands in this page:

# the command under target board, adb
$ the command on host.
(god) the command under gdb shell.

to debug use gdb, tell adb forward all tcp to gdb port.

$ adb forward tcp:5039 tcp:5039

start gdb server at board.
# gbdserver :5039 --attach 257 & 
or 
# gdbserver :5039 /system/bin/surfacefligner

start debugging
$ prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi-gdb out/target/product/sabresd_6q/symbols/system/bin/surfaceflinger

(gdb) set solib-absolute-prefix /home/xxxx/proj/ics/out/target/product/sabresd_6q/symbols/
(gdb) set solib-search-path /home/xxxx/proj/ics/out/target/product/sabresd_6q/symbols/system/lib
(gdb) target remote :5039

// don't let other scheduler during your debugging.
(gdb) set scheduler-locking on

//  continue can start remote debugging.
(gbd) continue

Tips:

0. use sshfs to remap the build dir to your local PC:

//  use adb require a usb cable connect to your board, so for some guy build the code on server, you can use sshfs to let all file system in server mapping to your PC.
// in my case, i use 

sshfs  b33xxx@10.192.224.xx:/home/b33xxx/  ~/shdroid1

start gdb command become:
prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi-gdb /home/xxx/shdroid1/proj/ics/out/target/product/sabresd_6q/symbols/system/bin/surfaceflinger

and the path in gbd 's input is become:

set solib-absolute-prefix /home/xxx/shdroid1/proj/ics/out/target/product/sabresd_6q/symbols/
set solib-search-path /home/xxx/shdroid1/proj/ics/out/target/product/sabresd_6q/symbols/system/lib

1. how to keep gdb run
modify init.freescale.rc, change this line from:
setprop persist.sys.usb.config mtp
--> setprop persist.sys.usb.config gdb

2. How to let gdb load all symbol

gdbserver will stop at linker:begin.S when start,   before continue, you should set a break point at main() function, after you stop at main, the all symbol will loaded, you can set break point by function's name
(gdb) b main
(gdb) continue
<--- after stop at main --->
b SurfaceFlinger::publishAndJoinThreadPool() # set break point by function name

3. how to restart debuging, restart debugging like this can keep the break points.

(gbd) kill 
# gdbserver xxxx // needs to restart server
(gbd)  target remote :5039    // reconnect.
(gbd) set scheduler-locking on

4. how to extract the stack dump quickly,

(going to android build dir)
$ . build/envsetup.sh
$ lunch 
( choose your product)
(make sure this was full build dir)

run 
$ ./development/scripts/stack
when you see this:
Reading native crash info from stdin
you can copy the stack dump from logcat, begin with 

I/DEBUG   ( 2167): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

such as:

I/DEBUG   ( 2167): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

I/DEBUG   ( 2167): Build fingerprint: 'freescale/sabresd_6q/sabresd_6q:4.0.3/R13.2-rc3/eng.b33651.20120327.172909:eng/test-keys'

I/DEBUG   ( 2167): pid: 2649, tid: 2649  >>> /system/bin/surfaceflinger <<<

I/DEBUG   ( 2167): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 002e0064

I/DEBUG   ( 2167):  r0 ffffffff  r1 002e0064  r2 401167d0  r3 0066791c

I/DEBUG   ( 2167):  r4 ffffffff  r5 002e0064  r6 bec42a50  r7 40208e85

I/DEBUG   ( 2167):  r8 bec429f0  r9 00000a59  10 000003e8  fp 00000000

I/DEBUG   ( 2167):  ip 40196078  sp bec429b8  lr 4004d0e8  pc 4004d0e8  cpsr 00000010

I/DEBUG   ( 2167):  d0  0000000000000000  d1  0000000000000000

I/DEBUG   ( 2167):  d2  0000000000000000  d3  0000000000000000

I/DEBUG   ( 2167):  d4  0000000000000000  d5  0000000000000000

I/DEBUG   ( 2167):  d6  3f80000000000000  d7  000000003f800000

I/DEBUG   ( 2167):  d8  0000000000000000  d9  0000000000000000

I/DEBUG   ( 2167):  d10 0000000000000000  d11 0000000000000000

I/DEBUG   ( 2167):  d12 0000000000000000  d13 0000000000000000

I/DEBUG   ( 2167):  d14 0000000000000000  d15 0000000000000000

I/DEBUG   ( 2167):  d16 41a93d96b0b645a2  d17 3f50624dd2f1a9fc

I/DEBUG   ( 2167):  d18 41c5dae992000000  d19 0000000000000000

I/DEBUG   ( 2167):  d20 0000000000000000  d21 0000000000000000

I/DEBUG   ( 2167):  d22 0000000000000000  d23 0000000000000000

I/DEBUG   ( 2167):  d24 0000000000000000  d25 0000000000000000

I/DEBUG   ( 2167):  d26 0000000000000000  d27 0000000000000000

I/DEBUG   ( 2167):  d28 0000000000000000  d29 0000000000000000

I/DEBUG   ( 2167):  d30 0000000000000000  d31 0000000000000000

I/DEBUG   ( 2167):  scr 00000010

I/DEBUG   ( 2167):

I/DEBUG   ( 2167):       #00  pc 000050e8  /system/lib/libcutils.so (android_atomic_add)

I/DEBUG   ( 2167):       #01  pc 0001a058  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv)

I/DEBUG   ( 2167):       #02  pc 00019218  /system/lib/libbinder.so (_ZN7android2spINS_21IPermissionControllerEED1Ev)

I/DEBUG   ( 2167):       #03  pc 0001b1fa  /system/lib/libbinder.so (_ZN7android14IPCThreadState14executeCommandEi)

I/DEBUG   ( 2167):       #04  pc 0001b3c6  /system/lib/libbinder.so (_ZN7android14IPCThreadState14joinThreadPoolEb)

I/DEBUG   ( 2167):

I/DEBUG   ( 2167): code around pc:

I/DEBUG   ( 2167): 4004d0c8 e1853f92 e3530000 1afffffa e8bd8070  .?....S.....p...

I/DEBUG   ( 2167): 4004d0d8 e92d4070 e1a04000 e1a05001 ebffffd1  p@-..@...P......

I/DEBUG   ( 2167): 4004d0e8 e1950f9f e0802004 e1853f92 e3530000  ..... ...?....S.

I/DEBUG   ( 2167): 4004d0f8 1afffffa e8bd8070 e1a01000 e3e00000  ....p...........

I/DEBUG   ( 2167): 4004d108 eafffff2 e1a01000 e3a00001 eaffffef  ................

I/DEBUG   ( 2167):

I/DEBUG   ( 2167): memory map around addr 002e0064:

I/DEBUG   ( 2167): 00009000-0000a000 /system/bin/surfaceflinger

I/DEBUG   ( 2167): (no map for address)

I/DEBUG   ( 2167): 00662000-00668000 [heap]

I/DEBUG   ( 2167):

I/DEBUG   ( 2167): stack:

I/DEBUG   ( 2167): bec42978  bec42a20  [stack]

I/DEBUG   ( 2167): bec4297c  bec429f0  [stack]

I/DEBUG   ( 2167): bec42980  00000004  

I/DEBUG   ( 2167): bec42984  bec42a20  [stack]

I/DEBUG   ( 2167): bec42988  00000a59  

I/DEBUG   ( 2167): bec4298c  000003e8  

I/DEBUG   ( 2167): bec42990  00000000  

I/DEBUG   ( 2167): bec42994  4010ed0d  /system/lib/libsurfaceflinger.so

I/DEBUG   ( 2167): bec42998  00000010  

I/DEBUG   ( 2167): bec4299c  00000004  

I/DEBUG   ( 2167): bec429a0  bec42a20  [stack]

I/DEBUG   ( 2167): bec429a4  bec429f0  [stack]

I/DEBUG   ( 2167): bec429a8  0066791c  [heap]

I/DEBUG   ( 2167): bec429ac  00000004  

I/DEBUG   ( 2167): bec429b0  df0027ad  

I/DEBUG   ( 2167): bec429b4  00000000  

I/DEBUG   ( 2167): #00 bec429b8  002e0064  

I/DEBUG   ( 2167): bec429bc  00667f68  [heap]

I/DEBUG   ( 2167): bec429c0  bec42a50  [stack]

I/DEBUG   ( 2167): bec429c4  4018205b  /system/lib/libutils.so

I/DEBUG   ( 2167): #01 bec429c8  bec42a50  [stack]

I/DEBUG   ( 2167): bec429cc  00000000  

I/DEBUG   ( 2167): bec429d0  4021932c  /system/lib/libbinder.so

I/DEBUG   ( 2167): bec429d4  4020a21b  /system/lib/libbinder.so

then you type CTRL-D to tell the script EOF,

then you will see the full stack dump with source and lines like this;

Reading symbols from /home/b33651/proj/ics/out/target/product/sabresd_6q/symbols

pid: 2649, tid: 2649  >>> /system/bin/surfaceflinger <<<

signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 002e0064

 r0 ffffffff  r1 002e0064  r2 401167d0  r3 0066791c

 r4 ffffffff  r5 002e0064  r6 bec42a50  r7 40208e85

 r8 bec429f0  r9 00000a59  10 000003e8  fp 00000000

 ip 40196078  sp bec429b8  lr 4004d0e8  pc 4004d0e8

Stack Trace:

 RELADDR   FUNCTION                                        FILE:LINE

 000050e8  android_atomic_add+16                           /home/b33651/proj/ics/system/core/include/cutils/atomic-arm.h:158

 0001a058  android::RefBase::decStrong(void const*) const+12  /home/b33651/proj/ics/frameworks/base/libs/utils/RefBase.cpp:351

 v------>  ~sp                                             /home/b33651/proj/ics/frameworks/base/include/utils/StrongPointer.h:149

 00019218  android::sp<android::IMemoryHeap>::~sp()+20     /home/b33651/proj/ics/frameworks/base/include/utils/StrongPointer.h:149

 0001b1fa  android::IPCThreadState::executeCommand(int)+538   /home/b33651/proj/ics/frameworks/base/libs/binder/IPCThreadState.cpp:1029

 0001b3c6  android::IPCThreadState::joinThreadPool(bool)+186  /home/b33651/proj/ics/frameworks/base/libs/binder/IPCThreadState.cpp:468

Stack Data:

 ADDR   VALUE FILE:LINE/FUNCTION

 bec42978  bec42a20  

 bec4297c  bec429f0  

 bec42980  00000004  

 bec42984  bec42a20  

 bec42988  00000a59  

 bec4298c  000003e8  

 bec42990  00000000  

 bec42994  4010ed0d  

 bec42998  00000010  

 bec4299c  00000004  

 bec429a0  bec42a20  

 bec429a4  bec429f0  

 bec429a8  0066791c  

 bec429ac  00000004  

 bec429b0  df0027ad  

 bec429b4  00000000  

 bec429b8  002e0064  

 bec429bc  00667f68  

 bec429c0  bec42a50  

 bec429c4  4018205b  

 bec429c8  bec42a50  

 bec429cc  00000000  

 bec429d0  4021932c  

 bec429d4  4020a21b  

#####----------------------------
set solib-absolute-prefix /home/kzj/shdroid1/proj/ics/out/target/product/sabresd_6q/symbols/
set solib-search-path /home/kzj/shdroid1/proj/ics/out/target/product/sabresd_6q/symbols/system/lib

 

123…11
Jiejing Zhang

Jiejing Zhang

110 日志
11 分类
24 标签
© 2017 Jiejing Zhang
由 Hexo 强力驱动
主题 - NexT.Pisces