问:
C - pointer to pointer array
I am learning C and as I got stuck at the pointer chapter. Particullary at the pointer to pointer ( **p ) part, used with processing 2 dimensional arrays.

The following function generates a 2 dimmensional array with all its elements equal to 0 .

```<code>double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }
int main(void){

    double **tr;
    int m = 2 ;
    int n = 2 ;

    tr = transpose(m, n);
    return 0;}
</code>```

Is the tr returned by the function a "double pointer" to the first element of the tr array ? Or to its value ? Also, now (after the the function was called) how do I  access the elements of the array at the part of memory where **tr points to ?

Can someone explain me how this all works ? Or suggest me an article or a chapter in a book that does ?

答:
Throw away the book that contains this code - it doesn't even compile properly.  I get the following errors:

```<code>[fbgo448@n9dvap997]~/prototypes/buf: gcc -o stack -std=c99 -pedantic-errors -Wall stack.c
stack.c: In function âexampleâ:
stack.c:2: error: storage size of âtrâ isnât constant
stack.c:6: error: return from incompatible pointer type
</code>```

You cannot create a variable-length array with static storage duration.  Objects with static storage duration are allocated at program startup, so their sizes need to be known at compile time.  A VLA cannot be instantiated until you know the size of its dimensions at runtime.

Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

The expression tr has type "rows-element array of cols-element array of double"; in the return statement, this expression will "decay" to type "pointer to cols-element array of double", or double (*)[cols].  This is a completely different type from double **.

Multiple indirection shows up a lot, but this isn't a valid example.

You would normally see multiple indirection when you want a function to write to a parameter of pointer type:

```<code>void bar( T **p ) // for any type T
{
  *p = new_pointer_value();  // write a new value to the thing p points to
}

void foo( void )
{
   T *ptr;

   bar( &ptr ); // bar writes a value to ptr
}
</code>```

You can use multiple indirection to create a structure that kinda-sorta looks and behaves like a 2D array, but it's not the same thing as a 2D array:

```<code>double **arr;
size_t rows = some_number_of_rows();
size_t cols = sime_number_of_cols();

arr = malloc( sizeof *arr * rows ); // allocates an array of pointers to double
if ( arr )
{
  for ( size_t i = 0; i < rows; i++ )
  {
    arr[i] = malloc( sizeof *arr[i] * cols ); // allocates an array of double
  }
}
</code>```

When you're done, you have a structure that looks like this:

```<code>   +---+       +---+      +---+---+---+     +---+
a: |   |  ---> |   | ---> |   |   |   | ... |   |
   +---+       +---+      +---+---+---+     +---+
               |   | -+
               +---+  |   +---+---+---+     +---+
                ...   +-> |   |   |   | ... |   |
               +---+      +---+---+---+     +---+
               |   | -+
               +---+  |   +---+---+---+     +---+
                      +-> |   |   |   | ... |   |
                          +---+---+---+     +---+
</code>```

You can access elements using regular subscript notation (a[i][j]) like a 2D array, but the memory for this structure is not allocated contiguously like it would be for a 2D array:

```<code>   +---+---+---+---+---+
a: |   |   |   |   |   |
   +---+---+---+---+---+
   |   |   |   |   |   |
   +---+---+---+---+---+
   |   |   |   |   |   |
   +---+---+---+---+---+
   ...
</code>```

Title: C - pointer to pointer array

Body:
I am learning C and as I got stuck at the pointer chapter. Particullary at the pointer to pointer ( **p ) part, used with processing 2 dimensional arrays.

The following function generates a 2 dimmensional array with all its elements equal to 0 .

double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }
int main(void){

    double **tr;
    int m = 2 ;
    int n = 2 ;

    tr = transpose(m, n);
    return 0;}

Is the tr returned by the function a "double pointer" to the first element of the tr array ? Or to its value ? Also, now (after the the function was called) how do I  access the elements of the array at the part of memory where **tr points to ?

Can someone explain me how this all works ? Or suggest me an article or a chapter in a book that does ?

Body:
Throw away the book that contains this code - it doesn't even compile properly.  I get the following errors:

[fbgo448@n9dvap997]~/prototypes/buf: gcc -o stack -std=c99 -pedantic-errors -Wall stack.c
stack.c: In function âexampleâ:
stack.c:2: error: storage size of âtrâ isnât constant
stack.c:6: error: return from incompatible pointer type

You cannot create a variable-length array with static storage duration.  Objects with static storage duration are allocated at program startup, so their sizes need to be known at compile time.  A VLA cannot be instantiated until you know the size of its dimensions at runtime.

Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

The expression tr has type "rows-element array of cols-element array of double"; in the return statement, this expression will "decay" to type "pointer to cols-element array of double", or double (*)[cols].  This is a completely different type from double **.

Multiple indirection shows up a lot, but this isn't a valid example.

You would normally see multiple indirection when you want a function to write to a parameter of pointer type:

void bar( T **p ) // for any type T
{
  *p = new_pointer_value();  // write a new value to the thing p points to
}

void foo( void )
{
   T *ptr;

   bar( &ptr ); // bar writes a value to ptr
}

You can use multiple indirection to create a structure that kinda-sorta looks and behaves like a 2D array, but it's not the same thing as a 2D array:

double **arr;
size_t rows = some_number_of_rows();
size_t cols = sime_number_of_cols();

arr = malloc( sizeof *arr * rows ); // allocates an array of pointers to double
if ( arr )
{
  for ( size_t i = 0; i < rows; i++ )
  {
    arr[i] = malloc( sizeof *arr[i] * cols ); // allocates an array of double
  }
}

When you're done, you have a structure that looks like this:

   +---+       +---+      +---+---+---+     +---+
a: |   |  ---> |   | ---> |   |   |   | ... |   |
   +---+       +---+      +---+---+---+     +---+
               |   | -+
               +---+  |   +---+---+---+     +---+
                ...   +-> |   |   |   | ... |   |
               +---+      +---+---+---+     +---+
               |   | -+
               +---+  |   +---+---+---+     +---+
                      +-> |   |   |   | ... |   |
                          +---+---+---+     +---+

You can access elements using regular subscript notation (a[i][j]) like a 2D array, but the memory for this structure is not allocated contiguously like it would be for a 2D array:

   +---+---+---+---+---+
a: |   |   |   |   |   |
   +---+---+---+---+---+
   |   |   |   |   |   |
   +---+---+---+---+---+
   |   |   |   |   |   |
   +---+---+---+---+---+
   ...


来源: stackexchange

问:
Convert all letters from uppercase to lowercase in a sentence except words with all CAPS using R
I want to convert my data frame of text into lowercase but I do not want to convert the words with all CAPS letters. For example if have a string like

"My friEnd ENRIQUE is nOt GOoD in stuDies"

The output of this should be like

"my friend ENRIQUE is not good in studies"

It converted everything to lowercase except words with all capital letters.
I need a r function to do this task.

答:
We can split the string into different words and then find out those words which contain any lower case letter [a-z] and convert that word to lower case.

```<code>word_vec <- strsplit(x, " ")[[1]]
ifelse(grepl('[a-z]', word_vec), tolower(word_vec), word_vec)

#[1] "my"  "friend"  "ENRIQUE" "is"  "not"  "good"  "in"  "studies"
</code>```

To make it as a single string we can use paste0 with an empty collapse argument.

```<code>paste0(ifelse(grepl('[a-z]', word_vec), tolower(word_vec), word_vec), collapse = " ")

#[1] "my friend ENRIQUE is not good in studies"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We can split the string into different words and then find out those words which contain any lower case letter [a-z] and convert that word to lower case.

word_vec <- strsplit(x, " ")[[1]]
ifelse(grepl('[a-z]', word_vec), tolower(word_vec), word_vec)

#[1] "my"  "friend"  "ENRIQUE" "is"  "not"  "good"  "in"  "studies"

To make it as a single string we can use paste0 with an empty collapse argument.

paste0(ifelse(grepl('[a-z]', word_vec), tolower(word_vec), word_vec), collapse = " ")

#[1] "my friend ENRIQUE is not good in studies"


问:
Accessing the properties of an IEnumerable
I'm using TweetInvi to grab a bunch of tweets that match a specified hashtag. I do this with the following:

```<code>var matchingTweets = Search.SearchTweets(hashtag);
</code>```

This returns an IEnumerable (named ITweet, interface of Tweet), however I cannot create a List<> of Tweets, because Tweet is a static type.

I made, instead, a list of objects, using:

```<code>List<object> matches = matchingTweets.Cast<object>().ToList();
</code>```

However, although each member of the matchingTweets IEnumerable has a number of properties, I cannot access them using:

```<code>long tweetID = matches[i].<property>;
</code>```

Using matches[i].ToString() returns the tweet content, so how can I effectively cast the results in matchingTweets to a list, and subsequently access the properties of those list members? I would ideally like to avoid using dynamic.

答:
In your example above you were trying to grab the ID from the tweet.  ITweet implements ITweetIdentifier which contains the Id property.  You can literally just access it by:

```<code>var matchingTweets = Search.SearchTweets(hashtag);

//Grab the first 5 tweets from the results.
var firstFiveTweets = matchingTweets.Take(5).ToList();

//if you only want the ids and not the entire object
var firstFiveTweetIds = matchingTweets.Take(5).Select(t => t.Id).ToList();

//Iterate through and do stuff
foreach (var tweet in matchingTweets)
{
    //These are just examples of the properties accessible to you...
    if(tweet.Favorited)
    {
        var text = tweet.FullText;
    }
    if(tweet.RetweetCount > 100)
    {
        //TODO: Handle popular tweets...
    }
}

//Get item at specific index
matchingTweets.ElementAt(index);
</code>```

I don't know exactly what you want to do with all the info, but since the SearchTweets returns a IEnumerable of ITweets you have access to anything an ITweet has defined.

I highly recommend looking through their wiki.  It's pretty well organized and gives you clear examples of some basic tasks.

Body:
I'm using TweetInvi to grab a bunch of tweets that match a specified hashtag. I do this with the following:

var matchingTweets = Search.SearchTweets(hashtag);

This returns an IEnumerable (named ITweet, interface of Tweet), however I cannot create a List<> of Tweets, because Tweet is a static type.

I made, instead, a list of objects, using:

List<object> matches = matchingTweets.Cast<object>().ToList();

However, although each member of the matchingTweets IEnumerable has a number of properties, I cannot access them using:

long tweetID = matches[i].<property>;

Using matches[i].ToString() returns the tweet content, so how can I effectively cast the results in matchingTweets to a list, and subsequently access the properties of those list members? I would ideally like to avoid using dynamic.

Body:
In your example above you were trying to grab the ID from the tweet.  ITweet implements ITweetIdentifier which contains the Id property.  You can literally just access it by:

var matchingTweets = Search.SearchTweets(hashtag);

//Grab the first 5 tweets from the results.
var firstFiveTweets = matchingTweets.Take(5).ToList();

//if you only want the ids and not the entire object
var firstFiveTweetIds = matchingTweets.Take(5).Select(t => t.Id).ToList();

//Iterate through and do stuff
foreach (var tweet in matchingTweets)
{
    //These are just examples of the properties accessible to you...
    if(tweet.Favorited)
    {
        var text = tweet.FullText;
    }
    if(tweet.RetweetCount > 100)
    {
        //TODO: Handle popular tweets...
    }
}

//Get item at specific index
matchingTweets.ElementAt(index);

I don't know exactly what you want to do with all the info, but since the SearchTweets returns a IEnumerable of ITweets you have access to anything an ITweet has defined.

I highly recommend looking through their wiki.  It's pretty well organized and gives you clear examples of some basic tasks.


问:
Empty Ant <junitreport> report for SoapUI testrunner XML results
I am running a SoapUI project using Ant to get a JUnit report.

Here is my build.xml:

```<code><project basedir="." default="testreport" name="APIAutomation">
<target name="SoapUI">
    <exec dir="." executable="C:\Program Files (x86)\SmartBear\SoapUI-5.0.0\bin\testrunner.bat">
        <arg line="-r -j -a -f 'C:\Users\F3020722\Desktop\Notification\New folder' -sFirstLoginTest 'C:\Users\F3020722\Desktop\Notification\New folder\APIRegression.xml'"></arg>
    </exec>
</target>
<target name="testreport" depends="SoapUI">
    <junitreport todir="C:\Users\F3020722\Desktop\Notification\New folder\API">
        <fileset dir="C:\Users\F3020722\Desktop\Notification\New folder\API">
            <include name="TEST-*.xml"/>
        </fileset>
        <report format="frames"
            todir="C:\Users\F3020722\Desktop\Notification\New folder\reports\html">
        </report>
    </junitreport>
</target>
</project>
</code>```

I am getting an XML report properly. However, the JUnit report is empty. all contains 0 and successrate is Nan.

Can anyone check the build.xml is correct?

答:
Looks build script seems ok

Avoid spaces in the directory names

Use forward slashes like unix style even on windows

Use property file or properties in build script so that other members do not have it edit the build scripts as paths might change machine to machine.

For now, added properties in the below script, you may externalize to a property file too.

build.xml

```<code><project basedir="." default="testreport" name="APIAutomation">
   <property name="test.suite" value="FirstLoginTest"/>
   <property name="soapui.project" value="C:/Users/F3020722/Desktop/Notification/New folder/APIRegression.xml"/>
   <property name="soapui.home" value="C:/Program Files (x86)/SmartBear/SoapUI-5.0.0"/>
   <property name="results.dir" value="C:/Users/F3020722/Desktop/Notification/API/Results"/>
   <property name="reports.dir" value="${results.dir}/Reports"/>
   <property name="html.dir" value="${reports.dir}/html"/>
   <target name="execute.project">
     <exec dir="${soapui.home}/bin" executable="testrunner.bat">
        <arg line="-raj -f ${results.dir} -s ${test.suite} ${soapui.project}" />
     </exec>
  </target>
   <target name="testreport" depends="execute.project">
        <mkdir dir="${reports.dir}"/>
            <junitreport todir="${reports.dir}">
                <fileset dir="${results.dir}">
                    <include name="TEST-*.xml"/>
                </fileset>
                <report format="frames" todir="${html.dir}" />
            </junitreport>
   </target>
</project>
</code>```

You can also find a docker image for soapui and run tests & generate junit style html report as well. Refer soapui repository @ hub.docker.com

Note: that build script used docker images is exactly the same as above except the machine path.

Body:
I am running a SoapUI project using Ant to get a JUnit report.

Here is my build.xml:

<project basedir="." default="testreport" name="APIAutomation">
<target name="SoapUI">
    <exec dir="." executable="C:\Program Files (x86)\SmartBear\SoapUI-5.0.0\bin\testrunner.bat">
        <arg line="-r -j -a -f 'C:\Users\F3020722\Desktop\Notification\New folder' -sFirstLoginTest 'C:\Users\F3020722\Desktop\Notification\New folder\APIRegression.xml'"></arg>
    </exec>
</target>
<target name="testreport" depends="SoapUI">
    <junitreport todir="C:\Users\F3020722\Desktop\Notification\New folder\API">
        <fileset dir="C:\Users\F3020722\Desktop\Notification\New folder\API">
            <include name="TEST-*.xml"/>
        </fileset>
        <report format="frames"
            todir="C:\Users\F3020722\Desktop\Notification\New folder\reports\html">
        </report>
    </junitreport>
</target>
</project>

I am getting an XML report properly. However, the JUnit report is empty. all contains 0 and successrate is Nan.

Can anyone check the build.xml is correct?

Body:
Looks build script seems ok

Avoid spaces in the directory names

Use forward slashes like unix style even on windows

Use property file or properties in build script so that other members do not have it edit the build scripts as paths might change machine to machine.

For now, added properties in the below script, you may externalize to a property file too.

build.xml

<project basedir="." default="testreport" name="APIAutomation">
   <property name="test.suite" value="FirstLoginTest"/>
   <property name="soapui.project" value="C:/Users/F3020722/Desktop/Notification/New folder/APIRegression.xml"/>
   <property name="soapui.home" value="C:/Program Files (x86)/SmartBear/SoapUI-5.0.0"/>
   <property name="results.dir" value="C:/Users/F3020722/Desktop/Notification/API/Results"/>
   <property name="reports.dir" value="${results.dir}/Reports"/>
   <property name="html.dir" value="${reports.dir}/html"/>
   <target name="execute.project">
     <exec dir="${soapui.home}/bin" executable="testrunner.bat">
        <arg line="-raj -f ${results.dir} -s ${test.suite} ${soapui.project}" />
     </exec>
  </target>
   <target name="testreport" depends="execute.project">
        <mkdir dir="${reports.dir}"/>
            <junitreport todir="${reports.dir}">
                <fileset dir="${results.dir}">
                    <include name="TEST-*.xml"/>
                </fileset>
                <report format="frames" todir="${html.dir}" />
            </junitreport>
   </target>
</project>

You can also find a docker image for soapui and run tests & generate junit style html report as well. Refer soapui repository @ hub.docker.com

Note: that build script used docker images is exactly the same as above except the machine path.


问:
ZeroMQ: socket per data type or just one socket?
I've got a program which receives information from about 10 other (sensor reading) programs (all controlled by myself). I now want to make them communicate using ZeroMQ.

For most of the queues the important thing is that the central receiving program always has the latest sensor data, all older messages are not important anymore. If a couple messages get lost I don't care. So for all of them I started out with a separate PUB/SUB socket; one for each program. But I'm not sure if that is the right way to do it. As far as I understand I have two options:

Make a separate socket for every program and read them out in a loop. That way I know by the socket what the information is I'm receiving (I'm often just sending an int).

Make one socket to which all the programs connect, and with every message I send a string which tells the receiving end what the message is about.

All connections are on a PUB/SUB basis, so creating one socket would well work out. I'm just not sure if that is the most efficient way to do it.

All tips are welcome!

答:
Unless you're up against a tight real time requirement there's not much point in having more sockets than necessary. ZMQ's fair queuing ought to take care of giving each sensor program equal attention (see Figure 6 in the guide)

If your sensor programs are on other devices connected by Ethernet, the ultimate performance of your programs is limited by the bandwidth of the Ethernet NIC in your computer. A single thread program handling a single PULL socket stands a good chance of being able to process the data coming in faster than it can transit the NIC.

If that's so, then you may as well stick to a single socket and enjoy the simpler code. It's not very hard dealing with multiple sockets, but it's far easier to deal with one. For example, with one single socket you don't have to tell each sensor program what network port to connect to - it can be a constant.

PUSH/PULL sounds like a more natural pattern for your situation than PUB/SUB, but that won't make much difference.

Lastness

Lastness is going to be your (potential) problem. The whole point of things like ZMQ is that they will deliver messages in the order they're sent. Thus you read a message, it is by definition the "last" message so far as the recipient is concerned. The recipient has no idea as to whether or not there is another message on the way, in transit.

This is a feature of Actor model architectures (which is what ZMQ is). Messages get buffered up in the transport, and there's no information about the newness of the message to be learned when it's read. All you know is that it was sent some time beforehand. There is no execution rendezvous with the sender.

Now, you either process it as if it is the last message, or you wait for a period of time to see if another one comes along before processing it. The easiest thing to do is to simply process each message as if it is the last.

Contrast this with a Communicating Sequential Processes architecture. It's basically the same as an Actor model architecture, except that the transport does not buffer messages. Message sends block until the recipient has called message read.

Thus when you read a message, the recipient knows that it the last one sent by the sender. And the sender knows that the message it has sent has been received at that very instant by the recipient. So the knowledge of lastness is absolute - the message received really is the last one sent.

However, unless you have something fairly heavyweight going on I wouldn't worry about it. You are quite likely to be able to keep up with your sensor data stream even if the messages you're reading aren't the latest in the queue.

You can nearly make ZMQ into CSP by setting the high water limit on the sending end's socket to 1. That means that you can buffer up at most 1 message. That's not the same as 0, and unfortunately setting the HWM to 0 means "unlimited size buffer".


问:
Android BOOT_COMPLETED doesn't fire until user has gone past lock screen
I need a service to be running in the background for my app and I want it start up automatically when the phone is switched on.
I've got the usual intent-filter for BOOT_COMPLETED but what happens is this...

I switch the phone on.

It starts up until the lock screen.

I go through the lock screen.

The background job gets started up.

I want/need the job to start before I'm asked for the lock screen.

This is on a Pixel running Android N.

Cheers.

答:
Your problem is due to Android 7.0 running a secure Direct Boot mode when the device has been powered on but the user has not unlocked the device. This limits Credential encrypted storage from being accessed before the user has unlocked the device. Therefore your app has to register to use Device encrypted storage for use during Direct Boot mode and after the user has unlocked the device.

This article discusses how it works and example use cases (scheduled notifications, SMS apps, etc) but what your code is missing is a receiver and
intent-filter for ACTION_LOCKED_BOOT_COMPLETED.

Essentially, you need the following code in your manifest

```<code><receiver
  android:directBootAware="true" >
  ...
  <intent-filter>
    <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
  </intent-filter>
</receiver>
</code>```

Let me know if you need any more help!

Body:
Your problem is due to Android 7.0 running a secure Direct Boot mode when the device has been powered on but the user has not unlocked the device. This limits Credential encrypted storage from being accessed before the user has unlocked the device. Therefore your app has to register to use Device encrypted storage for use during Direct Boot mode and after the user has unlocked the device.

This article discusses how it works and example use cases (scheduled notifications, SMS apps, etc) but what your code is missing is a receiver and
intent-filter for ACTION_LOCKED_BOOT_COMPLETED.

Essentially, you need the following code in your manifest

<receiver
  android:directBootAware="true" >
  ...
  <intent-filter>
    <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
  </intent-filter>
</receiver>

Let me know if you need any more help!


问:
Problems while designing a database to manage all kind of products like Amazon
first of all sorry for my bad english hehehe I need some help, I want to design a database for a website, like a mini Amazon. This database will manage every kind of products (TV, cars, computers, books, videogames, penciles, tables, pants...), but also, each product must have some properties (that will be indexed) for example, if the product is a book, the properties will be something like genre, year, author. If the product is a TV, the properties will be something like size, color, also year. And if the product is a car, the properties will be something like year, color, model, for example. So, this is my idea:

One table to manage departments (like electronics, books...)

One table to manage categories of the departments, this table will be a child of the previous. If the department is electronics, here will be audio, tv and video, games... (each category belongs to one department, the relationship is one department to many categories)

One table to manage the products (each product belongs to one category, the relationship is one category to many products)

One table to manage properties (like year, color, genre, model...)

One table to engage products with properties, this table will be called ProductProperties

Im not sure if this is the best way, the database will be huge, I will develop the database on MySQL. But, I think this is not the best way, this article talks about "Database Abstraction: Aggregation and Generalization" http://cs-exhibitions.uni-klu.ac.at/index.php?id=433, in other words generic objects (I think), but this way is old (70s). In this article http://www.simple-talk.com/sql/database-administration/ten-common-database-design-mistakes/ in the section "One table to hold all domain values" says that this is a wrong way... Im saying all of this because of the table ProductProperties, I dont know if I make this table or if I make especific tables for each kind of products.

Do you have any suggestion? Or do you have a better idea?

Thanks in advance, take care!!!

答: I do not think that some database can work fast with 500,000,000 items. Complete tree of products categories for amazon.com contains 51,000 nodes (amazoncategories.info). Also the data is updated hourly, so saved product information can be incorrect. I think the optimal way is to store categories tree only get the product data at runtime using Amazon's API. </p>

ContentLicense: CC BY-SA 2.5


问:
using session in MVC5 application best approach
I am trying to implement session in asp.net mvc 5 application. The application does not have a login screen. The application checks if the user accessing the application exist in the database. The Active Director user name is captured in session and sent to the storedproc to verify of the user exist. If exist, I would need to store the Userprofile information in session.  I have created a repository class to access the data. I am calling the method from the session start method in global.asax. I would like to verify if my implementation is correct. How do  I update the session data if the information is changed.

MCRHelper

```<code> public static string GetShortname()
        {
            string username = HttpContext.Current.User.Identity.Name;
            return username.Split('\\')[1];
        }
</code>```

Model

```<code>[Serializable]
    public class UserProfileSessionData
    {
        public int UserProfileID { get; set; }
        public int EmployeeID { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
        public string PreferredName { get; set; }
        public string DefaultLanguageCode { get; set; }
        public string DefaultCountryCode { get; set; }
        public int TimeZoneID { get; set; }
        public string TimeZoneName { get; set; }
        public string Domain { get; set; }
        public string NetworkID { get; set; }
        public string EmailAddress { get; set; }
    }
</code>```

repository class

```<code>public class SessionRespository
    {
        public List<UserProfileSessionData> GetUserProfileByNetworkId()
        {
            MCREntities db = new MCREntities();

            if (MCRHelper.UserValidate() == 1)
            {
                var userProfiles = db.spGetUserProfileByNetworkID(MCRHelper.GetShortname());
                return Mapper.Map<List<UserProfileSessionData>>(userProfiles);

            }
            return null;
        }
    }
</code>```

Global.asax

```<code>  protected void Session_Start(object sender, EventArgs e)
        {
            // set SessionUtil.User here
            SessionRespository sessionRespository = new SessionRespository();
            Session["UserProfile"] = sessionRespository.GetUserProfileByNetworkId();
        }
</code>```

答:
I would like to verify if my implementation is correct.

First of all, you should not store logged-in user's information in Session State not to mention using Session State is discouraged in ASP.NET MVC if possible.

We used to store logged-in user information in Session State prior to ASP.NET Membership Provider which was 15 years ago.

Since you are using ASP.NET MVC 5, you want to use ASP.NET OWIN Cookie Middleware. Implementation is a lot easier than you think.

OwinAuthenticationService

```<code>private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";

public OwinAuthenticationService(HttpContextBase context)
{
    _context = context;
}

public void SignIn(User user)
{
    IList<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.Sid, user.Id.ToString()),
        new Claim(ClaimTypes.Name, user.UserName),
        new Claim(ClaimTypes.GivenName, user.FirstName),
        new Claim(ClaimTypes.Surname, user.LastName),
    };

    ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignIn(identity);
}

public void SignOut()
{
    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignOut(AuthenticationType);
}
</code>```

Startup.cs

You also need to configure Startup for all those to happen.

```<code>[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}
</code>```

Then you can start using [Authorize] attribute in Controller and Action methods.

```<code>[Authorize]
public class UsersController : Controller
{
   // ...
}
</code>```

Here is my sample application at GitHub which uses AD for Authentication. I have user friendly login screen, but you do not have use it if you do not want it.

Body:
I am trying to implement session in asp.net mvc 5 application. The application does not have a login screen. The application checks if the user accessing the application exist in the database. The Active Director user name is captured in session and sent to the storedproc to verify of the user exist. If exist, I would need to store the Userprofile information in session.  I have created a repository class to access the data. I am calling the method from the session start method in global.asax. I would like to verify if my implementation is correct. How do  I update the session data if the information is changed.

MCRHelper

 public static string GetShortname()
        {
            string username = HttpContext.Current.User.Identity.Name;
            return username.Split('\\')[1];
        }

Model

[Serializable]
    public class UserProfileSessionData
    {
        public int UserProfileID { get; set; }
        public int EmployeeID { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
        public string PreferredName { get; set; }
        public string DefaultLanguageCode { get; set; }
        public string DefaultCountryCode { get; set; }
        public int TimeZoneID { get; set; }
        public string TimeZoneName { get; set; }
        public string Domain { get; set; }
        public string NetworkID { get; set; }
        public string EmailAddress { get; set; }
    }

repository class

public class SessionRespository
    {
        public List<UserProfileSessionData> GetUserProfileByNetworkId()
        {
            MCREntities db = new MCREntities();

            if (MCRHelper.UserValidate() == 1)
            {
                var userProfiles = db.spGetUserProfileByNetworkID(MCRHelper.GetShortname());
                return Mapper.Map<List<UserProfileSessionData>>(userProfiles);

            }
            return null;
        }
    }

Global.asax

  protected void Session_Start(object sender, EventArgs e)
        {
            // set SessionUtil.User here
            SessionRespository sessionRespository = new SessionRespository();
            Session["UserProfile"] = sessionRespository.GetUserProfileByNetworkId();
        }

Body:
I would like to verify if my implementation is correct.

First of all, you should not store logged-in user's information in Session State not to mention using Session State is discouraged in ASP.NET MVC if possible.

We used to store logged-in user information in Session State prior to ASP.NET Membership Provider which was 15 years ago.

Since you are using ASP.NET MVC 5, you want to use ASP.NET OWIN Cookie Middleware. Implementation is a lot easier than you think.

OwinAuthenticationService

private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";

public OwinAuthenticationService(HttpContextBase context)
{
    _context = context;
}

public void SignIn(User user)
{
    IList<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.Sid, user.Id.ToString()),
        new Claim(ClaimTypes.Name, user.UserName),
        new Claim(ClaimTypes.GivenName, user.FirstName),
        new Claim(ClaimTypes.Surname, user.LastName),
    };

    ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignIn(identity);
}

public void SignOut()
{
    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignOut(AuthenticationType);
}

Startup.cs

You also need to configure Startup for all those to happen.

[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}

Then you can start using [Authorize] attribute in Controller and Action methods.

[Authorize]
public class UsersController : Controller
{
   // ...
}

Here is my sample application at GitHub which uses AD for Authentication. I have user friendly login screen, but you do not have use it if you do not want it.


问:
VS2017 Cordova iOS Local Device Deploy
I am using Visual Studio 2017 on Win10 with the blank Cordova app project.
I am able to build and deploy to Android and iOS simulators fine.
I am able to build and deploy to iOS "Remote Device" just fine.

However, I am having a problem with iOS "Local Device".
It builds fine, but the problem occurs in Deploy.
Here is the error:

File C:\Program Files (x86)\Microsoft Visual

  Studio\2017\Professional\Common7\IDE\node_modules\vs-libimobile\lib\ideviceprovision.exe
  could not be found.

After this failure, it deploys to iTunes. But, now this seems to require manually installing it, and iTunes always asks if I want to replace it each build. Plus, you can't actually run the VS TACO debugger this way. Obviously, this is not what is supposed to happen.

I have setup iOS Local Device Deploy on a Win7 PC with VS2015 and it works as expected. I'm just trying to migrate the tools to a new PC and get up and running with VS2017.

I'm a newbie with all of this, including npm and node.js. I've tried doing "npm install -g vs-libimobile", but it's not being installed where VS2017 seems to want it. I've also tried to copy/paste it there, but it's a read-only folder. This seems to be a bug with VS2017. Any ideas?

答:
Magically, "Local Device" deployment just started working!!

Honestly, I don't know exactly what changed. My best guess is that I opened a .config file that caused VS2015 to open (instead of VS2017). Maybe just opening/closing VS2015 caused something to change in an environment variable or Registry setting?

What I noticed is that the "node_modules" folder containing "vs-libimobile" is now being created at the same folder level as the .sln file. I suspect that's important.

Hope this helps someone.

Title: VS2017 Cordova iOS Local Device Deploy


问:
UseStatusCodePagesWithReExecute Unhandled Exception Duplicate Key: System.Object
AsP.Net Core UseStatusCodePagesWithReExecute(), I'm redirecting to /StatusCode/{0}. I was previously using UseStatusCodePagesWithRedirect() without any apparant issues but since changing, requests that previously redirected now result in an unhandled exception:

ArgumentException: An item with the same key has already been added. Key: System.Object

Here's the output from the VS15 debug window:

```<code>Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:5000/guides/some-guide/introdu
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method WebSite.Controllers.GuideController.ReadSection (WebSite) with arguments (some-guide, introdu) - ModelState is Valid
Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory:Information: Executed DbCommand (0ms) [Parameters=[@__permalink_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
SELECT TOP(2) [s].[SectionId], [s].[Description], [s].[DisplayPosition], [s].[DocumentId], [s].[Permalink], [s].[Title], [d].[DocumentId], [d].[CategoryId], [d].[Description], [d].[DisplayPosition], [d].[Permalink], [d].[Subtitle], [d].[Title]
FROM [Sections] AS [s]
INNER JOIN [Documents] AS [d] ON [s].[DocumentId] = [d].[DocumentId]
WHERE [s].[Permalink] = @__permalink_0
ORDER BY [s].[SectionId]
Microsoft.AspNetCore.Mvc.StatusCodeResult:Information: Executing HttpStatusCodeResult, setting HTTP status code 404
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action WebSite.Controllers.GuideController.ReadSection (WebSite) in 15.6192ms
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method WebSite.Controllers.ErrorController.StatusCode (WebSite) with arguments (404) - ModelState is Valid
WebSite.Controllers.ErrorController:Information: Unexpected Status Code: 404, OriginalPath: /guides/some-guide/introdu
'dotnet.exe' (CoreCLR: clrhost): Loaded 'g4tz3vmn.35h'. Cannot find or open the PDB file.
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor:Information: Executing ViewResult, running view at path /Views/Error/Index.cshtml.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action WebSite.Controllers.ErrorController.StatusCode (WebSite) in 86.9564ms
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Users\Me\.nuget\packages\System.Diagnostics.StackTrace\4.3.0\lib\netstandard1.3\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.1.0\System.IO.MemoryMappedFiles.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.1.0\System.IO.UnmanagedMemoryStream.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request

System.ArgumentException: An item with the same key has already been added. Key: System.Object
   at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at WebMarkupMin.AspNetCore1.WebMarkupMinMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.<>c__DisplayClass6_0.<<UseStatusCodePagesWithReExecute>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Web.BrowserLink.Runtime.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 342.116ms 500 text/html; charset=utf-8
</code>```

It looks like it's executing my StatusCode controller action fine, logging the original path of the error and then bam, I get the exception. What is causing this error?

答:
I was having the same issue and was not using BrowserLink. But like Rytmis said, it does seem to be caused by TempData. If you're not using TempData anywhere, changing your AddMvc call in Startup.cs to the following should fix it:

```<code> services.AddMvc(options =>
 {
     options.Filters.Remove(new SaveTempDataAttribute());
 });
</code>```

Be careful with that one, it's an ugly hack.

In my case, the root issue turned out to be that the base class my errors controller was inheriting from using the ControllerBase.HttpContext property. Once I changed that to get httpContext from IHttpContextAccessor the problem went away.

Body:
AsP.Net Core UseStatusCodePagesWithReExecute(), I'm redirecting to /StatusCode/{0}. I was previously using UseStatusCodePagesWithRedirect() without any apparant issues but since changing, requests that previously redirected now result in an unhandled exception:

ArgumentException: An item with the same key has already been added. Key: System.Object

Here's the output from the VS15 debug window:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:5000/guides/some-guide/introdu
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method WebSite.Controllers.GuideController.ReadSection (WebSite) with arguments (some-guide, introdu) - ModelState is Valid
Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory:Information: Executed DbCommand (0ms) [Parameters=[@__permalink_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
SELECT TOP(2) [s].[SectionId], [s].[Description], [s].[DisplayPosition], [s].[DocumentId], [s].[Permalink], [s].[Title], [d].[DocumentId], [d].[CategoryId], [d].[Description], [d].[DisplayPosition], [d].[Permalink], [d].[Subtitle], [d].[Title]
FROM [Sections] AS [s]
INNER JOIN [Documents] AS [d] ON [s].[DocumentId] = [d].[DocumentId]
WHERE [s].[Permalink] = @__permalink_0
ORDER BY [s].[SectionId]
Microsoft.AspNetCore.Mvc.StatusCodeResult:Information: Executing HttpStatusCodeResult, setting HTTP status code 404
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action WebSite.Controllers.GuideController.ReadSection (WebSite) in 15.6192ms
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method WebSite.Controllers.ErrorController.StatusCode (WebSite) with arguments (404) - ModelState is Valid
WebSite.Controllers.ErrorController:Information: Unexpected Status Code: 404, OriginalPath: /guides/some-guide/introdu
'dotnet.exe' (CoreCLR: clrhost): Loaded 'g4tz3vmn.35h'. Cannot find or open the PDB file.
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor:Information: Executing ViewResult, running view at path /Views/Error/Index.cshtml.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action WebSite.Controllers.ErrorController.StatusCode (WebSite) in 86.9564ms
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Users\Me\.nuget\packages\System.Diagnostics.StackTrace\4.3.0\lib\netstandard1.3\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.1.0\System.IO.MemoryMappedFiles.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.1.0\System.IO.UnmanagedMemoryStream.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request

System.ArgumentException: An item with the same key has already been added. Key: System.Object
   at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at WebMarkupMin.AspNetCore1.WebMarkupMinMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.<>c__DisplayClass6_0.<<UseStatusCodePagesWithReExecute>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Web.BrowserLink.Runtime.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 342.116ms 500 text/html; charset=utf-8

It looks like it's executing my StatusCode controller action fine, logging the original path of the error and then bam, I get the exception. What is causing this error?

Body:
I was having the same issue and was not using BrowserLink. But like Rytmis said, it does seem to be caused by TempData. If you're not using TempData anywhere, changing your AddMvc call in Startup.cs to the following should fix it:

 services.AddMvc(options =>
 {
     options.Filters.Remove(new SaveTempDataAttribute());
 });

Be careful with that one, it's an ugly hack.

In my case, the root issue turned out to be that the base class my errors controller was inheriting from using the ControllerBase.HttpContext property. Once I changed that to get httpContext from IHttpContextAccessor the problem went away.


问:
Chrome is being controlled by automated test software
I am running automated tests in Chrome with Serenity BDD (Selenium).

I had to download a new ChromeDriver, because my tests could not run -> The test would open ChromeDriver but could not "Browse as user". When I googled the issue, they said I had to update ChromeDriver.

So I updated ChromeDriver to version 2.28 and I also updated the Chrome version to Version 57.0.2987.98.

But now - EVERY TIME I run my tests this annoying text comes up:

Chrome is being controlled by automated test software

And it asks me if I want to save password. (I can't add pictures because I don't have enough "points")

In the previous version, I had managed to block these 2 things by:

```<code>public class CustomChromeDriver implements DriverSource {

    @Override
    public WebDriver newDriver() {
        try {
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            Proxy proxy = new Proxy();
            String proxyServer = String.format("AProxyIDontWantToDisplay", System.getenv("proxy.username"), System.getenv("proxy.password"));
            proxy.setHttpProxy(proxyServer);
            capabilities.setCapability("proxy", proxy);
            ChromeOptions options = new ChromeOptions();
            options.addArguments(Arrays.asList("--no-sandbox","--ignore-certificate-errors","--homepage=about:blank","--no-first-run"));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            ChromeDriver driver = new ChromeDriver(capabilities);
            return driver;
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    @Override
    public boolean takesScreenshots() {
        return true;
    }
}
</code>```

I know there is this one (A link to same issue),
but there are too many answers that don't work.

Anybody that knows how to remove that?

答:
Add this to the options you pass to the driver:</p>

```<code>options.addArguments("disable-infobars");
</code>```

Body:
I am running automated tests in Chrome with Serenity BDD (Selenium).

I had to download a new ChromeDriver, because my tests could not run -> The test would open ChromeDriver but could not "Browse as user". When I googled the issue, they said I had to update ChromeDriver.

So I updated ChromeDriver to version 2.28 and I also updated the Chrome version to Version 57.0.2987.98.

But now - EVERY TIME I run my tests this annoying text comes up:

Chrome is being controlled by automated test software

And it asks me if I want to save password. (I can't add pictures because I don't have enough "points")

In the previous version, I had managed to block these 2 things by:

public class CustomChromeDriver implements DriverSource {

    @Override
    public WebDriver newDriver() {
        try {
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            Proxy proxy = new Proxy();
            String proxyServer = String.format("AProxyIDontWantToDisplay", System.getenv("proxy.username"), System.getenv("proxy.password"));
            proxy.setHttpProxy(proxyServer);
            capabilities.setCapability("proxy", proxy);
            ChromeOptions options = new ChromeOptions();
            options.addArguments(Arrays.asList("--no-sandbox","--ignore-certificate-errors","--homepage=about:blank","--no-first-run"));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            ChromeDriver driver = new ChromeDriver(capabilities);
            return driver;
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    @Override
    public boolean takesScreenshots() {
        return true;
    }
}

I know there is this one (A link to same issue),
but there are too many answers that don't work.

Anybody that knows how to remove that?

Body:
Add this to the options you pass to the driver:

options.addArguments("disable-infobars");


问:
React - elegant way to re-render just one child component?
I'm working on a table component.  When I scroll left and right on the
 I want it to update the xOffset of just the <theader /> which is in a separate component I'll call .  Here's the structure:

```<code><Parent Component >
    <Header Component />
    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
</Parent Component >
</code>```

The scroll listener is on the parent component and the xOffset is part of the Parent Component's state.  When I scroll left and right, it also re-renders the very expensive to re-render body components.

What are my options for just the Header Component to re-render?

1) Use Redux and selectors.  Parent component dispatches an xOffset to app state and the  listens just for that on a selector.  Seems like overkill...

2) I break out all the <Very Expensive Body Comp divs > into their own component, and use ShouldComponentUpdate so that it doesn't re-render if everything stays the same besides xOffset.  This doesn't seem like overkill, but I feel like I'm going to be dealing with the same problem because I'll have to put the scroll listener on this new component... and then use the parent component as an intermediary.. oof.

Is there a third more elegant solution?

I'm hoping there's a way to pass a function into the  so that when the parent component scrolls left and right, it uses that function to update the state of the  which would cause just it to re-render.

答:
Option number 2! Break out your very expensive div tags into their own components and use shouldComponentUpdate. Keeping all elements inside one render() function does not scale well as you are beginning to see. The whole benefit of using React is that you can create simple, reusable components and build a more complex UI with those. You seem intent on keeping everything inside of one component, but that is essentially an anti-pattern in React.

However, do not add a new scroll listener to each component. Instead just keep it on the parent component like you are doing and pass the scroll value down as a prop to all of your new components. If they only need to change after a certain amount of the screen has been scrolled, you can update it in each child's shouldComponentUpdate function.

Body:
I'm working on a table component.  When I scroll left and right on the
 I want it to update the xOffset of just the <theader /> which is in a separate component I'll call .  Here's the structure:

<Parent Component >

    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
</Parent Component >

The scroll listener is on the parent component and the xOffset is part of the Parent Component's state.  When I scroll left and right, it also re-renders the very expensive to re-render body components.

What are my options for just the Header Component to re-render?

1) Use Redux and selectors.  Parent component dispatches an xOffset to app state and the  listens just for that on a selector.  Seems like overkill...

2) I break out all the <Very Expensive Body Comp divs > into their own component, and use ShouldComponentUpdate so that it doesn't re-render if everything stays the same besides xOffset.  This doesn't seem like overkill, but I feel like I'm going to be dealing with the same problem because I'll have to put the scroll listener on this new component... and then use the parent component as an intermediary.. oof.

Is there a third more elegant solution?

I'm hoping there's a way to pass a function into the  so that when the parent component scrolls left and right, it uses that function to update the state of the  which would cause just it to re-render.


问:
D3 v4 Update Bar Graph Does Not Plot Last Bar
I am new to D3 and javascript is not my first language, so I'll apologize in advance for probably not using the best js practices.

I am attempting to recreate this bar graph that will cycle through a dataset, adding in bars each time; but trying to modify it to be in D3 v4.

https://bl.ocks.org/RandomEtc/cff3610e7dd47bef2d01

I've got it mostly working except it would plot the last bar graph.  It will make a spot for it on the x-axis; but no bar graph appears.

https://jsfiddle.net/jimdholland/07p8z8pb/35/

From what I can see, my iteration function is grabbing the last element and the data values.

```<code>function cycler(data) {
    var slices = [];
  for (var i = 0; i < data.length; i++) {
    slices.push(data.slice(0, i+1));
  } //End for loop
  slices.forEach(function(slice, index){
    setTimeout(function(){
        drawChart(slice);
      console.log(slice);
    }, index * 300);
  }); //End for Each
};  // End cycler function
</code>```

I created a function that draws the graph and I assume it maybe with me not properly clearing out the old data.

```<code>function drawChart(data) {
  x.domain(data.map(function(d) { return d.Word; }));
  y.domain([0, d3.max(data, function(d) { return d.Positive; })]);

  svg.select(".xAxis").transition().duration(300).call(d3.axisBottom(x));
  svg.select(".yAxis").transition().duration(300).call(d3.axisLeft(y));

  //svg.select('.xaxis').transition().duration(300).call(xAxis);
  var bar = svg.selectAll("rect").data(data);

  bar.exit()
    .transition()
    .duration(300)
    .attr("y", innerHeight)
    .attr("height", 0)
    .style('fill-opacity', 1e-6)
    .remove();

  bar.enter().append("rect")
    .attr("class", "bar")
    .merge(bar)
    .attr("y", innerHeight)
    .attr("height", 0);

  bar.transition().duration(300)
    .attr("x", function(d) {return x(d.Word); })
    .attr("width", x.bandwidth())
    .attr("y", function(d) {return y(d.Positive); })
    .attr("height", function(d) {return height - y(d.Positive); });

};
</code>```

Thanks for any help and I'm also open to better practices for writing my D3 code.

答:
Inside your cycler() function you just need to change the for loop < to <=

```<code>for (var i = 0; i <= data.length; i++) {
    slices.push(data.slice(0, i+1));
  }
</code>```

Body:
I am new to D3 and javascript is not my first language, so I'll apologize in advance for probably not using the best js practices.

I am attempting to recreate this bar graph that will cycle through a dataset, adding in bars each time; but trying to modify it to be in D3 v4.

https://bl.ocks.org/RandomEtc/cff3610e7dd47bef2d01

I've got it mostly working except it would plot the last bar graph.  It will make a spot for it on the x-axis; but no bar graph appears.

https://jsfiddle.net/jimdholland/07p8z8pb/35/

From what I can see, my iteration function is grabbing the last element and the data values.

function cycler(data) {
    var slices = [];
  for (var i = 0; i < data.length; i++) {
    slices.push(data.slice(0, i+1));
  } //End for loop
  slices.forEach(function(slice, index){
    setTimeout(function(){
        drawChart(slice);
      console.log(slice);
    }, index * 300);
  }); //End for Each
};  // End cycler function

I created a function that draws the graph and I assume it maybe with me not properly clearing out the old data.

function drawChart(data) {
  x.domain(data.map(function(d) { return d.Word; }));
  y.domain([0, d3.max(data, function(d) { return d.Positive; })]);

  svg.select(".xAxis").transition().duration(300).call(d3.axisBottom(x));
  svg.select(".yAxis").transition().duration(300).call(d3.axisLeft(y));

  //svg.select('.xaxis').transition().duration(300).call(xAxis);
  var bar = svg.selectAll("rect").data(data);

  bar.exit()
    .transition()
    .duration(300)
    .attr("y", innerHeight)
    .attr("height", 0)
    .style('fill-opacity', 1e-6)
    .remove();

  bar.enter().append("rect")
    .attr("class", "bar")
    .merge(bar)
    .attr("y", innerHeight)
    .attr("height", 0);

  bar.transition().duration(300)
    .attr("x", function(d) {return x(d.Word); })
    .attr("width", x.bandwidth())
    .attr("y", function(d) {return y(d.Positive); })
    .attr("height", function(d) {return height - y(d.Positive); });

};

Thanks for any help and I'm also open to better practices for writing my D3 code.

Body:
Inside your cycler() function you just need to change the for loop < to <=

for (var i = 0; i <= data.length; i++) {
    slices.push(data.slice(0, i+1));
  }


问:
MultipartMemoryStreamProvider and reading user data from MultiPart/Form Data
I have a file and user data that is being posted from Multipart/form data to a post method in my apicontroller class.
I am able to read the file without any problems but unable to read user data.

I tried couple of things like using model binding, passing the individual fields as a method parameter in the post method but i get: No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'multipart/form-data'.

```<code>var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
foreach (var item in provider.Contents)
{
    var fieldName = item.Headers.ContentDisposition.Name.Trim('"');
    if (item.Headers.ContentDisposition.FileName == null)
    {
        var data = await item.ReadAsStringAsync();
        if (fieldname == "name")
        {
            Name = data;
        }
        else
        {
            fileContents = await item.ReadAsByteArrayAsync();
        }
    }
}
</code>```

Thanks.

答:
It seems to me the OP, was really close.  This is some code that tries to clearly show how to get the form variables, as well as the file upload data.

First the ApiController:

```<code>using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    public class FormAndFileDataController : ApiController
    {
        private class FormItem
        {
            public FormItem() { }
            public string name { get; set; }
            public byte[] data { get; set; }
            public string fileName { get; set; }
            public string mediaType { get; set; }
            public string value { get { return Encoding.Default.GetString(data); } }
            public bool isAFileUpload { get { return !String.IsNullOrEmpty(fileName); } }
        }

        /// <summary>
        /// An ApiController to access an AJAX form post.
        /// </summary>
        /// <remarks>
        ///
        /// </remarks>
        /// <returns></returns>
        public async Task<HttpResponseMessage> Post()
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            var formItems = new List<FormItem>();

            // Scan the Multiple Parts
            foreach (HttpContent contentPart in provider.Contents)
            {
                var formItem = new FormItem();
                var contentDisposition = contentPart.Headers.ContentDisposition;
                formItem.name = contentDisposition.Name.Trim('"');
                formItem.data = await contentPart.ReadAsByteArrayAsync();
                formItem.fileName = String.IsNullOrEmpty(contentDisposition.FileName) ? "" : contentDisposition.FileName.Trim('"');
                formItem.mediaType = contentPart.Headers.ContentType == null ? "" : String.IsNullOrEmpty(contentPart.Headers.ContentType.MediaType) ? "" : contentPart.Headers.ContentType.MediaType;
                formItems.Add(formItem);
            }

            // We now have a list of all the distinct items from the *form post*.
            // We can now decide to do something with the items.
            foreach (FormItem formItemToProcess in formItems)
            {
                if (formItemToProcess.isAFileUpload)
                {

                    // This is a file. Do something with the file.  Write it to disk, store in a database.  Whatever you want to do.

                    // The name the client used to identify the *file* input element of the *form post* is stored in formItem.name.
                    // The *suggested* file name from the client is stored in formItemToProcess.fileName
                    // The media type (MimeType) of file (as far as the client knew) if available, is stored in formItemToProcess.mediaType
                    // The file data is stored in the byte[] formItemToProcess.data

                }
                else
                {
                    // This is a form variable.  Do something with the form variable.  Update a DB table, whatever you want to do.

                    // The name the client used to identify the input element of the *form post* is stored in formItem.name.
                    // The value the client input element is stored in formItem.value.

                }
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

    }
}
</code>```

and the MVC View to test it:

```<code>@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script type="text/javascript">

            var hiddenForm, hiddenFile;

            function initialize() {
                // Use a hidden file element so we can control the UI
                // of the file selection interface.  The built in browser
                // UI is not localizable to different languages.
                hiddenFile = document.createElement("input");
                hiddenFile.setAttribute("type", "file");
                hiddenFile.setAttribute("style", "display: none;");

                // We don't need the form really, but it makes it easy to
                // reset the selection.
                hiddenForm = document.createElement("form");
                hiddenForm.appendChild(hiddenFile);

                hiddenFile.onchange = function () {
                    var elementToUpdate = document.getElementById("fileNameToUpload");
                    var filesToUpload = hiddenFile.files;
                    var fileToUpload = filesToUpload[0];
                    elementToUpdate.value = fileToUpload.name;
                }
                document.body.appendChild(hiddenForm);
            }
            function chooseFile() {
                hiddenFile.click();
            }

            function clearFile() {
                var elementToUpdate = document.getElementById("fileNameToUpload");
                elementToUpdate.value = "";
                hiddenForm.reset();
            }
            function testAJAXUpload() {

                // We are going to use the FormData object and jQuery
                // to do our post test.
                var formToPost = new FormData();
                var formVariableNameElement = document.getElementById("variableNameToUpload");
                var formVariableValueElement = document.getElementById("variableValueToUpload");

                var formVariableName = formVariableNameElement.value || "formVar1";
                var formVariableValue = formVariableValueElement.value || "Form Value 1";
                var filesToUpload = hiddenFile.files;
                var fileToUpload = filesToUpload[0];

                formToPost.append(formVariableName,formVariableValue)
                formToPost.append("fileUpload", fileToUpload);

                // Call the Server.
                $.ajax({
                    url: '@Url.HttpRouteUrl("DefaultApi", new { controller = "FormAndFileData" })',
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    data: formToPost,
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("Failed: [" + textStatus + "]");
                    },
                    success: function (data, textStatus, jqXHR) {
                        alert("Success.");
                    }
                });

            }

    </script>
</head>
<body>
    <input id="variableNameToUpload" type="text" placeholder="Form Variable: Name" />
    <br />
    <input id="variableValueToUpload" type="text" placeholder="Form Variable: Value" />
    <br />
    <input id="fileNameToUpload" type="text" placeholder="Select A File..." /><button onclick="chooseFile()">Select File</button><button onclick="clearFile()">Reset</button>
    <br />
    <button onclick="testAJAXUpload()">Test AJAX Upload</button>
    <script type="text/javascript">
            initialize();
    </script>
</body>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a file and user data that is being posted from Multipart/form data to a post method in my apicontroller class.
I am able to read the file without any problems but unable to read user data.

I tried couple of things like using model binding, passing the individual fields as a method parameter in the post method but i get: No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'multipart/form-data'.

var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
foreach (var item in provider.Contents)
{
    var fieldName = item.Headers.ContentDisposition.Name.Trim('"');
    if (item.Headers.ContentDisposition.FileName == null)
    {
        var data = await item.ReadAsStringAsync();
        if (fieldname == "name")
        {
            Name = data;
        }
        else
        {
            fileContents = await item.ReadAsByteArrayAsync();
        }
    }
}

Thanks.

Body:
It seems to me the OP, was really close.  This is some code that tries to clearly show how to get the form variables, as well as the file upload data.

First the ApiController:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    public class FormAndFileDataController : ApiController
    {
        private class FormItem
        {
            public FormItem() { }
            public string name { get; set; }
            public byte[] data { get; set; }
            public string fileName { get; set; }
            public string mediaType { get; set; }
            public string value { get { return Encoding.Default.GetString(data); } }
            public bool isAFileUpload { get { return !String.IsNullOrEmpty(fileName); } }
        }

        /// <summary>
        /// An ApiController to access an AJAX form post.
        /// </summary>
        /// <remarks>
        ///
        /// </remarks>
        /// <returns></returns>
        public async Task<HttpResponseMessage> Post()
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            var formItems = new List<FormItem>();

            // Scan the Multiple Parts
            foreach (HttpContent contentPart in provider.Contents)
            {
                var formItem = new FormItem();
                var contentDisposition = contentPart.Headers.ContentDisposition;
                formItem.name = contentDisposition.Name.Trim('"');
                formItem.data = await contentPart.ReadAsByteArrayAsync();
                formItem.fileName = String.IsNullOrEmpty(contentDisposition.FileName) ? "" : contentDisposition.FileName.Trim('"');
                formItem.mediaType = contentPart.Headers.ContentType == null ? "" : String.IsNullOrEmpty(contentPart.Headers.ContentType.MediaType) ? "" : contentPart.Headers.ContentType.MediaType;
                formItems.Add(formItem);
            }

            // We now have a list of all the distinct items from the *form post*.
            // We can now decide to do something with the items.
            foreach (FormItem formItemToProcess in formItems)
            {
                if (formItemToProcess.isAFileUpload)
                {

                    // This is a file. Do something with the file.  Write it to disk, store in a database.  Whatever you want to do.

                    // The name the client used to identify the *file* input element of the *form post* is stored in formItem.name.
                    // The *suggested* file name from the client is stored in formItemToProcess.fileName
                    // The media type (MimeType) of file (as far as the client knew) if available, is stored in formItemToProcess.mediaType
                    // The file data is stored in the byte[] formItemToProcess.data

                }
                else
                {
                    // This is a form variable.  Do something with the form variable.  Update a DB table, whatever you want to do.

                    // The name the client used to identify the input element of the *form post* is stored in formItem.name.
                    // The value the client input element is stored in formItem.value.

                }
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

    }
}

and the MVC View to test it:

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script type="text/javascript">

            var hiddenForm, hiddenFile;

            function initialize() {
                // Use a hidden file element so we can control the UI
                // of the file selection interface.  The built in browser
                // UI is not localizable to different languages.
                hiddenFile = document.createElement("input");
                hiddenFile.setAttribute("type", "file");
                hiddenFile.setAttribute("style", "display: none;");

                // We don't need the form really, but it makes it easy to
                // reset the selection.
                hiddenForm = document.createElement("form");
                hiddenForm.appendChild(hiddenFile);

                hiddenFile.onchange = function () {
                    var elementToUpdate = document.getElementById("fileNameToUpload");
                    var filesToUpload = hiddenFile.files;
                    var fileToUpload = filesToUpload[0];
                    elementToUpdate.value = fileToUpload.name;
                }
                document.body.appendChild(hiddenForm);
            }
            function chooseFile() {
                hiddenFile.click();
            }

            function clearFile() {
                var elementToUpdate = document.getElementById("fileNameToUpload");
                elementToUpdate.value = "";
                hiddenForm.reset();
            }
            function testAJAXUpload() {

                // We are going to use the FormData object and jQuery
                // to do our post test.
                var formToPost = new FormData();
                var formVariableNameElement = document.getElementById("variableNameToUpload");
                var formVariableValueElement = document.getElementById("variableValueToUpload");

                var formVariableName = formVariableNameElement.value || "formVar1";
                var formVariableValue = formVariableValueElement.value || "Form Value 1";
                var filesToUpload = hiddenFile.files;
                var fileToUpload = filesToUpload[0];

                formToPost.append(formVariableName,formVariableValue)
                formToPost.append("fileUpload", fileToUpload);

                // Call the Server.
                $.ajax({
                    url: '@Url.HttpRouteUrl("DefaultApi", new { controller = "FormAndFileData" })',
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    data: formToPost,
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("Failed: [" + textStatus + "]");
                    },
                    success: function (data, textStatus, jqXHR) {
                        alert("Success.");
                    }
                });

            }

    </script>
</head>
<body>
    <input id="variableNameToUpload" type="text" placeholder="Form Variable: Name" />
    <br />
    <input id="variableValueToUpload" type="text" placeholder="Form Variable: Value" />
    <br />
    <input id="fileNameToUpload" type="text" placeholder="Select A File..." /><button onclick="chooseFile()">Select File</button><button onclick="clearFile()">Reset</button>
    <br />
    <button onclick="testAJAXUpload()">Test AJAX Upload</button>
    <script type="text/javascript">
            initialize();
    </script>
</body>
</html>


问:
How to get a RSAPrivateCrtKey from a RSAPrivateKey?
I have a java.security.interfaces.RSAPrivateKey and the corresponding java.security.interfaces.RSAPublicKey containing (only) modulus, private exponent and public exponent.

If I understand RSA right, it should be possible to recover the numbers for java.security.interfaces.RSAPrivateCrtKey (for CRT keys).

If so, how do I do it? (I assume there is some implementation already).

答:
It is possible to do this, and there is a relatively fast algorithm to find the parameters. Here is some Java code that illustrates the algorithm.

The code below is my implementation of the algorithm specified in Chapter 8 of the Handbook of Applied Cryptography, by A. Menezes, P. van Oorschot, and S. Vanstone, CRC Press, 1996, section 8.2.2(i):

```<code>/**
 * Find a factor of n by following the algorithm outlined in Handbook of Applied Cryptography, section
 * 8.2.2(i). See https://cacr.uwaterloo.ca/hac/about/chap8.pdf.
 *
 */

private static BigInteger findFactor(BigInteger e, BigInteger d, BigInteger n) {
    BigInteger edMinus1 = e.multiply(d).subtract(BigInteger.ONE);
    int s = edMinus1.getLowestSetBit();
    BigInteger t = edMinus1.shiftRight(s);

    for (int aInt = 2; true; aInt++) {
        BigInteger aPow = BigInteger.valueOf(aInt).modPow(t, n);
        for (int i = 1; i <= s; i++) {
            if (aPow.equals(BigInteger.ONE)) {
                break;
            }
            if (aPow.equals(n.subtract(BigInteger.ONE))) {
                break;
            }
            BigInteger aPowSquared = aPow.multiply(aPow).mod(n);
            if (aPowSquared.equals(BigInteger.ONE)) {
                return aPow.subtract(BigInteger.ONE).gcd(n);
            }
            aPow = aPowSquared;
        }
    }

}

public static RSAPrivateCrtKey createCrtKey(RSAPublicKey rsaPub, RSAPrivateKey rsaPriv) throws NoSuchAlgorithmException, InvalidKeySpecException {

    BigInteger e = rsaPub.getPublicExponent();
    BigInteger d = rsaPriv.getPrivateExponent();
    BigInteger n = rsaPub.getModulus();
    BigInteger p = findFactor(e, d, n);
    BigInteger q = n.divide(p);
    if (p.compareTo(q) > 0) {
        BigInteger t = p;
        p = q;
        q = t;
    }
    BigInteger exp1 = d.mod(p.subtract(BigInteger.ONE));
    BigInteger exp2 = d.mod(q.subtract(BigInteger.ONE));
    BigInteger coeff = q.modInverse(p);
    RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, exp1, exp2, coeff);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPrivateCrtKey) kf.generatePrivate(keySpec);

}
</code>```

Body:
It is possible to do this, and there is a relatively fast algorithm to find the parameters. Here is some Java code that illustrates the algorithm.

The code below is my implementation of the algorithm specified in Chapter 8 of the Handbook of Applied Cryptography, by A. Menezes, P. van Oorschot, and S. Vanstone, CRC Press, 1996, section 8.2.2(i):

/**
 * Find a factor of n by following the algorithm outlined in Handbook of Applied Cryptography, section
 * 8.2.2(i). See https://cacr.uwaterloo.ca/hac/about/chap8.pdf.
 *
 */

private static BigInteger findFactor(BigInteger e, BigInteger d, BigInteger n) {
    BigInteger edMinus1 = e.multiply(d).subtract(BigInteger.ONE);
    int s = edMinus1.getLowestSetBit();
    BigInteger t = edMinus1.shiftRight(s);

    for (int aInt = 2; true; aInt++) {
        BigInteger aPow = BigInteger.valueOf(aInt).modPow(t, n);
        for (int i = 1; i <= s; i++) {
            if (aPow.equals(BigInteger.ONE)) {
                break;
            }
            if (aPow.equals(n.subtract(BigInteger.ONE))) {
                break;
            }
            BigInteger aPowSquared = aPow.multiply(aPow).mod(n);
            if (aPowSquared.equals(BigInteger.ONE)) {
                return aPow.subtract(BigInteger.ONE).gcd(n);
            }
            aPow = aPowSquared;
        }
    }

}

public static RSAPrivateCrtKey createCrtKey(RSAPublicKey rsaPub, RSAPrivateKey rsaPriv) throws NoSuchAlgorithmException, InvalidKeySpecException {

    BigInteger e = rsaPub.getPublicExponent();
    BigInteger d = rsaPriv.getPrivateExponent();
    BigInteger n = rsaPub.getModulus();
    BigInteger p = findFactor(e, d, n);
    BigInteger q = n.divide(p);
    if (p.compareTo(q) > 0) {
        BigInteger t = p;
        p = q;
        q = t;
    }
    BigInteger exp1 = d.mod(p.subtract(BigInteger.ONE));
    BigInteger exp2 = d.mod(q.subtract(BigInteger.ONE));
    BigInteger coeff = q.modInverse(p);
    RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, exp1, exp2, coeff);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPrivateCrtKey) kf.generatePrivate(keySpec);

}


问:
Will F# perform well when writing math functions for a C# program?
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered here, but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places.

Edit:

It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point here was the following answer:

F# provides some performance-related
  features that can make a difference.

Firstly, the implementation of
  delegates on .NET is currently quite
  inefficient and, consequently, F# uses
  its own FastFunc type for
  high-performance first-class
  functions.

Secondly, F# uses .NET metadata to
  convey inline functions so that they
  can be exported across APIs and, of
  course, that can dramatically improve
  performance in certain circumstances.

Finally, pattern matching can be
  extremely laborious to express in C#
  because the language lacks pattern
  matching but it is almost impossible
  to maintain optimized C# code
  equivalent to many non-trivial pattern
  matches. In contrast, the F# compiler
  aggressively optimizes pattern matches
  during compilation.

Conversely, the C# compiler is better
  at optimizing loops using IEnumerables
  and is better at optimizing
  computations over value types (e.g.
  complex arithmetic).

Cheers, Jon Harrop.

答: My initial reaction is that the performance will be the same due to both C# and F# outputting MSIL. But the structures you use might turn out different IL. The topic has been discussed in detail at the links here on SO.</p>

OwnerDisplayName: Morten Christiansen

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: olle


问:
How to break a while loop in C on linux by taking any value from keyboard?
The program I am building runs in an infinite while loop with a switch case in it. I want to insert a while loop under each case and perform few operations in the loop, but the loop should exit as soon as a keyboard input is given. So that after taking the input from keyboard another case is run with the nested while loop in it, and the process continues.

The structure is:

```<code>while()//infinite loop
    {
    ...............      //operations
    ...............      //operations
    switch()
        {
        case 1:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;

        case 2:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;

        case n:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;
        }
  }
</code>```

Is there any way to do it???

答:
I had a similar desire for an old system that I have to maintain.  I wanted to add a "quit" as well as provide some timing. I stripped out all proprietary code and left the shell of what I learned from this site. Thank you.

I ended up using the above example by ring0. I wanted to comment but I'm not at that level yet.

I also took some information from here by Ulf and Walter

I could not use fcntl because of a global variable that was used in our code that conflicted with something within fcntl and I did not want to figure out how to avoid that conflict.

Anyway, here is an example. It worked for me on Debian (older version). Your mileage may vary.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>

#define SLEEP  500000. /*usec*/

#include <termios.h>
struct termios stdin_orig;

void term_reset() {
  tcsetattr(STDIN_FILENO, TCSANOW, &stdin_orig);
  tcsetattr(STDIN_FILENO, TCSAFLUSH, &stdin_orig);
}

void term_nonblocking() {
  struct termios term;
  tcgetattr(STDIN_FILENO, &stdin_orig);
  term = stdin_orig;
  term.c_iflag |= IGNBRK;
  //term.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
  term.c_lflag &= ~(ICANON);// | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);*/
  term.c_cc[VMIN] = 0;
  term.c_cc[VTIME] = 0;
  /*   fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // non-blocking */
  tcsetattr(STDIN_FILENO, TCSANOW, &term);
}
// end mikes timing

int main (void)
{
  int key=0;
  // mikes test variables
  long mnloops = 0;
  double mttot = 0.0;//total time elapsed in difference between start-end.
  term_nonblocking();
  // end mikes test variables

  /*main loop*/
  do{
    //mikes timing
    puts("Start Do");
    time_t mnow;
    struct timeval mtv;
    struct timezone mtz;
    time(&mnow);
    gettimeofday(&mtv, &mtz);
    double startTime = (double)mnow + mtv.tv_usec/1e6;
    // end mikes timing
    usleep(SLEEP);
    puts("got hey");
    //mikes timing
    time(&mnow);
    gettimeofday(&mtv, &mtz);
    mttot += (((double)mnow + mtv.tv_usec/1e6) - startTime);
    mnloops++;
    key = getchar();
    // end mikes timing
  }while (1 && key != 'q');/* end of main loop*/
  term_reset();
  printf("DONE: average time per loop = %-10.4e\n",mttot/mnloops);
  return 0;
}
</code>```

Body:
The program I am building runs in an infinite while loop with a switch case in it. I want to insert a while loop under each case and perform few operations in the loop, but the loop should exit as soon as a keyboard input is given. So that after taking the input from keyboard another case is run with the nested while loop in it, and the process continues.

The structure is:

while()//infinite loop
    {
    ...............      //operations
    ...............      //operations
    switch()
        {
        case 1:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;

        case 2:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;

        case n:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;
        }
  }

Is there any way to do it???

Body:
I had a similar desire for an old system that I have to maintain.  I wanted to add a "quit" as well as provide some timing. I stripped out all proprietary code and left the shell of what I learned from this site. Thank you.

I ended up using the above example by ring0. I wanted to comment but I'm not at that level yet.

I also took some information from here by Ulf and Walter

I could not use fcntl because of a global variable that was used in our code that conflicted with something within fcntl and I did not want to figure out how to avoid that conflict.

Anyway, here is an example. It worked for me on Debian (older version). Your mileage may vary.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>

#define SLEEP  500000. /*usec*/

#include <termios.h>
struct termios stdin_orig;

void term_reset() {
  tcsetattr(STDIN_FILENO, TCSANOW, &stdin_orig);
  tcsetattr(STDIN_FILENO, TCSAFLUSH, &stdin_orig);
}

void term_nonblocking() {
  struct termios term;
  tcgetattr(STDIN_FILENO, &stdin_orig);
  term = stdin_orig;
  term.c_iflag |= IGNBRK;
  //term.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
  term.c_lflag &= ~(ICANON);// | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);*/
  term.c_cc[VMIN] = 0;
  term.c_cc[VTIME] = 0;
  /*   fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // non-blocking */
  tcsetattr(STDIN_FILENO, TCSANOW, &term);
}
// end mikes timing

int main (void)
{
  int key=0;
  // mikes test variables
  long mnloops = 0;
  double mttot = 0.0;//total time elapsed in difference between start-end.
  term_nonblocking();
  // end mikes test variables

  /*main loop*/
  do{
    //mikes timing
    puts("Start Do");
    time_t mnow;
    struct timeval mtv;
    struct timezone mtz;
    time(&mnow);
    gettimeofday(&mtv, &mtz);
    double startTime = (double)mnow + mtv.tv_usec/1e6;
    // end mikes timing
    usleep(SLEEP);
    puts("got hey");
    //mikes timing
    time(&mnow);
    gettimeofday(&mtv, &mtz);
    mttot += (((double)mnow + mtv.tv_usec/1e6) - startTime);
    mnloops++;
    key = getchar();
    // end mikes timing
  }while (1 && key != 'q');/* end of main loop*/
  term_reset();
  printf("DONE: average time per loop = %-10.4e\n",mttot/mnloops);
  return 0;
}