问:
Retrieve selected row (class) from DataGridView as an object class (Unable to cast object)
I have the following class named Students:

```<code>namespace ClassLibrary
{
    using System;
    using System.Collections.Generic;

    public partial class Students
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Students()
        {
            this.Scenarios = new HashSet<Scenario>();
        }

        public int StudentsID { get; set; }
        public System.DateTime CreatedOn { get; set; }
        public string CreatedBy { get; set; }
        public System.DateTime UpdatedOn { get; set; }
        public string UpdatedBy { get; set; }
        public string StudentsCode { get; set; }
        public string StudentsName { get; set; }
        public bool isActive { get; set; }
        public string Comments { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Scenario> Scenarios { get; set; }
    }
}
</code>```

And I load data as a list in a DataGridView. This works fine:

```<code>public partial class myCLASS : Form
{
    ...

    private void myCLASS_Load(object sender, EventArgs e)
    {

        myDataGridView.DataSource = (from x in _context.Students
        orderby x.MFlowOrdering
        select new { x.StudentsID,x.StudentsCode,x.StudentsName}).ToList();
    }

    private void myDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      Students SelectedRow =(Students)(myDataGridView.CurrentRow.DataBoundItem);
      MessageBox.Show(SelectedRow.StudentsID);
    }
    ...
}
</code>```

Now, I want each time I click on a row in the DataGridView (only full row selection is enabled), I want to retrieve the object (Selected Class Students) behind the selected row:

```<code>private void myDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
  Students SelectedRow =(Students)(myDataGridView.CurrentRow.DataBoundItem);
  MessageBox.Show(SelectedRow.StudentsID);
}
</code>```

And I receive the following error:

Additional information: Unable to cast object of type '<>f__AnonymousType0`5[System.Int32,System.Int32,System.String,System.String,System.Boolean]' to type 'ClassLibrary.Students'.

I Google it and it seems that I use the correct syntax.

Could you please advice?

答:
You're using the anonymous type while binding the grid. Try selecting the Students type in the query as follows:

```<code>private void myCLASS_Load(object sender, EventArgs e)
{
    myDataGridView.DataSource = (from x in _context.Students
    orderby x.MFlowOrdering
    select new Students {
                StudentsId = x.StudentsID,
                StudentsCode = x.StudentsCode,
                StudentsName = x.StudentsName
    }).ToList();
}
</code>```

UPDATE

In case an anonymous type is preferred for binding, you could use dynamic keyword instead of casting the data bound item to Students entity as follows:

```<code>private void myCLASS_Load(object sender, EventArgs e)
{
    myDataGridView.DataSource = (from x in _context.Students
    orderby x.MFlowOrdering
    select new {
                StudentsId = x.StudentsID,
                StudentsCode = x.StudentsCode,
                StudentsName = x.StudentsName
    }).ToList();
}

private void myDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
  dynamic SelectedRow = myDataGridView.CurrentRow.DataBoundItem;
  MessageBox.Show(SelectedRow.StudentsID);
}
</code>```

Body:
I have the following class named Students:

namespace ClassLibrary
{
    using System;
    using System.Collections.Generic;

    public partial class Students
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Students()
        {
            this.Scenarios = new HashSet<Scenario>();
        }

        public int StudentsID { get; set; }
        public System.DateTime CreatedOn { get; set; }
        public string CreatedBy { get; set; }
        public System.DateTime UpdatedOn { get; set; }
        public string UpdatedBy { get; set; }
        public string StudentsCode { get; set; }
        public string StudentsName { get; set; }
        public bool isActive { get; set; }
        public string Comments { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Scenario> Scenarios { get; set; }
    }
}

And I load data as a list in a DataGridView. This works fine:

public partial class myCLASS : Form
{
    ...

    private void myCLASS_Load(object sender, EventArgs e)
    {

        myDataGridView.DataSource = (from x in _context.Students
        orderby x.MFlowOrdering
        select new { x.StudentsID,x.StudentsCode,x.StudentsName}).ToList();
    }

    private void myDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      Students SelectedRow =(Students)(myDataGridView.CurrentRow.DataBoundItem);
      MessageBox.Show(SelectedRow.StudentsID);
    }
    ...
}

Now, I want each time I click on a row in the DataGridView (only full row selection is enabled), I want to retrieve the object (Selected Class Students) behind the selected row:

private void myDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
  Students SelectedRow =(Students)(myDataGridView.CurrentRow.DataBoundItem);
  MessageBox.Show(SelectedRow.StudentsID);
}

And I receive the following error:

Additional information: Unable to cast object of type '<>f__AnonymousType0`5[System.Int32,System.Int32,System.String,System.String,System.Boolean]' to type 'ClassLibrary.Students'.

I Google it and it seems that I use the correct syntax.

Could you please advice?

Body:
You're using the anonymous type while binding the grid. Try selecting the Students type in the query as follows:

private void myCLASS_Load(object sender, EventArgs e)
{
    myDataGridView.DataSource = (from x in _context.Students
    orderby x.MFlowOrdering
    select new Students {
                StudentsId = x.StudentsID,
                StudentsCode = x.StudentsCode,
                StudentsName = x.StudentsName
    }).ToList();
}

UPDATE

In case an anonymous type is preferred for binding, you could use dynamic keyword instead of casting the data bound item to Students entity as follows:

private void myCLASS_Load(object sender, EventArgs e)
{
    myDataGridView.DataSource = (from x in _context.Students
    orderby x.MFlowOrdering
    select new {
                StudentsId = x.StudentsID,
                StudentsCode = x.StudentsCode,
                StudentsName = x.StudentsName
    }).ToList();
}

private void myDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
  dynamic SelectedRow = myDataGridView.CurrentRow.DataBoundItem;
  MessageBox.Show(SelectedRow.StudentsID);
}


来源: stackexchange

问:
Communication between a desktop application and a web application
I have a desktop and web application connected to same database.
Which is the most preferred method to make them communicate with each other?</p>

答:
You should use SOA and then both your desktop app and web app should communicate with the Service.

And the Service will be responsible for communicating with the database.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
IllegalArgumentException within JAVA SPRING REST Controller
I'm receiving following exception:

```<code>java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:471) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:667) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_51]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_51]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_51]
</code>```

My REST controller:

```<code>@GetMapping(path = "/users/{name}")
public @ResponseBody SystemUser getUserByName(@PathVariable("name") String name) {

    List<SystemUser> users = dataProvider.findSystemUsersByName(name);
    if (users != null && users.size() > 0) {
        return users.get(0);
    }
    else {
        return null;
    }
}

@GetMapping(path = "/usersByEmail/{email}")
public @ResponseBody SystemUser getUserByEmail(@PathVariable("email") String email) {

    List<SystemUser> users = dataProvider.findSystemUsersByEmail(email);
    if (users != null && users.size() > 0) {
        return users.get(0);
    }
    else {
        return null;
    }
}
</code>```

I'm passing simple strings without any special characters (also no '@') as parameters.

Could anyone tell why I'm getting the above exception and how to fix it. Thank you very much!

答:
I found the problem!

It was actually in the client implementation.

I mistakenly wrote following code in my angularjs client:

```<code>// Retrieves user by name
function GetByUsername(username) {
    return $http.get('http://localhost:5555/demo/users/{name}' + username).then(
        handleSuccess, handleError('Error getting user by username'));
}

// Retrieves user by email
function GetByEmail(email) {
    return $http.get('http://localhost:5555/demo/usersByEmail/{email}' + email).then(
        handleSuccess, handleError('Error getting user by email'));
}
</code>```

instead of

```<code>// Retrieves user by name
function GetByUsername(username) {
    return $http.get('http://localhost:5555/demo/users/' + username).then(
        handleSuccess, handleError('Error getting user by username'));
}

// Retrieves user by email
function GetByEmail(email) {
    return $http.get('http://localhost:5555/demo/usersByEmail/' + email).then(
        handleSuccess, handleError('Error getting user by email'));
}
</code>```

Body:
I'm receiving following exception:

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:471) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:667) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_51]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_51]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_51]

My REST controller:

@GetMapping(path = "/users/{name}")
public @ResponseBody SystemUser getUserByName(@PathVariable("name") String name) {

    List<SystemUser> users = dataProvider.findSystemUsersByName(name);
    if (users != null && users.size() > 0) {
        return users.get(0);
    }
    else {
        return null;
    }
}

@GetMapping(path = "/usersByEmail/{email}")
public @ResponseBody SystemUser getUserByEmail(@PathVariable("email") String email) {

    List<SystemUser> users = dataProvider.findSystemUsersByEmail(email);
    if (users != null && users.size() > 0) {
        return users.get(0);
    }
    else {
        return null;
    }
}

I'm passing simple strings without any special characters (also no '@') as parameters.

Could anyone tell why I'm getting the above exception and how to fix it. Thank you very much!

Body:
I found the problem!

It was actually in the client implementation.

I mistakenly wrote following code in my angularjs client:

// Retrieves user by name
function GetByUsername(username) {
    return $http.get('http://localhost:5555/demo/users/{name}' + username).then(
        handleSuccess, handleError('Error getting user by username'));
}

// Retrieves user by email
function GetByEmail(email) {
    return $http.get('http://localhost:5555/demo/usersByEmail/{email}' + email).then(
        handleSuccess, handleError('Error getting user by email'));
}

instead of

// Retrieves user by name
function GetByUsername(username) {
    return $http.get('http://localhost:5555/demo/users/' + username).then(
        handleSuccess, handleError('Error getting user by username'));
}

// Retrieves user by email
function GetByEmail(email) {
    return $http.get('http://localhost:5555/demo/usersByEmail/' + email).then(
        handleSuccess, handleError('Error getting user by email'));
}


答: You need to configure the DataBinding for the DGV. See example here: DataGridView databinding

Title: Retrieve selected row (class) from DataGridView as an object class (Unable to cast object)


问:
Swift Open Facebook Profile by FacebookUID
I'm trying to open a user's Facebook profile in Swift using their Facebook UID. In the Simulator, it works and opens up the web version of the profile and works fine, however on my actual device, it opens up the Facebook native app and gives me a "Page not Found" error.

```<code>guard let facebookUID = self.user?.facebookUID else {
    return
}

print(facebookUID)
let fbURLWeb: NSURL = NSURL(string: "https://www.facebook.com/\(facebookUID)")!
let fbURLID: NSURL = NSURL(string: "fb://profile/\(facebookUID)")!

if(UIApplication.sharedApplication().canOpenURL(fbURLID)){
    // FB installed
    UIApplication.sharedApplication().openURL(fbURLID)
} else {
    // FB is not installed, open in safari
    UIApplication.sharedApplication().openURL(fbURLWeb)
}
</code>```

What am I doing wrong?

Thanks in advance!

EDIT

I've noticed that if a user deletes or doesn't have the Facebook app installed on their phone, it will open up the profile correctly through Safari, which is why it worked on the simulator, but didn't on my device. However, I've also noticed I can get it to work in the Facebook app if I try a public profile like fb://profile/4 (which is Mark Zuckerburg's profile).

答:
Here is another solution that works for iOS 10 & Swift 3.

First of all, you should add LSApplicationQueriesSchemes key to Info.plist file. If you do not add this key, canOpenURL will always return false. Than you need to add what scheme(s) you want to check. Use fb for facebook.

It should looks like this:

The rest is Swift:

```<code>if UIApplication.shared.canOpenURL(URL(string: "fb://profile/PROFILE_ID")!) {
    UIApplication.shared.open(URL(string: "fb://profile/PROFILE_ID")!, options: [:])
} else {
    UIApplication.shared.open(URL(string: "https://facebook.com/PROFILE_ID")!, options: [:])
}
</code>```

Note: Replace PROFILE_ID with your target.

Body:
I'm trying to open a user's Facebook profile in Swift using their Facebook UID. In the Simulator, it works and opens up the web version of the profile and works fine, however on my actual device, it opens up the Facebook native app and gives me a "Page not Found" error.

guard let facebookUID = self.user?.facebookUID else {
    return
}

print(facebookUID)
let fbURLWeb: NSURL = NSURL(string: "https://www.facebook.com/\(facebookUID)")!
let fbURLID: NSURL = NSURL(string: "fb://profile/\(facebookUID)")!

if(UIApplication.sharedApplication().canOpenURL(fbURLID)){
    // FB installed
    UIApplication.sharedApplication().openURL(fbURLID)
} else {
    // FB is not installed, open in safari
    UIApplication.sharedApplication().openURL(fbURLWeb)
}

What am I doing wrong?

Thanks in advance!

EDIT

I've noticed that if a user deletes or doesn't have the Facebook app installed on their phone, it will open up the profile correctly through Safari, which is why it worked on the simulator, but didn't on my device. However, I've also noticed I can get it to work in the Facebook app if I try a public profile like fb://profile/4 (which is Mark Zuckerburg's profile).

Body:
Here is another solution that works for iOS 10 & Swift 3.

First of all, you should add LSApplicationQueriesSchemes key to Info.plist file. If you do not add this key, canOpenURL will always return false. Than you need to add what scheme(s) you want to check. Use fb for facebook.

It should looks like this:

The rest is Swift:

if UIApplication.shared.canOpenURL(URL(string: "fb://profile/PROFILE_ID")!) {
    UIApplication.shared.open(URL(string: "fb://profile/PROFILE_ID")!, options: [:])
} else {
    UIApplication.shared.open(URL(string: "https://facebook.com/PROFILE_ID")!, options: [:])
}

Note: Replace PROFILE_ID with your target.


问:
Using both CMAKE_INSTALL_PATH and CPack WiX generator
I'm trying to generate msi-package using CPack WiX Generator.

In my CMakeLists.txt there is CMAKE_INSTALL_PREFIX set to "C:/Program Files/My Project". I need to have the full path, because some significant part of project's source code depends on this path. Also, I split the project into some components, one of which is named core.

I successfully generate Visual Studio solution using cmake-gui. But when I try to build the project PACKAGE, I get the following error:

```<code>53>EXEC : CPack error : Problem creating temporary directory: D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/coreC:/Program Files/My Project
</code>```

The same error occurs, when I leave CMAKE_INSTALL_PREFIX empty. In that case this variable is initialized by default to "C:/Program Files/Project_Name" and the rror is:

```<code>53>EXEC : CPack error : Problem creating temporary directory: D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/coreC:/Program Files/Project_Name
</code>```

Only when I set CMAKE_INSTALL_PREFIX to just My Project (absent prepending C:/ or /) everything works well. The directory is created as D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/coreMy Project and msi-package is created.

It seems, that CPack tries to make DESTDIR="D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/core" install as an intermediate step, but as stated at cmake's documentation:

WARNING: DESTDIR may not be used on Windows because installation prefix usually contains a drive letter like in “C:/Program Files” which cannot be prepended with some other prefix.

Do I misunderstand the usage of CMAKE_INSTALL_PREFIX with CPack WiX Generator? Or is this is specific to Visual Studio? Or is there a workaround for this problem, like forcing DESTDIR to be empty (yes, I know that's dangerous)?

答:
I really was somewhat misunderstanding the usage of CPack. After reading some information on CPack, I managed to create an msi-package the following way.

For Windows-based package installations I turned off the usage of DESTDIR by setting CPACK_SET_DESTDIR to FALSE.

As stated in cmake's documentation on CPACK_SET_DESTDIR:

The most noticeable difference is that without CPACK_SET_DESTDIR,
  CPack uses CPACK_PACKAGING_INSTALL_PREFIX as a prefix whereas with
  CPACK_SET_DESTDIR set, CPack will use CMAKE_INSTALL_PREFIX as a
  prefix.

That is, I should set CPACK_PACKAGING_INSTALL_PREFIX variable to appropriate value.

If I set CPACK_PACKAGING_INSTALL_PREFIX to a non-empty value, e. g. to /My Project (note the leading /), CPack will append this to C:/Program files/${CPACK_PACKAGE_INSTALL_DIRECTORY}. CPACK_PACKAGE_INSTALL_DIRECTORY, in turn, defaults to "${CPACK_PACKAGE_NAME} ${CPACK_PACKAGE_VERSION}". The full install path would be C:/Program Files/my-project 1.0.0/My Project, if I set CPACK_PACKAGE_NAME to "my-project" and CPACK_PACKAGE_VERSION to 1.0.0.

So, to build an msi-package that will install the program to C:\Program files\My Project, I use the following lines in CMakeLists.txt:

```<code>SET(CMAKE_INSTALL_PREFIX "C:/Program Files/My Project" CACHE PATH "Install path" FORCE)
...
SET(CPACK_SET_DESTDIR FALSE)
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "My Project")
SET(CPACK_PACKAGING_INSTALL_PREFIX "")
</code>```

For WiX generator CPACK_PACKAGE_INSTALL_DIRECTORY may not contain the full path, so SET(CPACK_PACKAGE_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}) will not work.

CPACK_PACKAGING_INSTALL_PREFIX seems to be empty by default, so the last line is redundant.

Body:
I'm trying to generate msi-package using CPack WiX Generator.

In my CMakeLists.txt there is CMAKE_INSTALL_PREFIX set to "C:/Program Files/My Project". I need to have the full path, because some significant part of project's source code depends on this path. Also, I split the project into some components, one of which is named core.

I successfully generate Visual Studio solution using cmake-gui. But when I try to build the project PACKAGE, I get the following error:

53>EXEC : CPack error : Problem creating temporary directory: D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/coreC:/Program Files/My Project

The same error occurs, when I leave CMAKE_INSTALL_PREFIX empty. In that case this variable is initialized by default to "C:/Program Files/Project_Name" and the rror is:

53>EXEC : CPack error : Problem creating temporary directory: D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/coreC:/Program Files/Project_Name

Only when I set CMAKE_INSTALL_PREFIX to just My Project (absent prepending C:/ or /) everything works well. The directory is created as D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/coreMy Project and msi-package is created.

It seems, that CPack tries to make DESTDIR="D:/Projects/build-Project-MSVC2015/_CPack_Packages/win64/WIX/project-2.3.0-20.AMD64/core" install as an intermediate step, but as stated at cmake's documentation:

WARNING: DESTDIR may not be used on Windows because installation prefix usually contains a drive letter like in “C:/Program Files” which cannot be prepended with some other prefix.

Do I misunderstand the usage of CMAKE_INSTALL_PREFIX with CPack WiX Generator? Or is this is specific to Visual Studio? Or is there a workaround for this problem, like forcing DESTDIR to be empty (yes, I know that's dangerous)?

Body:
I really was somewhat misunderstanding the usage of CPack. After reading some information on CPack, I managed to create an msi-package the following way.

For Windows-based package installations I turned off the usage of DESTDIR by setting CPACK_SET_DESTDIR to FALSE.

As stated in cmake's documentation on CPACK_SET_DESTDIR:

The most noticeable difference is that without CPACK_SET_DESTDIR,
  CPack uses CPACK_PACKAGING_INSTALL_PREFIX as a prefix whereas with
  CPACK_SET_DESTDIR set, CPack will use CMAKE_INSTALL_PREFIX as a
  prefix.

That is, I should set CPACK_PACKAGING_INSTALL_PREFIX variable to appropriate value.

If I set CPACK_PACKAGING_INSTALL_PREFIX to a non-empty value, e. g. to /My Project (note the leading /), CPack will append this to C:/Program files/${CPACK_PACKAGE_INSTALL_DIRECTORY}. CPACK_PACKAGE_INSTALL_DIRECTORY, in turn, defaults to "${CPACK_PACKAGE_NAME} ${CPACK_PACKAGE_VERSION}". The full install path would be C:/Program Files/my-project 1.0.0/My Project, if I set CPACK_PACKAGE_NAME to "my-project" and CPACK_PACKAGE_VERSION to 1.0.0.

So, to build an msi-package that will install the program to C:\Program files\My Project, I use the following lines in CMakeLists.txt:

SET(CMAKE_INSTALL_PREFIX "C:/Program Files/My Project" CACHE PATH "Install path" FORCE)
...
SET(CPACK_SET_DESTDIR FALSE)
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "My Project")
SET(CPACK_PACKAGING_INSTALL_PREFIX "")

For WiX generator CPACK_PACKAGE_INSTALL_DIRECTORY may not contain the full path, so SET(CPACK_PACKAGE_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}) will not work.

CPACK_PACKAGING_INSTALL_PREFIX seems to be empty by default, so the last line is redundant.


问:
How to use ng-repeat in select angularjs
I have data like  this :

```<code> $scope.data = [
    {
      }
]
</code>```

How can i repeat it in select . I tried

```<code> <select>
      <option
      ng-repeat="d in data" value=" {{d.last_name.value}}{{d.first_name.value}}">
        {{d.last_name.value}}{{d.first_name.value}}
     </option>
    </select>
</code>```

but not work . Here is plnkr :
 http://plnkr.co/edit/GHSbBh9ddCiSFZZeKAQv?p=preview
Please help me

答:
You need to inject $scope to your controller like this: function ctrl($scope) {

 Working plunkr

Body:
I have data like  this :

 $scope.data = [
    {
      }
]

How can i repeat it in select . I tried

 <select>
      <option
      ng-repeat="d in data" value=" {{d.last_name.value}}{{d.first_name.value}}">
        {{d.last_name.value}}{{d.first_name.value}}
     </option>
    </select>

but not work . Here is plnkr :
 http://plnkr.co/edit/GHSbBh9ddCiSFZZeKAQv?p=preview
Please help me


问:
--workerCacheMB setting missing in apache beam 0.6?
In Google Cloud Dataflow 1.x, I presumably had access to this critical pipeline option called:

workerCacheMb

I tried to set in in my beam 0.6 pipeline, but couldn't do so (it said that no such option existed.). I then scoured through the options source code to see if any option had a similar name -- but I still couldn't find it.

I need to set it as I think that my worfklow's incredibly slowness is due to a side input that 3GB but that appears to be taking well over 20 minutes to read. (I have a View.asList() and then I'm trying to do a for-loop on the list -- it's taking more than 20 minutes and still going; even at 3 GB, that's way too slow.) So, I was hoping that setting the workerCacheMb would help. (The only other theory I have is to switch from serializablecoder to AvroCoder....)

答:
Are you using the right class of options?

The following code works for me in Beam:

```<code>    DataflowWorkerHarnessOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().create()
            .cloneAs(DataflowWorkerHarnessOptions.class);

    options.setWorkerCacheMb(3000);
</code>```

Body:
Are you using the right class of options?

The following code works for me in Beam:

    DataflowWorkerHarnessOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().create()
            .cloneAs(DataflowWorkerHarnessOptions.class);

    options.setWorkerCacheMb(3000);


问:
Selecting distinct keys and their counts from a dictionary series in python
I have a pandas dictionary series, that takes the values like

```<code>   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}
</code>```

I want to create a dictionary out of it based on the key and its occurrence in series, like:

```<code>{AA:3,BB:2,CC:1,CD:1}
</code>```

答:
I doubt there is a "built-in" solutiuon for this, so you'd have to manually iterate and count each key in every dictionary.

```<code>import pandas as pd
from collections import defaultdict

ser = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

count = defaultdict(int)

for d in ser:
    for key in d:
        count[key] += 1

print(count)
# defaultdict(<class 'int'>, {'CC': 1, 'BB': 2, 'AA': 3, 'CD': 1})
</code>```

You could also use Counter, however this looks rather "forced" in this situation:

```<code>import pandas as pd
from collections import Counter

total = Counter()

ser = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

for d in ser:
    total.update(d.keys())

print(total)
# Counter({'AA': 3, 'BB': 2, 'CD': 1, 'CC': 1})
</code>```

Body:
I have a pandas dictionary series, that takes the values like

   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}

I want to create a dictionary out of it based on the key and its occurrence in series, like:

{AA:3,BB:2,CC:1,CD:1}

Body:
I doubt there is a "built-in" solutiuon for this, so you'd have to manually iterate and count each key in every dictionary.

import pandas as pd
from collections import defaultdict

ser = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

count = defaultdict(int)

for d in ser:
    for key in d:
        count[key] += 1

print(count)
# defaultdict(<class 'int'>, {'CC': 1, 'BB': 2, 'AA': 3, 'CD': 1})

You could also use Counter, however this looks rather "forced" in this situation:

import pandas as pd
from collections import Counter

total = Counter()

ser = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

for d in ser:
    total.update(d.keys())

print(total)
# Counter({'AA': 3, 'BB': 2, 'CD': 1, 'CC': 1})


问:
how to change the direction of menu to rtl ionic2?
ionic version 3.3.0:

```<code><ion-menu [content]="Menu"
          [class.rtl]="isRtl"
          [attr.side]="isRtl?'right':'left'">
</ion-menu>
</code>```

I change the direction depending on what language chosen by the user ,
it works fine except when the menu change to rtl direction , the menu open from left to right (like animation), and the swipe still from left to right.
Kindly note that i don't want to duplicate my menu , one for rtl and one for ltr because it also not working for the new version 3.3.0

答:
i solved it by workaround with css ,
i did two menus one for rtl side (right) and another for ltr (left)
and i added the following to the app.scss file :

```<code>[dir="rtl"]{
  ion-menu[side=right] > .menu-inner {
    right: 0;
    direction: ltr;
  }

  ion-menu[side=right] ion-icon[aria-label^="arrow"]::before, ion-icon[flip-rtl]::before {
    -webkit-transform: scaleX(1);
    transform: scaleX(1);
    margin-left: 8px;
  }
}
</code>```

and change the dir attribute (rtl ot ltr)from html tag : when you need with:

```<code>this.platform.setDir('rtl',true);
</code>```

Body:
ionic version 3.3.0:

<ion-menu [content]="Menu"
          [class.rtl]="isRtl"
          [attr.side]="isRtl?'right':'left'">
</ion-menu>

I change the direction depending on what language chosen by the user ,
it works fine except when the menu change to rtl direction , the menu open from left to right (like animation), and the swipe still from left to right.
Kindly note that i don't want to duplicate my menu , one for rtl and one for ltr because it also not working for the new version 3.3.0

Body:
i solved it by workaround with css ,
i did two menus one for rtl side (right) and another for ltr (left)
and i added the following to the app.scss file :

[dir="rtl"]{
  ion-menu[side=right] > .menu-inner {
    right: 0;
    direction: ltr;
  }

  ion-menu[side=right] ion-icon[aria-label^="arrow"]::before, ion-icon[flip-rtl]::before {
    -webkit-transform: scaleX(1);
    transform: scaleX(1);
    margin-left: 8px;
  }
}

and change the dir attribute (rtl ot ltr)from html tag : when you need with:

this.platform.setDir('rtl',true);


问:
c++ boost interprocess exchange (copy) non-shared and shared string vector
I want to achieve what was achieved in the answer to this question, but for a vector of strings i.e. string objects. I want to be able to write common code that can be used with either heap memory or shared memory. I have emulated the code and wrote a class to implement a vector of strings that would work for with both heap memory or shared memory. I got it working for the most part. However, when I try to initialize/create a shared memory vector of strings from a heap allocated vector of strings I am getting compile errors. In the question referenced above, shared memory vector was initialized from non-shared memory vector (to quote "this works because of ... MAGIC!"). Not sure if its because that question was dealing with a vector of ints which are easily copyable and movable. I have provided the copy constructor for the shared memory string class but it still doesn't work. I've provided my code below (commented out the code that's giving me compilation errors). Any help is appreciated. Thanks.

```<code>#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <iostream>
#include <string>
#include <sstream>

namespace bip = boost::interprocess;

namespace generic
{

template <typename T, typename Alloc/* = std::allocator<T>*/ >
using vector = bip::vector<T, typename Alloc::template rebind<T>::other >;

template <typename Alloc/* = std::allocator<T>*/ >
using GenericString = bip::basic_string<char, std::char_traits<char>
                           , typename Alloc::template rebind<char>::other>;

template <typename Alloc>
class String
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator

  String(Alloc alloc = Alloc())
  : mString(alloc)
  {
  }

  String(const std::string str, Alloc alloc = Alloc())
  : mString(str.c_str(), alloc)
  {
  }

  String(const char* str, Alloc alloc = Alloc())
  : mString(str, alloc)
  {
  }

  template <typename OtherAlloc>
  String(String<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mString(other.mString.begin(), other.mString.end(), alloc)
  {
  }

  std::string ToString() { return std::string(mString.begin(), mString.end()); }

  friend std::ostream& operator<<(std::ostream& os, const String& str)
  {
    os << str.mString;
    return os;
  }

private:
  template<typename OtherAlloc> friend struct String;
  GenericString<Alloc> mString;
};

template <typename Alloc>
class StringVector
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator
  typedef vector<String<Alloc>, Alloc> GenericStringVector;
  using Iterator = typename GenericStringVector::iterator;
  using ConstIterator = typename GenericStringVector::const_iterator;

  StringVector(Alloc alloc = Alloc())
  : mStrings(alloc)
  {
  }

  template <typename OtherAlloc>
  StringVector(StringVector<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mStrings(other.mStrings.begin(), other.mStrings.end(), alloc)
  {
  }

  void Add(const String<Alloc> str) { mStrings.emplace_back(str); }

  void Remove(Iterator iter) { mStrings.erase(iter); }

  void Clear() { mStrings.clear(); }

  void Print() const
  {
    std::cout << "[";
    for (ConstIterator it = mStrings.begin(); it != mStrings.end(); it++)
      std::cout << (it == mStrings.begin() ? "" : ", ") << *it;
    std::cout << "]\n";
  }

private:
  template<typename OtherAlloc> friend struct StringVector;
  GenericStringVector mStrings;
};

}

namespace heap
{
  using VAlloc = std::allocator<void>;
  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

namespace shared
{
  using VAlloc =boost::container::scoped_allocator_adaptor<
          bip::allocator<void, bip::managed_shared_memory::segment_manager> >;

  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

int main(void)
{
  struct shm_remove {
      shm_remove()  { bip::shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove() { bip::shared_memory_object::remove("MySharedMemory"); }
  } remover;

  std::cout << "Heap based storage: \n";
  heap::StringVector svec;

  svec.Add(heap::String("test1"));
  svec.Add(heap::String("test2"));
  svec.Add(heap::String("test3"));
  svec.Add(heap::String("test4"));
  svec.Print();

  std::cout << "Shared memory storage: \n";
  bip::managed_shared_memory seg(bip::create_only, "MySharedMemory", 65536);
  shared::VAlloc shalloc(seg.get_segment_manager());

  shared::StringVector sh_svec(shalloc);
  sh_svec.Add(shared::String("test1", shalloc));
  sh_svec.Add(shared::String("test2", shalloc));
  sh_svec.Add(shared::String("test3", shalloc));
  sh_svec.Add(shared::String("test4", shalloc));
  sh_svec.Print();

  shared::StringVector sh_svec2(sh_svec, shalloc);
  sh_svec2.Print();

  //shared::StringVector sh_svec3(svec, shalloc);   // gives compile error :(
  //sh_svec3.Print();
}
</code>```

Including compilation errors:

```<code>In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp: In instantiation of ‘boost::container::container_detail::scoped_allocator_adaptor_base<OuterAlloc>::scoped_allocator_adaptor_base() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >]’:
/usr/include/boost/container/scoped_allocator.hpp:963:7:   required from ‘boost::container::scoped_allocator_adaptor<OuterAlloc, InnerAllocs>::scoped_allocator_adaptor() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >; InnerAllocs = {}]’
/usr/include/boost/container/vector.hpp:1174:15:   required from ‘void boost::container::vector<T, Allocator>::assign(FwdIt, FwdIt, typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type*) [with FwdIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type = void]’
/usr/include/boost/container/vector.hpp:864:7:   required from ‘boost::container::vector<T, Allocator>::vector(InIt, InIt, const allocator_type&) [with InIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; boost::container::vector<T, Allocator>::allocator_type = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:78:65:   required from ‘generic::StringVector<Alloc>::StringVector(const generic::StringVector<OtherAlloc>&, Alloc) [with OtherAlloc = std::allocator<void>; Alloc = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:151:46:   required from here
/usr/include/boost/container/scoped_allocator.hpp:762:7: error: no matching function for call to ‘boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::allocator()’
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note: candidate: template<class T2> boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T2, SegmentManager>&)
    allocator(const allocator<T2, SegmentManager> &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note:   template argument deduction/substitution failed:
In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp:762:7: note:   candidate expects 1 argument, 0 provided
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T, SegmentManager>&) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(const allocator &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note:   candidate expects 1 argument, 0 provided
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(boost::interprocess::allocator<T, SegmentManager>::segment_manager*) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>; boost::interprocess::allocator<T, SegmentManager>::segment_manager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(segment_manager *segment_mngr)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note:   candidate expects 1 argument, 0 provided
Makefile:16: recipe for target 'obj/test_string_vector.o' failed
make: *** [obj/test_string_vector.o] Error 1
</code>```

答:
I think I understand your intent now .
you want this piece of code where OtherAlloc = std::allocator , Alloc = bi:allocator

```<code>template <typename OtherAlloc>
  StringVector(StringVector<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mStrings(other.mStrings.begin(), other.mStrings.end(), alloc)
  {
  }
</code>```

to call a copy constructor you provided to convert from heap to shared type

```<code> template <typename OtherAlloc>
  String(String<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mString(other.mString.begin(), other.mString.end(), alloc)
  {
  }
</code>```

But boost::interprocess::vector::assign(first,last) does not pass instance of your allocator , and it looks like it uses  Alloc alloc = Alloc() where Alloc = boost::interprocess::allocator and it does not have default constructor. It correlates to all my posts :-)
I will try writing my code tomorrow , very challenging puzzle.

I have modified your code today please see below and see if you like it.

```<code>#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

namespace bip = boost::interprocess;

namespace generic
{

template <typename T, typename Alloc/* = std::allocator<T>*/ >
using vector = bip::vector<T, typename Alloc::template rebind<T>::other >;

template <typename Alloc/* = std::allocator<T>*/ >
using GenericString = bip::basic_string<char, std::char_traits<char>
                           , typename Alloc::template rebind<char>::other>;

template <typename Alloc>
class String
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator

  template<typename ...T>
  String(const std::string &str, T && ...t)
  : alloc_(std::forward<T>(t)...) , mString(str.c_str(), alloc_)
  {}

  template<typename ...T>
  String(const char* str, T && ...t)
  : alloc_(std::forward<T>(t)...) , mString(str, alloc_)
  {}

  template <typename OtherAlloc, typename ...T>
  String(String<OtherAlloc> const& other, T && ...t)
  : alloc_(std::forward<T>(t)...) , mString(other.mString.begin(), other.mString.end(), alloc_)
  {}

  std::string ToString() { return std::string(mString.begin(), mString.end()); }

  friend std::ostream& operator<<(std::ostream& os, const String& str)
  {
    os << str.mString;
    return os;
  }

private:
  template<typename OtherAlloc> friend struct String;
  Alloc alloc_;
  GenericString<Alloc> mString;
};

template <typename Alloc>
class StringVector
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator
  typedef vector<String<Alloc>, Alloc> GenericStringVector;
  using Iterator = typename GenericStringVector::iterator;
  using ConstIterator = typename GenericStringVector::const_iterator;

  StringVector()
  : alloc_(), mStrings(alloc_)
  {}

  template<typename T>
  StringVector(T && t)
  : alloc_(std::forward<T>(t)), mStrings(alloc_)
  {}

  template <typename OtherAlloc, typename ...T>
  StringVector(StringVector<OtherAlloc> const& other, T && ...t)
  : alloc_(std::forward<T>(t)...), mStrings(alloc_)
  {
      std::transform ( other.mStrings.begin(), other.mStrings.end(), std::back_inserter(mStrings), [&t...](auto &s) {
          return typename GenericStringVector::value_type(s, std::forward<T>(t)...);
      });
  }

  void Add(const String<Alloc> str) { mStrings.emplace_back(str); }

  void Remove(Iterator iter) { mStrings.erase(iter); }

  void Clear() { mStrings.clear(); }

  void Print() const
  {
    std::cout << "[";
    for (ConstIterator it = mStrings.begin(); it != mStrings.end(); it++)
      std::cout << (it == mStrings.begin() ? "" : ", ") << *it;
    std::cout << "]\n";
  }

private:
  template<typename OtherAlloc> friend struct StringVector;
  Alloc alloc_;
  GenericStringVector mStrings;
};

}

namespace heap
{
  using VAlloc = std::allocator<void>;
  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

namespace shared
{
  using VAlloc =boost::container::scoped_allocator_adaptor<
          bip::allocator<char, bip::managed_shared_memory::segment_manager> >;

  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

int main(void)
{
  struct shm_remove {
      shm_remove()  { bip::shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove() { bip::shared_memory_object::remove("MySharedMemory"); }
  } remover;

  std::cout << "Heap based storage: \n";
  heap::StringVector svec;

  svec.Add(heap::String("test1"));
  svec.Add(heap::String("test2"));
  svec.Add(heap::String("test3"));
  svec.Add(heap::String("test4"));
  svec.Print();

  std::cout << "Shared memory storage: \n";
  bip::managed_shared_memory seg(bip::create_only, "MySharedMemory", 65536);
  auto smp = seg.get_segment_manager();

  shared::StringVector sh_svec(smp);
  sh_svec.Add(shared::String("test1", smp));
  sh_svec.Add(shared::String("test2", smp));
  sh_svec.Add(shared::String("test3", smp));
  sh_svec.Add(shared::String("test4", smp));
  sh_svec.Print();

  shared::StringVector sh_svec2(sh_svec, smp);
  sh_svec2.Print();

  shared::StringVector sh_svec3(svec, smp);   // does not give compile error
  sh_svec3.Print();
}
</code>```

Body:
I want to achieve what was achieved in the answer to this question, but for a vector of strings i.e. string objects. I want to be able to write common code that can be used with either heap memory or shared memory. I have emulated the code and wrote a class to implement a vector of strings that would work for with both heap memory or shared memory. I got it working for the most part. However, when I try to initialize/create a shared memory vector of strings from a heap allocated vector of strings I am getting compile errors. In the question referenced above, shared memory vector was initialized from non-shared memory vector (to quote "this works because of ... MAGIC!"). Not sure if its because that question was dealing with a vector of ints which are easily copyable and movable. I have provided the copy constructor for the shared memory string class but it still doesn't work. I've provided my code below (commented out the code that's giving me compilation errors). Any help is appreciated. Thanks.

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <iostream>
#include <string>
#include <sstream>

namespace bip = boost::interprocess;

namespace generic
{

template <typename T, typename Alloc/* = std::allocator<T>*/ >
using vector = bip::vector<T, typename Alloc::template rebind<T>::other >;

template <typename Alloc/* = std::allocator<T>*/ >
using GenericString = bip::basic_string<char, std::char_traits<char>
                           , typename Alloc::template rebind<char>::other>;

template <typename Alloc>
class String
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator

  String(Alloc alloc = Alloc())
  : mString(alloc)
  {
  }

  String(const std::string str, Alloc alloc = Alloc())
  : mString(str.c_str(), alloc)
  {
  }

  String(const char* str, Alloc alloc = Alloc())
  : mString(str, alloc)
  {
  }

  template <typename OtherAlloc>
  String(String<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mString(other.mString.begin(), other.mString.end(), alloc)
  {
  }

  std::string ToString() { return std::string(mString.begin(), mString.end()); }

  friend std::ostream& operator<<(std::ostream& os, const String& str)
  {
    os << str.mString;
    return os;
  }

private:
  template<typename OtherAlloc> friend struct String;
  GenericString<Alloc> mString;
};

template <typename Alloc>
class StringVector
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator
  typedef vector<String<Alloc>, Alloc> GenericStringVector;
  using Iterator = typename GenericStringVector::iterator;
  using ConstIterator = typename GenericStringVector::const_iterator;

  StringVector(Alloc alloc = Alloc())
  : mStrings(alloc)
  {
  }

  template <typename OtherAlloc>
  StringVector(StringVector<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mStrings(other.mStrings.begin(), other.mStrings.end(), alloc)
  {
  }

  void Add(const String<Alloc> str) { mStrings.emplace_back(str); }

  void Remove(Iterator iter) { mStrings.erase(iter); }

  void Clear() { mStrings.clear(); }

  void Print() const
  {
    std::cout << "[";
    for (ConstIterator it = mStrings.begin(); it != mStrings.end(); it++)
      std::cout << (it == mStrings.begin() ? "" : ", ") << *it;
    std::cout << "]\n";
  }

private:
  template<typename OtherAlloc> friend struct StringVector;
  GenericStringVector mStrings;
};

}

namespace heap
{
  using VAlloc = std::allocator<void>;
  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

namespace shared
{
  using VAlloc =boost::container::scoped_allocator_adaptor<
          bip::allocator<void, bip::managed_shared_memory::segment_manager> >;

  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

int main(void)
{
  struct shm_remove {
      shm_remove()  { bip::shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove() { bip::shared_memory_object::remove("MySharedMemory"); }
  } remover;

  std::cout << "Heap based storage: \n";
  heap::StringVector svec;

  svec.Add(heap::String("test1"));
  svec.Add(heap::String("test2"));
  svec.Add(heap::String("test3"));
  svec.Add(heap::String("test4"));
  svec.Print();

  std::cout << "Shared memory storage: \n";
  bip::managed_shared_memory seg(bip::create_only, "MySharedMemory", 65536);
  shared::VAlloc shalloc(seg.get_segment_manager());

  shared::StringVector sh_svec(shalloc);
  sh_svec.Add(shared::String("test1", shalloc));
  sh_svec.Add(shared::String("test2", shalloc));
  sh_svec.Add(shared::String("test3", shalloc));
  sh_svec.Add(shared::String("test4", shalloc));
  sh_svec.Print();

  shared::StringVector sh_svec2(sh_svec, shalloc);
  sh_svec2.Print();

  //shared::StringVector sh_svec3(svec, shalloc);   // gives compile error :(
  //sh_svec3.Print();
}

Including compilation errors:

In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp: In instantiation of ‘boost::container::container_detail::scoped_allocator_adaptor_base<OuterAlloc>::scoped_allocator_adaptor_base() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >]’:
/usr/include/boost/container/scoped_allocator.hpp:963:7:   required from ‘boost::container::scoped_allocator_adaptor<OuterAlloc, InnerAllocs>::scoped_allocator_adaptor() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >; InnerAllocs = {}]’
/usr/include/boost/container/vector.hpp:1174:15:   required from ‘void boost::container::vector<T, Allocator>::assign(FwdIt, FwdIt, typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type*) [with FwdIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type = void]’
/usr/include/boost/container/vector.hpp:864:7:   required from ‘boost::container::vector<T, Allocator>::vector(InIt, InIt, const allocator_type&) [with InIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; boost::container::vector<T, Allocator>::allocator_type = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:78:65:   required from ‘generic::StringVector<Alloc>::StringVector(const generic::StringVector<OtherAlloc>&, Alloc) [with OtherAlloc = std::allocator<void>; Alloc = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:151:46:   required from here
/usr/include/boost/container/scoped_allocator.hpp:762:7: error: no matching function for call to ‘boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::allocator()’
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note: candidate: template<class T2> boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T2, SegmentManager>&)
    allocator(const allocator<T2, SegmentManager> &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note:   template argument deduction/substitution failed:
In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp:762:7: note:   candidate expects 1 argument, 0 provided
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T, SegmentManager>&) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(const allocator &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note:   candidate expects 1 argument, 0 provided
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(boost::interprocess::allocator<T, SegmentManager>::segment_manager*) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>; boost::interprocess::allocator<T, SegmentManager>::segment_manager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(segment_manager *segment_mngr)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note:   candidate expects 1 argument, 0 provided
Makefile:16: recipe for target 'obj/test_string_vector.o' failed
make: *** [obj/test_string_vector.o] Error 1

Body:
I think I understand your intent now .
you want this piece of code where OtherAlloc = std::allocator , Alloc = bi:allocator

template <typename OtherAlloc>
  StringVector(StringVector<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mStrings(other.mStrings.begin(), other.mStrings.end(), alloc)
  {
  }

to call a copy constructor you provided to convert from heap to shared type

 template <typename OtherAlloc>
  String(String<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mString(other.mString.begin(), other.mString.end(), alloc)
  {
  }

But boost::interprocess::vector::assign(first,last) does not pass instance of your allocator , and it looks like it uses  Alloc alloc = Alloc() where Alloc = boost::interprocess::allocator and it does not have default constructor. It correlates to all my posts :-)
I will try writing my code tomorrow , very challenging puzzle.

I have modified your code today please see below and see if you like it.

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

namespace bip = boost::interprocess;

namespace generic
{

template <typename T, typename Alloc/* = std::allocator<T>*/ >
using vector = bip::vector<T, typename Alloc::template rebind<T>::other >;

template <typename Alloc/* = std::allocator<T>*/ >
using GenericString = bip::basic_string<char, std::char_traits<char>
                           , typename Alloc::template rebind<char>::other>;

template <typename Alloc>
class String
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator

  template<typename ...T>
  String(const std::string &str, T && ...t)
  : alloc_(std::forward<T>(t)...) , mString(str.c_str(), alloc_)
  {}

  template<typename ...T>
  String(const char* str, T && ...t)
  : alloc_(std::forward<T>(t)...) , mString(str, alloc_)
  {}

  template <typename OtherAlloc, typename ...T>
  String(String<OtherAlloc> const& other, T && ...t)
  : alloc_(std::forward<T>(t)...) , mString(other.mString.begin(), other.mString.end(), alloc_)
  {}

  std::string ToString() { return std::string(mString.begin(), mString.end()); }

  friend std::ostream& operator<<(std::ostream& os, const String& str)
  {
    os << str.mString;
    return os;
  }

private:
  template<typename OtherAlloc> friend struct String;
  Alloc alloc_;
  GenericString<Alloc> mString;
};

template <typename Alloc>
class StringVector
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator
  typedef vector<String<Alloc>, Alloc> GenericStringVector;
  using Iterator = typename GenericStringVector::iterator;
  using ConstIterator = typename GenericStringVector::const_iterator;

  StringVector()
  : alloc_(), mStrings(alloc_)
  {}

  template<typename T>
  StringVector(T && t)
  : alloc_(std::forward<T>(t)), mStrings(alloc_)
  {}

  template <typename OtherAlloc, typename ...T>
  StringVector(StringVector<OtherAlloc> const& other, T && ...t)
  : alloc_(std::forward<T>(t)...), mStrings(alloc_)
  {
      std::transform ( other.mStrings.begin(), other.mStrings.end(), std::back_inserter(mStrings), [&t...](auto &s) {
          return typename GenericStringVector::value_type(s, std::forward<T>(t)...);
      });
  }

  void Add(const String<Alloc> str) { mStrings.emplace_back(str); }

  void Remove(Iterator iter) { mStrings.erase(iter); }

  void Clear() { mStrings.clear(); }

  void Print() const
  {
    std::cout << "[";
    for (ConstIterator it = mStrings.begin(); it != mStrings.end(); it++)
      std::cout << (it == mStrings.begin() ? "" : ", ") << *it;
    std::cout << "]\n";
  }

private:
  template<typename OtherAlloc> friend struct StringVector;
  Alloc alloc_;
  GenericStringVector mStrings;
};

}

namespace heap
{
  using VAlloc = std::allocator<void>;
  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

namespace shared
{
  using VAlloc =boost::container::scoped_allocator_adaptor<
          bip::allocator<char, bip::managed_shared_memory::segment_manager> >;

  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

int main(void)
{
  struct shm_remove {
      shm_remove()  { bip::shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove() { bip::shared_memory_object::remove("MySharedMemory"); }
  } remover;

  std::cout << "Heap based storage: \n";
  heap::StringVector svec;

  svec.Add(heap::String("test1"));
  svec.Add(heap::String("test2"));
  svec.Add(heap::String("test3"));
  svec.Add(heap::String("test4"));
  svec.Print();

  std::cout << "Shared memory storage: \n";
  bip::managed_shared_memory seg(bip::create_only, "MySharedMemory", 65536);
  auto smp = seg.get_segment_manager();

  shared::StringVector sh_svec(smp);
  sh_svec.Add(shared::String("test1", smp));
  sh_svec.Add(shared::String("test2", smp));
  sh_svec.Add(shared::String("test3", smp));
  sh_svec.Add(shared::String("test4", smp));
  sh_svec.Print();

  shared::StringVector sh_svec2(sh_svec, smp);
  sh_svec2.Print();

  shared::StringVector sh_svec3(svec, smp);   // does not give compile error
  sh_svec3.Print();
}


问:
Retrieve an Integer part from a String
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

```<code>int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());
</code>```

But for this code i get the error message

```<code>java.lang.NumberFormatException: For input string: "123456_b"
</code>```

Is there any way, to convert a combination of int and string to int?

答:
Remove the non numeric characters first and then try parsing it</p>

```<code>String str = did+a;
str = str.replaceAll("/[^0-9]/g", "");
int nid = Integer.parseInt(str);
</code>```

Title: Retrieve an Integer part from a String

Body:
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());

But for this code i get the error message

java.lang.NumberFormatException: For input string: "123456_b"

Is there any way, to convert a combination of int and string to int?

Body:
Remove the non numeric characters first and then try parsing it

String str = did+a;
str = str.replaceAll("/[^0-9]/g", "");
int nid = Integer.parseInt(str);


问:
Calculate difference between two dates and count the number of occurrences
I am trying to calculate the difference between two dates and in the same query trying to count the frequency of occurence.

```<code>SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate'
     , count ([Mydate])
  FROM Table1
 group
    by 'Mydate'
</code>```

I am expecting the query to calculate and count but getting an error msg "Each GROUP BY expression must contain at least one column that is not an outer reference."
what I am expecting is, something like this:

```<code>Mydate  Count
0        5
1        4
2        5
</code>```

Can someone help me please? Thanks

答:
First of all this doesn't look like MySQL rather SQL Server. Secondly you can't use the alias in Count() function like that. Rather say count(*)

```<code>  SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate',
         Count (*)
    FROM Table1
GROUP BY DATEDIFF(day,[Date1],[Date2])
</code>```

Body:
I am trying to calculate the difference between two dates and in the same query trying to count the frequency of occurence.

SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate'
     , count ([Mydate])
  FROM Table1
 group
    by 'Mydate'

I am expecting the query to calculate and count but getting an error msg "Each GROUP BY expression must contain at least one column that is not an outer reference."
what I am expecting is, something like this:

Mydate  Count
0        5
1        4
2        5

Can someone help me please? Thanks

Body:
First of all this doesn't look like MySQL rather SQL Server. Secondly you can't use the alias in Count() function like that. Rather say count(*)

  SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate',
         Count (*)
    FROM Table1
GROUP BY DATEDIFF(day,[Date1],[Date2])


问:
Swift - Present UIAlertController in extension function
I've wrote a label extension which detect links in the label.
It's attributed text with NSLinkAttributeName for links and I'm using
func handleTapOnLabel(_ tapGesture:UITapGestureRecognizer){} to detect where is the tap and which link to choose to open. The problem is that I use the function in extension for UILabel and I want to present an UIAlertController to ask the person - "You are about to open this link in Safari. Would you like to proceed?"... So I can't access viewcontroller to use the function present(UIAlertController... to display the alert. Any suggestions how this can be happened in extension? How to access label's viewcontroller directly from extension ?

答:
Method 1) Present UIAlertController on top most ViewController in ViewController's hierarchy

```<code>extension UILabel { //your extension
   func openLinkAction() {  //your extension custom method
     //code
      if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
      }

    // topController should now be your topmost view controller
    // present alert on this controller
}
       //and present here with vcInstance
   }
}
</code>```

Method 2) Pass ViewController's object as parameter

```<code>extension UILabel { //your extension
   func openLink(vc: UIViewController) { //your extension custom method function
       // code
       // present alert on this vc
   }
}
</code>```

// For getting top most controller you ca use..

```<code>extension UIApplication {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

//  topController
if let topController = UIApplication.topViewController() {

}
</code>```

Body:
Method 1) Present UIAlertController on top most ViewController in ViewController's hierarchy

extension UILabel { //your extension
   func openLinkAction() {  //your extension custom method
     //code
      if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
      }

    // topController should now be your topmost view controller
    // present alert on this controller
}
       //and present here with vcInstance
   }
}

Method 2) Pass ViewController's object as parameter

extension UILabel { //your extension
   func openLink(vc: UIViewController) { //your extension custom method function
       // code
       // present alert on this vc
   }
}

// For getting top most controller you ca use..

extension UIApplication {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

//  topController
if let topController = UIApplication.topViewController() {

}


问:
AVPlayer, how to save the current recording time
When I press pause and then play, the music playing again how to solve this problem?
I know that I need to use seekTime(: CMTime), but I don't get

Gif

It's all code

```<code>class ViewControllerAudioDetail: UIViewController {

@IBOutlet var list: TableViewControllerAudioList!

@IBOutlet weak var playChange: UIButton!
@IBOutlet weak var timeAudio: UILabel!
@IBOutlet weak var playbackSlider: UISlider!

var player = AVPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "БИБЛИОТЕКА"
   }

@IBAction func play(_ sender: Any) {
    if player.rate == 0 {

        let url = URL(string: ViewControllerAudioDetail.urlAudio[0])
        let playerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem:playerItem)
        player.rate = 1.0;
        player.play()
        playChange.setImage(UIImage(named:"Pause.png"), for: UIControlState.normal)

        let duration : CMTime = playerItem.asset.duration
        let seconds : Float64 = CMTimeGetSeconds(duration)
        playbackSlider.tintColor = UIColor.green

        let _ = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in
            self?.playbackSlider.value = Float(CMTimeGetSeconds(time)) / Float(seconds)

       }

    } else {

        playChange.setImage(UIImage(named:"Play.png"), for: UIControlState.normal)
        player.pause()

    }
}

@IBAction func audioPlaybackSlider(_ sender: Any) {

    //перемотка аудиозвука
     let duration : CMTime = player.currentItem!.duration
    let totalDuration : Float64 = CMTimeGetSeconds(duration)

    let value = self.playbackSlider.value
    let durationToSeek = Float(totalDuration) * value
    player.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),player.currentItem!.duration.timescale)) { [](state) in
    }

}

}
</code>```

答:
The problem in your code is, you always create a new player object inside your play method. That is why it always starts from the beginning of the audio.

This should solve your problem

```<code>class ViewControllerAudioDetail: UIViewController {

    @IBOutlet var list: TableViewControllerAudioList!

    @IBOutlet weak var playChange: UIButton!
    @IBOutlet weak var timeAudio: UILabel!
    @IBOutlet weak var playbackSlider: UISlider!

    var player:AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "БИБЛИОТЕКА"
        setupAudioPlayer()

    }

    func setupAudioPlayer(){

        let url = URL(string: ViewControllerAudioDetail.urlAudio[0])
        let playerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem:playerItem)
        playbackSlider.tintColor = UIColor.green

        let _ = player!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in
            self?.updateSlider(time: time)
        }

    }

    func updateSlider(time:CMTime){

        let duration = CMTimeGetSeconds(player!.currentItem!.asset.duration)
        self.playbackSlider.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    @IBAction func play(_ sender: Any) {

        if player?.rate == 0 {

            player?.rate = 1.0;
            player?.play()
            playChange.setImage(UIImage(named:"Pause.png"), for: UIControlState.normal)

        } else {

            playChange.setImage(UIImage(named:"Play.png"), for: UIControlState.normal)
            player?.pause()

        }
    }

    @IBAction func audioPlaybackSlider(_ sender: Any) {

        //перемотка аудиозвука
        let duration = CMTimeGetSeconds(player!.currentItem!.asset.duration)
        let value = self.playbackSlider.value
        let durationToSeek = Float(duration) * value

        self.player?.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),player!.currentItem!.duration.timescale)) { [](state) in

        }

    }

}
</code>```

Body:
When I press pause and then play, the music playing again how to solve this problem?
I know that I need to use seekTime(: CMTime), but I don't get

Gif

It's all code

class ViewControllerAudioDetail: UIViewController {

@IBOutlet var list: TableViewControllerAudioList!

@IBOutlet weak var playChange: UIButton!
@IBOutlet weak var timeAudio: UILabel!
@IBOutlet weak var playbackSlider: UISlider!

var player = AVPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "БИБЛИОТЕКА"
   }

@IBAction func play(_ sender: Any) {
    if player.rate == 0 {

        let url = URL(string: ViewControllerAudioDetail.urlAudio[0])
        let playerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem:playerItem)
        player.rate = 1.0;
        player.play()
        playChange.setImage(UIImage(named:"Pause.png"), for: UIControlState.normal)

        let duration : CMTime = playerItem.asset.duration
        let seconds : Float64 = CMTimeGetSeconds(duration)
        playbackSlider.tintColor = UIColor.green

        let _ = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in
            self?.playbackSlider.value = Float(CMTimeGetSeconds(time)) / Float(seconds)

       }

    } else {

        playChange.setImage(UIImage(named:"Play.png"), for: UIControlState.normal)
        player.pause()

    }
}

@IBAction func audioPlaybackSlider(_ sender: Any) {

    //перемотка аудиозвука
     let duration : CMTime = player.currentItem!.duration
    let totalDuration : Float64 = CMTimeGetSeconds(duration)

    let value = self.playbackSlider.value
    let durationToSeek = Float(totalDuration) * value
    player.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),player.currentItem!.duration.timescale)) { [](state) in
    }

}

}

Body:
The problem in your code is, you always create a new player object inside your play method. That is why it always starts from the beginning of the audio.

This should solve your problem

class ViewControllerAudioDetail: UIViewController {

    @IBOutlet var list: TableViewControllerAudioList!

    @IBOutlet weak var playChange: UIButton!
    @IBOutlet weak var timeAudio: UILabel!
    @IBOutlet weak var playbackSlider: UISlider!

    var player:AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "БИБЛИОТЕКА"
        setupAudioPlayer()

    }

    func setupAudioPlayer(){

        let url = URL(string: ViewControllerAudioDetail.urlAudio[0])
        let playerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem:playerItem)
        playbackSlider.tintColor = UIColor.green

        let _ = player!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in
            self?.updateSlider(time: time)
        }

    }

    func updateSlider(time:CMTime){

        let duration = CMTimeGetSeconds(player!.currentItem!.asset.duration)
        self.playbackSlider.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    @IBAction func play(_ sender: Any) {

        if player?.rate == 0 {

            player?.rate = 1.0;
            player?.play()
            playChange.setImage(UIImage(named:"Pause.png"), for: UIControlState.normal)

        } else {

            playChange.setImage(UIImage(named:"Play.png"), for: UIControlState.normal)
            player?.pause()

        }
    }

    @IBAction func audioPlaybackSlider(_ sender: Any) {

        //перемотка аудиозвука
        let duration = CMTimeGetSeconds(player!.currentItem!.asset.duration)
        let value = self.playbackSlider.value
        let durationToSeek = Float(duration) * value

        self.player?.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),player!.currentItem!.duration.timescale)) { [](state) in

        }

    }

}


问:
Asp.Net Forms Authentication when using iPhone UIWebView
I am writing a Asp.net MVC 2 application that uses Forms Authentication and currently I am having a problem with our iPhone application in regards to the authentication/login over the web. We have developed a simple iPhone app that uses the the UIWebView control. At this stage, all the app does is navigate to our Asp.Net website. Simple, right? The problem is, that the user cannot get past the login page. The repro steps are:

Open iPhone app.

The app navigates to the home page.

the user is not authenticated, so they are redirected to the login screen/page

The user enters the correct user name and password. clicks submit.

on the server side, the user is authenticated and a cookie is generated and sent to the client using FormsAuthentication.GetAuthCookie.

The server sends are redirect to send the user to the correct home page.

But the user is then redirected BACK to the login screen!

I've done some extensive debugging on this and what I do know is:

The cookie is being sent to the client, and the client is storing the cookie. Verified this in the iPhone debugger and also by using Javsascript to display cookie data on the page. The cookie is being sent back to the server. Verified this in the Visual Studio debugger. It is the correct cookie (it's the same one that was set). The property User.Identity.IsAuthenticated returns false for some reason, even though the auth cookie is contained in the Request object.  I have verified that the iPhone app is setup to accept cookies, and they are on the client.

Here is the funny thing: It works fine if you open the Safari browser on the iPhone and go to our site directly.

It has the same behaviour on the iPad too in that it doesn't get past the login screen. This repros on the emulators, and on devices.

This same web site has been tested with IE 7-8, Safari (for Windows), Blackberry, IEMobile 6.5, Phone 7 and it works find. The only circumstance that it doesn't work on is the UIWebView in the iPhone app.

答:
Have you specified a
DestinationPageUrl in markup?

Have you specified the defaultURL in
web.config?

Example web.config

```<code><authentication mode="Forms">
     <forms loginUrl="~/Login.aspx" defaultUrl="~/CustomerArea/Default.aspx"/>
</authentication>
</code>```

Example DestinationPageUrl

```<code> <asp:Login ID="Login" runat="server" DestinationPageUrl="~/Secret/Default.aspx" />
</code>```

Lastly have you looked in the cookie jar and seen if your session cookie actually exists?

Where are an UIWebView's cookies stored?

Body:
Have you specified a
DestinationPageUrl in markup?

Have you specified the defaultURL in
web.config?

Example web.config

<authentication mode="Forms">
     <forms loginUrl="~/Login.aspx" defaultUrl="~/CustomerArea/Default.aspx"/>
</authentication>

Example DestinationPageUrl

 <asp:Login ID="Login" runat="server" DestinationPageUrl="~/Secret/Default.aspx" />

Lastly have you looked in the cookie jar and seen if your session cookie actually exists?

Where are an UIWebView's cookies stored?


问:
POST method is sent as GET to the servlet
I am trying to fill a table using a POST command to my servlet, but instead of sending a POST request, my webpage sends a GET request to the servlet. Here is my

$(document).ready(function() {
  $.get("league", function(responseJson) {
    if (responseJson != null) {
      $("#tableleague").find("tr:gt(0)").remove();
      var table1 = $("#tableleague");
      $.each(responseJson, function(key, value) {
        var rowNew = $("

");
        rowNew.children().eq(0).text(value['teams']);
        rowNew.children().eq(1).text(value['playedgames']);
        rowNew.children().eq(2).text(value['wongames']);
        rowNew.children().eq(3).text(value['tiegames']);
        rowNew.children().eq(4).text(value['lostgames']);
        rowNew.children().eq(5).text(value['scoredgoal']);
        rowNew.children().eq(6).text(value['scoredgoal']);
        rowNew.children().eq(7).text(value['scoredgoal']);
        rowNew.appendTo(table1);
      });
    }
  });
});

function addData() {
  var t1 = $("#firstteam").val();
  var t2 = $("#secondteam").val();
  var s1 = $("#score1").val();
  var s2 = $("#score2").val();
  $("#firstteam").val('');
  $("#secondteam").val('');
  $("#score1").val('');
  $("#score2").val('');
  var data = {
    firstteam: "t1",
    secondteam: "t2",
    score1: "s1",
    score2: "s2"
  }

  $.ajax({
    type: "POST",
    url: "league",
    data: JSON.stringify(data),
    contentType: "application/x-www-form-urlencoded",
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("
Success!
" + data);
      } else {
        $("#error").html("
Information is Invalid!
" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });
}
```

<pre class="lang-html prettyprint-override"><code><h1>League Table</h1>
<table cellspacing="0" id="tableleague" style="width:100%">
  <tr>
    <th scope="col">Teams</th>
    <th scope="col">Won</th>
    <th scope="col">Tie</th>
    <th scope="col">Lost</th>
    <th scope="col">Scored</th>
    <th scope="col">Received</th>
    <th scope="col">Points</th>
  </tr>
</table>

<form method="POST">
  <div class="form_group">
    <label for="FirstTeam">FirstTeam:</label>
    <input type="text" class="form_control" id="firstteam">
  </div>
  <div class="form_group">
    <label for="Score1">Score1:</label>
    <input type="text" class="form_control" id="score1">
  </div>
  <div class="form_group">
    <label for="Score2">Score2:</label>
    <input type="text" class="form_control" id="score2">
  </div>
  <div class="form_group">
    <label for="SecondTeam">SecondTeam:</label>
    <input type="text" class="form_control" id="secondteam">
  </div>
  <div class="form_group">
    <button type="submit" class="addbutton" id="addbut" onclick="addData();">Add match</button>
  </div>
</form>

<div id="error"></div>
</code>```

Here is what I see in my debugger immediately after I press the Add match button:

The error I receive in the console is this one:

POST http://localhost:8080/league/league 500 (Internal Server Error)

What am I doing wrong with my code? I tried many solutions but nothing worked.

My servlet code:

```<code>@WebServlet("/league/*")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;

public PopulateTable()
{

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try
    {
        ArrayList<League> league = new ArrayList<League>();
        league= Controller.getAllController();
        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(league, new TypeToken<List<League>>() {}.getType());

        JsonArray jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try {
        PrintWriter out = response.getWriter();
        JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);

        int s1 = Integer.parseInt(data.get("score1").getAsString());
        int s2 = Integer.parseInt(data.get("score2").getAsString());

        String t1 = data.get("firstteam").getAsString();;
        String t2 = data.get("secondteam").getAsString();;
        int ok = Controller.update(t1, t2, s1, s2);
        JsonObject myObj = new JsonObject();

        if(ok ==  1)
        {
            myObj.addProperty("success", true);
        }
        else {
            myObj.addProperty("success", false);
        }
        out.println(myObj.toString());

        out.close();

    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

}
</code>```

答:
It is because of content-type, when you are sending data by using post method you have to use x-www-form-urlencoded (which is default in $.ajax) like,

```<code>contentType: "application/x-www-form-urlencoded"
</code>```

and not

```<code>contentType: "application/json",
</code>```

also use dataType:'json' to get JSON response. Read more about contentType and dataType on $.ajax()

Body:
I am trying to fill a table using a POST command to my servlet, but instead of sending a POST request, my webpage sends a GET request to the servlet. Here is my

$(document).ready(function() {
  $.get("league", function(responseJson) {
    if (responseJson != null) {
      $("#tableleague").find("tr:gt(0)").remove();
      var table1 = $("#tableleague");
      $.each(responseJson, function(key, value) {
        var rowNew = $("

");
        rowNew.children().eq(0).text(value['teams']);
        rowNew.children().eq(1).text(value['playedgames']);
        rowNew.children().eq(2).text(value['wongames']);
        rowNew.children().eq(3).text(value['tiegames']);
        rowNew.children().eq(4).text(value['lostgames']);
        rowNew.children().eq(5).text(value['scoredgoal']);
        rowNew.children().eq(6).text(value['scoredgoal']);
        rowNew.children().eq(7).text(value['scoredgoal']);
        rowNew.appendTo(table1);
      });
    }
  });
});

function addData() {
  var t1 = $("#firstteam").val();
  var t2 = $("#secondteam").val();
  var s1 = $("#score1").val();
  var s2 = $("#score2").val();
  $("#firstteam").val('');
  $("#secondteam").val('');
  $("#score1").val('');
  $("#score2").val('');
  var data = {
    firstteam: "t1",
    secondteam: "t2",
    score1: "s1",
    score2: "s2"
  }

  $.ajax({
    type: "POST",
    url: "league",
    data: JSON.stringify(data),
    contentType: "application/x-www-form-urlencoded",
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("
Success!
" + data);
      } else {
        $("#error").html("
Information is Invalid!
" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });
}

League Table

    Teams
    Won
    Tie
    Lost
    Scored
    Received
    Points

<form method="POST">

    FirstTeam:
    <input type="text" class="form_control" id="firstteam">

    Score1:
    <input type="text" class="form_control" id="score1">

    Score2:
    <input type="text" class="form_control" id="score2">

    SecondTeam:
    <input type="text" class="form_control" id="secondteam">

    <button type="submit" class="addbutton" id="addbut" onclick="addData();">Add match</button>

</form>

Here is what I see in my debugger immediately after I press the Add match button:

The error I receive in the console is this one:

POST http://localhost:8080/league/league 500 (Internal Server Error)

What am I doing wrong with my code? I tried many solutions but nothing worked.

My servlet code:

@WebServlet("/league/*")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;

public PopulateTable()
{

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try
    {
        ArrayList<League> league = new ArrayList<League>();
        league= Controller.getAllController();
        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(league, new TypeToken<List<League>>() {}.getType());

        JsonArray jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try {
        PrintWriter out = response.getWriter();
        JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);

        int s1 = Integer.parseInt(data.get("score1").getAsString());
        int s2 = Integer.parseInt(data.get("score2").getAsString());

        String t1 = data.get("firstteam").getAsString();;
        String t2 = data.get("secondteam").getAsString();;
        int ok = Controller.update(t1, t2, s1, s2);
        JsonObject myObj = new JsonObject();

        if(ok ==  1)
        {
            myObj.addProperty("success", true);
        }
        else {
            myObj.addProperty("success", false);
        }
        out.println(myObj.toString());

        out.close();

    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

}

Body:
It is because of content-type, when you are sending data by using post method you have to use x-www-form-urlencoded (which is default in $.ajax) like,

contentType: "application/x-www-form-urlencoded"

and not

contentType: "application/json",

also use dataType:'json' to get JSON response. Read more about contentType and dataType on $.ajax()


问:
How to count every row from select
I want to extract the data from my table and I want to have this result:

```<code>1 Valore
2 Valore
3 Valore
4 Valore
</code>```

So I want to numeration every ROW from 1 to N.

This is my query but not works:

```<code>  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)
</code>```

EDIT

My Database is Tsql

and this is my extract data:

```<code>1 Valore
1 Pippo
1 Pluto
</code>```

Instead of

```<code>1 Valore
2 Pippo
3 Pluto
</code>```

答:
This is my solution is the fastest

```<code>CREATE TABLE Test (
  ID INT PRIMARY KEY,
  VAL VARCHAR(64));

INSERT INTO Test (ID,VAL) VALUES (8,"a"),(156,"b"),(99,"c");

SET @t1=0;
SELECT @t1:=@t1 + 1 as 'num', VAL FROM Test;
</code>```

OUT

```<code>num | VAL
1   | a
2   | c
3   | b
</code>```

Title: How to count every row from select

Body:
I want to extract the data from my table and I want to have this result:

1 Valore
2 Valore
3 Valore
4 Valore

So I want to numeration every ROW from 1 to N.

This is my query but not works:

  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)

EDIT

My Database is Tsql

and this is my extract data:

1 Valore
1 Pippo
1 Pluto

Instead of

1 Valore
2 Pippo
3 Pluto

Body:
This is my solution is the fastest

CREATE TABLE Test (
  ID INT PRIMARY KEY,
  VAL VARCHAR(64));

INSERT INTO Test (ID,VAL) VALUES (8,"a"),(156,"b"),(99,"c");

SET @t1=0;
SELECT @t1:=@t1 + 1 as 'num', VAL FROM Test;

OUT

num | VAL
1   | a
2   | c
3   | b