问:
UIButton contentVerticalAlignment doesn't center button image
I created a UIButton programmatically and set its image, but the image just won't center vertically, it's always rendered at the bottom of the button.

Here is my code:

```<code>CGFloat logoutButtonSize = self.profileItem.detailView.frame.size.height;
CGFloat logoutButtonX = self.profileItem.detailView.frame.size.width - logoutButtonSize - 8;
CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);
UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame];
[logoutButton setImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];
logoutButton.imageView.contentMode = UIViewContentModeCenter;
logoutButton.contentMode = UIViewContentModeCenter;
[logoutButton addTarget:self
                 action:@selector(confirmLogout)
       forControlEvents:UIControlEventTouchUpInside];
logoutButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
logoutButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
logoutButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
</code>```

After setting a distinct background color for the imageView of the button I can see that it's still aligned to the bottom:

(blue = button, red = image view)

Why is it not working?

答:
Based on your posted image, it looks like the Button itself is being clipped at the bottom, as opposed to the image not being centered vertically.

Your code:

```<code>CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);
</code>```

says the Button (blue rectangle) should be square. Yet in the image you posted, the blue rectangle is 120 x 88.

The bottom portion of your button is not being displayed, so it looks like your image is not centered.

By the way, you shouldn't need much of the code you are using:

```<code>    // define the frame size
    CGFloat logoutButtonSize = self.profileItem.detailView.frame.size.height;
    CGFloat logoutButtonX = self.profileItem.detailView.frame.size.width - logoutButtonSize - 8;
    CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);

    // instantiate the UIButton
    UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame];

    // set the image
    [logoutButton setImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];

    // add the button action target
    [logoutButton addTarget:self
                     action:@selector(confirmLogout)
           forControlEvents:UIControlEventTouchUpInside];

    // set the resizing mask properties
    logoutButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;

    // shouldn't need any of the following
    //logoutButton.imageView.contentMode = UIViewContentModeCenter;
    //logoutButton.contentMode = UIViewContentModeCenter;
    //logoutButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    //logoutButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
</code>```

Body:
I created a UIButton programmatically and set its image, but the image just won't center vertically, it's always rendered at the bottom of the button.

Here is my code:

CGFloat logoutButtonSize = self.profileItem.detailView.frame.size.height;
CGFloat logoutButtonX = self.profileItem.detailView.frame.size.width - logoutButtonSize - 8;
CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);
UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame];
[logoutButton setImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];
logoutButton.imageView.contentMode = UIViewContentModeCenter;
logoutButton.contentMode = UIViewContentModeCenter;
[logoutButton addTarget:self
                 action:@selector(confirmLogout)
       forControlEvents:UIControlEventTouchUpInside];
logoutButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
logoutButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
logoutButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

After setting a distinct background color for the imageView of the button I can see that it's still aligned to the bottom:

(blue = button, red = image view)

Why is it not working?

Body:
Based on your posted image, it looks like the Button itself is being clipped at the bottom, as opposed to the image not being centered vertically.

Your code:

CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);

says the Button (blue rectangle) should be square. Yet in the image you posted, the blue rectangle is 120 x 88.

The bottom portion of your button is not being displayed, so it looks like your image is not centered.

By the way, you shouldn't need much of the code you are using:

    // define the frame size
    CGFloat logoutButtonSize = self.profileItem.detailView.frame.size.height;
    CGFloat logoutButtonX = self.profileItem.detailView.frame.size.width - logoutButtonSize - 8;
    CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);

    // instantiate the UIButton
    UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame];

    // set the image
    [logoutButton setImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];

    // add the button action target
    [logoutButton addTarget:self
                     action:@selector(confirmLogout)
           forControlEvents:UIControlEventTouchUpInside];

    // set the resizing mask properties
    logoutButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;

    // shouldn't need any of the following
    //logoutButton.imageView.contentMode = UIViewContentModeCenter;
    //logoutButton.contentMode = UIViewContentModeCenter;
    //logoutButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    //logoutButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;


来源: stackexchange

问:
Java file get content to first empty line
I need to split the first section of a file in Java, before the first empty line and the second section, after this line. How can I do this? Currently, I read the files with this code:

```<code>try {
        Scanner scanner = new Scanner(file);
        return scanner.useDelimiter("\\Z").next();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        return "500 - Server Error";
    }
</code>```

Any suggestions ?

答:
If i understand correctly,see following code:

```<code>    Scanner scanner = new Scanner(new File("d:\\tmp\\zyr.txt"));
    String delimiter = System.getProperty("line.separator");
    scanner.useDelimiter(delimiter);
    StringBuilder sb=new StringBuilder();
    List<String> result=new ArrayList<>();
    while (scanner.hasNextLine()){
        String line = scanner.nextLine();
        if(!(line.trim().length()==0)){
            sb.append(line).append(delimiter);
        }else if(sb.toString().length()>0) {
            result.add(sb.toString());
            sb.setLength(0);
        }
    }
    if(sb.toString().length()>0) {
        result.add(sb.toString());
    }

    System.out.println("first section:");
    System.out.println(result.get(0));
    System.out.println("second section:");
    System.out.println(result.get(1));
</code>```

the zyr.txt file is like:

```<code>abc
abc
abc

123
123
</code>```

and the the first section which you want is first item in result list,the second is the second item.

the print result is:

```<code>first section:
abc
abc
abc

second section:
123
123
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to split the first section of a file in Java, before the first empty line and the second section, after this line. How can I do this? Currently, I read the files with this code:

try {
        Scanner scanner = new Scanner(file);
        return scanner.useDelimiter("\\Z").next();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        return "500 - Server Error";
    }

Any suggestions ?

Body:
If i understand correctly,see following code:

    Scanner scanner = new Scanner(new File("d:\\tmp\\zyr.txt"));
    String delimiter = System.getProperty("line.separator");
    scanner.useDelimiter(delimiter);
    StringBuilder sb=new StringBuilder();
    List<String> result=new ArrayList<>();
    while (scanner.hasNextLine()){
        String line = scanner.nextLine();
        if(!(line.trim().length()==0)){
            sb.append(line).append(delimiter);
        }else if(sb.toString().length()>0) {
            result.add(sb.toString());
            sb.setLength(0);
        }
    }
    if(sb.toString().length()>0) {
        result.add(sb.toString());
    }

    System.out.println("first section:");
    System.out.println(result.get(0));
    System.out.println("second section:");
    System.out.println(result.get(1));

the zyr.txt file is like:

abc
abc
abc

123
123

and the the first section which you want is first item in result list,the second is the second item.

the print result is:

first section:
abc
abc
abc

second section:
123
123


问:
How do you store preferences on multilanguage apps?
Lets say I save a position setting by its string Top.
Upon changing app language, that string becomes meaningless since in the new language it would be Arriba for example, and those those strings aren't equal.

So I have to store the position value 1 because it would be the same across languages.

But then the summary for the preference becomes 1 instead of whatever way "Top" is translated to in that other language.

So I map the code to the position text 1 -> Top for summary displaying purposes only and leave the position code alone.

I still have to translate back and forth everywhere that setting is displayed to the user (if it ever is), along with maintaining the arrays with the codes for each preference on each language and the mapping itself.

The upside is that i can use and apply the setting to the app by its code without mapping it back from its name beforehand and the fact that the app translates the code to it's string upon displaying the preferences (using the code from "Settings Activity" for that).

So I wonder, how do you manage this so it doesn't become unmanageable or comes back to bite you down the road?

答:
I think you should see the problem from the opposite side. Now you are focusing on store a preference by its value but let's start from defining a type which represent all the possible values for a setting, eg:

```<code>enum Position
{
  TOP("position_top"),
  BOTTOM("position_bottom"),
  LEFT("position_left")
  ;

  public final String identifier;
  private Position(String identifier) { this->identifier = identifier; }
}
</code>```

Now you have all the possible values for the setting and you associated an identifier (you could use the enum toString() value directly if you preferred).

This identifier can be used both for serialization in preferences both to refer a localized resource in strings.xml.

Body:
I think you should see the problem from the opposite side. Now you are focusing on store a preference by its value but let's start from defining a type which represent all the possible values for a setting, eg:

enum Position
{
  TOP("position_top"),
  BOTTOM("position_bottom"),
  LEFT("position_left")
  ;

  public final String identifier;
  private Position(String identifier) { this->identifier = identifier; }
}

Now you have all the possible values for the setting and you associated an identifier (you could use the enum toString() value directly if you preferred).

This identifier can be used both for serialization in preferences both to refer a localized resource in strings.xml.


Title: python / pandas from timetable to timedate dataframe

Body:
i have a set of data like this:

    Unnamed: 0  0:30  1:00  1:30  2:00  2:30  3:00  3:30  4:00  4:30  ...   \
0   2016-01-01  26.9  26.4  26.9  26.1  26.4  26.7  26.5  25.5  25.4  ...
1   2016-01-02  26.8  25.9  25.7  26.0  25.2  25.3  25.6  25.0  25.1  ...
2   2016-01-03  25.6  25.4  25.2  25.5  24.5  24.5  24.9  24.6  24.3  ...
3   2016-01-04  24.9  24.2  23.7  23.5  23.4  23.4  23.6  23.3  23.7  ...
..         ...   ...   ...   ...   ...   ...   ...   ...   ...   ...  ...
361 2016-12-27  15.6  15.5  15.5  15.7  16.1  16.2  16.3  16.2  16.2  ...
362 2016-12-28  15.3  15.7  16.3  16.4  16.2  16.1  16.3  16.1  16.2  ...
363 2016-12-29  15.9  16.3  16.1  16.4  16.4  16.2  16.1  16.1  15.9  ...
364 2016-12-30  16.2  16.3  16.3  16.3  16.2  16.3  16.3  16.3  16.3  ...
365 2016-12-31  16.1  16.0  16.2  16.3  16.2  16.2  16.3  16.3  16.3  ...

that I would like to rearrange with date+time for each value at each row. something like:

0   2016-01-01 0:30 26.9
1   2016-01-01 1:00 26.4
2   2016-01-01 1:30 26.9
3   2016-01-01 2:00 26.1

but i haven't a clue how to append the values into a new dataframe without iterating (which is very slow as i have several big data-sets)

i tried something like

df = pd.DataFrame(index = data['Unnamed: 0'] + ' ' + data.columns[1:len(data.columns)])

but this isn't right - it is the data structure that i don't get i think

ideas? thanks

Body:
You can use pandas stack() for this

df.set_index('Unnamed: 0').stack().reset_index()

    Unnamed: 0  level_1 0
0   2016-01-01  0:30    26.9
1   2016-01-01  1:00    26.4
2   2016-01-01  1:30    26.9
3   2016-01-01  2:00    26.1
4   2016-01-01  2:30    26.4
5   2016-01-01  3:00    26.7
6   2016-01-01  3:30    26.5
7   2016-01-01  4:00    25.5
8   2016-01-01  4:30    25.4
9   2016-01-02  0:30    26.8
10  2016-01-02  1:00    25.9
11  2016-01-02  1:30    25.7
12  2016-01-02  2:00    26.0
13  2016-01-02  2:30    25.2
14  2016-01-02  3:00    25.3
15  2016-01-02  3:30    25.6


问:
jQuery Ajax function does not work?
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

```<code><script>
 function submitForLogin()
 {
    $.ajax({
            type: "POST",
            url: "php/login.php",
            data: { email: "example@abc.com",password:"123" }}).done(function(data){alert(data);});

 }

</script>
</code>```

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

```<code><?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>
</code>```

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

答:
Change your php file like below :

```<code><?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection

header('Content-type: application/json');

$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
    die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
     $res = "userExist";
     $data = json_encode($res);
     echo $data;
     die();

}
else
{

    $res = "fakeUser";
    $data = json_encode($res);
    echo $data;
    die();
}
mysqli_close($con);

?>
</code>```

And your script :

```<code>$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example@abc.com",password:"123" },
success:function(data){
    alert(data);
};
});
</code>```

Title: jQuery Ajax function does not work?

Body:
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

Body:
Change your php file like below :

<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection

header('Content-type: application/json');

$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
    die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
     $res = "userExist";
     $data = json_encode($res);
     echo $data;
     die();

}
else
{

    $res = "fakeUser";
    $data = json_encode($res);
    echo $data;
    die();
}
mysqli_close($con);

?>

And your script :

$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example@abc.com",password:"123" },
success:function(data){
    alert(data);
};
});


问:
Spring cloud stream Kafka Reactive stream partition assignment
How does spring cloud stream assign multiple Kafka partitions to reactive streams belonging to same consumer group?

I noticed that if I use plain non-reactive stream listener each thread gets assigned to one partition, depending on the consumer concurrency configuration. Whereas, in case of stream (Flux input) I did not notice any such parrallel  behavior. It seems like only one stream is defined to process messages from all the partitions.

My expectation is to have separate stream for each Kafka topic partition, even on same node backed up by different threads.

答: Thanks for bringing it up. I've created an issue to track this: https://github.com/spring-cloud/spring-cloud-stream/issues/980</p>


问:
If module did not create properly then remove data from which tables for reinstall the module in vtiger
am new in vtiger. Could anyone tell me which tables are store for module related data? Suppose I create a module ABC for any purpose. Then it will create two tables (1) vtiger_ABC and (2) vtiger_ABCcf and vtiger_crm is common. My questions are

1) without this three tables which tables are required extra.

2) If module did not create properly then remove data from which tables for reinstall the module in vtiger7. Please tell me the tables name.

答:
1) Those three tables are the only ones strictly needed (vtiger_yourmodule, vtiger_yourmodulecf and vtiger_crmentity). Of course you could create additional tables, but only if you have a special need. For basic entity modules you only need those three.

2) you should run a script for module uninstallation:

```<code><?php
require_once 'vtlib/Vtiger/Module.php';
$Vtiger_Utils_Log = true;

$MODULENAME = 'yourmodule';

$moduleInstance = Vtiger_Module::getInstance($MODULENAME);
if ($moduleInstance) {
    echo "Module is present - deleting module instance...\n";
    $moduleInstance->delete();
} else {
    echo "Module not found...\n";
}
</code>```

put it on your vtiger root folder and execute it through a browser. That script will delete some entries in some other tables. You can also manually delete tables vtiger_yourmodule and vtiger_yourmodulecf and delete your module's folder in vtiger_root/modules/yourmodule

Body:
1) Those three tables are the only ones strictly needed (vtiger_yourmodule, vtiger_yourmodulecf and vtiger_crmentity). Of course you could create additional tables, but only if you have a special need. For basic entity modules you only need those three.

2) you should run a script for module uninstallation:

<?php
require_once 'vtlib/Vtiger/Module.php';
$Vtiger_Utils_Log = true;

$MODULENAME = 'yourmodule';

$moduleInstance = Vtiger_Module::getInstance($MODULENAME);
if ($moduleInstance) {
    echo "Module is present - deleting module instance...\n";
    $moduleInstance->delete();
} else {
    echo "Module not found...\n";
}

put it on your vtiger root folder and execute it through a browser. That script will delete some entries in some other tables. You can also manually delete tables vtiger_yourmodule and vtiger_yourmodulecf and delete your module's folder in vtiger_root/modules/yourmodule


问:
Modify an embedded Connection String in microsoft excel macro
I have an Excel document that has a macro which when run will modify a CommandText of that connection to pass in parameters from the Excel spreadsheet, like so:

```<code>Sub RefreshData()
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary")
  .OLEDBConnection.CommandText = "Job_Cost_Code_Transaction_Summary_Percentage_Pending @monthEndDate='" & Worksheets("Cost to Complete").Range("MonthEndDate").Value & "', @job ='" & Worksheets("Cost to Complete").Range("Job").Value & "'"
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").Refresh
End Sub
</code>```

I would like the refresh to not only modify the connection command but also modify the connection as I would like to use it with a different database also:

Just like the macro replaces the command parameters with values from the spreadsheet I would like it to also replace the database server name and database name from values from the spreadsheet.

A complete implementation is not required, just the code to modify the connection with values from the sheet will be sufficient, I should be able to get it working from there.

I tried to do something like this:

```<code> ActiveWorkbook
 .Connections("Job_Cost_Code_Transaction_Summary")
 .OLEDBConnection.Connection = "new connection string"
</code>```

but that does not work. Thanks.

答:
I would like to give my small contribute here to this old topic.
If you have many connections in your Excel file, and you want to change the DB name and DB server for all of them, you can use the following code as well:

It iterates through all connections and extracts the connection string

Each connection string is split into an array of strings

It iterates through the array searching for the right connection values to modify, the others are not touched

The it recompose the array into the string and commit the change

This way you don't need to use replace and to know the previous value, and the rest of the string will remain intact.
Also, we can refer to a cell name, so you can have names in your Excel file

I hope it can help

```<code>Sub RelinkConnections()

Dim currConnValues() As String

For Each currConnection In ThisWorkbook.Connections
    currConnValues = Split(currConnection.OLEDBConnection.Connection, ";")
    For i = 0 To UBound(currConnValues)
        If (InStr(currConnValues(i), "Initial Catalog") <> 0) Then
            currConnValues(i) = "Initial Catalog=" + Range("DBName").value
        ElseIf (InStr(currConnValues(i), "Data Source") <> 0) Then
            currConnValues(i) = "Data Source=" + Range("DBServer").value
        End If
    Next
    currConnection.OLEDBConnection.Connection = Join(currConnValues, ";")
    currConnection.Refresh
Next

End Sub
</code>```

Body:
I have an Excel document that has a macro which when run will modify a CommandText of that connection to pass in parameters from the Excel spreadsheet, like so:

Sub RefreshData()
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary")
  .OLEDBConnection.CommandText = "Job_Cost_Code_Transaction_Summary_Percentage_Pending @monthEndDate='" & Worksheets("Cost to Complete").Range("MonthEndDate").Value & "', @job ='" & Worksheets("Cost to Complete").Range("Job").Value & "'"
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").Refresh
End Sub

I would like the refresh to not only modify the connection command but also modify the connection as I would like to use it with a different database also:

Just like the macro replaces the command parameters with values from the spreadsheet I would like it to also replace the database server name and database name from values from the spreadsheet.

A complete implementation is not required, just the code to modify the connection with values from the sheet will be sufficient, I should be able to get it working from there.

I tried to do something like this:

 ActiveWorkbook
 .Connections("Job_Cost_Code_Transaction_Summary")
 .OLEDBConnection.Connection = "new connection string"

but that does not work. Thanks.

Body:
I would like to give my small contribute here to this old topic.
If you have many connections in your Excel file, and you want to change the DB name and DB server for all of them, you can use the following code as well:

It iterates through all connections and extracts the connection string

Each connection string is split into an array of strings

It iterates through the array searching for the right connection values to modify, the others are not touched

The it recompose the array into the string and commit the change

This way you don't need to use replace and to know the previous value, and the rest of the string will remain intact.
Also, we can refer to a cell name, so you can have names in your Excel file

I hope it can help

Sub RelinkConnections()

Dim currConnValues() As String

For Each currConnection In ThisWorkbook.Connections
    currConnValues = Split(currConnection.OLEDBConnection.Connection, ";")
    For i = 0 To UBound(currConnValues)
        If (InStr(currConnValues(i), "Initial Catalog") <> 0) Then
            currConnValues(i) = "Initial Catalog=" + Range("DBName").value
        ElseIf (InStr(currConnValues(i), "Data Source") <> 0) Then
            currConnValues(i) = "Data Source=" + Range("DBServer").value
        End If
    Next
    currConnection.OLEDBConnection.Connection = Join(currConnValues, ";")
    currConnection.Refresh
Next

End Sub


问:
Icecast 2 ~ use pls or m3u on a listen.mp3 from caster.fm
Today I decided to make a Online Radio Station using a free account on caster.fm. I decided that it wasn't anything to do with them and it was more to do with general Icecast 2.

I own a game server and there is a plugin to allow radio streams but in the format of M3U & PLS playlists not stream files. I know you can mount the stream onto the PLS/M3U but, it doesn't seem to work. I added this to a file I called listen.pls:

```<code>   [playlist] File1=http://shaincast.caster.fm:port/listen.mp3 Title1= Velocity FM
</code>```

The port is specified in actual file.

But it doesn't seem to work. I understand PLS is only a playlist, could this be the cause?

答:
You need some line breaks in your file.  I'd also make sure you don't have a space after your equals sign... parsers for these INI-style files vary and can be a bit finicky sometimes.

```<code>[playlist]
File1=http://shaincast.caster.fm:80/listen.mp3
Title1=Velocity FM
</code>```

You could also switch to M3U which is more broadly compatible (but it sounds like in your case you can handle either):

```<code>#EXTM3U
#EXTINF:-1,Velocity FM
http://shaincast.caster.fm:80/listen.mp3
</code>```

Body:
Today I decided to make a Online Radio Station using a free account on caster.fm. I decided that it wasn't anything to do with them and it was more to do with general Icecast 2.

I own a game server and there is a plugin to allow radio streams but in the format of M3U & PLS playlists not stream files. I know you can mount the stream onto the PLS/M3U but, it doesn't seem to work. I added this to a file I called listen.pls:

   [playlist] File1=http://shaincast.caster.fm:port/listen.mp3 Title1= Velocity FM

The port is specified in actual file.

But it doesn't seem to work. I understand PLS is only a playlist, could this be the cause?

Body:
You need some line breaks in your file.  I'd also make sure you don't have a space after your equals sign... parsers for these INI-style files vary and can be a bit finicky sometimes.

[playlist]
File1=http://shaincast.caster.fm:80/listen.mp3
Title1=Velocity FM

You could also switch to M3U which is more broadly compatible (but it sounds like in your case you can handle either):

#EXTM3U
#EXTINF:-1,Velocity FM
http://shaincast.caster.fm:80/listen.mp3


问:
Fiddler not capturing certain websites
I am using fiddler version 4 and am unable to capture some websites like Facebook, google, gmail, yahoo; however, it captures some other websites correctly.

I checked the filters option and found that they use filters option "Unchecked" and also checked fiddler through its IP and its running correctly.

答:
I think that's causes by missing https decryption.

There is a menu point to import the fiddler root certificate in the local certificate store.

http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/TrustFiddlerRootCert

How to:

Click Tools > Fiddler Options > HTTPS.

Click the Decrypt HTTPS Traffic box.

Title: Fiddler not capturing certain websites


问:
In R: how to sum a variable by group between two dates
I have two data frames (DF1 and DF2):

(1) DF1 contains information on individual-level, i.e. on 10.000 individuals nested in 30 units across 11 years (2000-2011). It contains four variables:

"individual" (numeric id for each individual; ranging from 1-10.000)

"unit" (numeric id for each unit; ranging from 1-30)

"date1" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2010-12-31)

"date2" ("Date1" + 1 year)

(2) DF2 contains information on unit-level, i.e. on the same 30 units as in DF1 across the same time period (2000-2011) and further contains a numeric variable ("x"):

"unit" (numeric id for each unit; ranging from 1-30)

"date" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2011-12-31)

"x" (a numeric variable, ranging from 0 to 200)

I would like to create new variable ("newvar") that gives me for each "individual" per "unit" the sum of "x" (DF2) counting from "date1" (DF1) to "date2" (DF2). This means that I would like to add this new variable to DF1.

For instance, if "individual"=1 in "unit"=1 has "date1"=2000-01-01 and "date2"=2001-01-01, and in DF2 "unit"=1 has three observations in the time period "date1" to "date2" (i.e. 2000-01-01 to 2001-01-01) with "x"=1, "x"=2 and "x"=3, then I would like add a new variable that gives for "individual"=1 in "unit"=1 "newvar"=6.

I assume that I need to use a for loop in R and have been using the following code:

```<code>for(i in length(DF1)){

DF1$newvar[i] <-sum(DF2$x[which(DF1$date == DF1$date1[i] &
                     DF1$date == DF1P$date1[i] &
                     DF2$unit == DF1P$unit[i]),])
</code>```

}

but get the error message:

```<code>Error in DF2$x[which(DF2$date ==  : incorrect number of dimensions
</code>```

Any ideas of how to create this variable would be tremendously appreciated!

Here is a small example as well as the expected output, using one unit for the sake of simplicity:

Assume DF1 looks as follows:

```<code>individual  unit  date1        date2
1           1     2000-01-01   2001-01-01
2           1     2000-02-02   2001-02-02
3           1     2000-03-03   2000-03-03
4           1     2000-04-04   2000-04-04
5           1     2000-12-31   2001-12-31
(...)
996         1     2010-01-01   2011-01-01
997         1     2010-02-15   2011-02-15
998         1     2010-03-05   2011-03-05
999         1     2010-04-10   2011-04-10
1000        1     2010-12-27  2011-12-27
1001        2     2000-01-01   2001-01-01
1002        2     2000-02-02   2001-02-02
1003        2     2000-03-03   2000-03-03
1004        2     2000-04-04   2000-04-04
1005        2     2000-12-31   2001-12-31
(...)
1996        2     2010-01-01   2011-01-01
1997        2     2010-02-15   2011-02-15
1998        2     2010-03-05   2011-03-05
1999        2     2010-04-10   2011-04-10
2000        2     2010-12-027  2011-12-27
(...)
3000        34    2000-02-02   2002-02-02
3001        34    2000-05-05   2001-05-05
3002        34    2000-06-06   2001-06-06
3003        34    2000-07-07   2001-07-07
3004        34    2000-11-11   2001-11-11
(...)
9996        34    2010-02-06   2011-02-06
9997        34    2010-05-05   2011-05-05
9998        34    2010-09-09   2011-09-09
9999        34    2010-09-25   2011-09-25
10000       34    2010-10-15   2011-10-15
</code>```

Assume DF2 looks as follows:

```<code>unit      date         x
1         2000-01-01   1
1         2000-05-01   2
1         2000-12-01   3
1         2001-01-02   10
1         2001-07-05   20
1         2001-12-31   30
(...)
2         2010-05-05   1
2         2010-07-01   1
2         2010-08-09   1
3         (...)
</code>```

This is what I would like DF1 to look like after running the code:

```<code>individual  unit      date1        date2        newvar
    1           1     2000-01-01   2001-01-01   6
    2           1     2000-02-02   2001-02-02   16
    3           1     2000-03-03   2001-03-03   15
    4           1     2000-04-04   2001-04-04   15
    5           1     2000-12-31   2001-12-31   60
    (...)
    996         1     2010-01-01   2011-01-01    3
    997         1     2010-02-15   2011-02-15    2
    998         1     2010-03-05   2011-03-05    2
    999         1     2010-04-10   2011-04-10    2
    1000        1     2010-12-27  2011-12-27     0
    (...)
</code>```

However, I cannot simply aggregate: Imagine that in DF1 each "unit" has several hundreds of individuals for each year between 2000 and 2011. And DF2 has many observations for each unit across the years 2000-2011.

答:
We can use data.table

```<code>library(data.table)
setDT(DF1)
setDT(DF2)
DF1[DF2[, .(newvar = sum(x)), .(unit, individual = cumsum(date %in% DF1$date1))],
             newvar := newvar, on = .(individual, unit)]
DF1
#    individual unit      date1      date2 newvar
#1:          1    1 2000-01-01 2001-01-01      6
#2:          2    1 2001-01-02 2002-01-02     60
</code>```

Or we can use a non-equi join

```<code>DF1[DF2[DF1, sum(x), on = .(unit, date >= date1, date <= date2),
        by = .EACHI], newvar := V1, on = .(unit, date1=date)]

DF1
#   individual unit      date1      date2 newvar
#1:          1    1 2000-01-01 2001-01-01      6
#2:          2    1 2001-01-02 2002-01-02     60
</code>```

Body:
I have two data frames (DF1 and DF2):

(1) DF1 contains information on individual-level, i.e. on 10.000 individuals nested in 30 units across 11 years (2000-2011). It contains four variables:

"individual" (numeric id for each individual; ranging from 1-10.000)

"unit" (numeric id for each unit; ranging from 1-30)

"date1" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2010-12-31)

"date2" ("Date1" + 1 year)

(2) DF2 contains information on unit-level, i.e. on the same 30 units as in DF1 across the same time period (2000-2011) and further contains a numeric variable ("x"):

"unit" (numeric id for each unit; ranging from 1-30)

"date" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2011-12-31)

"x" (a numeric variable, ranging from 0 to 200)

I would like to create new variable ("newvar") that gives me for each "individual" per "unit" the sum of "x" (DF2) counting from "date1" (DF1) to "date2" (DF2). This means that I would like to add this new variable to DF1.

For instance, if "individual"=1 in "unit"=1 has "date1"=2000-01-01 and "date2"=2001-01-01, and in DF2 "unit"=1 has three observations in the time period "date1" to "date2" (i.e. 2000-01-01 to 2001-01-01) with "x"=1, "x"=2 and "x"=3, then I would like add a new variable that gives for "individual"=1 in "unit"=1 "newvar"=6.

I assume that I need to use a for loop in R and have been using the following code:

for(i in length(DF1)){

DF1$newvar[i] <-sum(DF2$x[which(DF1$date == DF1$date1[i] &
                     DF1$date == DF1P$date1[i] &
                     DF2$unit == DF1P$unit[i]),])

}

but get the error message:

Error in DF2$x[which(DF2$date ==  : incorrect number of dimensions

Any ideas of how to create this variable would be tremendously appreciated!

Here is a small example as well as the expected output, using one unit for the sake of simplicity:

Assume DF1 looks as follows:

individual  unit  date1        date2
1           1     2000-01-01   2001-01-01
2           1     2000-02-02   2001-02-02
3           1     2000-03-03   2000-03-03
4           1     2000-04-04   2000-04-04
5           1     2000-12-31   2001-12-31
(...)
996         1     2010-01-01   2011-01-01
997         1     2010-02-15   2011-02-15
998         1     2010-03-05   2011-03-05
999         1     2010-04-10   2011-04-10
1000        1     2010-12-27  2011-12-27
1001        2     2000-01-01   2001-01-01
1002        2     2000-02-02   2001-02-02
1003        2     2000-03-03   2000-03-03
1004        2     2000-04-04   2000-04-04
1005        2     2000-12-31   2001-12-31
(...)
1996        2     2010-01-01   2011-01-01
1997        2     2010-02-15   2011-02-15
1998        2     2010-03-05   2011-03-05
1999        2     2010-04-10   2011-04-10
2000        2     2010-12-027  2011-12-27
(...)
3000        34    2000-02-02   2002-02-02
3001        34    2000-05-05   2001-05-05
3002        34    2000-06-06   2001-06-06
3003        34    2000-07-07   2001-07-07
3004        34    2000-11-11   2001-11-11
(...)
9996        34    2010-02-06   2011-02-06
9997        34    2010-05-05   2011-05-05
9998        34    2010-09-09   2011-09-09
9999        34    2010-09-25   2011-09-25
10000       34    2010-10-15   2011-10-15

Assume DF2 looks as follows:

unit      date         x
1         2000-01-01   1
1         2000-05-01   2
1         2000-12-01   3
1         2001-01-02   10
1         2001-07-05   20
1         2001-12-31   30
(...)
2         2010-05-05   1
2         2010-07-01   1
2         2010-08-09   1
3         (...)

This is what I would like DF1 to look like after running the code:

individual  unit      date1        date2        newvar
    1           1     2000-01-01   2001-01-01   6
    2           1     2000-02-02   2001-02-02   16
    3           1     2000-03-03   2001-03-03   15
    4           1     2000-04-04   2001-04-04   15
    5           1     2000-12-31   2001-12-31   60
    (...)
    996         1     2010-01-01   2011-01-01    3
    997         1     2010-02-15   2011-02-15    2
    998         1     2010-03-05   2011-03-05    2
    999         1     2010-04-10   2011-04-10    2
    1000        1     2010-12-27  2011-12-27     0
    (...)

However, I cannot simply aggregate: Imagine that in DF1 each "unit" has several hundreds of individuals for each year between 2000 and 2011. And DF2 has many observations for each unit across the years 2000-2011.

Body:
We can use data.table

library(data.table)
setDT(DF1)
setDT(DF2)
DF1[DF2[, .(newvar = sum(x)), .(unit, individual = cumsum(date %in% DF1$date1))],
             newvar := newvar, on = .(individual, unit)]
DF1
#    individual unit      date1      date2 newvar
#1:          1    1 2000-01-01 2001-01-01      6
#2:          2    1 2001-01-02 2002-01-02     60

Or we can use a non-equi join

DF1[DF2[DF1, sum(x), on = .(unit, date >= date1, date <= date2),
        by = .EACHI], newvar := V1, on = .(unit, date1=date)]

DF1
#   individual unit      date1      date2 newvar
#1:          1    1 2000-01-01 2001-01-01      6
#2:          2    1 2001-01-02 2002-01-02     60


问:
libGDX RoboVM fork iOS build error
I always get the same strange error when I try to run the iOS version of my libGDX game. The error only shows this message: Error:com.android.tools.idea.gradle.util.Projects.lastGradleSyncFailed(Lcom/intellij/openapi/project/Project;)Z

I can sync gradle successfully but the error message stays the same. It was suggested to use the same android studio version as the RoboVM fork version, so I did that. Now I use version 2.3.0 for them both, but it wasn't fixed by doing this. To set up RoboVM I followed the instructions from the RoboVM fork website: http://robovm.mobidevelop.com/.

Does someone know how to fix this problem?

答:
RoboVM having some incompatibly issue with Android Studio/IDEA, version 2.3.0.

Try to use MobiDevelop RoboVM 2.3.2-SNAPSHOT version that having fixes for the same.

There is a pull request for this problem in master branch, you can check that.

Title: libGDX RoboVM fork iOS build error


问:
SQL Query to check if student1 has a course with student 2
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

```
Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)
```

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

答:
You could do it with a subselect:</p>

```<code>select id_group
from  jos_gj_users
where (id_user = 20)
and id_group in (select id_group from jos_gj_users where id_user = 21)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

Body:
You could do it with a subselect:

select id_group
from  jos_gj_users
where (id_user = 20)
and id_group in (select id_group from jos_gj_users where id_user = 21)


问:
Show or Hide field when selected radio button codeigniter
I am currently doing a project. I have 2 radio button,1) One way 2) Round trip. When the user tried to select the One way radio button, the return text field will hide.

I've saw a thread and someone comment regarding to this problem. Scenario: I chose the One way radio button, the return field will disappear, yes it is working but there's some problem. What if I change my mind, from one way radio button to Round trip? The problem is the return field didn't came back

**View **

// my radio button

```<code><div class="pure-u-1-1 radiobtn">
     <form action="">
           <input type="radio" name="flight_type"  value="one_way" class="onew" style=""  >One Way
           <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
     </form>
</div>
</code>```

// the return field that will hide/show

```<code><div class="pure-u-1-1 dr" id="try">
      <label for="return" class="drr">Return</label>
      <input type="text" id="return" name="return" class="departreturn"><br>

</div>
</code>```

JS

```<code><script type="text/javascript">
$(document).on('change', 'input:radio[name=flight_type]', function(){
    $('div[id^="try"]').hide(); // hide all DIVs begining with "my_radio_"
    $('#' + $(this).attr('id') + '_text').show(); // show the current one
});

</script>
</code>```

答:
Just use .toggle()

.toggle()

Description: Display or hide the matched elements.

With no parameters, the .toggle() method simply toggles the visibility of elements:

REF: http://api.jquery.com/toggle/

  <form action="">
    <input type="radio" name="flight_type" value="one_way" class="onew" style="">One Way
    <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
  </form>

  Return
  <input type="text" id="return" name="return" class="departreturn">

```

Body:
I am currently doing a project. I have 2 radio button,1) One way 2) Round trip. When the user tried to select the One way radio button, the return text field will hide.

I've saw a thread and someone comment regarding to this problem. Scenario: I chose the One way radio button, the return field will disappear, yes it is working but there's some problem. What if I change my mind, from one way radio button to Round trip? The problem is the return field didn't came back

**View **

// my radio button

     <form action="">
           <input type="radio" name="flight_type"  value="one_way" class="onew" style=""  >One Way
           <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
     </form>

// the return field that will hide/show

      Return
      <input type="text" id="return" name="return" class="departreturn">

JS

Body:
Just use .toggle()

.toggle()

Description: Display or hide the matched elements.

With no parameters, the .toggle() method simply toggles the visibility of elements:

REF: http://api.jquery.com/toggle/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pure-u-1-1 radiobtn">
  <form action="">
    <input type="radio" name="flight_type" value="one_way" class="onew" style="">One Way
    <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
  </form>
</div>

<div class="pure-u-1-1 dr" id="try">
  <label for="return" class="drr">Return</label>
  <input type="text" id="return" name="return" class="departreturn"><br>

</div>

<script type="text/javascript">
  $(document).on('change', 'input:radio[name=flight_type]', function() {
    $('div[id^="try"]').toggle(); // toggle all DIVs begining with "my_radio_"
    $('#' + $(this).attr('id') + '_text').show(); // show the current one
  });
</script>


问:
Xcode not printing crash log on iOS real device
Lastly I realize this issue using my real device in Xcode

If the app that I'm developing crashes, the crash log is not printed in Xcode but, if I run the same project in simulator and replicate the same crash the log is successfully printed.

If the app crashes using a real device this is printed:

After a crash it prints a single line:

```<code>libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

Also I receive this log:

```<code>If the app crashes using a real device this is printed:
warning: could not load any Objective-C class information from the dyld shared cache. This will significantly reduce the quality of type information available.
</code>```

I'm using:

Xcode 7.3.1 with iOS 10 developers disk image see reference.

Real device: iOS 10.0.2

Is there a way to solve this issue and see the crash information again using a real device in Xcode?

Thanks in advance

答: I've experienced same issue, and resolved it by removing "OS_ACTIVITY_MODE" - disable from scheme environment variables.</p>

Body:
Lastly I realize this issue using my real device in Xcode

If the app that I'm developing crashes, the crash log is not printed in Xcode but, if I run the same project in simulator and replicate the same crash the log is successfully printed.

If the app crashes using a real device this is printed:

After a crash it prints a single line:

libc++abi.dylib: terminating with uncaught exception of type NSException

Also I receive this log:

If the app crashes using a real device this is printed:
warning: could not load any Objective-C class information from the dyld shared cache. This will significantly reduce the quality of type information available.

I'm using:

Xcode 7.3.1 with iOS 10 developers disk image see reference.

Real device: iOS 10.0.2

Is there a way to solve this issue and see the crash information again using a real device in Xcode?

Thanks in advance


问:
How to convert lowercase characters of a string to uppercase characters in C++?
I have a question where all lowercase characters of a string should be converted into uppercase characters.But as per the question, certain lines in the code should not be changed. I have written the code below.

```<code> #include <iostream>
 #include <string>
 #include <stdio.h>
 #include <ctype.h>
 using namespace std;

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }
</code>```

I get the output as:

```<code>HELLO WORLDHello World
</code>```

But the required output is:

```<code>HELLO WORLD HELLO WORLD
</code>```

How do I make the

```<code> cout<<str;
</code>```

statement in main() to print the result computed in the function :

```<code> void stringToUpper(string &s)
</code>```

答:
You are just printing the string with making each character as upper character, but the string that passed to function (by reference) "s" does not get changed.

```<code>void stringToUpper(string &s)
</code>```

A line can be added to make s to get changed in void stringToUpper(string &s)

```<code> s[i] = toupper(c);
</code>```

Code will look

```<code> c=s[i];
 s[i] = toupper(c);
 putchar (toupper(c));
 i++;
</code>```

Output will be

```<code>HELLO WORLDHELLO WORLD
</code>```

Body:
I have a question where all lowercase characters of a string should be converted into uppercase characters.But as per the question, certain lines in the code should not be changed. I have written the code below.

 #include <iostream>
 #include <string>
 #include <stdio.h>
 #include <ctype.h>
 using namespace std;

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }

I get the output as:

HELLO WORLDHello World

But the required output is:

HELLO WORLD HELLO WORLD

How do I make the

 cout<<str;

statement in main() to print the result computed in the function :

 void stringToUpper(string &s)

Body:
You are just printing the string with making each character as upper character, but the string that passed to function (by reference) "s" does not get changed.

void stringToUpper(string &s)

A line can be added to make s to get changed in void stringToUpper(string &s)

 s[i] = toupper(c);

Code will look

 c=s[i];
 s[i] = toupper(c);
 putchar (toupper(c));
 i++;

Output will be

HELLO WORLDHELLO WORLD


问:
Implicit conversions and pointers?
Why does an implicit conversion not happen when making a float pointer point to an integer, such as when you assign a float variable an integer value?</p>

答:
I think it's easy to reason about it via allegory.

Think of a pointer as slip of paper with the address of a house written on it. The type of the data is the name of the person who resides in said house.

Now, casting a pointer is like taking that slip of paper, keeping the address the same (for the most part), but changing the name of the person who supposedly lives in the house.

Just because we changed the name on the paper from Alice to Bob, doesn't mean Alice magically becomes Bob. The paper doesn't influence the house.

That's why using such a pointer has undefined behavior. The code think it's addressing a Bob, when in fact it's Alice.

Title: Implicit conversions and pointers?


问:
How do you loop inside sub directories in windows, and repeat command using windows batch scripting
I am on Windows 10. I have a folder with sub folder. All subfolders have "Subs" folder inside them. I want to loop through all subdirectories, goto Subs directory, unrar a file, Goto next subdirectory and repeat. </p>

<p>I tried below script but could not get to work. </p>

```<code>@echo off
setlocal enableextensions enabledelayedexpansion

set "rootFolder=C:\Users\MNM\MAT"

 echo ----------------------------------------------------------------------
for /d /r "%rootFolder%" %%a in (.) do (
    set mypath=%cd%
    @echo %mypath%
    cd %%a
    set mypath=%cd%
    @echo %mypath%
    cd Subs
    set mypath=%cd%
    @echo %mypath%
    C:\Users\MNM\MAT\unrar e *subs.rar C:\Users\MNM\mat2\
    cd C:\Users\MNM\MAT
)
</code>```

答:
Just because recursing all subdirectories and extracting all *subs.rar files wasn't requested here's an example that is based upon my assumptions:

@ECHO OFF
SET "rootDir=%USERPROFILE%\MAT"
IF /I NOT "%CD%"=="%rootDir%" CD /D "%rootDir%"
FOR /D %%A IN (*
) DO IF EXIST "%%A\Subs\*subs.rar" UNRAR e "%%A\Subs\*subs.rar" mat2\
```

Body:
I am on Windows 10. I have a folder with sub folder. All subfolders have "Subs" folder inside them. I want to loop through all subdirectories, goto Subs directory, unrar a file, Goto next subdirectory and repeat.

I tried below script but could not get to work.

@echo off
setlocal enableextensions enabledelayedexpansion

set "rootFolder=C:\Users\MNM\MAT"

 echo ----------------------------------------------------------------------
for /d /r "%rootFolder%" %%a in (.) do (
    set mypath=%cd%
    @echo %mypath%
    cd %%a
    set mypath=%cd%
    @echo %mypath%
    cd Subs
    set mypath=%cd%
    @echo %mypath%
    C:\Users\MNM\MAT\unrar e *subs.rar C:\Users\MNM\mat2\
    cd C:\Users\MNM\MAT
)


问:
Trying to push using bot framework
Getting started with bot framework and trying to "push" a message to user. I copied some code from a previous post here using SendToConversationAsync and pasting in ids, etc from the emulator but it's not sending. I've pasted the code below. Any help appreciated.

```<code>namespace Bot
{
    [BotAuthentication]
    public class MessagesController : ApiController
    {
        public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // calculate something for us to return
                int length = (activity.Text ?? string.Empty).Length;

                //create reply here

                // return our reply to the user
                Activity reply = activity.CreateReply($"You sent **{activity.Text}** which was {length} characters");
                await connector.Conversations.ReplyToActivityAsync(reply);

                SendMessage("Blah!");
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }

        private void SendMessage(string msg)
        {
            var userAccount = new ChannelAccount(name: "", id: "default-user");
            var botAccount = new ChannelAccount(name: "Bot", id: "m374hm6j2b474lei9");
            var connector = new ConnectorClient(new Uri("http://localhost:3979/"));

            // conversationId for Real Bot
            //var conversationId = connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount).Result;

    // conversationId for Bot Emulator
    //var conversationId = _activityHistory.Conversation;

            IMessageActivity message = Activity.CreateMessageActivity();
            message.From = botAccount;
            message.Recipient = userAccount;
            message.Conversation = new ConversationAccount(id: "0dkmb2e3lf1dn2g69");
            message.Text = msg;
            message.Locale = "en-Us";
            connector.Conversations.SendToConversationAsync((Activity)message);
        }
    }
}
</code>```

More info:

JSON

```<code>{
  "type": "message",
  "text": "test",
  "from": {
    "id": "default-user",
    "name": "User"
  },
  "locale": "en-US",
  "textFormat": "plain",
  "timestamp": "2017-06-02T21:33:24.737Z",
  "channelData": {
    "clientActivityId": "1496437792941.9667812978932935.10"
  },
  "id": "hfncb55l7j7ea0c26",
  "channelId": "emulator",
  "localTimestamp": "2017-06-02T14:33:24-07:00",
  "recipient": {
    "id": "m374hm6j2b474lei9",
    "name": "Bot"
  },
  "conversation": {
    "id": "icn5ed433edc0kh99"
  },
  "serviceUrl": "http://127.0.0.1:56303"
}
</code>```

SendMessage:

```<code>private void SendMessage(string msg)
{
    var userAccount = new ChannelAccount(name: "User", id: "default-user");
    var botAccount = new ChannelAccount(name: "Bot", id: "m374hm6j2b474lei9");
    var connector = new ConnectorClient(new Uri("http://localhost:3979/"));

    // conversationId for Real Bot
    //var conversationId = connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount).Result;

    // conversationId for Bot Emulator
    //var conversationId = _activityHistory.Conversation;

    IMessageActivity message = Activity.CreateMessageActivity();
    message.From = botAccount;
    message.Recipient = userAccount;
    message.Conversation = new ConversationAccount(id: "icn5ed433edc0kh99");
    message.Text = msg;
    message.Locale = "en-Us";
    //message.Type = "message";
    //message.ChannelId = "emulator";
    //message.ReplyToId = "62ehe9jk6kn2eg23i";
    message.ServiceUrl = "http://127.0.0.1:56303";

    connector.Conversations.SendToConversationAsync((Activity)message);
}
</code>```

答: Thanks all. I think I'm going to go with using Microsoft.Bot.Builder.Dialogs. They've got some examples on github with a push that works on a timer and that's working for me. BotBuilder-Samples</p>

Title: Trying to push using bot framework

Body:
Getting started with bot framework and trying to "push" a message to user. I copied some code from a previous post here using SendToConversationAsync and pasting in ids, etc from the emulator but it's not sending. I've pasted the code below. Any help appreciated.

namespace Bot
{
    [BotAuthentication]
    public class MessagesController : ApiController
    {
        public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // calculate something for us to return
                int length = (activity.Text ?? string.Empty).Length;

                //create reply here

                // return our reply to the user
                Activity reply = activity.CreateReply($"You sent **{activity.Text}** which was {length} characters");
                await connector.Conversations.ReplyToActivityAsync(reply);

                SendMessage("Blah!");
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }

        private void SendMessage(string msg)
        {
            var userAccount = new ChannelAccount(name: "", id: "default-user");
            var botAccount = new ChannelAccount(name: "Bot", id: "m374hm6j2b474lei9");
            var connector = new ConnectorClient(new Uri("http://localhost:3979/"));

            // conversationId for Real Bot
            //var conversationId = connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount).Result;

    // conversationId for Bot Emulator
    //var conversationId = _activityHistory.Conversation;

            IMessageActivity message = Activity.CreateMessageActivity();
            message.From = botAccount;
            message.Recipient = userAccount;
            message.Conversation = new ConversationAccount(id: "0dkmb2e3lf1dn2g69");
            message.Text = msg;
            message.Locale = "en-Us";
            connector.Conversations.SendToConversationAsync((Activity)message);
        }
    }
}

More info:

JSON

{
  "type": "message",
  "text": "test",
  "from": {
    "id": "default-user",
    "name": "User"
  },
  "locale": "en-US",
  "textFormat": "plain",
  "timestamp": "2017-06-02T21:33:24.737Z",
  "channelData": {
    "clientActivityId": "1496437792941.9667812978932935.10"
  },
  "id": "hfncb55l7j7ea0c26",
  "channelId": "emulator",
  "localTimestamp": "2017-06-02T14:33:24-07:00",
  "recipient": {
    "id": "m374hm6j2b474lei9",
    "name": "Bot"
  },
  "conversation": {
    "id": "icn5ed433edc0kh99"
  },
  "serviceUrl": "http://127.0.0.1:56303"
}

SendMessage:

private void SendMessage(string msg)
{
    var userAccount = new ChannelAccount(name: "User", id: "default-user");
    var botAccount = new ChannelAccount(name: "Bot", id: "m374hm6j2b474lei9");
    var connector = new ConnectorClient(new Uri("http://localhost:3979/"));

    // conversationId for Real Bot
    //var conversationId = connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount).Result;

    // conversationId for Bot Emulator
    //var conversationId = _activityHistory.Conversation;

    IMessageActivity message = Activity.CreateMessageActivity();
    message.From = botAccount;
    message.Recipient = userAccount;
    message.Conversation = new ConversationAccount(id: "icn5ed433edc0kh99");
    message.Text = msg;
    message.Locale = "en-Us";
    //message.Type = "message";
    //message.ChannelId = "emulator";
    //message.ReplyToId = "62ehe9jk6kn2eg23i";
    message.ServiceUrl = "http://127.0.0.1:56303";

    connector.Conversations.SendToConversationAsync((Activity)message);
}


问:
Determine language in functions.php [wpml]
I have function in functions.php , which automatically adds woocommerce product by ID to cart when website is visited.

The website is bilingual and the function can't determine translated product ID.

So, I want to know if is possible to add wpml function in functions.php, which determines first language of front end, then executes function, something like this:

```<code><?php if(wpml_getLanguage()=='en'); ?>
---do function for product 22---
<?php elseif(wpml_getLanguage()=='it'); ?>
---do function for product 45--
<?php endif; ?>
</code>```

My code:

```<code>add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 22;
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->id == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}
</code>```

答:
You can easily get this by using the native WPML variable ICL_LANGUAGE_CODE.

You can find more information about this topic on the following page:
https://wpml.org/documentation/support/wpml-coding-api/

Body:
I have function in functions.php , which automatically adds woocommerce product by ID to cart when website is visited.

The website is bilingual and the function can't determine translated product ID.

So, I want to know if is possible to add wpml function in functions.php, which determines first language of front end, then executes function, something like this:

<?php if(wpml_getLanguage()=='en'); ?>
---do function for product 22---
<?php elseif(wpml_getLanguage()=='it'); ?>
---do function for product 45--
<?php endif; ?>

My code:

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 22;
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->id == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}


问:
Show image without scaling
Given an image of 500x500 pixels I want to show that image 1:1 on my screen. Additionally I want to have an x and y axes.

plt.imshow() automatically adds axes to my image and centers the image in the window, but the image is scaled and not shown as 500x500 pixels on my screen.

fig.figimage() shows the image 1:1 on my screen but adds no axes and displays the image in the bottom left corner of the window. Especially maximizing the window / resizing the windows does not change the size of image.

Now what I need, is a combination of both – diplay the image 1:1 like fig.figshow does, add the axes that plt.imshow() adds and display the image centered like plt.imshow() does.

How can I do that?
Or in other terms: How to tell plt.imshow() to display im image unscaled like fig.figimage() does?

Sample code demonstrating the problem:

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

width=500;
height=500;

# using plt.imshow()
dummyImage = np.zeros((width, height))
plt.imshow(dummyImage)
plt.show()

# using fig.figimage()
fig = plt.figure(figsize=(width, height))
fig.figimage(dummyImage)
plt.show()
</code>```

Result:

using plt.imshow(): not exactly 500x500 pixels and actual size depends on size of the window.

using fig.figimage(): exactly 500x500 pixels, independent of window size

答:
You will need to do a little bit of calculation yourself.
Say, you want 50 pixel margin on all sides, and you have a dpi of 100, you can then calculate the figure size to be figsize=((width+2*margin)/dpi, (height+2*margin)/dpi) inches. You would then need to calculate the borders, e.g. the left border will be margin divided by dpi divided by figure width. You can set the calculated figure size (figsize argument of plt.figure()) and borders (using subplots_adjust) to your figure.

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

width=500 # pixels
height=150
margin=50 # pixels
dpi=100. # dots per inch

figsize=((width+2*margin)/dpi, (height+2*margin)/dpi) # inches
left = margin/dpi/figsize[0] #axes ratio
bottom = margin/dpi/figsize[1]

fig = plt.figure(figsize=figsize, dpi=dpi)
fig.subplots_adjust(left=left, bottom=bottom, right=1.-left, top=1.-bottom)

dummyImage = np.zeros((height, width))
plt.imshow(dummyImage)
plt.show()
</code>```

Note that to have an image of dimensions width width and height height, you need an array np.zeros((height, width)), not the inverse.

In order to make sure the figure keeps its original size, one may add the following code, which resizes the figure back to its original size on every attempt to change the figure size:

```<code>def update(event=None):
    fig.set_size_inches(figsize)

update()
ci = fig.canvas.mpl_connect("resize_event", update)
plt.show()
</code>```

Title: Show image without scaling

Body:
Given an image of 500x500 pixels I want to show that image 1:1 on my screen. Additionally I want to have an x and y axes.

plt.imshow() automatically adds axes to my image and centers the image in the window, but the image is scaled and not shown as 500x500 pixels on my screen.

fig.figimage() shows the image 1:1 on my screen but adds no axes and displays the image in the bottom left corner of the window. Especially maximizing the window / resizing the windows does not change the size of image.

Now what I need, is a combination of both – diplay the image 1:1 like fig.figshow does, add the axes that plt.imshow() adds and display the image centered like plt.imshow() does.

How can I do that?
Or in other terms: How to tell plt.imshow() to display im image unscaled like fig.figimage() does?

Sample code demonstrating the problem:

import matplotlib.pyplot as plt
import numpy as np

width=500;
height=500;

# using plt.imshow()
dummyImage = np.zeros((width, height))
plt.imshow(dummyImage)
plt.show()

# using fig.figimage()
fig = plt.figure(figsize=(width, height))
fig.figimage(dummyImage)
plt.show()

Result:

using plt.imshow(): not exactly 500x500 pixels and actual size depends on size of the window.

using fig.figimage(): exactly 500x500 pixels, independent of window size

Body:
You will need to do a little bit of calculation yourself.
Say, you want 50 pixel margin on all sides, and you have a dpi of 100, you can then calculate the figure size to be figsize=((width+2*margin)/dpi, (height+2*margin)/dpi) inches. You would then need to calculate the borders, e.g. the left border will be margin divided by dpi divided by figure width. You can set the calculated figure size (figsize argument of plt.figure()) and borders (using subplots_adjust) to your figure.

import matplotlib.pyplot as plt
import numpy as np

width=500 # pixels
height=150
margin=50 # pixels
dpi=100. # dots per inch

figsize=((width+2*margin)/dpi, (height+2*margin)/dpi) # inches
left = margin/dpi/figsize[0] #axes ratio
bottom = margin/dpi/figsize[1]

fig = plt.figure(figsize=figsize, dpi=dpi)
fig.subplots_adjust(left=left, bottom=bottom, right=1.-left, top=1.-bottom)

dummyImage = np.zeros((height, width))
plt.imshow(dummyImage)
plt.show()

Note that to have an image of dimensions width width and height height, you need an array np.zeros((height, width)), not the inverse.

In order to make sure the figure keeps its original size, one may add the following code, which resizes the figure back to its original size on every attempt to change the figure size:

def update(event=None):
    fig.set_size_inches(figsize)

update()
ci = fig.canvas.mpl_connect("resize_event", update)
plt.show()


问:
How to reference first list item inside ListView?
I would like to add Top Margin on the first item in the ListView. Is that possible?
Or, how can I reference first list item in the List View?

I tried

```<code>lv = (ListView)getListView();
View myRowItem = lv.getChildAt(0);
</code>```

Probably, it doesn't work, because at the moment I executed it, list items didn't exist yet. I assume I should try above code in something like onPostRender event. Is there something like that in Java Android?

答:
In order to get the items, write your code wherever you set the list adapter.

By the way, in order to set the margin, just set android:PaddingTop of the ListView on the layout file (XML file).

Body:
I would like to add Top Margin on the first item in the ListView. Is that possible?
Or, how can I reference first list item in the List View?

I tried

lv = (ListView)getListView();
View myRowItem = lv.getChildAt(0);

Probably, it doesn't work, because at the moment I executed it, list items didn't exist yet. I assume I should try above code in something like onPostRender event. Is there something like that in Java Android?


问:
Create JSON object from HTML elements (jQuery)
Is there any way to get object formated like this from html via button click?

```<code>var Movie = [{id:"tt3783958", title:"La La Land", type:"Comedy, Drama, Music", year:"2016"}];
</code>```

And then whit next button click, to append next object like this?

```<code>var Movie = [ {id:"tt3783958", title:"La La Land", type:"Comedy, Drama, Music", year:"2016"}, {id:"tt0488120", title:"Fracture", type:"Crime, Drama, Mystery", year:"2007"} ];
</code>```

Live Demo: https://jsfiddle.net/q94eemn8/1/

答:
Here is a way you can do something like this. It's not entirely clear what you're looking to accomplish, so I took some guesses.

Working Example: https://jsfiddle.net/Twisty/tre7dx8a/

Added add as a class for each button in HTML.

JavaScript

```<code>$(function() {
  var Movies = [];
  $(".btn.btn-outline-success").click(function(e) {
    if ($(this).hasClass("add")) {
      var row = $(this).closest("tr");
      var movie = {};
      movie.id = row.find("td:eq(0)").html();
      movie.title = row.find("td:eq(1)").html();
      movie.year = row.find("td:eq(2)").html();
      movie.type = row.find("td:eq(3)").html();
      Movies.push(movie);
      console.log("Added Movie:", movie);
      $(this).html("Remove").toggleClass("add remove");
    } else {
      var id = $(this).closest("tr").find("td:eq(0)").html();
      var index = -1;
      $.each(Movies, function(k, v) {
        if (v.id == id) {
          index = k;
        }
      });
      if (index > -1) {
        Movies.splice(index, 1);
        console.log("Removed Movie:", id);
        $(this).html("Add").toggleClass("add remove");
      }
    }
  });
});
</code>```

When Add is clicked, a movie object is created and populated with the items from the  in that
. I used the :eq() selector to specifically identify each element. I then used .html() to read the content of the element. I could have also used .text().

I then considered that the user may make a mistake or change their mind, so I set the button to toggle itself to a Remove. This has a similar action, but will find and remove the movie from the storage array.

You can move them to local storage in a similar manner. Might be worthwhile writing a function to send the data back and forth to/from local storage.

Body:
Is there any way to get object formated like this from html via button click?

var Movie = [{id:"tt3783958", title:"La La Land", type:"Comedy, Drama, Music", year:"2016"}];

And then whit next button click, to append next object like this?

var Movie = [ {id:"tt3783958", title:"La La Land", type:"Comedy, Drama, Music", year:"2016"}, {id:"tt0488120", title:"Fracture", type:"Crime, Drama, Mystery", year:"2007"} ];

Live Demo: https://jsfiddle.net/q94eemn8/1/

Body:
Here is a way you can do something like this. It's not entirely clear what you're looking to accomplish, so I took some guesses.

Working Example: https://jsfiddle.net/Twisty/tre7dx8a/

Added add as a class for each button in HTML.

JavaScript

$(function() {
  var Movies = [];
  $(".btn.btn-outline-success").click(function(e) {
    if ($(this).hasClass("add")) {
      var row = $(this).closest("tr");
      var movie = {};
      movie.id = row.find("td:eq(0)").html();
      movie.title = row.find("td:eq(1)").html();
      movie.year = row.find("td:eq(2)").html();
      movie.type = row.find("td:eq(3)").html();
      Movies.push(movie);
      console.log("Added Movie:", movie);
      $(this).html("Remove").toggleClass("add remove");
    } else {
      var id = $(this).closest("tr").find("td:eq(0)").html();
      var index = -1;
      $.each(Movies, function(k, v) {
        if (v.id == id) {
          index = k;
        }
      });
      if (index > -1) {
        Movies.splice(index, 1);
        console.log("Removed Movie:", id);
        $(this).html("Add").toggleClass("add remove");
      }
    }
  });
});

When Add is clicked, a movie object is created and populated with the items from the <td> in that <tr>. I used the :eq() selector to specifically identify each element. I then used .html() to read the content of the element. I could have also used .text().

I then considered that the user may make a mistake or change their mind, so I set the button to toggle itself to a Remove. This has a similar action, but will find and remove the movie from the storage array.

You can move them to local storage in a similar manner. Might be worthwhile writing a function to send the data back and forth to/from local storage.


问:
Setuptools: how to distribute configuration files without erasing existing ones?
I'm trying to find a nice way to ship default configuration files with my python setuptools project.

For now I'm doing it like this:

```<code>from setuptools import setup

setup(
    ...
    data_files = [('/usr/local/etc', ['files/myproject.conf', ...])]
    ...
)
</code>```

The problem is that the configuration files are erased if I uninstall my package. Usually, when uninstalling a package on Linux or FreeBSD, the configuration files are not deleted. I think this is good, because sometimes you just want to uninstall a package to reinstall another version, or to install it with other options etc... You don't expect your configurations files to be deleted.

How to achieve the same with setuptools? How to install configurations files only if they don't already exist?

答:
Why can't you? setup.py is also a python script, maybe you can manually add your configuration files to avoid adding them into metadata? Like the following code:

```<code>from setuptools import setup
from shutil import copyfile
import os
...
setup(
...
# no data_files option
...
)
if not os.path.exists(configuration_file):
    copyfile(configuration, configuration_file)
</code>```

Body:
I'm trying to find a nice way to ship default configuration files with my python setuptools project.

For now I'm doing it like this:

from setuptools import setup

setup(
    ...
    data_files = [('/usr/local/etc', ['files/myproject.conf', ...])]
    ...
)

The problem is that the configuration files are erased if I uninstall my package. Usually, when uninstalling a package on Linux or FreeBSD, the configuration files are not deleted. I think this is good, because sometimes you just want to uninstall a package to reinstall another version, or to install it with other options etc... You don't expect your configurations files to be deleted.

How to achieve the same with setuptools? How to install configurations files only if they don't already exist?

Body:
Why can't you? setup.py is also a python script, maybe you can manually add your configuration files to avoid adding them into metadata? Like the following code:

from setuptools import setup
from shutil import copyfile
import os
...
setup(
...
# no data_files option
...
)
if not os.path.exists(configuration_file):
    copyfile(configuration, configuration_file)


问:
Python class calling function that belongs to same class
I am trying to call function that belongs to same function. Below is the code

```<code>class Asrconfig():
    def __init__(self, hostname, net_username, net_password):

        ''' SSH connection Establish '''
        self.hostname = hostname
        self.net_username = net_username
        self.net_password = net_password
    def connect(self, cmd):
        print "connect"
        self.cmd = cmd
        self.remote_conn_pre = paramiko.SSHClient()
        self.remote_conn_pre.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())
        self.remote_conn_pre.connect(self.hostname, username=self.net_username,
            password=self.net_password,look_for_keys=False, allow_agent=False)
        self.remote_conn = self.remote_conn_pre.invoke_shell()
        buff = ''
        remote_conn.send(cmd)
        while not buff.endswith('#'):
            resp = remote_conn.recv(9999)
            buff += resp
            print resp
    def inventory(self, cmd):
        cmd = "show inventory"
        self.connect(cmd)
asr = Asrconfig(hostname, net_username, net_password)
asr.inventory()
</code>```

I am getting below output when I run the output:

```<code>RP#
Traceback (most recent call last):
  File "onboard/testpara1.py", line 43, in <module>
    asr.inventory()
TypeError: inventory() takes exactly 2 arguments (1 given)
</code>```

I need below help

I am not able to call connect function in class Asrconfig under inventory function.

答:
Solution to your question:</p>

```<code>class Asrconfig:
def __init__(self, hostname, net_username, net_password):
    ''' SSH connection Establish '''
    self.hostname = hostname
    self.net_username = net_username
    self.net_password = net_password
def connect(self, cmd):
    print "connect"
    self.cmd = cmd
    self.remote_conn_pre = paramiko.SSHClient()
    self.remote_conn_pre.set_missing_host_key_policy(
        paramiko.AutoAddPolicy())
    self.remote_conn_pre.connect(self.hostname, username=self.net_username,
        password=self.net_password,look_for_keys=False, allow_agent=False)
    self.remote_conn = self.remote_conn_pre.invoke_shell()
    buff = ''
    remote_conn.send(cmd)
    while not buff.endswith('#'):
        resp = remote_conn.recv(9999)
        buff += resp
        print resp
def inventory(self, cmd):
    cmd = "show inventory"
    self.connect(cmd)

asr = Asrconfig(hostname, net_username, net_password)
# You need to pass parameter in inventory() method.
asr.inventory("Hello kitty...")
</code>```

Body:
I am trying to call function that belongs to same function. Below is the code

class Asrconfig():
    def __init__(self, hostname, net_username, net_password):

        ''' SSH connection Establish '''
        self.hostname = hostname
        self.net_username = net_username
        self.net_password = net_password
    def connect(self, cmd):
        print "connect"
        self.cmd = cmd
        self.remote_conn_pre = paramiko.SSHClient()
        self.remote_conn_pre.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())
        self.remote_conn_pre.connect(self.hostname, username=self.net_username,
            password=self.net_password,look_for_keys=False, allow_agent=False)
        self.remote_conn = self.remote_conn_pre.invoke_shell()
        buff = ''
        remote_conn.send(cmd)
        while not buff.endswith('#'):
            resp = remote_conn.recv(9999)
            buff += resp
            print resp
    def inventory(self, cmd):
        cmd = "show inventory"
        self.connect(cmd)
asr = Asrconfig(hostname, net_username, net_password)
asr.inventory()

I am getting below output when I run the output:

RP#
Traceback (most recent call last):
  File "onboard/testpara1.py", line 43, in <module>
    asr.inventory()
TypeError: inventory() takes exactly 2 arguments (1 given)

I need below help

I am not able to call connect function in class Asrconfig under inventory function.

Body:
Solution to your question:

class Asrconfig:
def __init__(self, hostname, net_username, net_password):
    ''' SSH connection Establish '''
    self.hostname = hostname
    self.net_username = net_username
    self.net_password = net_password
def connect(self, cmd):
    print "connect"
    self.cmd = cmd
    self.remote_conn_pre = paramiko.SSHClient()
    self.remote_conn_pre.set_missing_host_key_policy(
        paramiko.AutoAddPolicy())
    self.remote_conn_pre.connect(self.hostname, username=self.net_username,
        password=self.net_password,look_for_keys=False, allow_agent=False)
    self.remote_conn = self.remote_conn_pre.invoke_shell()
    buff = ''
    remote_conn.send(cmd)
    while not buff.endswith('#'):
        resp = remote_conn.recv(9999)
        buff += resp
        print resp
def inventory(self, cmd):
    cmd = "show inventory"
    self.connect(cmd)

asr = Asrconfig(hostname, net_username, net_password)
# You need to pass parameter in inventory() method.
asr.inventory("Hello kitty...")

ContentLicense: CC BY-SA 4.0


问:
Angular expression evaluates in Chrome extension but not in Edge extension
I have a simple browser extension, using Angular (v1.6.3), but the Angular expression in the pop-up window of the browser extension is failing to evaluate in Edge, but it is in Chrome.

The Angular expression is simply
{{2+2}}
.

When I browse to a relevant website (as configured in the manifest file, namely http://marketplace.visualstudio.com, https://marketplace.visualstudio.com or http://www.bbc.com, and click the extension button, Chrome evaluates the html output to "4", but Edge evaluates the html output to "{{2+2}}".

Chrome example

Edge example

I believe the html and angular interaction itself is fundamentally sound, because when I browse directly to the pop up page, using a URL such as file:///C:/temp/app/popup.html, both Chrome and Edge correctly evaluate the expression {{2+2}} to "4".

Chrome example when brosing directly to popup.html

Edge example when browsing directly to popup.html

To summarize, it is only as an Edge extension that the expression evaluation fails; as a Chrome extension or with direct browsing in both Edge and Chrome it works.

Thirty second video demo on You Tube:

I have placed a full version of the source code on GitHub but code is quite simple and consists of the following:

A popup.html file page for the pop-up window, which contains the Angular expression:

```<code><html>
 <head>
  <script type="text/javascript" src="scripts/angular.min.js"></script>
  <script type="text/javascript" src="scripts/app.js"></script>
 </head>
 <body>
  <div ng-app="myApp">
   <div>{{2+2}}</div>
  </div>
 </body>
</html>
</code>```

An app.js file to define the angular module:

```<code>var myApp = angular.module('myApp', []);
</code>```

A contentscript.js that tells the website to open the pop-up:

```<code>// Set the window object for multiple browser compatibility
window.browser = (function () {
return window.msBrowser ||
  window.browser ||
  window.chrome;
})();

window.browser.runtime.sendMessage({ action: "openPopUp" });
</code>```

A background.js script that actually opens the popup.html file:

```<code>// Set the window object for multiple browser compatibility
window.browser = (function () {
return window.msBrowser ||
  window.browser ||
  window.chrome;
})();

window.browser.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.action == "openPopUp") {
            window.browser.tabs.query({ active: true, currentWindow: true },
                function (tabs) {
                    window.browser.pageAction.show(tabs[0].id);
                });
        }
    });
</code>```

And finally a manifest.json file that wires everything up together, which both browsers understand:

```<code>{
  "manifest_version": 2,
  "name": "BrowserExtensionUsingAngularWorksChromeNotEdge",
  "version": "1.0.0",
  "author": "Greg Trevellick",
  "page_action": {
    "default_icon": {
      "19": "icon_19x19.png"
    },
     "default_popup": "popup.html"
    },
  "background": {
    "scripts": [ "scripts/background.js" ],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": [
        "http://marketplace.visualstudio.com/*",
        "https://marketplace.visualstudio.com/*",
        "http://www.bbc.co.uk/*"
      ],
      "js": [
        "scripts/contentscript.js",
        "scripts/angular.min.js"
      ]
    }
  ],
  "permissions": [
    "activeTab",
    "declarativeContent",
    "http://marketplace.visualstudio.com/",
    "https://marketplace.visualstudio.com/",
    "http://www.bbc.co.uk/"
  ],
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
</code>```

For what its worth, some instructions on getting started with Chrome extensions can be found here and for Edge here.

答:
Currently AngularJS will not bootstrap for the Edge extension protocol. I've submitted a PR on GitHub to address this. If you make this change in the angular.js file you will see it start working.

You can also bootstrap manually as a workaround.

Body:
I have a simple browser extension, using Angular (v1.6.3), but the Angular expression in the pop-up window of the browser extension is failing to evaluate in Edge, but it is in Chrome.

The Angular expression is simply
{{2+2}}
.

When I browse to a relevant website (as configured in the manifest file, namely http://marketplace.visualstudio.com, https://marketplace.visualstudio.com or http://www.bbc.com, and click the extension button, Chrome evaluates the html output to "4", but Edge evaluates the html output to "{{2+2}}".

Chrome example

Edge example

I believe the html and angular interaction itself is fundamentally sound, because when I browse directly to the pop up page, using a URL such as file:///C:/temp/app/popup.html, both Chrome and Edge correctly evaluate the expression {{2+2}} to "4".

Chrome example when brosing directly to popup.html

Edge example when browsing directly to popup.html

To summarize, it is only as an Edge extension that the expression evaluation fails; as a Chrome extension or with direct browsing in both Edge and Chrome it works.

Thirty second video demo on You Tube:

I have placed a full version of the source code on GitHub but code is quite simple and consists of the following:

A popup.html file page for the pop-up window, which contains the Angular expression:

{{2+2}}

An app.js file to define the angular module:

var myApp = angular.module('myApp', []);

A contentscript.js that tells the website to open the pop-up:

// Set the window object for multiple browser compatibility
window.browser = (function () {
return window.msBrowser ||
  window.browser ||
  window.chrome;
})();

window.browser.runtime.sendMessage({ action: "openPopUp" });

A background.js script that actually opens the popup.html file:

// Set the window object for multiple browser compatibility
window.browser = (function () {
return window.msBrowser ||
  window.browser ||
  window.chrome;
})();

window.browser.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.action == "openPopUp") {
            window.browser.tabs.query({ active: true, currentWindow: true },
                function (tabs) {
                    window.browser.pageAction.show(tabs[0].id);
                });
        }
    });

And finally a manifest.json file that wires everything up together, which both browsers understand:

{
  "manifest_version": 2,
  "name": "BrowserExtensionUsingAngularWorksChromeNotEdge",
  "version": "1.0.0",
  "author": "Greg Trevellick",
  "page_action": {
    "default_icon": {
      "19": "icon_19x19.png"
    },
     "default_popup": "popup.html"
    },
  "background": {
    "scripts": [ "scripts/background.js" ],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": [
        "http://marketplace.visualstudio.com/*",
        "https://marketplace.visualstudio.com/*",
        "http://www.bbc.co.uk/*"
      ],
      "js": [
        "scripts/contentscript.js",
        "scripts/angular.min.js"
      ]
    }
  ],
  "permissions": [
    "activeTab",
    "declarativeContent",
    "http://marketplace.visualstudio.com/",
    "https://marketplace.visualstudio.com/",
    "http://www.bbc.co.uk/"
  ],
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

For what its worth, some instructions on getting started with Chrome extensions can be found here and for Edge here.


问:
Spring MVC Resource not found 404
I am getting 404 response not found when I try to call a RESTful Web Service from AngularJS. Following is the code sample :

WebAppConfiguration.java

```<code>public class WebAppConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
       InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
       viewResolver.setViewClass(JstlView.class);
       viewResolver.setPrefix("/WEB-INF/");
       viewResolver.setSuffix(".html");
       registry.viewResolver(viewResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/app/**").addResourceLocations("/app/");
    }
}
</code>```

WebAppInitializer.java

```<code>public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebBeanConfig.class);
        ctx.setServletContext(servletContext);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);
        servlet.addMapping("/");
        servlet.setAsyncSupported(true);
        servlet.setLoadOnStartup(1);
    }
}
</code>```

WebBeanConfig.java

```<code>@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.rvc.releaseSessionDemo")
public class WebBeanConfig {
}
</code>```

SessionController.java

```<code>@RestController
@RequestMapping("/session")
public class SessionController {
   @Autowired
   private ISessionService sessionService;

   @RequestMapping(value = "/releaseSession", method = RequestMethod.POST,  produces = MediaType.APPLICATION_JSON_VALUE)
   public ResponseEntity<Boolean> releaseSession(@RequestBody String sessionId) throws Exception {
       Boolean response = sessionService.releaseSession(sessionId());
       return new ResponseEntity<Boolean>(response, HttpStatus.OK);
   }
}
</code>```

session.service.js

```<code>angular.module('session', []).factory('sessionService', ['$http', '$q', sessionService]);

function sessionService($http, $q) {
   return {
      releaseSession : releaseSession
   }

function releaseSession(sessionId) {
    var deferred = $q.defer();
    var req = {sessionId : sessionId};
    $http.post('session/releaseSession', req).then(function(response) {
        deferred.resolve(response.data);
    }, function(errorResponse) {
        deferred.reject(errorResponse);
    });
    return deferred.promise;
  }
}
</code>```

答:
You shoud use wrapper class for @ResponseBody.

Use something like this:

```<code>public class Session {
    private String sessionId;
    //getter setter
}
</code>```

And pass it into controller @RequestBody Session session. Then you can get your session id by getter.

Title: Spring MVC Resource not found 404

Body:
I am getting 404 response not found when I try to call a RESTful Web Service from AngularJS. Following is the code sample :

WebAppConfiguration.java

public class WebAppConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
       InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
       viewResolver.setViewClass(JstlView.class);
       viewResolver.setPrefix("/WEB-INF/");
       viewResolver.setSuffix(".html");
       registry.viewResolver(viewResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/app/**").addResourceLocations("/app/");
    }
}

WebAppInitializer.java

public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebBeanConfig.class);
        ctx.setServletContext(servletContext);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);
        servlet.addMapping("/");
        servlet.setAsyncSupported(true);
        servlet.setLoadOnStartup(1);
    }
}

WebBeanConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.rvc.releaseSessionDemo")
public class WebBeanConfig {
}

SessionController.java

@RestController
@RequestMapping("/session")
public class SessionController {
   @Autowired
   private ISessionService sessionService;

   @RequestMapping(value = "/releaseSession", method = RequestMethod.POST,  produces = MediaType.APPLICATION_JSON_VALUE)
   public ResponseEntity<Boolean> releaseSession(@RequestBody String sessionId) throws Exception {
       Boolean response = sessionService.releaseSession(sessionId());
       return new ResponseEntity<Boolean>(response, HttpStatus.OK);
   }
}

session.service.js

angular.module('session', []).factory('sessionService', ['$http', '$q', sessionService]);

function sessionService($http, $q) {
   return {
      releaseSession : releaseSession
   }

function releaseSession(sessionId) {
    var deferred = $q.defer();
    var req = {sessionId : sessionId};
    $http.post('session/releaseSession', req).then(function(response) {
        deferred.resolve(response.data);
    }, function(errorResponse) {
        deferred.reject(errorResponse);
    });
    return deferred.promise;
  }
}

Body:
You shoud use wrapper class for @ResponseBody.

Use something like this:

public class Session {
    private String sessionId;
    //getter setter
}

And pass it into controller @RequestBody Session session. Then you can get your session id by getter.