问:
How to add 2 buttons in Panel to collapse/expand all groups in a grid in ExtJs?
I have a panel and inside of it I have a grid, so my question is how to have 2 buttons to collapse/expand all groups in a grid? I'm still new to ExtJs.

Here's the code that I'm using. It works just fine.

```<code>var store = Ext.create('Ext.data.Store', {
fields: ['name', 'seniority', 'department'],
groupField: 'department',
data: [
    { name: 'Michael Scott', seniority: 7, department: 'Management' },
    { name: 'Dwight Schrute', seniority: 2, department: 'Sales' },
    { name: 'Jim Halpert', seniority: 3, department: 'Sales' },
    { name: 'Kevin Malone', seniority: 4, department: 'Accounting' },
    { name: 'Angela Martin', seniority: 5, department: 'Accounting' }
]
});

Ext.create('Ext.grid.Panel', {
title: 'Employees',
store: store,
columns: [
    { text: 'Name', dataIndex: 'name', flex: 1 },
    { text: 'Seniority', dataIndex: 'seniority', flex: 1 }
],
features: [{ftype:'grouping'}],
renderTo: Ext.getBody()
});
</code>```

Maybe using dockedItem in the Panel will be the way I want it.

答:
shortcut

you can directly set the collapsible property attributes of a grid as per your requirement.

Body:
I have a panel and inside of it I have a grid, so my question is how to have 2 buttons to collapse/expand all groups in a grid? I'm still new to ExtJs.

Here's the code that I'm using. It works just fine.

var store = Ext.create('Ext.data.Store', {
fields: ['name', 'seniority', 'department'],
groupField: 'department',
data: [
    { name: 'Michael Scott', seniority: 7, department: 'Management' },
    { name: 'Dwight Schrute', seniority: 2, department: 'Sales' },
    { name: 'Jim Halpert', seniority: 3, department: 'Sales' },
    { name: 'Kevin Malone', seniority: 4, department: 'Accounting' },
    { name: 'Angela Martin', seniority: 5, department: 'Accounting' }
]
});

Ext.create('Ext.grid.Panel', {
title: 'Employees',
store: store,
columns: [
    { text: 'Name', dataIndex: 'name', flex: 1 },
    { text: 'Seniority', dataIndex: 'seniority', flex: 1 }
],
features: [{ftype:'grouping'}],
renderTo: Ext.getBody()
});

Maybe using dockedItem in the Panel will be the way I want it.


来源: stackexchange

问:
While sending mail using PHP mail() function, Japanese header text is not shown in readable format

I am using PHP mail() function to send mail. Headers include Japanese text. Mail was sent and all body text (Japanese text) is readable except the header text (Japanese text). I am using following code to send mail.

```<code>$test_admin_email="test@test.com";
$test_admin_headers  = "MIME-Version: 1.0 \n" ;
$test_admin_headers .= "From: 株式会社テスト <test@test.com>\n";
$test_admin_headers .= "Reply-To: 株式会社テ<reply@test@test.com>\n";
$test_admin_headers .= "Content-Type: text/plain;charset=UTF-8\n";

$test_user_headers  = "MIME-Version: 1.0 \n" ;
$test_user_headers .= "From: 株式会社テスト <test@test.com>\n";
$test_user_headers .= "Reply-To: 株式会社テスト <test@test.com>\n";
$test_user_headers .= "Content-Type: text/plain;charset=UTF-8\n";

$res=mail($test_admin_email, $test_admin_subject, $test_admin_message, $test_admin_headers);

@mail($user_email, $test_user_subject, $test_user_message, $test_user_headers);
</code>```

I want to show the readable Japanese headers in both user and admin email.

I am currently getting unreadable text format in header section (having Japanese text). But all other section (having japanese text) is displaying in readable format.

答:
Finally, I am able to pass readable Japanese text through header. And it works fine on outlook mail too. I added mb_encode_mimeheader() code to encode the japanese text as shown in below code:

```<code>$test_admin_email="test@test.com";
$test_admin_headers  = "MIME-Version: 1.0 \n" ;
$test_admin_headers .= "From: 株式会社テスト <test@test.com>\n";
$test_admin_headers .= "Reply-To: 株式会社テ<reply@test@test.com>\n";
$test_admin_headers .= "Content-Type: text/plain;charset=UTF-8\n";

$from = mb_encode_mimeheader("株式会社テスト", "ISO-2022-JP"); //newly added code.
$replyTo = mb_encode_mimeheader("株式会社テスト", "ISO-2022-JP"); //newly added code.

$test_user_headers  = "MIME-Version: 1.0 \n" ;
$test_user_headers .= "From: $from <test@test.com>\n";
$test_user_headers .= "Reply-To: $replyTo <test@test.com>\n";
$test_user_headers .= "Content-Type: text/plain;charset=UTF-8\n";

  $res=mail($test_admin_email, $test_admin_subject, $test_admin_message, $test_admin_headers);

  @mail($user_email, $test_user_subject, $test_user_message, $test_user_headers);
</code>```

Reference: http://php.net/manual/ja/function.mail.php

ContentLicense: CC BY-SA 3.0

Body:
I am using PHP mail() function to send mail. Headers include Japanese text. Mail was sent and all body text (Japanese text) is readable except the header text (Japanese text). I am using following code to send mail.

$test_admin_email="test@test.com";
$test_admin_headers  = "MIME-Version: 1.0 \n" ;
$test_admin_headers .= "From: 株式会社テスト <test@test.com>\n";
$test_admin_headers .= "Reply-To: 株式会社テ<reply@test@test.com>\n";
$test_admin_headers .= "Content-Type: text/plain;charset=UTF-8\n";

$test_user_headers  = "MIME-Version: 1.0 \n" ;
$test_user_headers .= "From: 株式会社テスト <test@test.com>\n";
$test_user_headers .= "Reply-To: 株式会社テスト <test@test.com>\n";
$test_user_headers .= "Content-Type: text/plain;charset=UTF-8\n";

$res=mail($test_admin_email, $test_admin_subject, $test_admin_message, $test_admin_headers);

@mail($user_email, $test_user_subject, $test_user_message, $test_user_headers);

I want to show the readable Japanese headers in both user and admin email.

I am currently getting unreadable text format in header section (having Japanese text). But all other section (having japanese text) is displaying in readable format.

Body:
Finally, I am able to pass readable Japanese text through header. And it works fine on outlook mail too. I added mb_encode_mimeheader() code to encode the japanese text as shown in below code:

$test_admin_email="test@test.com";
$test_admin_headers  = "MIME-Version: 1.0 \n" ;
$test_admin_headers .= "From: 株式会社テスト <test@test.com>\n";
$test_admin_headers .= "Reply-To: 株式会社テ<reply@test@test.com>\n";
$test_admin_headers .= "Content-Type: text/plain;charset=UTF-8\n";

$from = mb_encode_mimeheader("株式会社テスト", "ISO-2022-JP"); //newly added code.
$replyTo = mb_encode_mimeheader("株式会社テスト", "ISO-2022-JP"); //newly added code.

$test_user_headers  = "MIME-Version: 1.0 \n" ;
$test_user_headers .= "From: $from <test@test.com>\n";
$test_user_headers .= "Reply-To: $replyTo <test@test.com>\n";
$test_user_headers .= "Content-Type: text/plain;charset=UTF-8\n";

  $res=mail($test_admin_email, $test_admin_subject, $test_admin_message, $test_admin_headers);

  @mail($user_email, $test_user_subject, $test_user_message, $test_user_headers);

Reference: http://php.net/manual/ja/function.mail.php


问:
How to get the row where it's value has a continuous decrease compared to the last two rows in python

I have a data frame create by pandas like this:

```<code>import pandas as pd
df = pd.DataFrame({'name':['q1','q2','q3','q4','q5'],'vlue':[17,20,16,13,17]})

   name vlue
0   q1  17
1   q2  20
2   q3  16
3   q4  13
4   q5  17
</code>```

I want the row that has a continuous decrease compared to the last two rows.

In this case, the value of q4 is 13, it's decreased compared to q3's value 16 and q2's  value 20.
so the answer should be q4.

what's an efficient way to do this?

答:
In two lines :</p>

```<code>In [19]: dicrease = df.vlue.diff() < 0

In [20]: df.name[dicrease & dicrease.shift()]
Out[20]:
3    q4
Name: name, dtype: object
</code>```

Body:
I have a data frame create by pandas like this:

import pandas as pd
df = pd.DataFrame({'name':['q1','q2','q3','q4','q5'],'vlue':[17,20,16,13,17]})

   name vlue
0   q1  17
1   q2  20
2   q3  16
3   q4  13
4   q5  17

I want the row that has a continuous decrease compared to the last two rows.

In this case, the value of q4 is 13, it's decreased compared to q3's value 16 and q2's  value 20.
so the answer should be q4.

what's an efficient way to do this?

Body:
In two lines :

In [19]: dicrease = df.vlue.diff() < 0

In [20]: df.name[dicrease & dicrease.shift()]
Out[20]:
3    q4
Name: name, dtype: object


问:
Data structure for game Dots and Boxes
What would be a good data structure to represent the status of the game Dots and Boxes?

I came up with using 2 matrices of boolean, for horizontal and vertical lines, but maybe there's a more elegant way of doing this (and the operations: add line, check line, check square).

答:
Using a pair of two-dimensional arrays of booleans called linesX and linesY makes sense to me. Each array would have one more row/column than the total number of squares on the board in that given X/Y direction. Here's a code sample of check square with that solution:

```<code>bool isSquareComplete(int x, int y) {
    return linesX[x][y] && linesX[x + 1][y] && linesY[x][y] && linesY[x][y + 1];
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Data structure for game Dots and Boxes

Body:
Using a pair of two-dimensional arrays of booleans called linesX and linesY makes sense to me. Each array would have one more row/column than the total number of squares on the board in that given X/Y direction. Here's a code sample of check square with that solution:

bool isSquareComplete(int x, int y) {
    return linesX[x][y] && linesX[x + 1][y] && linesY[x][y] && linesY[x][y + 1];
}


问:
Custom Button with two TextView
I'm trying to Customize button with two TextView with different typeface within a single button. For that I just extended Button and with have written the following code inside the constructor,

```<code>LayoutInflater layoutInflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.custom_button,
        (ViewGroup) findViewById(R.id.custom_button_view));

TextView firstTextView = (TextView) layout
        .findViewById(R.id.firstTextView);
TextView secondTextView = (TextView) layout
        .findViewById(R.id.secondTextView);
</code>```

in the layout custom_button I have placed two TextView with different typeface and text and custom_button_view is the ID of that LinearLayout, what I got is an empty button with no text.

Any Ideas, Thanks.

答:
You can surround the button with a FrameLayout and then add a textview within the FrameLayout. You can manage the typeface in the activity. If the text doesn't show try using bringToFront()

layout:

```<code> <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:id="@+id/button_frame"
            >
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_border"
            android:gravity="center"
            android:onClick="onClick"
            android:text="@string/get_more"
            android:id="@+id/get_more"
            android:stateListAnimator="@null"

        />

            <TextView
                android:id="@+id/linearTimer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_gravity="right"
                android:padding="10dp"
                android:text="123"
             >
    </FrameLayout>
</code>```

Activity:

```<code> countDownView = (TextView) findViewById(R.id.linearTimer);
 Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/digital-7.ttf");
 countDownView.setTypeface(tf);
 countDownView.bringToFront();
</code>```

Title: Custom Button with two TextView

Body:
I'm trying to Customize button with two TextView with different typeface within a single button. For that I just extended Button and with have written the following code inside the constructor,

LayoutInflater layoutInflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.custom_button,
        (ViewGroup) findViewById(R.id.custom_button_view));

TextView firstTextView = (TextView) layout
        .findViewById(R.id.firstTextView);
TextView secondTextView = (TextView) layout
        .findViewById(R.id.secondTextView);

in the layout custom_button I have placed two TextView with different typeface and text and custom_button_view is the ID of that LinearLayout, what I got is an empty button with no text.

Any Ideas, Thanks.

Body:
You can surround the button with a FrameLayout and then add a textview within the FrameLayout. You can manage the typeface in the activity. If the text doesn't show try using bringToFront()

layout:

 <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:id="@+id/button_frame"
            >
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_border"
            android:gravity="center"
            android:onClick="onClick"
            android:text="@string/get_more"
            android:id="@+id/get_more"
            android:stateListAnimator="@null"

        />

            <TextView
                android:id="@+id/linearTimer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_gravity="right"
                android:padding="10dp"
                android:text="123"
             >
    </FrameLayout>

Activity:

 countDownView = (TextView) findViewById(R.id.linearTimer);
 Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/digital-7.ttf");
 countDownView.setTypeface(tf);
 countDownView.bringToFront();


问:
Server Side using C# to access Oracle DB through ODBC datasource failed while C# long datatype mapping to Oracle Number
I am writing a WebApi to provide client users to upload files and the file information will saved to Oracle Database through ODBC(32-bit). The WebApi server side language is C#. The filesize datatype in Oracle is Number.
I get the filesize from "new System.IO.FileInfo(fileSavePath).Length" and its datatype is long. Then I pass it by the following codes:

```<code>String strCmd = "INSERT INTO UPLOAD_FILE (FILENAME, FILETYPE, FILESIZE) Values (:Filename, :Filetype, :Filesize)";
using (OdbcConnection conn = new OdbcConnection(strConn))
{
  using (OdbcCommand cmd = new OdbcCommand(strCmd, conn))
  {
    cmd.Parameters.AddWithValue(":Filename", FILE.FILENAME); //FILE is CLASS.
    cmd.Parameters.AddWithValue(":Filetype", FILE.FILETYPE);
    cmd.Parameters.AddWithValue(":Filesize", FILE.FILESIZE);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}
</code>```

And the Insert action fails.
According the two Datatype mapping tables:

https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/odbc-data-type-mappings

https://docs.oracle.com/cd/E15817_01/server.111/e10311/apa.htm

I thought it should be no problem.
Even though I changed the codes to:

```<code>cmd.Parameters.Add(new OdbcParameter
{
   ParameterName = ":Filesize",
   OdbcType = OdbcType.BigInt,
   Value = FILE.FILESIZE
});
</code>```

And set the datatype of the filesize to Number(19,0)...It still faild.

However, if I let the datatype be int or decimal and it works:

```<code>Convert.ToInt32(FILE.FILESIZE) / Convert.ToDecimal(FILE.FILESIZE)
</code>```

SO my question is why the SQL_BIGINT(ODBC) or long(C#/.Net) can't map to Oracle Number datatype??? Or I miss some conversion processes???

答:
Did you try it like this?</p>

```<code>cmd.Parameters.Add(":Filename", OdbcType.BigInt);
cmd.Parameters[":Filename"].DbType = DbType.Int64;
cmd.Parameters[":Filename"].Value = FILE.FILENAME;

cmd.Parameters.Add(new OdbcParameter {
    ParameterName = ":Filename",
    OdbcType = OdbcType.BigInt,
    DbType = DbType.Int64,
    Value = FILE.FILENAME
});
</code>```

Body:
I am writing a WebApi to provide client users to upload files and the file information will saved to Oracle Database through ODBC(32-bit). The WebApi server side language is C#. The filesize datatype in Oracle is Number.
I get the filesize from "new System.IO.FileInfo(fileSavePath).Length" and its datatype is long. Then I pass it by the following codes:

String strCmd = "INSERT INTO UPLOAD_FILE (FILENAME, FILETYPE, FILESIZE) Values (:Filename, :Filetype, :Filesize)";
using (OdbcConnection conn = new OdbcConnection(strConn))
{
  using (OdbcCommand cmd = new OdbcCommand(strCmd, conn))
  {
    cmd.Parameters.AddWithValue(":Filename", FILE.FILENAME); //FILE is CLASS.
    cmd.Parameters.AddWithValue(":Filetype", FILE.FILETYPE);
    cmd.Parameters.AddWithValue(":Filesize", FILE.FILESIZE);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}

And the Insert action fails.
According the two Datatype mapping tables:

https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/odbc-data-type-mappings

https://docs.oracle.com/cd/E15817_01/server.111/e10311/apa.htm

I thought it should be no problem.
Even though I changed the codes to:

cmd.Parameters.Add(new OdbcParameter
{
   ParameterName = ":Filesize",
   OdbcType = OdbcType.BigInt,
   Value = FILE.FILESIZE
});

And set the datatype of the filesize to Number(19,0)...It still faild.

However, if I let the datatype be int or decimal and it works:

Convert.ToInt32(FILE.FILESIZE) / Convert.ToDecimal(FILE.FILESIZE)

SO my question is why the SQL_BIGINT(ODBC) or long(C#/.Net) can't map to Oracle Number datatype??? Or I miss some conversion processes???

Body:
Did you try it like this?

cmd.Parameters.Add(":Filename", OdbcType.BigInt);
cmd.Parameters[":Filename"].DbType = DbType.Int64;
cmd.Parameters[":Filename"].Value = FILE.FILENAME;

cmd.Parameters.Add(new OdbcParameter {
    ParameterName = ":Filename",
    OdbcType = OdbcType.BigInt,
    DbType = DbType.Int64,
    Value = FILE.FILENAME
});


问:
querybuilder select sums and joined entity

I'm trying to select sums and full joined entity

```<code>$qb = $this->createQueryBuilder('trl')
        ->select('sum(trl.billable_amount) as billable_amount,
          sum(trl.billable_duration) as billable_duration,
          r as resource')
        ->join('trl.time_report', 'tr')
        ->join('trl.contact', 'c')
        ->leftJoin('c.resource', 'r')
        ->where('tr.id = :id')
        ->setParameter('id', $timeReportId)
        ->groupBy('r.id')
        ->having('billable_amount > 0');
</code>```

error I get: [Semantical Error] line 0, col -1 near 'SELECT sum(trl.billable_amount)': Error: Cannot select entity through identification variables without choosing at least one root entity alias.

it works fine without "r as resource". Is it possible to join like this or should I get only resource id and get the entity with second query?

答:
select root entity alias too, try this</p>

```<code>$qb = $this->createQueryBuilder('trl')
    ->select('trl, sum(trl.billable_amount) as billable_amount,
      sum(trl.billable_duration) as billable_duration,
      r as resource')
</code>```

Body:
I'm trying to select sums and full joined entity

$qb = $this->createQueryBuilder('trl')
        ->select('sum(trl.billable_amount) as billable_amount,
          sum(trl.billable_duration) as billable_duration,
          r as resource')
        ->join('trl.time_report', 'tr')
        ->join('trl.contact', 'c')
        ->leftJoin('c.resource', 'r')
        ->where('tr.id = :id')
        ->setParameter('id', $timeReportId)
        ->groupBy('r.id')
        ->having('billable_amount > 0');

error I get: [Semantical Error] line 0, col -1 near 'SELECT sum(trl.billable_amount)': Error: Cannot select entity through identification variables without choosing at least one root entity alias.

it works fine without "r as resource". Is it possible to join like this or should I get only resource id and get the entity with second query?

Body:
select root entity alias too, try this

$qb = $this->createQueryBuilder('trl')
    ->select('trl, sum(trl.billable_amount) as billable_amount,
      sum(trl.billable_duration) as billable_duration,
      r as resource')


问:
Eclipse intermittent "cannot be resolved to a type" error
I keep running into a strange intermittent issue with eclipse for the past few days where I will be editing code, save it, and then eclipse starts reporting hundreds (or sometimes thousands) of MyClassName cannot be resolved to a type errors. The errors are completely bogus as the classes do exist, and if I do a clean and rebuild on the entire workspace the issue goes away. This is the second workspace in a row that it has suddenly happened to.

Has anyone else ever run into this before? Is there some way to fix this issue without recreating an entirely new workspace (which is extremely frustrating). I'm not entirely sure what keeps happening to seemingly corrupt my workspaces.

[Update]

For clarification this is happening with multiple projects that are all Java (web application) projects using only the standard 'Java Builder.'

答: Happened to me with Eclipse Neon after git merge with multiple confilicts, I solved the issue with deleting and re-importing my project.</p>


问:
How to parallelize python code on pyspark
I used python to build and visualize ad graph using networkx. Now the problem is that; i don't know if i can apply networkx on spark or not. i want to confirm that networkx is working as parallel processing. The graph should be stored on HDFS, and need to be queried, the result should be visualized. Should i use spark library instead like graphx, despite the graphx i difficult to me and no visualization provided in it so i prefer to use networkx it is more easiest. thanks</p>

```<code>import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

# directed graph
G = nx.DiGraph()

# undirected graph G = nx.Graph()

G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1,complementray= 1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2,complementray= 0)
G.add_edges_from([('B','C'),('E','F')], weight=3,complementray= 1)
G.add_edges_from([('C','F')], weight=4,complementray= 0)

#val_map = {'A': 1.0,
#                   'D': 0.5714285714285714,
#                              'H': 0.0}
val_map = {'A': 1.0, 'D': 0.5714285714285714, 'H':0.0}

values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v),d['weight'])
                 for u,v,d in G.edges(data=True)])
node_labels=dict([(n)
                 for n in G.nodes(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]

pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw_networkx_labels(G,pos,node_labels=node_labels)

#arrows=True for directed graph without calling the G = nx.DiGraph()
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()
</code>```

答:
I've done some comparison on graph libraries (SNAP vs Igraph vs GraphX) back in 2015, and this is what I can share.

If you want to work in Spark, you're better off learning GraphX to take advantage of the parallel processing. Else just try to find a machine with a bigger RAM and use NetworkX.

We ended up using a combination of igraph + SNAP on a decent spec desktop (28GB RAM) and made some custom heuristics to be able to process some 20M nodes and 300M++ edges. At that point visualizing the network simply didn't make any sense (20M nodes..), and we were more interested in analyzing communities within our subscriber base (telco), so all in all everything was OK. We didn't use GraphX since it was relatively new at that time, and also not much state of the art algos were available.

Body:
I used python to build and visualize ad graph using networkx. Now the problem is that; i don't know if i can apply networkx on spark or not. i want to confirm that networkx is working as parallel processing. The graph should be stored on HDFS, and need to be queried, the result should be visualized. Should i use spark library instead like graphx, despite the graphx i difficult to me and no visualization provided in it so i prefer to use networkx it is more easiest. thanks

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

# directed graph
G = nx.DiGraph()

# undirected graph G = nx.Graph()

G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1,complementray= 1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2,complementray= 0)
G.add_edges_from([('B','C'),('E','F')], weight=3,complementray= 1)
G.add_edges_from([('C','F')], weight=4,complementray= 0)

#val_map = {'A': 1.0,
#                   'D': 0.5714285714285714,
#                              'H': 0.0}
val_map = {'A': 1.0, 'D': 0.5714285714285714, 'H':0.0}

values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v),d['weight'])
                 for u,v,d in G.edges(data=True)])
node_labels=dict([(n)
                 for n in G.nodes(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]

pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw_networkx_labels(G,pos,node_labels=node_labels)

#arrows=True for directed graph without calling the G = nx.DiGraph()
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()


问:
converting numbers to currency format when text changes
I am using RxTextView.textChanges for EditText that when the user is typing change value of EditText to convert numbers to currency format like below:

```<code>1,000
</code>```

But I can't see any convert numbers to currency format.

I am using from:  NumberFormat.getNumberInstance(Locale.US).format(productPrice);

My code is like bellow:

```<code>Observable<CharSequence> observableDiscountPrice = RxTextView.textChanges(discountPriceEdittext);
        observableDiscountPrice.map(new Function<CharSequence, Boolean>() {
            @Override
            public Boolean apply(@io.reactivex.annotations.NonNull CharSequence charSequence) throws Exception {
                try {
                    if (charSequence.length() > 0) {
                        String pPrice = NumberFormat.getNumberInstance(Locale.US).format(charSequence.toString());
                        originalPriceEdittext.setText(String.valueOf(pPrice));
                        return true;
                    } else {
                        return false;
                    }
                } catch (Exception e) {
                    return true;
                }
            }
        }).subscribe(new Subject<Boolean>() {
            @Override
            public boolean hasObservers() {
                return false;
            }

            @Override
            public boolean hasThrowable() {
                return false;
            }

            @Override
            public boolean hasComplete() {
                return false;
            }

            @Override
            public Throwable getThrowable() {
                return null;
            }

            @Override
            protected void subscribeActual(Observer<? super Boolean> observer) {

            }

            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Boolean aBoolean) {
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
</code>```

答:
Take a look at https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html</p>

```<code>    DecimalFormat myFormatter = new DecimalFormat("###,###.###");
    String output = myFormatter.format(156456.673);
    System.out.println(156456.673 + " " + "###,###.###" + " " + output);

// I/System.out: 156456.673 ###,###.### 156,456.673
</code>```

Body:
I am using RxTextView.textChanges for EditText that when the user is typing change value of EditText to convert numbers to currency format like below:

1,000

But I can't see any convert numbers to currency format.

I am using from:  NumberFormat.getNumberInstance(Locale.US).format(productPrice);

My code is like bellow:

Observable<CharSequence> observableDiscountPrice = RxTextView.textChanges(discountPriceEdittext);
        observableDiscountPrice.map(new Function<CharSequence, Boolean>() {
            @Override
            public Boolean apply(@io.reactivex.annotations.NonNull CharSequence charSequence) throws Exception {
                try {
                    if (charSequence.length() > 0) {
                        String pPrice = NumberFormat.getNumberInstance(Locale.US).format(charSequence.toString());
                        originalPriceEdittext.setText(String.valueOf(pPrice));
                        return true;
                    } else {
                        return false;
                    }
                } catch (Exception e) {
                    return true;
                }
            }
        }).subscribe(new Subject<Boolean>() {
            @Override
            public boolean hasObservers() {
                return false;
            }

            @Override
            public boolean hasThrowable() {
                return false;
            }

            @Override
            public boolean hasComplete() {
                return false;
            }

            @Override
            public Throwable getThrowable() {
                return null;
            }

            @Override
            protected void subscribeActual(Observer<? super Boolean> observer) {

            }

            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Boolean aBoolean) {
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

Body:
Take a look at https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

    DecimalFormat myFormatter = new DecimalFormat("###,###.###");
    String output = myFormatter.format(156456.673);
    System.out.println(156456.673 + " " + "###,###.###" + " " + output);

// I/System.out: 156456.673 ###,###.### 156,456.673


问:
How to show a form on startup if there is data found in database in C#
What I am trying to do is if for example a user has registered or saved data in the database they will be automatically redirected to a certain form on startup...

Here is the code I've tried so far and it it is not working according to how I want it to be...

In Form1:

```<code>// I declared the rowcounts as public
public int rowcounts;

public void Form1_Load(object sender, EventArgs e)
{
        SqlConnection connCount = locald.DB.GetSqlConnection();
        System.Data.SqlClient.SqlCommand com = new
        System.Data.SqlClient.SqlCommand();
        com.Connection = connCount;
        com.CommandType = CommandType.StoredProcedure;
        com.CommandText = @"countval";
        rowcounts = Convert.ToInt32(com.ExecuteScalar());
        label1.Text = rowcounts.ToString();
}
</code>```

In Program.cs:

```<code>static void Main()
{
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form1 f1 = new Form1();

        if (f1.rowcounts == 0)
        {
            Application.Run(new Form2());    // if database has no records
        }
        else
        {
            Application.Run(new Form1());
        }
}
</code>```

I created a class DB.cs for connection

```<code>public class DB
{
    public static string ConnectionString
    {
        get
        {
            string connStr = ConfigurationManager.ConnectionStrings["locald.Properties.Settings.localdConnectionString"].ToString();

            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(connStr);
            sb.ApplicationName = ApplicationName ?? sb.ApplicationName;
            sb.ConnectTimeout = (ConnectionTimeout > 0) ? ConnectionTimeout : sb.ConnectTimeout;

            return sb.ToString();
        }
    }

    public static string ApplicationName { get; set; }
    public static int ConnectionTimeout { get; set; }

    public static SqlConnection GetSqlConnection()
    {
        SqlConnection cnn = new SqlConnection(ConnectionString);
        cnn.Open();
        return cnn;
    }
}
</code>```

The problem is even if the database has or without data it would still show the Form1 on startup. What I want is if the database has data it would automatically be redirected to the Form1 and if it has not then it will be in Form2 on startup...

Please help.. Thanks in advance...

答:
defects in your program are,

what is f1 ?
i am seeing that you have coded SQL functions in Form1.cs.

why don't you perform all the SQL operations on program.cs
and redirect to the form as per your query result.

follow as below,

program.cs

```<code> static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            int rowcounts = 0;

            SqlConnection connCount = locald.DB.GetSqlConnection();
            System.Data.SqlClient.SqlCommand com = new
            System.Data.SqlClient.SqlCommand();
            com.Connection = connCount;
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = @"countval";
            rowcounts = Convert.ToInt32(com.ExecuteScalar());

            if (rowcounts == 0){
                Application.Run(new Form2()); //if database has no records
            }
            else
            {
                Application.Run(new Form1());
            }
        }
</code>```

Form1.cs

```<code>private void Form1_Load()
{

}
</code>```

Body:
What I am trying to do is if for example a user has registered or saved data in the database they will be automatically redirected to a certain form on startup...

Here is the code I've tried so far and it it is not working according to how I want it to be...

In Form1:

// I declared the rowcounts as public
public int rowcounts;

public void Form1_Load(object sender, EventArgs e)
{
        SqlConnection connCount = locald.DB.GetSqlConnection();
        System.Data.SqlClient.SqlCommand com = new
        System.Data.SqlClient.SqlCommand();
        com.Connection = connCount;
        com.CommandType = CommandType.StoredProcedure;
        com.CommandText = @"countval";
        rowcounts = Convert.ToInt32(com.ExecuteScalar());
        label1.Text = rowcounts.ToString();
}

In Program.cs:

static void Main()
{
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form1 f1 = new Form1();

        if (f1.rowcounts == 0)
        {
            Application.Run(new Form2());    // if database has no records
        }
        else
        {
            Application.Run(new Form1());
        }
}

I created a class DB.cs for connection

public class DB
{
    public static string ConnectionString
    {
        get
        {
            string connStr = ConfigurationManager.ConnectionStrings["locald.Properties.Settings.localdConnectionString"].ToString();

            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(connStr);
            sb.ApplicationName = ApplicationName ?? sb.ApplicationName;
            sb.ConnectTimeout = (ConnectionTimeout > 0) ? ConnectionTimeout : sb.ConnectTimeout;

            return sb.ToString();
        }
    }

    public static string ApplicationName { get; set; }
    public static int ConnectionTimeout { get; set; }

    public static SqlConnection GetSqlConnection()
    {
        SqlConnection cnn = new SqlConnection(ConnectionString);
        cnn.Open();
        return cnn;
    }
}

The problem is even if the database has or without data it would still show the Form1 on startup. What I want is if the database has data it would automatically be redirected to the Form1 and if it has not then it will be in Form2 on startup...

Please help.. Thanks in advance...

Body:
defects in your program are,

what is f1 ?
i am seeing that you have coded SQL functions in Form1.cs.

why don't you perform all the SQL operations on program.cs
and redirect to the form as per your query result.

follow as below,

program.cs

 static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            int rowcounts = 0;

            SqlConnection connCount = locald.DB.GetSqlConnection();
            System.Data.SqlClient.SqlCommand com = new
            System.Data.SqlClient.SqlCommand();
            com.Connection = connCount;
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = @"countval";
            rowcounts = Convert.ToInt32(com.ExecuteScalar());

            if (rowcounts == 0){
                Application.Run(new Form2()); //if database has no records
            }
            else
            {
                Application.Run(new Form1());
            }
        }

Form1.cs

private void Form1_Load()
{

}


问:
How can I insert multiple rows into database in Laravel?
Here is my code:

```<code>$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}
</code>```

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?

答:
If you already have a model instance, you may use the fill method to populate it with an array of attributes:

```<code>$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $payload = [];
    $payload['prefix'] = $request->prefix;
    $payload['token'] = $token;
    $payload['description'] = $request->description;
    $payload['date_time'] = time();

    $voucher->fill($payload);
}
</code>```

Documentation

Body:
Here is my code:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?

Body:
If you already have a model instance, you may use the fill method to populate it with an array of attributes:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $payload = [];
    $payload['prefix'] = $request->prefix;
    $payload['token'] = $token;
    $payload['description'] = $request->description;
    $payload['date_time'] = time();

    $voucher->fill($payload);
}

Documentation


问:
Input as number in JavaScript prompt
Can we customize a prompt box in JavaScript so it takes time as input?</p>

```<code>var r = prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED");
</code>```

答:
No you can't customize the built-in browser prompt for security reasons.

Your best bet is to use a JavaScript library which offers such a feature like SweetAlert

You can create a number prompt like this:

```<code>swal({
    input: 'number',
    title: 'Enter a number',
}).then(function(result){
    alert("You picked number " + result.value);
});
</code>```

Alternatively you could verify the user's input yourself and stick with prompt like this:

```<code>// need a way to check if input is a valid number
var isNumber = Number.isInteger || function(number){ return !isNaN(parseFloat(n)) && isFinite(n) }

var result = prompt("Enter your number");
if (!isNumber(result)){
   prompt("Please try again and enter your number");
}
</code>```

I would strongly advice against using prompts as the user's browser will most likely block too many prompts in a row. Also keep in mind that the native prompt will block every other interaction a user can make with your side, you don't receive events and your UI won't update. Your website basically freezes until a user interacts with said prompt/alert/confirm.

Title: Input as number in JavaScript prompt

Body:
Can we customize a prompt box in JavaScript so it takes time as input?

var r = prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED");

Body:
No you can't customize the built-in browser prompt for security reasons.

Your best bet is to use a JavaScript library which offers such a feature like SweetAlert

You can create a number prompt like this:

swal({
    input: 'number',
    title: 'Enter a number',
}).then(function(result){
    alert("You picked number " + result.value);
});

Alternatively you could verify the user's input yourself and stick with prompt like this:

// need a way to check if input is a valid number
var isNumber = Number.isInteger || function(number){ return !isNaN(parseFloat(n)) && isFinite(n) }

var result = prompt("Enter your number");
if (!isNumber(result)){
   prompt("Please try again and enter your number");
}

I would strongly advice against using prompts as the user's browser will most likely block too many prompts in a row. Also keep in mind that the native prompt will block every other interaction a user can make with your side, you don't receive events and your UI won't update. Your website basically freezes until a user interacts with said prompt/alert/confirm.


问:
How do you set the height of a Vaadin 8 Grid to be undefined?
I've tried both Grid.setUndefined() and Grid.setHeight("-1px") and neither works. They should both be doing the same but if my grid only has say 3 items then the bottom of the grid is empty and the height is significantly taller than 3 rows.

答:
Here is my proposition for workaround:

grid.getDataProvider().addDataProviderListener( dataProviderEvent ->
                grid.setHeightByRows( grid.getDataProvider().size( new Query() ) )
);
```


答:
You are using same instance everytime!
Create new one in every for loop like:</p>

```<code>$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}
</code>```

Title: How can I insert multiple rows into database in Laravel?

Body:
You are using same instance everytime!
Create new one in every for loop like:

$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}


问:
What's the semantic of assignment in Rust?
How could know the type of a binding if I use auto type deduction when creating a binding? what if the expression on the right side is a borrow(like let x = &5;), will it be value or a borrow? What will happen if I re-assign a borrow or a value?

Just for check, I do can re-assign a borrow if I use let mut x: &mut T = &mut T{}; or let mut x:&T = & T{};, right?

答:
I sense some confusion between binding and assigning:

Binding introduces a new variable, and associates it to a value,

Assigning overwrites a value with another.

This can be illustrated in two simple lines:

```<code>let mut x = 5;    //  Binding
x = 10;           //  Assigning
</code>```

A binding may appear in multiple places in Rust:

let statements,

if let/while let conditions,

cases in a match expression,

and even in a for expression, on the left side of in.

Whenever there is a binding, Rust's grammar also allows pattern matching:

in the case of let statements and for expressions, the patterns must be irrefutable,

in the case of if let, while let and match cases, the patterns may fail to match.

Pattern matching means that the type of the variable introduced by the binding differs based on how the binding is made:

```<code>let x = &5;    //  x: &i32
let &y = &5;   //  y: i32
</code>```

Assigning always requires using =, the assignment operator.

When assigning, the former value is overwritten, and drop is called on it if it implements Drop.

```<code>let mut x = 5;
x = 6;
//  Now x == 6, drop was not called because it's a i32.

let mut s = String::from("Hello, World!");
s = String::from("Hello, 神秘德里克!");
//  Now s == "Hello, 神秘德里克!", drop was called because it's a String.
</code>```

The value that is overwritten may be as simple as an integer or float, a more involved struct or enum, or a reference.

```<code>let mut r = &5;
r = &6;
//  Now r points to 6, drop was not called as it's a reference.
</code>```

Overwriting a reference does not overwrite the value pointed to by the reference, but the reference itself. The original value still lives on, and will be dropped when it's ready.

To overwrite the pointed to value, one needs to use *, the dereference operator:

```<code>let mut x = 5;
let r = &mut x;
*r = 6;
//  r still points to x, and now x = 6.
</code>```

If the type of the dereferenced value requires it, drop will be called:

```<code>let mut s = String::from("Hello, World!");
let r = &mut s;
*r = String::from("Hello, 神秘德里克!");
//  r still points to s, and now s = "Hello, 神秘德里克!".
</code>```

I invite you to use to playground to and toy around, you can start from here:

```<code>fn main() {
    let mut s = String::from("Hello, World!");
    {
        let r = &mut s;
        *r = String::from("Hello, 神秘德里克!");
    }
    println!("{}", s);
}
</code>```

Hopefully, things should be a little clearer now, so let's check your samples.

```<code>let x = &5;
</code>```

x is a reference to i32 (&i32). What happens is that the compiler will introduce a temporary in which 5 is stored, and then borrow this temporary.

```<code>let mut x: &mut T = T{};
</code>```

Is impossible. The type of T{} is T not &mut T, so this fails to compile. You could change it to let mut x: &mut T = &mut T{};.

And your last example is similar.

Body:
I sense some confusion between binding and assigning:

Binding introduces a new variable, and associates it to a value,

Assigning overwrites a value with another.

This can be illustrated in two simple lines:

let mut x = 5;    //  Binding
x = 10;           //  Assigning

A binding may appear in multiple places in Rust:

let statements,

if let/while let conditions,

cases in a match expression,

and even in a for expression, on the left side of in.

Whenever there is a binding, Rust's grammar also allows pattern matching:

in the case of let statements and for expressions, the patterns must be irrefutable,

in the case of if let, while let and match cases, the patterns may fail to match.

Pattern matching means that the type of the variable introduced by the binding differs based on how the binding is made:

let x = &5;    //  x: &i32
let &y = &5;   //  y: i32

Assigning always requires using =, the assignment operator.

When assigning, the former value is overwritten, and drop is called on it if it implements Drop.

let mut x = 5;
x = 6;
//  Now x == 6, drop was not called because it's a i32.

let mut s = String::from("Hello, World!");
s = String::from("Hello, 神秘德里克!");
//  Now s == "Hello, 神秘德里克!", drop was called because it's a String.

The value that is overwritten may be as simple as an integer or float, a more involved struct or enum, or a reference.

let mut r = &5;
r = &6;
//  Now r points to 6, drop was not called as it's a reference.

Overwriting a reference does not overwrite the value pointed to by the reference, but the reference itself. The original value still lives on, and will be dropped when it's ready.

To overwrite the pointed to value, one needs to use *, the dereference operator:

let mut x = 5;
let r = &mut x;
*r = 6;
//  r still points to x, and now x = 6.

If the type of the dereferenced value requires it, drop will be called:

let mut s = String::from("Hello, World!");
let r = &mut s;
*r = String::from("Hello, 神秘德里克!");
//  r still points to s, and now s = "Hello, 神秘德里克!".

I invite you to use to playground to and toy around, you can start from here:

fn main() {
    let mut s = String::from("Hello, World!");
    {
        let r = &mut s;
        *r = String::from("Hello, 神秘德里克!");
    }
    println!("{}", s);
}

Hopefully, things should be a little clearer now, so let's check your samples.

let x = &5;

x is a reference to i32 (&i32). What happens is that the compiler will introduce a temporary in which 5 is stored, and then borrow this temporary.

let mut x: &mut T = T{};

Is impossible. The type of T{} is T not &mut T, so this fails to compile. You could change it to let mut x: &mut T = &mut T{};.

And your last example is similar.


问:
Data Structure in Cassandra
Is there a way to read the SSTable in Cassandra? I see from the documentation that sstabledump is an enterprise version, Is it possible to get the trial version of sstabledump?

Or is there a way to read the SSTable using the existing utilities in Cassandra/bin folder?

答:
You can use sstable2json for that.

http://docs.datastax.com/en/archived/cassandra/2.2/cassandra/tools/toolsSSTable2Json.html

https://www.datastax.com/dev/blog/debugging-sstables-in-3-0-with-sstabledump

ContentLicense: CC BY-SA 4.0

Title: Data Structure in Cassandra


问:
Creating ordered factor based on values in various columns
I have a dataset which I obtained by exposing plants to different treatments. At the end of the experiment I scored whether the plant had survived, and if they survived, how many seeds they produced.
I will use ordered logit models to analyze the outcome. For that, I want to create a column with an ordered factor.In this factor I want to distinguish between plants that died, plants that survived but didn't form seeds, and plants that survived and formed seeds.
Mock dataset and code I used:

```<code>df <-    data.frame(ID=c(1,2,3,4,5,6),alive=c(0,0,1,1,1,1),seeds=c(0,0,0,0,15,14))
df$dead<-as.numeric(df$alive<1)
df$alive_no_seeds<-as.numeric(df$alive>0&df$seeds==0)
df$alive_seeds<-as.numeric(df$alive>0&df$seeds>0)
df$status<-as.character(df$dead>0="dead"&df$alive_no_seeds>0="alive_no_seeds"&df$alive_seeds>0="alive_seeds")
</code>```

here is where things go wrong. I get

```<code>Error: unexpected '=' in "df$status<-as.character(df$dead>0="
</code>```

If I get this factor I'd like to continue with:

```<code>ordered.status <- factor(status, levels=c("dead", "alive_no_seeds", "alive_seeds"), ordered=TRUE)
</code>```

It probably is a simple syntax issue; I'd be very happy if someone could help me out. I have seen several posts were an ordered factor is based on values in single columns, but couldn't find a solution for my problem yet.

答:
```<code>df$status[df$alive<1] = 'dead'
df$status[df$alive>1 & df$alive_no_seeds==0] = "alive_no_seeds"
df$status[df$alive_no_seeds>0] = "alive_seeds"
</code>```

something like this. Not sure in your data if alive or dead is 0

Body:
I have a dataset which I obtained by exposing plants to different treatments. At the end of the experiment I scored whether the plant had survived, and if they survived, how many seeds they produced.
I will use ordered logit models to analyze the outcome. For that, I want to create a column with an ordered factor.In this factor I want to distinguish between plants that died, plants that survived but didn't form seeds, and plants that survived and formed seeds.
Mock dataset and code I used:

df <-    data.frame(ID=c(1,2,3,4,5,6),alive=c(0,0,1,1,1,1),seeds=c(0,0,0,0,15,14))
df$dead<-as.numeric(df$alive<1)
df$alive_no_seeds<-as.numeric(df$alive>0&df$seeds==0)
df$alive_seeds<-as.numeric(df$alive>0&df$seeds>0)
df$status<-as.character(df$dead>0="dead"&df$alive_no_seeds>0="alive_no_seeds"&df$alive_seeds>0="alive_seeds")

here is where things go wrong. I get

Error: unexpected '=' in "df$status<-as.character(df$dead>0="

If I get this factor I'd like to continue with:

ordered.status <- factor(status, levels=c("dead", "alive_no_seeds", "alive_seeds"), ordered=TRUE)

It probably is a simple syntax issue; I'd be very happy if someone could help me out. I have seen several posts were an ordered factor is based on values in single columns, but couldn't find a solution for my problem yet.

Body:
df$status[df$alive<1] = 'dead'
df$status[df$alive>1 & df$alive_no_seeds==0] = "alive_no_seeds"
df$status[df$alive_no_seeds>0] = "alive_seeds"

something like this. Not sure in your data if alive or dead is 0


问:
Java - eleven random numbers between 0-9
I'm trying to create an ID number for Map , so basically I have Customer class , and Map which will contain all the customers with String name , Double balance and int idNumber , the problem is that idNumber must be a collection of random numbers between 0-9 : example : 01019074902 . How can I do this ?</p>

答:
Its will generate 11 digit Random Numbers </p>

```<code>long randomNumber = (long) Math.floor(Math.random() * 9_000_000_0000L) + 1_000_000_0000L;
</code>```

Body:
Its will generate 11 digit Random Numbers

long randomNumber = (long) Math.floor(Math.random() * 9_000_000_0000L) + 1_000_000_0000L;


问:
Confused about the depth-first-search result when using Golang
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

```<code>import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}
</code>```

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code

答:
If list has capacity, then it will be modified and therefore you are modifying your argument. Instead make a copy of list, and then append nums[i] to it.

See Go Slices: usage and internals

Body:
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code


问:
Permitting user agent (chrome) CORS requests programmatically
I need to get some data from external API, from other domain.
I use test app, runned on localhost and I get error:

Origin http://localhost is not allowed by Access-Control-Allow-Origin.

I try to get access to: https://api.coinmarketcap.com/v1/ticker/ by get method

I did a lot of search and:

I know that I can ask that API by using node.js, CURL, and also by running my frontend code in jest tests

By using chrome extension - https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en also everything works correctly

But unfortunatelly by simply AJAX request on my page load I can't reach that API and get an error.

And my prediction is that user agent (chrome) somehow block my request.
I can't use chrome extension because I want also access my website from my mobile phone which can't get that desktop extension.

For now my solution is "proxy", node.js server which can access that API and flow looks like:

FE

-- ASK BE -->

BE

-- ASK API -->

-- RESPONSE TO BE -->

BE

-- RESPONSE TO FE -->

FE SHOWS EVERYTHING

FE - Frontend, BE - Backend (node.js proxy), API - external API

But I want to avoid unnecessary code on the BE. Maybe there is some solution?
Like some magical header which will tell chrome to let me pass to external domain without any additional extension?

答:
If all you pages uses HTML5,you can try using Window.postMessage.

Another common solution is creating a proxy-server.


问:
Flume running failed in Linux
when I installed flume into Linux.I am getting some warning while running flume
I  followed this procedure to install a flume .

```<code>>> sudo tar -xvf flume-ng-1.1.0-cdh4.0.1\(1\).tar.gz
>> export PATH=/home/hduser/downloads/flume-1.1.0- cdh4.0.1/bin:$PATH
>> $ sudo cp conf/flume-conf.properties.template conf/flume.conf
</code>```

for running the flume I used this command

```<code>>> $ bin/flume-ng agent -n agent -f conf/flume.conf
</code>```

but it is showing some warnings

```<code>hadoopmaster@HadoopMaster:/home/hduser/downloads/flume-ng$ sudo bin/flume-ng agent -n agent -f conf/flume.conf
Warning: No configuration directory set! Use --conf <dir> to override.
Warning: JAVA_HOME not set!
+ exec /usr/bin/java -Xmx20m -cp '/home/hduser/downloads/flume-ng/lib/*' -Djava.library.path= org.apache.flume.node.Application -n agent -f conf/flume.conf
log4j:WARN No appenders could be found for logger (org.apache.flume.lifecycle.LifecycleSupervisor).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code>```

答:
You have to set the Java_Home path in flume-env.sh file

export Java_Home = /user/lib/jvm/java_version_name

Title: Flume running failed in Linux

Body:
when I installed flume into Linux.I am getting some warning while running flume
I  followed this procedure to install a flume .

>> sudo tar -xvf flume-ng-1.1.0-cdh4.0.1\(1\).tar.gz
>> export PATH=/home/hduser/downloads/flume-1.1.0- cdh4.0.1/bin:$PATH
>> $ sudo cp conf/flume-conf.properties.template conf/flume.conf

for running the flume I used this command

>> $ bin/flume-ng agent -n agent -f conf/flume.conf

but it is showing some warnings

hadoopmaster@HadoopMaster:/home/hduser/downloads/flume-ng$ sudo bin/flume-ng agent -n agent -f conf/flume.conf
Warning: No configuration directory set! Use --conf <dir> to override.
Warning: JAVA_HOME not set!
+ exec /usr/bin/java -Xmx20m -cp '/home/hduser/downloads/flume-ng/lib/*' -Djava.library.path= org.apache.flume.node.Application -n agent -f conf/flume.conf
log4j:WARN No appenders could be found for logger (org.apache.flume.lifecycle.LifecycleSupervisor).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.


问:
Recive a alert API in PHP POST web service
i used flightstates API  to create get an live flight status.
And they provide a alert messaging in their api. and they says "To use the Alerts API, the developer must implement a web service that accepts an HTTP POST and parses an Alerts Message, then set up a rule specifying that service as the destination.".
I create a web service like this:

```<code>$data = json_decode(file_get_contents('php://input'), true);
$que = mysqli_query($con,"insert into firetable (datas) values ('$data')");
</code>```

but it store value "Array".
how  can store the data in database?

```<code> "alert":{
          "event":{  },
          "dataSource":"Airline",
          "dateTimeRecorded":"2017-12-05T08:36:24.957Z",
          "rule":{  },
          "flightStatus":{
             "flightId":"942163187",
             "carrierFsCode":"9W",
             "flightNumber":"527",
             "departureAirportFsCode":"DXB",
             "arrivalAirportFsCode":"COK",
             "departureDate":{
                "dateLocal":"2017-12-05T12:25:00.000",
                "dateUtc":"2017-12-05T08:25:00.000Z"
             },
             "arrivalDate":{
                "dateLocal":"2017-12-05T17:50:00.000",
                "dateUtc":"2017-12-05T12:20:00.000Z"
             },...............
............................
</code>```

API response like this(this response i get in my email,when i give mail email id as the service).
How i can store the 'flightId','flightNumber' etc to the database?

答:
```<code>// remove json_decode
    $data = json_decode(file_get_contents('php://input'), true);
</code>```

to

```<code>$data = file_get_contents('php://input');

$que = mysqli_query($con,"insert into firetable (datas) values ('$data')");
</code>```

data will be stored in JSON format in DB.

Body:
i used flightstates API  to create get an live flight status.
And they provide a alert messaging in their api. and they says "To use the Alerts API, the developer must implement a web service that accepts an HTTP POST and parses an Alerts Message, then set up a rule specifying that service as the destination.".
I create a web service like this:

$data = json_decode(file_get_contents('php://input'), true);
$que = mysqli_query($con,"insert into firetable (datas) values ('$data')");

but it store value "Array".
how  can store the data in database?

 "alert":{
          "event":{  },
          "dataSource":"Airline",
          "dateTimeRecorded":"2017-12-05T08:36:24.957Z",
          "rule":{  },
          "flightStatus":{
             "flightId":"942163187",
             "carrierFsCode":"9W",
             "flightNumber":"527",
             "departureAirportFsCode":"DXB",
             "arrivalAirportFsCode":"COK",
             "departureDate":{
                "dateLocal":"2017-12-05T12:25:00.000",
                "dateUtc":"2017-12-05T08:25:00.000Z"
             },
             "arrivalDate":{
                "dateLocal":"2017-12-05T17:50:00.000",
                "dateUtc":"2017-12-05T12:20:00.000Z"
             },...............
............................

API response like this(this response i get in my email,when i give mail email id as the service).
How i can store the 'flightId','flightNumber' etc to the database?

Body:
// remove json_decode
    $data = json_decode(file_get_contents('php://input'), true);

to

$data = file_get_contents('php://input');

$que = mysqli_query($con,"insert into firetable (datas) values ('$data')");

data will be stored in JSON format in DB.


问:
Why distinct produces syntax error when mixed with other none distinct rows?
All these attempts fail:

```<code>SELECT DISTINCT(row1,row2), * FROM foo

SELECT *, DISTINCT (row1,row2) FROM foo

SELECT *, DISTINCT row1,row2 FROM foo
</code>```

I want to fetch all rows but not duplicate rows on row1 & row2

PS. I don't want to use GROUP By.

Thanks!

答:
You can only use DISTINCT on the entire row, not part of it.

PS. I don't want to use GROUP By.

That's a shame, because GROUP BY would have been the correct way to do this.

Body:
All these attempts fail:

SELECT DISTINCT(row1,row2), * FROM foo

SELECT *, DISTINCT (row1,row2) FROM foo

SELECT *, DISTINCT row1,row2 FROM foo

I want to fetch all rows but not duplicate rows on row1 & row2

PS. I don't want to use GROUP By.

Thanks!


答:
Simply you can use json_decode function:

```<code>$obj = json_decode($json,true); // this is the string you are storing in the database
echo $obj['alert'][0]['flightStatus'][0]['flightId']; // here is 942163187
</code>```

More information about the function:
enter link description here

Title: Recive a alert API in PHP POST web service

Body:
Simply you can use json_decode function:

$obj = json_decode($json,true); // this is the string you are storing in the database
echo $obj['alert'][0]['flightStatus'][0]['flightId']; // here is 942163187

More information about the function:
enter link description here


问:
Two Android App with SalesForce Sdk conflicting on single device
I have two android app with the SalesForce SDK integrated, but the case is if I installed one app in mobile and I launched another then it's SalesForce login page is not getting appeared.

Please give me solution or tell me the reason why it is happening if anyone know.

Thanks in advance.

答:
Add "account_type" tag in your strings.xml

It will avoid conflict of two sales force sdk in single device.


问:
Creating MongoDB documents inside chained Promisified functions
An app runs a process every 15 minutes that creates many output files with the following format:

```<code><timestamp>-<piece-code>.txt
</code>```

All files created by the process will share the "timestamp" component but the "piece-code" will differ, meaning I have a relationship of One Timestamp to Many Pieces, that I want to save in mongodb as:

```<code>"Registry" { time: (numeric) }
"Piece" { file: (string), piece: (string), registry: (reference) }
</code>```

In the process I want to find if a timestamp exists already before creating it to avoid duplicates, but my code seems to fail to do this.

Thanks in advance for your help!

```<code>const mongoose = require('mongoose');

const Registry = require('../model/Registry');
const Piece = require('../model/Piece');
mongoose.Promise = require('bluebird');

// Set up default mongoose connection
let mongoDB = 'mongodb://127.0.0.1/numbers';
mongoose.connect(mongoDB, {
  useMongoClient: true
});

//Get the default connection
let db = mongoose.connection;

// Bind connection to error event
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Error handler
let error = (err) => {
  console.log("** Error: ", err);
  db.close();
};

// Finish routine
let finish = () => {
    console.log("I have finished");
    db.close();
};

// Create a number if it does not exist already
let newRegistry = (timestamp) => {
  return new Promise((resolve, reject) => {
    Registry.count({}).then((c) => { console.log(c) })

    // Does this Registry exist?
    Registry.findOne({ time: timestamp })
      .then((reg, err) => {
        if (err) {
          reject(err);
        }
        // Create when it does not exist
        if (!reg) {
          Registry.create({
            time: timestamp
          }).then((doc, err) => {
            if (err) {
              reject(err);
            }
            resolve(doc._id);
          })
          .catch(error);
        } else {
          // Else, resolve
          resolve(reg._id);
        }

      });
  });
}

let newPiece = (registryId, filename, piece) => {
  return Piece.create({
    registry: mongoose.Types.ObjectId(registryId),
    file: filename,
    piece: piece
  });

};

let createRegs = (files) => {
  return new Promise((resolve, reject) => {
    let promises = [];
    let total = files.length;
    for (let i=0; i<total; i++) {
      let fileAr = files[i].split("-");
      let time = fileAr[0];
      let piece = fileAr[1];

      let promise = newRegistry(time)
        .then((regId) => {
          return newPiece(regId, files[i], piece);
        });

      promises.push(promise);
    }

    Promise.all(promises)
      .then(() => {
        resolve();
      })
      .catch(error);
  });
}

// Register input time and file pieces: one "time" can have many "pieces"
let filenames = ["1512473256-e.txt", "1512471758-a.txt", "1512471892-a.txt", "1512471758-b.txt"];

// Must end up with 3 "Registry" and 4 "Piece" documents
createRegs(filenames)
  .then(finish)
  .catch(error);
</code>```

答:
Maybe it worth to get rid from duplicating numbers in your array?
By doing something like this:

```<code>let filtered = [];
numbers.forEach((num) => {
  // in case we don't have such entity creating it
  if (!filtered.includes(num)) {
    filtered.push(num);
  }
  // in case we have just returning resolved promise
  return Promise.resolve();
});
</code>```

And then create your entities in DB:

```<code>const promises = filtered.map(n => {
  Number.findOne({ number: n })
    .then(result => if(!result) {
      return Number.create({ number: n });
    }).catch(err => console.log(err));
});
Promise.all(promise).then(() => /* Doing what you want to do after saving */)
</code>```

Body:
An app runs a process every 15 minutes that creates many output files with the following format:

<timestamp>-<piece-code>.txt

All files created by the process will share the "timestamp" component but the "piece-code" will differ, meaning I have a relationship of One Timestamp to Many Pieces, that I want to save in mongodb as:

"Registry" { time: (numeric) }
"Piece" { file: (string), piece: (string), registry: (reference) }

In the process I want to find if a timestamp exists already before creating it to avoid duplicates, but my code seems to fail to do this.

Thanks in advance for your help!

const mongoose = require('mongoose');

const Registry = require('../model/Registry');
const Piece = require('../model/Piece');
mongoose.Promise = require('bluebird');

// Set up default mongoose connection
let mongoDB = 'mongodb://127.0.0.1/numbers';
mongoose.connect(mongoDB, {
  useMongoClient: true
});

//Get the default connection
let db = mongoose.connection;

// Bind connection to error event
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Error handler
let error = (err) => {
  console.log("** Error: ", err);
  db.close();
};

// Finish routine
let finish = () => {
    console.log("I have finished");
    db.close();
};

// Create a number if it does not exist already
let newRegistry = (timestamp) => {
  return new Promise((resolve, reject) => {
    Registry.count({}).then((c) => { console.log(c) })

    // Does this Registry exist?
    Registry.findOne({ time: timestamp })
      .then((reg, err) => {
        if (err) {
          reject(err);
        }
        // Create when it does not exist
        if (!reg) {
          Registry.create({
            time: timestamp
          }).then((doc, err) => {
            if (err) {
              reject(err);
            }
            resolve(doc._id);
          })
          .catch(error);
        } else {
          // Else, resolve
          resolve(reg._id);
        }

      });
  });
}

let newPiece = (registryId, filename, piece) => {
  return Piece.create({
    registry: mongoose.Types.ObjectId(registryId),
    file: filename,
    piece: piece
  });

};

let createRegs = (files) => {
  return new Promise((resolve, reject) => {
    let promises = [];
    let total = files.length;
    for (let i=0; i<total; i++) {
      let fileAr = files[i].split("-");
      let time = fileAr[0];
      let piece = fileAr[1];

      let promise = newRegistry(time)
        .then((regId) => {
          return newPiece(regId, files[i], piece);
        });

      promises.push(promise);
    }

    Promise.all(promises)
      .then(() => {
        resolve();
      })
      .catch(error);
  });
}

// Register input time and file pieces: one "time" can have many "pieces"
let filenames = ["1512473256-e.txt", "1512471758-a.txt", "1512471892-a.txt", "1512471758-b.txt"];

// Must end up with 3 "Registry" and 4 "Piece" documents
createRegs(filenames)
  .then(finish)
  .catch(error);

Body:
Maybe it worth to get rid from duplicating numbers in your array?
By doing something like this:

let filtered = [];
numbers.forEach((num) => {
  // in case we don't have such entity creating it
  if (!filtered.includes(num)) {
    filtered.push(num);
  }
  // in case we have just returning resolved promise
  return Promise.resolve();
});

And then create your entities in DB:

const promises = filtered.map(n => {
  Number.findOne({ number: n })
    .then(result => if(!result) {
      return Number.create({ number: n });
    }).catch(err => console.log(err));
});
Promise.all(promise).then(() => /* Doing what you want to do after saving */)


问:
Building Hadoop on Windows 7
I followed this tutorial for building Apache Hadoop in Windows 7 environment.
To cut the long story short. I can compile Hadoop with mvn compile command and can build  packages with mvn -package -DskipTests

However I am unable to mvn package -Pdist,native-win -DskipTests -Dtar
I get I/O exceptions and unable to resolve those exceptions.  I don't get these exception when building Hadoop without -Dtar parameter

Can someone help me in resolving these exceptions?

```<code>[INFO] Executing tasks
main:
      [get] Destination already exists (skipping): C:\hadoop\hadoop-hdfs-    project\hadoop-hdfs-httpfs\downloads\tomcat.tar.gz
    [mkdir] Created dir: C:\hadoop\hadoop-hdfs-project\hadoop-hdfs-httpfs\target\tomcat.exp
 [exec] tar (child): C\:hadoophadoop-hdfs-projecthadoop-hdfs-httpfs/downloads/tomcat.tar.gz: Cannot open: I/O error
 [exec] tar (child): Error is not recoverable: exiting now
 [exec]
 [exec] gzip: stdin: unexpected end of file
 [exec] tar: Child returned status 2
 [exec] tar: Error exit delayed from previous errors
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Apache Hadoop Main ................................ SUCCESS [  1.018 s]
[INFO] Apache Hadoop Project POM ......................... SUCCESS [  1.653 s]
[INFO] Apache Hadoop Annotations ......................... SUCCESS [  2.181 s]
[INFO] Apache Hadoop Assemblies .......................... SUCCESS [  0.200 s]
[INFO] Apache Hadoop Project Dist POM .................... SUCCESS [  2.889 s]
[INFO] Apache Hadoop Auth ................................ SUCCESS [  1.957 s]
[INFO] Apache Hadoop Auth Examples ....................... SUCCESS [  1.570 s]
[INFO] Apache Hadoop Common .............................. SUCCESS [ 50.085 s]
[INFO] Apache Hadoop Common Project ...................... SUCCESS [  0.090 s]
[INFO] Apache Hadoop HDFS ................................ SUCCESS [ 35.510 s]
[INFO] Apache Hadoop HttpFS .............................. FAILURE [  5.155 s]
[INFO] Apache Hadoop HDFS Project ........................ SKIPPED
[INFO] hadoop-yarn ....................................... SKIPPED
[INFO] hadoop-yarn-api ................................... SKIPPED
[INFO] hadoop-yarn-common ................................ SKIPPED
[INFO] hadoop-yarn-server ................................ SKIPPED
[INFO] hadoop-yarn-server-common ......................... SKIPPED
[INFO] hadoop-yarn-server-nodemanager .................... SKIPPED
[INFO] hadoop-yarn-server-web-proxy ...................... SKIPPED
[INFO] hadoop-yarn-server-resourcemanager ................ SKIPPED
[INFO] hadoop-yarn-server-tests .......................... SKIPPED
[INFO] hadoop-yarn-client ................................ SKIPPED
[INFO] hadoop-mapreduce-client ........................... SKIPPED
[INFO] hadoop-mapreduce-client-core ...................... SKIPPED
[INFO] hadoop-yarn-applications .......................... SKIPPED
[INFO] hadoop-yarn-applications-distributedshell ......... SKIPPED
[INFO] hadoop-yarn-site .................................. SKIPPED
[INFO] hadoop-yarn-project ............................... SKIPPED
[INFO] hadoop-mapreduce-client-common .................... SKIPPED
[INFO] hadoop-mapreduce-client-shuffle ................... SKIPPED
[INFO] hadoop-mapreduce-client-app ....................... SKIPPED
[INFO] hadoop-mapreduce-client-hs ........................ SKIPPED
[INFO] hadoop-mapreduce-client-jobclient ................. SKIPPED
[INFO] hadoop-mapreduce-client-hs-plugins ................ SKIPPED
[INFO] Apache Hadoop MapReduce Examples .................. SKIPPED
[INFO] hadoop-mapreduce .................................. SKIPPED
[INFO] Apache Hadoop MapReduce Streaming ................. SKIPPED
[INFO] Apache Hadoop Distributed Copy .................... SKIPPED
[INFO] Apache Hadoop Archives ............................ SKIPPED
[INFO] Apache Hadoop Rumen ............................... SKIPPED
[INFO] Apache Hadoop Gridmix ............................. SKIPPED
[INFO] Apache Hadoop Data Join ........................... SKIPPED
[INFO] Apache Hadoop Extras .............................. SKIPPED
[INFO] Apache Hadoop Pipes ............................... SKIPPED
[INFO] Apache Hadoop Tools Dist .......................... SKIPPED
[INFO] Apache Hadoop Tools ............................... SKIPPED
[INFO] Apache Hadoop Distribution ........................ SKIPPED
[INFO] Apache Hadoop Client .............................. SKIPPED
[INFO] Apache Hadoop Mini-Cluster ........................ SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:43 min
[INFO] Finished at: 2014-05-19T11:24:25+00:00
[INFO] Final Memory: 49M/179M
[INFO] ------------------------------------------------------------------------
[WARNING] The requested profile "native-win" could not be activated because it does not
exist.
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.6:run      dist) on project hadoop-hdfs-httpfs: An Ant BuildExcept ion has occured: exec returned: 2 -    > [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the
following articles:

[ERROR] [Help 1]     http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

[ERROR]

[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :hadoop-hdfs-httpfs
c:\hadoop>
</code>```

答:
If you are using Higher versions of Hadoop i.e. Hadoop-2.6, 2.7 or 2.8, then there is no need to build Hadoop-src for getting windows native Hadoop. Here is a GitHub link which has winutils for recent versions of Hadoop.

I have also faced the similar issue while building Hadoop-src using maven, these steps worked for me.

Download & Install Java in c:/java/

(make sure the path is this way, if java is installed in program
  files, then hadoop-env.cmd will not recognize java path )

Download Hadoop binary distribution.

(I am using binary distribution Hadoop-2.8.1)

Set Environment Variables:

```<code>JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"
</code>```

Hadoop will work on windows if Hadoop-src is built using maven in
  your windows machine. Building the Hadoop-src(distribution) will
  create a Hadoop binary distribution, which will work as windows native
  version.

But if you don't want to do that, then download pre-builted winutils of Hadoop distribution.
Here is a GitHub link, which has winutils of some versions of Hadoop.

(if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link)

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link & set JAVA_HOME path in hadoop-env.cmd file

From cmd go to:

```<code><HADOOP_HOME>/bin/> hdfs namenode -format
<HADOOP_HOME>/sbin> start-all.cmd
</code>```

Hope this helps.

Title: Building Hadoop on Windows 7

Body:
I followed this tutorial for building Apache Hadoop in Windows 7 environment.
To cut the long story short. I can compile Hadoop with mvn compile command and can build  packages with mvn -package -DskipTests

However I am unable to mvn package -Pdist,native-win -DskipTests -Dtar
I get I/O exceptions and unable to resolve those exceptions.  I don't get these exception when building Hadoop without -Dtar parameter

Can someone help me in resolving these exceptions?

[INFO] Executing tasks
main:
      [get] Destination already exists (skipping): C:\hadoop\hadoop-hdfs-    project\hadoop-hdfs-httpfs\downloads\tomcat.tar.gz
    [mkdir] Created dir: C:\hadoop\hadoop-hdfs-project\hadoop-hdfs-httpfs\target\tomcat.exp
 [exec] tar (child): C\:hadoophadoop-hdfs-projecthadoop-hdfs-httpfs/downloads/tomcat.tar.gz: Cannot open: I/O error
 [exec] tar (child): Error is not recoverable: exiting now
 [exec]
 [exec] gzip: stdin: unexpected end of file
 [exec] tar: Child returned status 2
 [exec] tar: Error exit delayed from previous errors
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Apache Hadoop Main ................................ SUCCESS [  1.018 s]
[INFO] Apache Hadoop Project POM ......................... SUCCESS [  1.653 s]
[INFO] Apache Hadoop Annotations ......................... SUCCESS [  2.181 s]
[INFO] Apache Hadoop Assemblies .......................... SUCCESS [  0.200 s]
[INFO] Apache Hadoop Project Dist POM .................... SUCCESS [  2.889 s]
[INFO] Apache Hadoop Auth ................................ SUCCESS [  1.957 s]
[INFO] Apache Hadoop Auth Examples ....................... SUCCESS [  1.570 s]
[INFO] Apache Hadoop Common .............................. SUCCESS [ 50.085 s]
[INFO] Apache Hadoop Common Project ...................... SUCCESS [  0.090 s]
[INFO] Apache Hadoop HDFS ................................ SUCCESS [ 35.510 s]
[INFO] Apache Hadoop HttpFS .............................. FAILURE [  5.155 s]
[INFO] Apache Hadoop HDFS Project ........................ SKIPPED
[INFO] hadoop-yarn ....................................... SKIPPED
[INFO] hadoop-yarn-api ................................... SKIPPED
[INFO] hadoop-yarn-common ................................ SKIPPED
[INFO] hadoop-yarn-server ................................ SKIPPED
[INFO] hadoop-yarn-server-common ......................... SKIPPED
[INFO] hadoop-yarn-server-nodemanager .................... SKIPPED
[INFO] hadoop-yarn-server-web-proxy ...................... SKIPPED
[INFO] hadoop-yarn-server-resourcemanager ................ SKIPPED
[INFO] hadoop-yarn-server-tests .......................... SKIPPED
[INFO] hadoop-yarn-client ................................ SKIPPED
[INFO] hadoop-mapreduce-client ........................... SKIPPED
[INFO] hadoop-mapreduce-client-core ...................... SKIPPED
[INFO] hadoop-yarn-applications .......................... SKIPPED
[INFO] hadoop-yarn-applications-distributedshell ......... SKIPPED
[INFO] hadoop-yarn-site .................................. SKIPPED
[INFO] hadoop-yarn-project ............................... SKIPPED
[INFO] hadoop-mapreduce-client-common .................... SKIPPED
[INFO] hadoop-mapreduce-client-shuffle ................... SKIPPED
[INFO] hadoop-mapreduce-client-app ....................... SKIPPED
[INFO] hadoop-mapreduce-client-hs ........................ SKIPPED
[INFO] hadoop-mapreduce-client-jobclient ................. SKIPPED
[INFO] hadoop-mapreduce-client-hs-plugins ................ SKIPPED
[INFO] Apache Hadoop MapReduce Examples .................. SKIPPED
[INFO] hadoop-mapreduce .................................. SKIPPED
[INFO] Apache Hadoop MapReduce Streaming ................. SKIPPED
[INFO] Apache Hadoop Distributed Copy .................... SKIPPED
[INFO] Apache Hadoop Archives ............................ SKIPPED
[INFO] Apache Hadoop Rumen ............................... SKIPPED
[INFO] Apache Hadoop Gridmix ............................. SKIPPED
[INFO] Apache Hadoop Data Join ........................... SKIPPED
[INFO] Apache Hadoop Extras .............................. SKIPPED
[INFO] Apache Hadoop Pipes ............................... SKIPPED
[INFO] Apache Hadoop Tools Dist .......................... SKIPPED
[INFO] Apache Hadoop Tools ............................... SKIPPED
[INFO] Apache Hadoop Distribution ........................ SKIPPED
[INFO] Apache Hadoop Client .............................. SKIPPED
[INFO] Apache Hadoop Mini-Cluster ........................ SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:43 min
[INFO] Finished at: 2014-05-19T11:24:25+00:00
[INFO] Final Memory: 49M/179M
[INFO] ------------------------------------------------------------------------
[WARNING] The requested profile "native-win" could not be activated because it does not
exist.
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.6:run      dist) on project hadoop-hdfs-httpfs: An Ant BuildExcept ion has occured: exec returned: 2 -    > [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the
following articles:

[ERROR] [Help 1]     http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

[ERROR]

[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :hadoop-hdfs-httpfs
c:\hadoop>

Body:
If you are using Higher versions of Hadoop i.e. Hadoop-2.6, 2.7 or 2.8, then there is no need to build Hadoop-src for getting windows native Hadoop. Here is a GitHub link which has winutils for recent versions of Hadoop.

I have also faced the similar issue while building Hadoop-src using maven, these steps worked for me.

Download & Install Java in c:/java/

(make sure the path is this way, if java is installed in program
  files, then hadoop-env.cmd will not recognize java path )

Download Hadoop binary distribution.

(I am using binary distribution Hadoop-2.8.1)

Set Environment Variables:

JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"

Hadoop will work on windows if Hadoop-src is built using maven in
  your windows machine. Building the Hadoop-src(distribution) will
  create a Hadoop binary distribution, which will work as windows native
  version.

But if you don't want to do that, then download pre-builted winutils of Hadoop distribution.
Here is a GitHub link, which has winutils of some versions of Hadoop.

(if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link)

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link & set JAVA_HOME path in hadoop-env.cmd file

From cmd go to:

<HADOOP_HOME>/bin/> hdfs namenode -format
<HADOOP_HOME>/sbin> start-all.cmd

Hope this helps.