问:
C++ Libcurl: curl_easy_perform returned error code 28 when transferring files from linux system to windows remote system
I’m using libcurl 7.37.0 in my C++ project to communicate with remote by FTP protocol.

below is the code.

```<code>curl_easy_setopt(CurlSessionHandle, CURLOPT_URL, remoteFileUrl);
curl_easy_setopt(CurlSessionHandle, CURLOPT_UPLOAD, ON);

// Set the input local file handle
curl_easy_setopt(CurlSessionHandle, CURLOPT_READDATA, localFileHandle);

// Set on/off all wanted options
// Enable ftp data connection
curl_easy_setopt(CurlSessionHandle, CURLOPT_NOBODY, OFF);

// Create missing directory into FTP path
curl_easy_setopt(CurlSessionHandle, CURLOPT_FTP_CREATE_MISSING_DIRS , ON) ;

// Set the progress function, in order to check the stop transfer request
curl_easy_setopt(CurlSessionHandle, CURLOPT_NOPROGRESS, OFF);
curl_easy_setopt(CurlSessionHandle, CURLOPT_PROGRESSFUNCTION, progressCb);
curl_easy_setopt(CurlSessionHandle, CURLOPT_PROGRESSDATA, this);

CURLcode Result = curl_easy_perform(CurlSessionHandle);
</code>```

many times i have observed uploading of files is failing due to error code 28.

CURLE_OPERATION_TIMEDOUT (28)
Operation timeout. The specified time-out period was reached according to the conditions.

i didn't set any timeout in the code, after doing a lot of search i came to know we can use CURLOPT_TIMEOUT to set the timeout value, by default it's value is 0 where it doesn't timeout until it finishes the respective operation, in my case i performed file upload operation.

after going through the wireshark logs, i have observed that when data transfer is initiated from port 20, i see libcurl sends [FIN,ACK] without any known reason to port 21, because of that remote sends response code 426(transfer aborted) to libcurl and it returns 28 error code to application.

Please check the image which has wireshark traces.

Source IP: 18 is Linux server & Destination IP: 36 is Windows remote system

This problem is happening randomly.
Could anyone know the reason & a way to avoid this problem.

答: When this issue occurs, reset the curl context CurlSessionHandle and re initialize it. This might work.</p>

Body:
I’m using libcurl 7.37.0 in my C++ project to communicate with remote by FTP protocol.

below is the code.

curl_easy_setopt(CurlSessionHandle, CURLOPT_URL, remoteFileUrl);
curl_easy_setopt(CurlSessionHandle, CURLOPT_UPLOAD, ON);

// Set the input local file handle
curl_easy_setopt(CurlSessionHandle, CURLOPT_READDATA, localFileHandle);

// Set on/off all wanted options
// Enable ftp data connection
curl_easy_setopt(CurlSessionHandle, CURLOPT_NOBODY, OFF);

// Create missing directory into FTP path
curl_easy_setopt(CurlSessionHandle, CURLOPT_FTP_CREATE_MISSING_DIRS , ON) ;

// Set the progress function, in order to check the stop transfer request
curl_easy_setopt(CurlSessionHandle, CURLOPT_NOPROGRESS, OFF);
curl_easy_setopt(CurlSessionHandle, CURLOPT_PROGRESSFUNCTION, progressCb);
curl_easy_setopt(CurlSessionHandle, CURLOPT_PROGRESSDATA, this);

CURLcode Result = curl_easy_perform(CurlSessionHandle);

many times i have observed uploading of files is failing due to error code 28.

CURLE_OPERATION_TIMEDOUT (28)
Operation timeout. The specified time-out period was reached according to the conditions.

i didn't set any timeout in the code, after doing a lot of search i came to know we can use CURLOPT_TIMEOUT to set the timeout value, by default it's value is 0 where it doesn't timeout until it finishes the respective operation, in my case i performed file upload operation.

after going through the wireshark logs, i have observed that when data transfer is initiated from port 20, i see libcurl sends [FIN,ACK] without any known reason to port 21, because of that remote sends response code 426(transfer aborted) to libcurl and it returns 28 error code to application.

Please check the image which has wireshark traces.

Source IP: 18 is Linux server & Destination IP: 36 is Windows remote system

This problem is happening randomly.
Could anyone know the reason & a way to avoid this problem.


来源: stackexchange

问:
What is the purpose of VSTS dot net core build task version 2 purpose
What is the difference between the version one?

答:
.NET Core BUild task (dotnet build) only build the specified project and it's dependencies. It not provide converting .ts to .js and js.map (you can refer TypeScript).

More detail about dotnet build, you can refer dotnet-build.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Check validity of UMLS licence in UmlsDictionaryLookupAnnotator
In UmlsDictionaryLookupAnnotator there is a function isValidUMLSUser having four parameters. In which two of them are username and pass which i have entered correctly but other two are license code and url. Can anyone help me out to find the correct URL if they have used up for validating user.</p>

答:
URL is

```<code>https://uts-ws.nlm.nih.gov/restful/isValidUMLSUser?user=gprakhar&password=XXXXXXXXX&licenseCode=NLM-999915557
</code>```

Just so you know this URL is part of UMLS REST API for user validation.

BTW why exactly do you need need to call 'isValidUMLSUser' function ?

I ask since it is automatically called whenever a Analysis Engine uses UMLS dictionary components.

Hope this helps.

Body:
URL is

https://uts-ws.nlm.nih.gov/restful/isValidUMLSUser?user=gprakhar&password=XXXXXXXXX&licenseCode=NLM-999915557

Just so you know this URL is part of UMLS REST API for user validation.

BTW why exactly do you need need to call 'isValidUMLSUser' function ?

I ask since it is automatically called whenever a Analysis Engine uses UMLS dictionary components.

Hope this helps.


问:
Kotlin android studio I try to change the button text but get an "exepected a value of type boolean" message
Kotlin in Android Studio. I'm trying to change the button text but I'm getting an "exepected a value of type boolean" message. How can I fix this?

```<code>    button11.setOnLongClickListener{
        button11.text = ""
    }
</code>```

答:
The onLongClick method in the View.OnLongClickListener interface that you're implementing here via SAM conversion returns a boolean value, signaling whether you've consumed the long click event.

Therefore, you need to return a Boolean from your lambda in Kotlin, for example, like this (the last expression of a lambda is returned):

```<code>button11.setOnLongClickListener {
    button11.text = ""
    true
}
</code>```

Body:
Kotlin in Android Studio. I'm trying to change the button text but I'm getting an "exepected a value of type boolean" message. How can I fix this?

    button11.setOnLongClickListener{
        button11.text = ""
    }

Body:
The onLongClick method in the View.OnLongClickListener interface that you're implementing here via SAM conversion returns a boolean value, signaling whether you've consumed the long click event.

Therefore, you need to return a Boolean from your lambda in Kotlin, for example, like this (the last expression of a lambda is returned):

button11.setOnLongClickListener {
    button11.text = ""
    true
}


问:
How to run and work with Node.js on my remote VPS
Maybe it is dummy or noob question, but this is the first time I am trying to run / deploy my local Node.js application to the internet via my VPS hosting.

When working locally, I am using nodemon package to auto restart the server on each change.
Also, when turn off the terminal or shut down the Mac, the Node.js will be shut down too.

How these things could be handled via a remote VPS with a public domain?

Btw, another thing is how to compress/compile/hide/secure my client side code so it wont be able to be read or something.
I am asking this because when I am doing source code, It is very clear to see the whole app requests and therefore "play" with this.

Thanks.

答:
check out pm2 (production node manager)
you can install like this

```<code>npm install pm2 -g
</code>```

so instead of nodemon app.js you'll run

```<code>pm2 start app.js
</code>```

instead. This keeps your app running even if you restart your server
check out the official site for more info on pm2

Body:
check out pm2 (production node manager)
you can install like this

npm install pm2 -g

so instead of nodemon app.js you'll run

pm2 start app.js

instead. This keeps your app running even if you restart your server
check out the official site for more info on pm2


问:
How to apply css in JSP?
```<code> #section>.snb .tit{position:relative;}
    #section>.snb .tit h1{color:#2765b1;font-size:20px;text-indent:25px;}
</code>```

I am not sure how to apply the css code above to jsp page. It looks different from the basic css with

```<code>body {
    background: #00ff00 url("smiley.gif") no-repeat fixed center;
}
</code>```

kind format.

答:
You can apply like this :

test text

```
</div>
</div>
</p>

<p>Please refer this it will help you to understand css selectors.
In  </p>

```#section>.snb .tit h1{color:#2765b1;font-size:20px;text-indent:25px;}
```

it look for h1 tag in element with 'tit' class inside all element's with class value as 'snb' in element with id 'section'.

Title: How to apply css in JSP?

Body:
 #section>.snb .tit{position:relative;}
    #section>.snb .tit h1{color:#2765b1;font-size:20px;text-indent:25px;}

I am not sure how to apply the css code above to jsp page. It looks different from the basic css with

body {
    background: #00ff00 url("smiley.gif") no-repeat fixed center;
}

kind format.

Body:
You can apply like this :

<html>
<head>
<style>
 #section>.snb .tit{position:relative;}
    #section>.snb .tit h1{color:#2765b1;font-size:20px;text-indent:25px;}

</style>
</head>
<body>

<div id="section">
<div class="snb">
<div class="tit">
<h1>test text</h1>
</div>
</div>
</div>

</body>
</html>

Please refer this it will help you to understand css selectors.
In

#section>.snb .tit h1{color:#2765b1;font-size:20px;text-indent:25px;}

it look for h1 tag in element with 'tit' class inside all element's with class value as 'snb' in element with id 'section'.


问:
How can I use DataProvider and CGridView in Yii to display array in array data?
now i have the code like this:

```<code>$testArray1 = array(array(
                    'user_id'=>'1',
                    'name'=>array(
                        'david',
                        'haword'),
                    ),
                    array(
                    'user_id'=>'2',
                    'name'=>'andrew',
                    ),
            );

            print_r($testArray1);
            $arrayDataProvider = new CArrayDataProvider ($testArray1,array(
                //'KeyField'=>'_id',
                'pagination'=>array(
                    'pageSize'=>10,
                ),
                'sort'=>array(
                ),
            ));
            $this->widget('zii.widgets.grid.CGridView', array(
                'id' =>'BCImported-grid',
                'dataProvider' =>$arrayDataProvider,
                'columns' =>array('name'),
            ));
</code>```

here is my result:

so the form only display name = andrew,and name = david and haword is not display.
how can I use DataProvider and CGridView in Yii to display array in array data like name = david and haword where 'user_id'=>'1'?

答:
there is no way to display array in CGridView except you custom that value.
create some static function in your model

```<code>public static function implodeName($data)
{
    if(isset($data['name'])) {
        if(is_array($data['name'])) {
            return implode(',', $data['name']);
        }
        else {
            return $data['name'];
        }
    }
    return '';
}
</code>```

then in CGridView will be like this

```<code> $this->widget('zii.widgets.grid.CGridView', array(
        'id' =>'BCImported-grid',
        'dataProvider' =>$arrayDataProvider,
        'columns' =>array(
            array(
              'header' => 'Names',
              'name' => 'name',
              'value' => 'YourModelName::implodeName($data)'
            ),
        ),
 ));
</code>```

and the result should be :
david, hawords

Body:
now i have the code like this:

$testArray1 = array(array(
                    'user_id'=>'1',
                    'name'=>array(
                        'david',
                        'haword'),
                    ),
                    array(
                    'user_id'=>'2',
                    'name'=>'andrew',
                    ),
            );

            print_r($testArray1);
            $arrayDataProvider = new CArrayDataProvider ($testArray1,array(
                //'KeyField'=>'_id',
                'pagination'=>array(
                    'pageSize'=>10,
                ),
                'sort'=>array(
                ),
            ));
            $this->widget('zii.widgets.grid.CGridView', array(
                'id' =>'BCImported-grid',
                'dataProvider' =>$arrayDataProvider,
                'columns' =>array('name'),
            ));

here is my result:

so the form only display name = andrew,and name = david and haword is not display.
how can I use DataProvider and CGridView in Yii to display array in array data like name = david and haword where 'user_id'=>'1'?

Body:
there is no way to display array in CGridView except you custom that value.
create some static function in your model

public static function implodeName($data)
{
    if(isset($data['name'])) {
        if(is_array($data['name'])) {
            return implode(',', $data['name']);
        }
        else {
            return $data['name'];
        }
    }
    return '';
}

then in CGridView will be like this

 $this->widget('zii.widgets.grid.CGridView', array(
        'id' =>'BCImported-grid',
        'dataProvider' =>$arrayDataProvider,
        'columns' =>array(
            array(
              'header' => 'Names',
              'name' => 'name',
              'value' => 'YourModelName::implodeName($data)'
            ),
        ),
 ));

and the result should be :
david, hawords


问:
C pointer to another struct
i'm currently reading some source codes for packet sending. For the following pseudo code, for the line "packet->packet2 = (char*) data", what does it mean actually? Can i understand as storing the character datatype in variable data into packet2, which is also defined as a character datatype?</p>

```<code>struct Node1
{
    char packet1;
    int num1;
}

struct Node2
{
   char *packet2;
   int num2;
}

int main(void)
{
   struct Node1 *data;
   struct Node1 var1;

   struct Node2 *packet;
   struct node2 var2;

   data = &var1;
   packet = &var2;

   packet->packet2 = (char*) data;
}
</code>```

答:
```<code>struct Node1
{
    Node2*/or Node1*.... packet1;
    int num1;
}

struct Node2
{
   Node1* packet2;
   int num2;
}

int main(void)
{
   struct Node1 *data;
   struct Node1 var1;

   struct Node2 *packet;
   struct Node2 var2;

   data = &var1;
   packet = &var2;

   packet->packet2 =  data;
}
</code>```

Title: C pointer to another struct

Body:
i'm currently reading some source codes for packet sending. For the following pseudo code, for the line "packet->packet2 = (char*) data", what does it mean actually? Can i understand as storing the character datatype in variable data into packet2, which is also defined as a character datatype?

struct Node1
{
    char packet1;
    int num1;
}

struct Node2
{
   char *packet2;
   int num2;
}

int main(void)
{
   struct Node1 *data;
   struct Node1 var1;

   struct Node2 *packet;
   struct node2 var2;

   data = &var1;
   packet = &var2;

   packet->packet2 = (char*) data;
}


问:
Get item positions in string array android?
Let's say I have an array like this:

```<code>String[] = {
    "#abc #def",
    "#abc",
    "#def",
    "#xyz #def"
}
</code>```

My question is I want to search for specific character or string like "#abc" or "a" and get their positions in the array.

答:
```<code>String[] values = { "1a", "2a", "3a"};
int pos = new ArrayList<String>(Arrays.asList(values)).indexOf("3a");
</code>```

Body:
Let's say I have an array like this:

String[] = {
    "#abc #def",
    "#abc",
    "#def",
    "#xyz #def"
}

My question is I want to search for specific character or string like "#abc" or "a" and get their positions in the array.


问:
ionic build ios error ( ionic cordova build ios )
When i run "ionic cordova build ios" get error below in terminal:

The following build commands failed:
    Ld build/emulator/Posify\ Kitchen.app/Posify\ Kitchen normal x86_64
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/YJD/Mayun_POS/posify-pos-fb-united/platforms/ios/cordova/build-debug.xcconfig,-workspace,Posify Kitchen.xcworkspace,-scheme,Posify Kitchen,-configuration,Debug,-sdk,iphonesimulator,-destination,platform=iOS Simulator,name=iPhone X,build,CONFIGURATION_BUILD_DIR=/Users/YJD/Mayun_POS/posify-pos-fb-united/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/YJD/Mayun_POS/posify-pos-fb-united/platforms/ios/build/sharedpch

ionic info:

cli packages: (/Users/YJD/Mayun_POS/posify-pos-fb-united/node_modules)

```<code>@ionic/cli-utils  : 1.17.0
ionic (Ionic CLI) : 3.17.0
</code>```

global packages:

```<code>cordova (Cordova CLI) : 7.1.0
</code>```

local packages:

```<code>@ionic/app-scripts : 1.3.7
Cordova Platforms  : android 6.3.0 ios 4.5.3
Ionic Framework    : ionic-angular 3.8.0
</code>```

System:

```<code>ios-deploy : 1.9.2
Node       : v6.11.5
npm        : 5.5.1
OS         : macOS Sierra
Xcode      : Xcode 9.0.1 Build version 9A1004
</code>```

Environment Variables:

```<code>ANDROID_HOME : not set
</code>```

Misc:

```<code>backend : pro
</code>```

答: I figured it out myself. All of errors seem like "Error: Error code 65 for command: xcodebuild......" are because of certification or Provision profile.I applied the newest provision profile and it fixed.</p>

Body:
When i run "ionic cordova build ios" get error below in terminal:

The following build commands failed:
    Ld build/emulator/Posify\ Kitchen.app/Posify\ Kitchen normal x86_64
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/YJD/Mayun_POS/posify-pos-fb-united/platforms/ios/cordova/build-debug.xcconfig,-workspace,Posify Kitchen.xcworkspace,-scheme,Posify Kitchen,-configuration,Debug,-sdk,iphonesimulator,-destination,platform=iOS Simulator,name=iPhone X,build,CONFIGURATION_BUILD_DIR=/Users/YJD/Mayun_POS/posify-pos-fb-united/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/YJD/Mayun_POS/posify-pos-fb-united/platforms/ios/build/sharedpch

ionic info:

cli packages: (/Users/YJD/Mayun_POS/posify-pos-fb-united/node_modules)

@ionic/cli-utils  : 1.17.0
ionic (Ionic CLI) : 3.17.0

global packages:

cordova (Cordova CLI) : 7.1.0

local packages:

@ionic/app-scripts : 1.3.7
Cordova Platforms  : android 6.3.0 ios 4.5.3
Ionic Framework    : ionic-angular 3.8.0

System:

ios-deploy : 1.9.2
Node       : v6.11.5
npm        : 5.5.1
OS         : macOS Sierra
Xcode      : Xcode 9.0.1 Build version 9A1004

Environment Variables:

ANDROID_HOME : not set

Misc:

backend : pro


问:
flex box button element not getting 50% of width

div{
  display:flex;
  border:1px solid red;
}

div button{
  flex:0 0 1;
  border:1px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
   <button>Button one</button>
   <button>Button two</button>
</div></code>```

答:
Try this

div{
  display:flex;
  border:1px solid red;
}

div button{
  flex: 1;
  border:1px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
   <button>Button one</button>
   <button>Button two</button>
</div></code>```

Body:
div{
  display:flex;
  border:1px solid red;
}

div button{
  flex:0 0 1;
  border:1px solid gray;
}

   <button>Button one</button>
   <button>Button two</button>

Body:
Try this

div{
  display:flex;
  border:1px solid red;
}

div button{
  flex: 1;
  border:1px solid gray;
}

<div>
   <button>Button one</button>
   <button>Button two</button>
</div>


问:
How to give border to any element using css without adding border-width to the whole width of element?
How to give border to any element using css without adding border-width to the whole width of element?

Like in Photoshop we can give stroke-  Inside , center and outside

I think default css border properties is center like center in photoshop, am i right?

I want to give border inside the box not outside. and don't want to include border width in box width.

答:
outline:3px solid black || border:3px solid black

div{
height:50px;
width:150px;
text-align:center;

}

div{    /*this is what you need ! */
outline:1px solid black
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
hello world
</div></code>```

Body:
outline:3px solid black || border:3px solid black

div{
height:50px;
width:150px;
text-align:center;

}

div{    /*this is what you need ! */
outline:1px solid black
}

<div>
hello world
</div>


问:
Showing part of the ImageView which is cover by another ImageView
I have a Framelayout, where the first element is an ImageView which height and width is match parent and let the id is A. Second element is also an ImageView which height and width also match parent and let the id is B. Third element is a View which height and width is 100 dp and can be move to the whole screen and let the id is C. I am using transparent color in background C, so inside C we should see B, because B is above A. But I want to show A in inside C , how can I do that?</p>

答: use relative layout to wrap your framelayout then you can use layout above and then work with visibility of views</p>


问:
Array highest value or create next value?
I have an array of names and id's.

```<code>Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)
</code>```

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

答:
Start by dividing your task into smaller ones. The first filter criterion seems to be can=1. Let's check that with array_filter.

```<code>$ar = array(array('name'=>'New York', 'id'=>45763448349, 'can'=>1), array('name'=>'New York2', 'id'=>45763464566, 'can'=>0), array('name'=>'New York3', 'id'=>45763464854, 'can'=>0), array('name'=>'New York4', 'id'=>45763464955, 'can'=>0), array('name'=>'New York5', 'id'=>45763464745, 'can'=>0), array('name'=>'New York6', 'id'=>45763464235, 'can'=>1), array('name'=>'New Yorkistan', 'id'=>0, 'can'=1));
$ar = array_filter($ar, function($el) {return $el['can'];});
// Now $ar contains the entries 'New York', 'New York2', and 'New Yorkistan'
</code>```

Now, filter out the entries which do not match New York(and a number).

```<code>$ar = array_filter($ar, function($el) {
    $search = 'New York';
    $name = $ar['name'];
    $potentialNumber = substr($name, strlen($search));
    return ((substr($name, 0, strlen($search)) == $search) && // starts with NY
            ($potentialNumber == '' || is_numeric($potentialNumber)); // [0-9]*
});
// $ar contains only 'New York' and 'New York6' now
</code>```

Now, you just need some sorting with usort and pick the first element:

```<code>usort($ar, function($el1, $el2) {
    $id1 = $el1['id']; $id2 = $el2['id'];
    if ($id1 == $id2) return 0;
    return $id1 < $id2 ? 1 : -1;
});
if (count($ar) > 0) {
    $result = $ar[0];
} else {
    // Nothing matched your criteria
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an array of names and id's.

Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

Body:
Start by dividing your task into smaller ones. The first filter criterion seems to be can=1. Let's check that with array_filter.

$ar = array(array('name'=>'New York', 'id'=>45763448349, 'can'=>1), array('name'=>'New York2', 'id'=>45763464566, 'can'=>0), array('name'=>'New York3', 'id'=>45763464854, 'can'=>0), array('name'=>'New York4', 'id'=>45763464955, 'can'=>0), array('name'=>'New York5', 'id'=>45763464745, 'can'=>0), array('name'=>'New York6', 'id'=>45763464235, 'can'=>1), array('name'=>'New Yorkistan', 'id'=>0, 'can'=1));
$ar = array_filter($ar, function($el) {return $el['can'];});
// Now $ar contains the entries 'New York', 'New York2', and 'New Yorkistan'

Now, filter out the entries which do not match New York(and a number).

$ar = array_filter($ar, function($el) {
    $search = 'New York';
    $name = $ar['name'];
    $potentialNumber = substr($name, strlen($search));
    return ((substr($name, 0, strlen($search)) == $search) && // starts with NY
            ($potentialNumber == '' || is_numeric($potentialNumber)); // [0-9]*
});
// $ar contains only 'New York' and 'New York6' now

Now, you just need some sorting with usort and pick the first element:

usort($ar, function($el1, $el2) {
    $id1 = $el1['id']; $id2 = $el2['id'];
    if ($id1 == $id2) return 0;
    return $id1 < $id2 ? 1 : -1;
});
if (count($ar) > 0) {
    $result = $ar[0];
} else {
    // Nothing matched your criteria
}


问:
JMeter Groovy re execute a Sampler X times under condition
I want to re execute a Sampler for 5 times or until a certain variable has the value "true", Is there any method in Groovy or do I have to do something in JMeter?</p>

答:
Just use While Controller with condition like

```<code>${__javaScript(("${certain variable}" != "true" && ${counter} < 5),)}
</code>```

Where counter is the reference name of the Counter test element.

Put the request you want to re-execute as a child of the While Controller and it will be something you're looking for

Body:
Just use While Controller with condition like

${__javaScript(("${certain variable}" != "true" && ${counter} < 5),)}

Where counter is the reference name of the Counter test element.

Put the request you want to re-execute as a child of the While Controller and it will be something you're looking for


问:
Am I using flex correctly in this situation?
Say I want to a container of courses that would look something like this

Is this bad making essentially each part of the "course" it's own flexbox?

.course-container {
  display: flex;
  flex-direction: column;
}

.course-options {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.course-title {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.course-grade {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="course-container">
  <div class="course">
    <div class="course-options">
      <i class='fa fa-pencil-square-o fa-lg' aria-hidden="true"></i>
      <i class='fa fa-trash-o fa-lg' aria-hidden="true"></i>
    </div>
    <div class="course-title">
      Course 1
    </div>
    <div class="course-grade">
      Grade: 0.00%
    </div>
  </div>
  <div class="course">
    <div class="course-options">
      <i class='fa fa-pencil-square-o fa-lg' aria-hidden="true"></i>
      <i class='fa fa-trash-o fa-lg' aria-hidden="true"></i>
    </div>
    <div class="course-title">
      Course 2
    </div>
    <div class="course-grade">
      Grade: 0.00%
    </div>
  </div>
</div></code>```

答:
This situation does NOT require flexbox. Flexbox still has less than 90% browser support worldwide (unprefixed), so I would not use it yet, unless you have absolutely no alternative.

This is a proper solution that works in all browsers:

.card {
  text-align: center;
  position: relative;
  width: 100%;
  max-width: 300px;
  height: 100px;
  line-height: 100px;
  border: 1px solid black;
  margin: 5px;
}
.card > * {line-height: 1.4em; position: absolute;}
.card > .edit {left: 0; top: 0;}
.card > .delete {right: 0; top: 0;}
.card > .grade {right: 0; bottom: 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
  edit
  delete
  <span class="grade">grade</span>
  course 1
</div>
<div class="card">
  edit
  delete
  <span class="grade">grade</span>
  course 2
</div></code>```

Body:
Say I want to a container of courses that would look something like this

Is this bad making essentially each part of the "course" it's own flexbox?

.course-container {
  display: flex;
  flex-direction: column;
}

.course-options {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.course-title {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.course-grade {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

      Course 1

      Grade: 0.00%

      Course 2

      Grade: 0.00%

Body:
This situation does NOT require flexbox. Flexbox still has less than 90% browser support worldwide (unprefixed), so I would not use it yet, unless you have absolutely no alternative.

This is a proper solution that works in all browsers:

.card {
  text-align: center;
  position: relative;
  width: 100%;
  max-width: 300px;
  height: 100px;
  line-height: 100px;
  border: 1px solid black;
  margin: 5px;
}
.card > * {line-height: 1.4em; position: absolute;}
.card > .edit {left: 0; top: 0;}
.card > .delete {right: 0; top: 0;}
.card > .grade {right: 0; bottom: 0;}

<div class="card">
  <a href="#" class="edit">edit</a>
  <a href="#" class="delete">delete</a>
  <span class="grade">grade</span>
  course 1
</div>
<div class="card">
  <a href="#" class="edit">edit</a>
  <a href="#" class="delete">delete</a>
  <span class="grade">grade</span>
  course 2
</div>


问:
Xamarin Mono ClientWebSocket implementation doesn't work for secure sockets
I'm having issues implementing a secure web socket client on Osx.
I am using ClientWebSocket from System.Net.WebSockets. Here is some test code:

```<code>    static async Task RunLoop()
    {
        ClientWebSocket ws = new ClientWebSocket();
        await ws.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None);

        do
        {
            Console.Write("Enter message:");
            var msg = Console.ReadLine();
            if (msg == "quit")
            {
                break;
            }

            var b = new ArraySegment<byte>(UTF8Encoding.UTF8.GetBytes(msg));
            await ws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);

            byte[] bb = new byte[2048];
            ArraySegment<byte> buffer = new ArraySegment<byte>(bb);

            var result = await ws.ReceiveAsync(buffer, CancellationToken.None);

            switch (result.MessageType)
            {
                case WebSocketMessageType.Text:
                    Console.WriteLine(UTF8Encoding.UTF8.GetString(buffer.Array));
                    break;
                case WebSocketMessageType.Close:
                    await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                    break;
            }

        } while (true);
    }

    static void Main(string[] args)
    {
        var task = RunLoop();
        task.Wait();
    }
</code>```

Every time I received this exception when ReceiveAsync is called.

```<code>Cannot access a disposed object.
</code>```

Object name: 'System.Net.Sockets.NetworkStream'.

```<code>    at System.Net.WebConnection.Read (System.Net.HttpWebRequest request, System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x0001f] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/System/System.Net/WebConnection.cs:1038
  at System.Net.WebSockets.ClientWebSocket+<ReceiveAsync>c__AnonStorey5.<>m__0 () [0x0017c] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/System/System.Net.WebSockets/ClientWebSocket.cs:259
  at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x00012] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/threading/Tasks/Future.cs:680
  at System.Threading.Tasks.Task.Execute () [0x00016] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/threading/Tasks/Task.cs:2502
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
      at Test.MainClass+<RunLoop>c__async2.MoveNext () [0x001c0] in Program.cs:81
</code>```

It looks like the socket is somehow getting disposed but I have no idea why and where. The same code works fine for non secure websockets ("ws://echo.websocket.org").

Tried also WebSocket.Portable implementation but had almost the same issues. For non secure websockets it worked fine but for secure websockets the OnMessage event was never called.
    https://github.com/NVentimiglia/WebSocket.Portable

答:
I found an workaround for this issue. I used SocketRocker which is an Objective C implementation. Square.SocketRocket is a Xamarin wrapper for the native Objective C library.
On GitHub you will find also some examples in the sample directory. </p>

Body:
I'm having issues implementing a secure web socket client on Osx.
I am using ClientWebSocket from System.Net.WebSockets. Here is some test code:

    static async Task RunLoop()
    {
        ClientWebSocket ws = new ClientWebSocket();
        await ws.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None);

        do
        {
            Console.Write("Enter message:");
            var msg = Console.ReadLine();
            if (msg == "quit")
            {
                break;
            }

            var b = new ArraySegment<byte>(UTF8Encoding.UTF8.GetBytes(msg));
            await ws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);

            byte[] bb = new byte[2048];
            ArraySegment<byte> buffer = new ArraySegment<byte>(bb);

            var result = await ws.ReceiveAsync(buffer, CancellationToken.None);

            switch (result.MessageType)
            {
                case WebSocketMessageType.Text:
                    Console.WriteLine(UTF8Encoding.UTF8.GetString(buffer.Array));
                    break;
                case WebSocketMessageType.Close:
                    await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                    break;
            }

        } while (true);
    }

    static void Main(string[] args)
    {
        var task = RunLoop();
        task.Wait();
    }

Every time I received this exception when ReceiveAsync is called.

Cannot access a disposed object.

Object name: 'System.Net.Sockets.NetworkStream'.

    at System.Net.WebConnection.Read (System.Net.HttpWebRequest request, System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x0001f] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/System/System.Net/WebConnection.cs:1038
  at System.Net.WebSockets.ClientWebSocket+<ReceiveAsync>c__AnonStorey5.<>m__0 () [0x0017c] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/System/System.Net.WebSockets/ClientWebSocket.cs:259
  at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x00012] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/threading/Tasks/Future.cs:680
  at System.Threading.Tasks.Task.Execute () [0x00016] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/threading/Tasks/Task.cs:2502
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /private/tmp/source-mono-4.6.0-c8sr0/bockbuild-mono-4.6.0-branch-c8sr0/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
      at Test.MainClass+<RunLoop>c__async2.MoveNext () [0x001c0] in Program.cs:81

It looks like the socket is somehow getting disposed but I have no idea why and where. The same code works fine for non secure websockets ("ws://echo.websocket.org").

Tried also WebSocket.Portable implementation but had almost the same issues. For non secure websockets it worked fine but for secure websockets the OnMessage event was never called.
    https://github.com/NVentimiglia/WebSocket.Portable


问:
data grouping in pandas for dataFrame have same row value
I have csv file in below format

```<code>10  1
20  2
30  3
40  4
50  5
10  6
20  7
30  8
40  9
50  10
10  11
20  12
30  13
40  14
50  15
</code>```

Here col1 is input and col2 is output. I want this data to be transformed into something like this

```<code>10  1   6  11
20  2   7  12
30  3   8  13
40  4   9  14
50  5  10  15
</code>```

how can I do this using pandas?

Body:
I have csv file in below format

10  1
20  2
30  3
40  4
50  5
10  6
20  7
30  8
40  9
50  10
10  11
20  12
30  13
40  14
50  15

Here col1 is input and col2 is output. I want this data to be transformed into something like this

10  1   6  11
20  2   7  12
30  3   8  13
40  4   9  14
50  5  10  15

how can I do this using pandas?

Body:
I believe you need create groups by cumcount for new columns names and then reshape by unstack:

df = df.set_index(['a', df.groupby('a').cumcount()])['b'].unstack()
print (df)
    0   1   2
a
10  1   6  11
20  2   7  12
30  3   8  13
40  4   9  14
50  5  10  15

For dictionary use to_dict, but swap values in set_index:

d = df.set_index([df.groupby('a').cumcount(), 'a'])['b'].unstack().to_dict('l')
print (d)

{40: [4, 9, 14], 10: [1, 6, 11], 20: [2, 7, 12], 50: [5, 10, 15], 30: [3, 8, 13]}

Detail:

print (df.groupby('a').cumcount())
0     0
1     0
2     0
3     0
4     0
5     1
6     1
7     1
8     1
9     1
10    2
11    2
12    2
13    2
14    2
dtype: int64

Setup:

print (df)
     a   b
0   10   1
1   20   2
2   30   3
3   40   4
4   50   5
5   10   6
6   20   7
7   30   8
8   40   9
9   50  10
10  10  11
11  20  12
12  30  13
13  40  14
14  50  15


问:
How can I test my tls implementation written using HTTP component
For my current project i need to implement http over tls at client ,for this i need a local server able to simulate this . is there any online or offline tool. which i can use and and see the handshake in wireshark .</p>

答:
For achieving this you need a Web Server accepting connection over TLS.I have achieved this on Apache Tomcat web Server.

TLS configuration needs to be done in the server.xml file present in config directory of Tomcat webserver. Connector tag needs to be added in the server.xml file that contains information like
TLS version to be used, port, List of supported Cipher Suites, Keystore path and password, Truststore path and password.

Any regular Rest client can be used to make a call like Postman client. But to use that over TLS/SSL certificate is needed to be installed in Chrome browser.

Hope this answers your doubt.


问:
Is there a server-side dom engine suitable for crawling?
I found a project, jaxer which embeds Firefox's JavaScript engine on the server side, so it can parse HTML server-side very well. But, this project seems dead. It is really helpful for crawling web pages to parse HTML & extract data.

Is there some new technology useful for extracting information?

答: ItsNat is similar to Jaxer the main difference is Java based, instead of JavaScript.</p>


问:
Dev Mode for Node, Webpack-Dev-Server, React - No Such File or Directory for Nested Routes
I am trying to get my application to work in development mode with Node and Webpack-Dev-Server. When I serve up '/' I get back exactly what I intend. However, when I do '/test' I get 'no such file or directory'. I have read a lot of documentation on Webpack's website and React Router Training, none seem to really answer this issue. I want to be able to use browserHistory instead of hashHistory (I am still using React-Router v3).

package.json:

```<code>{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "clean": "rimraf dist",
    "build": "NODE_ENV=production npm run clean && webpack -p",
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.15.3",
    "babel-core": "^6.7.2",
    "babel-loader": "^6.2.4",
    "babel-plugin-transform-class-properties": "^6.22.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-react": "^6.5.0",
    "css-loader": "^0.26.1",
    "express": "^4.14.0",
    "html-webpack-plugin": "^2.26.0",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^4.4.1",
    "react-router": "^3.2.0",
    "redux": "^3.3.1",
    "redux-promise": "^0.5.3",
    "rimraf": "^2.5.4",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^3.8.1"
  },
  "devDependencies": {
    "nodemon": "^1.11.0",
    "webpack-dev-middleware": "^1.9.0",
    "webpack-dev-server": "^2.2.0-rc.0",
    "webpack-hot-middleware": "^2.20.0"
  }
}
</code>```

webpack.config.js

```<code>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const VENDOR_LIBS = [
  'axios', 'react', 'redux', 'react-dom', 'react-redux',
  'react-router', 'redux-promise'
];

module.exports = {
  entry: {
    bundle: './client/src/index.js',
    vendor: VENDOR_LIBS
  },
  output: {
    chunkFilename: '[name].[chunkhash].js',
    path: path.join(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      },
      {
        test: /\.(jpe?g|png|gif|svg|)$/,
        use: [
          {
            loader: 'url-loader',
            options: {limit: 40000}
          },
          'image-webpack-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new HtmlWebpackPlugin({
      template: './client/src/index.html'
    })
  ],
  devtool: 'inline-source-map',
  devServer: {
    contentBase: '/dist',
    historyApiFallback: true
  },
};
</code>```

server.js:

```<code>const express = require('express');
const path = require('path');
const app = express();

if (process.env.NODE_ENV !== 'production') {
  app.use(express.static(path.join(__dirname, 'dist')));
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const config = require('./webpack.config.js');
  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
  }));
} else {
  app.use(express.static('dist'));
}

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(process.env.PORT || 3050, () => console.log('Listening'));
</code>```

routes.js:

```<code>import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import App from './components/app';
import Home from './components/home';

const componentRoutes = (
  <Route component={App} path='/'>
    <Route component={Home} path='/test' />
  </Route>
);

const Routes = () => {
  return <Router history={ browserHistory } routes={ componentRoutes } />
};

export default Routes;
</code>```

The App component renders a single div saying it loaded and same for the Home component. If you care to see the entire thing on Github, here is a link:

https://github.com/jlag34/nodeWebpackSupport

The main goal is to be able to load '/test' in dev mode without using hashHistory.

Wepback docs: https://webpack.js.org/guides/development/

答:
The main goal is to be able to load '/test' in dev mode without using hashHistory.

React-router type as static, browser, hash and so one can be easily selected by generative jsx-function, which is selected by control flow or webpack predefined constants. Such technique is used for SSR (server-side rendering), when jsx with applied routes is returned, dependent on environment.

```<code>const RootComponent = () => {/* root component */};
const EntryPoint = process.env.NODE_ENV === 'production'
    ? (props) => (<BrowserRouter><RootComponent {...props} /></BrowserRouter>)
    : (props) => (<HashRouter><RootComponent {...props} /></HashRouter>)
export default EntryPoint
</code>```

Body:
I am trying to get my application to work in development mode with Node and Webpack-Dev-Server. When I serve up '/' I get back exactly what I intend. However, when I do '/test' I get 'no such file or directory'. I have read a lot of documentation on Webpack's website and React Router Training, none seem to really answer this issue. I want to be able to use browserHistory instead of hashHistory (I am still using React-Router v3).

package.json:

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "clean": "rimraf dist",
    "build": "NODE_ENV=production npm run clean && webpack -p",
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.15.3",
    "babel-core": "^6.7.2",
    "babel-loader": "^6.2.4",
    "babel-plugin-transform-class-properties": "^6.22.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-react": "^6.5.0",
    "css-loader": "^0.26.1",
    "express": "^4.14.0",
    "html-webpack-plugin": "^2.26.0",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^4.4.1",
    "react-router": "^3.2.0",
    "redux": "^3.3.1",
    "redux-promise": "^0.5.3",
    "rimraf": "^2.5.4",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^3.8.1"
  },
  "devDependencies": {
    "nodemon": "^1.11.0",
    "webpack-dev-middleware": "^1.9.0",
    "webpack-dev-server": "^2.2.0-rc.0",
    "webpack-hot-middleware": "^2.20.0"
  }
}

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const VENDOR_LIBS = [
  'axios', 'react', 'redux', 'react-dom', 'react-redux',
  'react-router', 'redux-promise'
];

module.exports = {
  entry: {
    bundle: './client/src/index.js',
    vendor: VENDOR_LIBS
  },
  output: {
    chunkFilename: '[name].[chunkhash].js',
    path: path.join(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      },
      {
        test: /\.(jpe?g|png|gif|svg|)$/,
        use: [
          {
            loader: 'url-loader',
            options: {limit: 40000}
          },
          'image-webpack-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new HtmlWebpackPlugin({
      template: './client/src/index.html'
    })
  ],
  devtool: 'inline-source-map',
  devServer: {
    contentBase: '/dist',
    historyApiFallback: true
  },
};

server.js:

const express = require('express');
const path = require('path');
const app = express();

if (process.env.NODE_ENV !== 'production') {
  app.use(express.static(path.join(__dirname, 'dist')));
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const config = require('./webpack.config.js');
  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
  }));
} else {
  app.use(express.static('dist'));
}

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(process.env.PORT || 3050, () => console.log('Listening'));

routes.js:

import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import App from './components/app';
import Home from './components/home';

const componentRoutes = (
  <Route component={App} path='/'>
    <Route component={Home} path='/test' />
  </Route>
);

const Routes = () => {
  return <Router history={ browserHistory } routes={ componentRoutes } />
};

export default Routes;

The App component renders a single div saying it loaded and same for the Home component. If you care to see the entire thing on Github, here is a link:

https://github.com/jlag34/nodeWebpackSupport

The main goal is to be able to load '/test' in dev mode without using hashHistory.

Wepback docs: https://webpack.js.org/guides/development/

Body:
The main goal is to be able to load '/test' in dev mode without using hashHistory.

React-router type as static, browser, hash and so one can be easily selected by generative jsx-function, which is selected by control flow or webpack predefined constants. Such technique is used for SSR (server-side rendering), when jsx with applied routes is returned, dependent on environment.

const RootComponent = () => {/* root component */};
const EntryPoint = process.env.NODE_ENV === 'production'
    ? (props) => (<BrowserRouter><RootComponent {...props} /></BrowserRouter>)
    : (props) => (<HashRouter><RootComponent {...props} /></HashRouter>)
export default EntryPoint


问:
How can we resolve DB2 java.io.CharConversionException during Spark submission
I am getting this below error during spark submit:

org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
  Caused by: com.ibm.db2.jcc.am.SqlException: [jcc][t4][1065][12306][4.17.28] Caught java.io.CharConversionException.  See attached Throwable for details. ERRORCODE=-4220, SQLSTATE=null
          at com.ibm.db2.jcc.am.fd.a(fd.java:731)

As per IBM documentation Click here, I added this below property but till getting same error. I am using db2jcc4.jar driver.

Is there any way to pass db2.jcc.charsetDecoderEncoder during spark
  submission.

```<code>System.setProperty("db2.jcc.charsetDecoderEncoder", "3")
val prop = new Properties()
prop.put("driver", driver)
prop.put("db2.jcc.charsetDecoderEncoder", "3")
prop.put("-Ddb2.jcc.charsetDecoderEncoder", "3")
prop.put("continueBatchOnError", "true")`

sqlContext.read.jdbc(
  url = url,
  table = table,
  predicates = parts,
  connectionProperties = prop)
</code>```

答:
Finally I have resolved DB2 java.io.CharConversionException  issue only passing two parameter to spark driver & executor. </p>

```<code>--conf 'spark.executor.extraJavaOptions=-Ddb2.jcc.charsetDecoderEncoder=3'
--conf 'spark.driver.extraJavaOptions=-Ddb2.jcc.charsetDecoderEncoder=3'
</code>```

Body:
I am getting this below error during spark submit:

org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
  Caused by: com.ibm.db2.jcc.am.SqlException: [jcc][t4][1065][12306][4.17.28] Caught java.io.CharConversionException.  See attached Throwable for details. ERRORCODE=-4220, SQLSTATE=null
          at com.ibm.db2.jcc.am.fd.a(fd.java:731)

As per IBM documentation Click here, I added this below property but till getting same error. I am using db2jcc4.jar driver.

Is there any way to pass db2.jcc.charsetDecoderEncoder during spark
  submission.

System.setProperty("db2.jcc.charsetDecoderEncoder", "3")
val prop = new Properties()
prop.put("driver", driver)
prop.put("db2.jcc.charsetDecoderEncoder", "3")
prop.put("-Ddb2.jcc.charsetDecoderEncoder", "3")
prop.put("continueBatchOnError", "true")`

sqlContext.read.jdbc(
  url = url,
  table = table,
  predicates = parts,
  connectionProperties = prop)

Body:
Finally I have resolved DB2 java.io.CharConversionException  issue only passing two parameter to spark driver & executor.

--conf 'spark.executor.extraJavaOptions=-Ddb2.jcc.charsetDecoderEncoder=3'
--conf 'spark.driver.extraJavaOptions=-Ddb2.jcc.charsetDecoderEncoder=3'


问:
Laravel - multiple resource routes to single controller with argument
Can we have a single controller for multiple routes, and get the parameter?

Currently, I have these routes:

```<code>Route::resource('/customers', 'CustomerController');
Route::resource('/agents', 'AgentController');
</code>```

And a CustomerController and a AgentController with all resource functions working.

But as CustomerController and AgentController are almost same except for one database field, i.e. group_id. I was thinking to use one controller i.e. PartyController and one route as:

```<code>Route::resource('/parties/customers', 'PartyController ');
Route::resource('/parties/agents', 'PartyController ');
</code>```

or if someone suggests:

```<code>Route::resource('/parties/{group}', 'PartyController ');
</code>```

I have been searching for a while but finding it hard to follow this path. I've added this code in the constructor of PartyController, to check the calling route:

```<code>    $path = Request::capture()->path();
    $this->group = ucwords(explode("/", $path)[1]);
    echo($this->group );
</code>```

All seems to be going well till here. But when in my index.blade.php, I have this statement:

```<code><p>{{ link_to_route('parties.create', 'Add new') }}</p>
</code>```

I get an exception:

```<code>Route [parties.create] not defined.
</code>```

I've tried multiple combinations, without any success and more errors come through, like accessing /parties/customers/create doesn't work now.

So, is it possible anyway or should I abandon this idea?

EDIT: My question is different from Same Laravel resource controller for multiple routes as I am not using a trait.

答:
I did it by using my own approach, I used the same routes.

```<code>Route::resource('/parties/agents', 'PartyController');
Route::resource('/parties/customers', 'PartyController');
</code>```

and in constructor of PartyController

```<code>$path = Request::capture()->path();
$group = strtolower(explode("/", $path)[1]);
</code>```

Now I've the $group variable to identify which group I am working with.

And in my blade documents I replaced parties.create with $group.create

```<code><a href="{{ route($group.'.create')}}" > Add new </a>
</code>```

Same for other routes.. Now it is working just as I wanted.

Thank all for help.

Body:
Can we have a single controller for multiple routes, and get the parameter?

Currently, I have these routes:

Route::resource('/customers', 'CustomerController');
Route::resource('/agents', 'AgentController');

And a CustomerController and a AgentController with all resource functions working.

But as CustomerController and AgentController are almost same except for one database field, i.e. group_id. I was thinking to use one controller i.e. PartyController and one route as:

Route::resource('/parties/customers', 'PartyController ');
Route::resource('/parties/agents', 'PartyController ');

or if someone suggests:

Route::resource('/parties/{group}', 'PartyController ');

I have been searching for a while but finding it hard to follow this path. I've added this code in the constructor of PartyController, to check the calling route:

    $path = Request::capture()->path();
    $this->group = ucwords(explode("/", $path)[1]);
    echo($this->group );

All seems to be going well till here. But when in my index.blade.php, I have this statement:

{{ link_to_route('parties.create', 'Add new') }}

I get an exception:

Route [parties.create] not defined.

I've tried multiple combinations, without any success and more errors come through, like accessing /parties/customers/create doesn't work now.

So, is it possible anyway or should I abandon this idea?

EDIT: My question is different from Same Laravel resource controller for multiple routes as I am not using a trait.

Body:
I did it by using my own approach, I used the same routes.

Route::resource('/parties/agents', 'PartyController');
Route::resource('/parties/customers', 'PartyController');

and in constructor of PartyController

$path = Request::capture()->path();
$group = strtolower(explode("/", $path)[1]);

Now I've the $group variable to identify which group I am working with.

And in my blade documents I replaced parties.create with $group.create

<a href="{{ route($group.'.create')}}" > Add new </a>

Same for other routes.. Now it is working just as I wanted.

Thank all for help.


问:
Android TextView inside RelativeLayout not acting properly
So I have a custom Header view that contains several widgets. My idea is to have a frame layout with ImageView (icon) aligned parent start and ImageButton (menu) aligned parent end. Also, TextView (title) to right of ImageView.. Those should always be visible.

To right of ImageView(icon) there should be a TextView (title) whose text should expand based on visibility of other widgets on the right side of it..

So the order from left to right goes like this: ImageView(icon) - TextView (title) - ImageView (unread messages) - ImageView (battery) - ImageButton (menu)

The problem is, the text from TextView goes behind the widgets on the right side of it, like it's visible on this image:

Here is my xml preview :

And this is the actual xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="58dp"
android:background="@color/view_controller_header">

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:layout_margin="10dp">

    <ImageView
        android:id="@+id/imageViewIC"
        android:layout_width="@dimen/view_controller_header_icon_width"
        android:layout_height="@dimen/view_controller_header_icon_height"
        android:layout_gravity="center" />

    <TextView
        android:id="@+id/textViewKK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:focusable="false"
        android:gravity="center"
        android:padding="10dp"
        android:shadowColor="@color/text_shadow"
        android:shadowDx="-1"
        android:shadowDy="-1"
        android:shadowRadius="1"
        android:textColor="@color/main_text_color"
        android:textSize="@dimen/view_controller_header_kk_texSize"
        android:visibility="gone" />

    <ProgressBar
        android:id="@+id/progressBarVC"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />

</FrameLayout>

<TextView
    android:id="@+id/textViewDName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_gravity="center"
    android:layout_marginRight="@dimen/view_controller_header_margin2"
    android:layout_toRightOf="@id/frame"
    android:ellipsize="end"
    android:fontFamily="sans-serif"
    android:gravity="center|left"
    android:maxLines="2"
    android:textColor="@color/main_text_color"
    android:textSize="17sp"
    tools:text="This is the text that is too long .........." />

<ImageButton
    android:id="@+id/imgSubMenu"
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:layout_alignParentEnd="true"
    android:layout_gravity="center"
    android:background="?android:selectableItemBackground"
    android:scaleType="center"
    android:src="@drawable/ic_more_vert_white_24dp" />

<LinearLayout
    android:id="@+id/bat"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_toStartOf="@id/imgSubMenu"
    android:gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageViewBattery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:visibility="visible"
        app:srcCompat="@drawable/ic_battery_full" />

    <TextView
        android:id="@+id/textViewBattery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:visibility="visible"
        tools:text="100%" />

</LinearLayout>

<TextView
    android:id="@+id/unreadMessages"
    android:layout_width="22dp"
    android:layout_height="22dp"
    android:layout_centerInParent="true"
    android:layout_toStartOf="@id/bat"
    android:background="@color/color_widget_security_back_red"
    android:gravity="center"
    android:textStyle="bold"
    android:visibility="visible"
    tools:text="2" />
</code>```

Any ideas, why does this text goes behind those widgets? I want it to resize if batery and unread messages are visible, like it goes into two lines instead of one, or to show ... if it's too long..

答:
Probably you forgot add one more properties text as below :

android:layout_toLeftOf

```<code>android:layout_toLeftOf="@+id/imgSubMenu"
</code>```

As per you requirement you want show text right to left icon and left to right menu icon but you add one relative reference toRight not toLeft so it's overlap on right side menu icon

Body:
So I have a custom Header view that contains several widgets. My idea is to have a frame layout with ImageView (icon) aligned parent start and ImageButton (menu) aligned parent end. Also, TextView (title) to right of ImageView.. Those should always be visible.

To right of ImageView(icon) there should be a TextView (title) whose text should expand based on visibility of other widgets on the right side of it..

So the order from left to right goes like this: ImageView(icon) - TextView (title) - ImageView (unread messages) - ImageView (battery) - ImageButton (menu)

The problem is, the text from TextView goes behind the widgets on the right side of it, like it's visible on this image:

Here is my xml preview :

And this is the actual xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="58dp"
android:background="@color/view_controller_header">

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:layout_margin="10dp">

    <ImageView
        android:id="@+id/imageViewIC"
        android:layout_width="@dimen/view_controller_header_icon_width"
        android:layout_height="@dimen/view_controller_header_icon_height"
        android:layout_gravity="center" />

    <TextView
        android:id="@+id/textViewKK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:focusable="false"
        android:gravity="center"
        android:padding="10dp"
        android:shadowColor="@color/text_shadow"
        android:shadowDx="-1"
        android:shadowDy="-1"
        android:shadowRadius="1"
        android:textColor="@color/main_text_color"
        android:textSize="@dimen/view_controller_header_kk_texSize"
        android:visibility="gone" />

    <ProgressBar
        android:id="@+id/progressBarVC"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />

</FrameLayout>

<TextView
    android:id="@+id/textViewDName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_gravity="center"
    android:layout_marginRight="@dimen/view_controller_header_margin2"
    android:layout_toRightOf="@id/frame"
    android:ellipsize="end"
    android:fontFamily="sans-serif"
    android:gravity="center|left"
    android:maxLines="2"
    android:textColor="@color/main_text_color"
    android:textSize="17sp"
    tools:text="This is the text that is too long .........." />

<ImageButton
    android:id="@+id/imgSubMenu"
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:layout_alignParentEnd="true"
    android:layout_gravity="center"
    android:background="?android:selectableItemBackground"
    android:scaleType="center"
    android:src="@drawable/ic_more_vert_white_24dp" />

<LinearLayout
    android:id="@+id/bat"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_toStartOf="@id/imgSubMenu"
    android:gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageViewBattery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:visibility="visible"
        app:srcCompat="@drawable/ic_battery_full" />

    <TextView
        android:id="@+id/textViewBattery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:visibility="visible"
        tools:text="100%" />

</LinearLayout>

<TextView
    android:id="@+id/unreadMessages"
    android:layout_width="22dp"
    android:layout_height="22dp"
    android:layout_centerInParent="true"
    android:layout_toStartOf="@id/bat"
    android:background="@color/color_widget_security_back_red"
    android:gravity="center"
    android:textStyle="bold"
    android:visibility="visible"
    tools:text="2" />

Any ideas, why does this text goes behind those widgets? I want it to resize if batery and unread messages are visible, like it goes into two lines instead of one, or to show ... if it's too long..

Body:
Probably you forgot add one more properties text as below :

android:layout_toLeftOf

android:layout_toLeftOf="@+id/imgSubMenu"

As per you requirement you want show text right to left icon and left to right menu icon but you add one relative reference toRight not toLeft so it's overlap on right side menu icon


问:
i'am Getting This error. Conversion failed when converting the nvarchar value '- Select -' to data type int. My Code Is Given below
This Is my Sql table Structure so maybe its details what Is Problem Is...
This is the problem Iam getting In website

I am getting Error In this code:

```<code> protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Getreality();
            GetAds();
        }
    }

    private void Getreality()
    {
        conn.Open();
        cmd = new SqlCommand("Getallreality", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@Type", SqlDbType.NVarChar).Value = "Reality Show";
        DataTable dt = new DataTable();
        da.Fill(dt);
        ListViewSerials.DataSource = dt;
        ListViewSerials.DataBind();
        conn.Close();
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        Getreality();
    }
</code>```

答:
you are going great. After watching your piece of code i have realized you are using SqlDbType.NVarChar to send the value to your parameter used in your stored procedure. But unfortunately your SP (stored procedure) need the varchar or nvarchar parameter to accept with the same definition as of your table have.

You need to check the parameter @type and its datatype and change it to nvarchar. also check the table definition it would be same as datatype.

PS - If you are converting the parameter values in query then you can use

CAST(@your_Parameter_Name AS nvarchar(15)) would an alternative to resolve your concern.

Could you send the SP and table definition. I will give you the more precise solution.

Body:
This Is my Sql table Structure so maybe its details what Is Problem Is...
This is the problem Iam getting In website

I am getting Error In this code:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Getreality();
            GetAds();
        }
    }

    private void Getreality()
    {
        conn.Open();
        cmd = new SqlCommand("Getallreality", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@Type", SqlDbType.NVarChar).Value = "Reality Show";
        DataTable dt = new DataTable();
        da.Fill(dt);
        ListViewSerials.DataSource = dt;
        ListViewSerials.DataBind();
        conn.Close();
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        Getreality();
    }


问:
asp.net mvc routing issues
I haved added this routing to my global asax.

```<code>routes.MapRoute(
    "News", // Route name
    "News/{timePeriod}/{categoryName}/{page}", // URL with parameters
    new { controller = "News", action = "Index",
        timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
    new { page = @"^\d{1,3}$" }// Parameter defaults
);

routes.MapRoute(
    "News2", // Route name
    "News/{categoryName}/{page}", // URL with parameters
    new { controller = "News", action = "Index",
        timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
    new { page = @"^\d{1,3}$" }// Parameter defaults
);
</code>```

The problem is urls like /News/add wont work (unless i add the specific route)
is there a better way without having to specify url action in global asax?

答:
Your two routes above will each route to the News controller and hit the "Index" action. If you don't have overloads for the Index action that will take the parameters you are specifying then the route won't work properly.  For instance, you should have these two actions:

```<code>public ActionResult Index(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Index(string categoryName, int page) {..}
</code>```

Also, you should remove the default parameter of TimePeriod from your second route since you aren't using it in the route itself:

```<code>routes.MapRoute(
                "News2", // Route name
                "News/{categoryName}/{page}", // URL with parameters
                new { controller = "News", action = "Index", categoryName = "All", page = 1 },
                new { page = @"^\d{1,3}$" }// Parameter defaults
            );
</code>```

I would recommend having an action for every category instead of creating a route for each category. You could simplify your routes to this:

```<code>routes.MapRoute(
                "News", // Route name
                "News/{action}/{timePeriod}/{page}", // URL with parameters
                new { controller = "News", action = "Index", timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
                new { page = @"^\d{1,3}$" }// Parameter defaults
            );
</code>```

Then having an action for each category:

```<code>public ActionResult All(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Sports(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Weather(TimePeriod timePeriod, string categoryName, int page) {..}
</code>```

This way all you will need is the one route.

Title: asp.net mvc routing issues

Body:
I haved added this routing to my global asax.

routes.MapRoute(
    "News", // Route name
    "News/{timePeriod}/{categoryName}/{page}", // URL with parameters
    new { controller = "News", action = "Index",
        timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
    new { page = @"^\d{1,3}$" }// Parameter defaults
);

routes.MapRoute(
    "News2", // Route name
    "News/{categoryName}/{page}", // URL with parameters
    new { controller = "News", action = "Index",
        timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
    new { page = @"^\d{1,3}$" }// Parameter defaults
);

The problem is urls like /News/add wont work (unless i add the specific route)
is there a better way without having to specify url action in global asax?

Body:
Your two routes above will each route to the News controller and hit the "Index" action. If you don't have overloads for the Index action that will take the parameters you are specifying then the route won't work properly.  For instance, you should have these two actions:

public ActionResult Index(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Index(string categoryName, int page) {..}

Also, you should remove the default parameter of TimePeriod from your second route since you aren't using it in the route itself:

routes.MapRoute(
                "News2", // Route name
                "News/{categoryName}/{page}", // URL with parameters
                new { controller = "News", action = "Index", categoryName = "All", page = 1 },
                new { page = @"^\d{1,3}$" }// Parameter defaults
            );

I would recommend having an action for every category instead of creating a route for each category. You could simplify your routes to this:

routes.MapRoute(
                "News", // Route name
                "News/{action}/{timePeriod}/{page}", // URL with parameters
                new { controller = "News", action = "Index", timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
                new { page = @"^\d{1,3}$" }// Parameter defaults
            );

Then having an action for each category:

public ActionResult All(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Sports(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Weather(TimePeriod timePeriod, string categoryName, int page) {..}

This way all you will need is the one route.


问:
How to remove jar file from classpath during runtime?
I have a Apache Commons library (commons-io.jar) added to my project classpath and I want to remove this library classes from my classpath during runtime and then I want to add after some work.

Is there any way to remove all classes from classpath during runtime and add these classes after some operation?

```<code>public static void main(String [] args){

    //Some apache commons operations

    //Remove apache commons classes from classpath

    doSomeWork();

    //Add apache commons classes to classpath

}
</code>```

答:
The problem you are experiencing is known as classpath hell.

There is no such functionality in Java. The reason behind this is the design of classloaders, which can only load classes and not unload them. In all likelyhood, this is not going to happen even in the future.

You could use a special classloader to load different classes from different jars, but even this way you quickly stumble into other limitations. For example, a classloader should only load the class if the parent has not yet loaded it. This means that other parts of your code cannot use apache-commons.jar. You could separate your program into two parts and have each run in its own classloader/classpath, but then you'll realize you can't share objects between them anymore. And so on.

In the end, you can either (a) try to find a combination of jars that works with both, (b) fix one part of the program so that it works with the other jar, or (c) break the program into two parts and have each run in separate JVMs.

Body:
I have a Apache Commons library (commons-io.jar) added to my project classpath and I want to remove this library classes from my classpath during runtime and then I want to add after some work.

Is there any way to remove all classes from classpath during runtime and add these classes after some operation?

public static void main(String [] args){

    //Some apache commons operations

    //Remove apache commons classes from classpath

    doSomeWork();

    //Add apache commons classes to classpath

}


问:
How to declare overloads function with same parameters, different return type in TypeScript?
I have a function that can be curried(functional programming), I declare it as below:

```<code>declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number, list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number) => (list: T[]) => T[];
</code>```

But in this case, the last line of code will never work because it has same parameters with the penultimate line.

I also consider the Union Types, just like:

```<code>declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): ((index: number, list: T[]) => T[]) | ((index: number) => (list: T[]) => T[]);
</code>```

But it will cause a ts mistake:

```<code>TS2349:Cannot invoke an expression whose type lacks a call signature. Type '((index: number, list: number[]) => number[]) | ((index: number) => (list: number[]) => number[])' has no compatible call signatures
</code>```

So, How can I correct it?

答:
You can use a interface with call signature as your return type for the last function:</p>

```<code>declare interface AdjustReturnFunction<T>{
    (index: number, list: T[]): T[];
    (index: number): (list: T[]) => T[];

}

declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): AdjustReturnFunction<T>;
</code>```

Body:
I have a function that can be curried(functional programming), I declare it as below:

declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number, list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number) => (list: T[]) => T[];

But in this case, the last line of code will never work because it has same parameters with the penultimate line.

I also consider the Union Types, just like:

declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): ((index: number, list: T[]) => T[]) | ((index: number) => (list: T[]) => T[]);

But it will cause a ts mistake:

TS2349:Cannot invoke an expression whose type lacks a call signature. Type '((index: number, list: number[]) => number[]) | ((index: number) => (list: number[]) => number[])' has no compatible call signatures

So, How can I correct it?

Body:
You can use a interface with call signature as your return type for the last function:

declare interface AdjustReturnFunction<T>{
    (index: number, list: T[]): T[];
    (index: number): (list: T[]) => T[];

}

declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): AdjustReturnFunction<T>;


问:
how to append array in formData ,array in which includes 2 values with keys
Code :

```<code>let options = new RequestOptions({ headers: headers });
let array1;

array1 = [{ "subfolder_name": subfolder, "file_upload": file }];
let formData: FormData = new FormData();
formData.append("folder_name",folder );
formData.append("counselor",array1 );
</code>```

it return counselor:[Object Object]

答:
FormData is an interface to construct set of key-value pairs, therefore, it does not support any kind of nested structure, but you could, however, denote nesting in the key like so:

let array1 = [{ "subfolder_name": "foo", "file_upload": "bar" }];
let formData = new FormData();
formData.append('counselor[0].subfolder_name', array1[0].subfolder_name );
formData.append('counselor[0].file_upload', array1[0].file_upload );

for (let pair of formData.entries()) {
    console.log(pair[0] + ': ' + pair[1]);
}```

Body:
Code :

let options = new RequestOptions({ headers: headers });
let array1;

array1 = [{ "subfolder_name": subfolder, "file_upload": file }];
let formData: FormData = new FormData();
formData.append("folder_name",folder );
formData.append("counselor",array1 );

it return counselor:[Object Object]


问:
jQuery context menu get clicked item
I am using jQuery context menu plugin by Chris Domigan to appy a context menu. This is how I do it:

```<code>$('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
        'copy': function(t) {
             alert('Trigger was '+t.id+'\nAction was Copy');
         },

        'delete': function(t) {
             alert('Trigger was '+t.id+'\nAction was Delete');
        }
    },
});
</code>```

My question is, how do I get the content of the clicked tr item? I tried with

```<code>$(t.target).html()
</code>```

but it returns null. Any idea?

EDIT: here is the example http://jsfiddle.net/gqhRV/

答:
not familiar with the plugin, but from the looks of it you should be able to write:

```<code>$("#" + t.id).html();
</code>```

but in the case of most jQuery plugins you should be able to do this:

```<code>$(this).html();
</code>```

from within the context of the 'copy': function(t) { and 'delete': function(t) {

```<code>$('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
        'open': function(t) { ShowAction(t, "Open"); },
        'email': function(t) { ShowAction(t, "Email"); },
        'save': function(t) { ShowAction(t, "Save"); },
        'delete': function(t) { ShowAction(t, "Delete"); }
    }
});

function ShowAction(t, a) {
    alert('Trigger was ' + t.id + '\nAction was ' + a + "\nHtml is " + $(t).html());
}
</code>```

Here's a working example: http://jsfiddle.net/dNUgg/

I'm guessing your
 tags do not have an id attribute

Even when the
 does not have an ID this still works: http://jsfiddle.net/dNUgg/1/

```<code> alert('content is ' + $(t).text() + '\nAction was Delete');
</code>```

updated your jsfiddle: http://jsfiddle.net/gqhRV/1/

you were doing $(t.target).text() when you should be doing $(t).text()

Title: jQuery context menu get clicked item

Body:
I am using jQuery context menu plugin by Chris Domigan to appy a context menu. This is how I do it:

$('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
        'copy': function(t) {
             alert('Trigger was '+t.id+'\nAction was Copy');
         },

        'delete': function(t) {
             alert('Trigger was '+t.id+'\nAction was Delete');
        }
    },
});

My question is, how do I get the content of the clicked tr item? I tried with

$(t.target).html()

but it returns null. Any idea?

EDIT: here is the example http://jsfiddle.net/gqhRV/

Body:
not familiar with the plugin, but from the looks of it you should be able to write:

$("#" + t.id).html();

but in the case of most jQuery plugins you should be able to do this:

$(this).html();

from within the context of the 'copy': function(t) { and 'delete': function(t) {

$('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
        'open': function(t) { ShowAction(t, "Open"); },
        'email': function(t) { ShowAction(t, "Email"); },
        'save': function(t) { ShowAction(t, "Save"); },
        'delete': function(t) { ShowAction(t, "Delete"); }
    }
});

function ShowAction(t, a) {
    alert('Trigger was ' + t.id + '\nAction was ' + a + "\nHtml is " + $(t).html());
}

Here's a working example: http://jsfiddle.net/dNUgg/

I'm guessing your <tr> tags do not have an id attribute

Even when the <tr> does not have an ID this still works: http://jsfiddle.net/dNUgg/1/

 alert('content is ' + $(t).text() + '\nAction was Delete');

updated your jsfiddle: http://jsfiddle.net/gqhRV/1/

you were doing $(t.target).text() when you should be doing $(t).text()