问:
Python, replacing characters in a string while preserving original string
More specifically:

Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

```<code>def(base,word):
plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
</code>```

My original thought was this:

```<code>def main():

    x = base.split(word)
    y = ''.join(x)
    print(y.replace(y,'+')*len(y))
</code>```

From here I have trouble reinserting the word back into the str in the correct places. Any help is appreciated.

答:
A regex is not required. We can solve this without any libraries, iterating through exactly once.

We want to iterate through the indices i of the string, yielding the word and jumping ahead by len(word) if the slice of len(word) starting at i matches the word, and by yielding '+' and incrementing by one otherwise.

```<code>def replace_chars_except_word(string, word):
    def generate_chars():
        i = 0
        while i < len(string):
            if string[i:(i+len(word))] == word:
                i += len(word)
                yield word
            else:
                yield '+'
                i+= 1
    return ''.join(generate_chars())

if __name__ == '__main__':
    test_string = 'stringabcdefg string11010string1'
    result = replace_chars_except_word(test_string, word = 'string')
    assert result == 'string++++++++string+++++string+'
</code>```

I use an internal generator function to yield the strings, but you could use a buffer to replace the internal function. (This is slightly less memory efficient).

buffer = []
if (condition)
    buffer.append(word)
else:
    buffer.append'+'
return ''.join(buffer)

Body:
More specifically:

Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

def(base,word):
plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

My original thought was this:

def main():

    x = base.split(word)
    y = ''.join(x)
    print(y.replace(y,'+')*len(y))

From here I have trouble reinserting the word back into the str in the correct places. Any help is appreciated.

Body:
A regex is not required. We can solve this without any libraries, iterating through exactly once.

We want to iterate through the indices i of the string, yielding the word and jumping ahead by len(word) if the slice of len(word) starting at i matches the word, and by yielding '+' and incrementing by one otherwise.

def replace_chars_except_word(string, word):
    def generate_chars():
        i = 0
        while i < len(string):
            if string[i:(i+len(word))] == word:
                i += len(word)
                yield word
            else:
                yield '+'
                i+= 1
    return ''.join(generate_chars())

if __name__ == '__main__':
    test_string = 'stringabcdefg string11010string1'
    result = replace_chars_except_word(test_string, word = 'string')
    assert result == 'string++++++++string+++++string+'

I use an internal generator function to yield the strings, but you could use a buffer to replace the internal function. (This is slightly less memory efficient).

buffer = []
if (condition)
    buffer.append(word)
else:
    buffer.append'+'
return ''.join(buffer)


来源: stackexchange

问:
R weatherData Detroit station error
I keep getting errors in my attempt to pull weather data for Detroit airport. I am able to manually go to wunderground.com to get the historical hourly data, so it does exist there for Detroit location. But R package keeps sending me errors. I used "KDTW" for the airport code but it did not work. I tried "72537" for the station ID, which I got by using  getStationCode("Detroit). I will appreciate any help with getting hour historical data for any close to Detroit station for the time interval January 1, 2017 through March 28, 2017.

Here is what I tried:

```<code> install.packages("weatherData")
 library ('weatherData')

getStationCode("Detroit")
checkDataAvailabilityForDateRange(station_type ="KARB", start_date="2017-01-01", end_date="2017-03-28")
checkDataAvailabilityForDateRange(station_id ="KDTW", start_date="2017-01-01", end_date="2017-03-28")
</code>```

Thank you!

答:
I was able to get the weather data for KDTW.
temp <- getWeatherForDate(station_id = "KDTW", start_date = "2017-01-01", end_date="2017-01-10")

Here is my output for the date range

```<code>structure(c("Min.   :2017-01-01 00:00:00  ", "1st Qu.:2017-01-03 06:00:00  ",
"Median :2017-01-05 12:00:00  ", "Mean   :2017-01-05 12:00:00  ",
"3rd Qu.:2017-01-07 18:00:00  ", "Max.   :2017-01-10 00:00:00  ",
"Min.   :17.0  ", "1st Qu.:18.5  ", "Median :34.5  ", "Mean   :31.9  ",
"3rd Qu.:42.5  ", "Max.   :49.0  ", "Min.   :11.00  ", "1st Qu.:13.75  ",
"Median :26.50  ", "Mean   :25.20  ", "3rd Qu.:34.25  ", "Max.   :41.00  ",
"Min.   : 5.0  ", "1st Qu.: 9.0  ", "Median :17.5  ", "Mean   :18.2  ",
"3rd Qu.:26.0  ", "Max.   :37.0  "), .Dim = c(6L, 4L), .Dimnames = list(
    c("", "", "", "", "", ""), c("     Date", "Max_TemperatureF",
    "Mean_TemperatureF", "Min_TemperatureF")), class = "table")
</code>```

I just got temperature data, but if you'd like, you can also get other information (like humidity, cloud cover, etc) by changing the opt_all_columns flag to TRUE.

Hope that Helps!

Edit: Looking at your code you have station_type ="KARB" Did you mean that to be station_id?

ContentLicense: CC BY-SA 3.0

Title: R weatherData Detroit station error

Body:
I keep getting errors in my attempt to pull weather data for Detroit airport. I am able to manually go to wunderground.com to get the historical hourly data, so it does exist there for Detroit location. But R package keeps sending me errors. I used "KDTW" for the airport code but it did not work. I tried "72537" for the station ID, which I got by using  getStationCode("Detroit). I will appreciate any help with getting hour historical data for any close to Detroit station for the time interval January 1, 2017 through March 28, 2017.

Here is what I tried:

 install.packages("weatherData")
 library ('weatherData')

getStationCode("Detroit")
checkDataAvailabilityForDateRange(station_type ="KARB", start_date="2017-01-01", end_date="2017-03-28")
checkDataAvailabilityForDateRange(station_id ="KDTW", start_date="2017-01-01", end_date="2017-03-28")

Thank you!

Body:
I was able to get the weather data for KDTW.
temp <- getWeatherForDate(station_id = "KDTW", start_date = "2017-01-01", end_date="2017-01-10")

Here is my output for the date range

structure(c("Min.   :2017-01-01 00:00:00  ", "1st Qu.:2017-01-03 06:00:00  ",
"Median :2017-01-05 12:00:00  ", "Mean   :2017-01-05 12:00:00  ",
"3rd Qu.:2017-01-07 18:00:00  ", "Max.   :2017-01-10 00:00:00  ",
"Min.   :17.0  ", "1st Qu.:18.5  ", "Median :34.5  ", "Mean   :31.9  ",
"3rd Qu.:42.5  ", "Max.   :49.0  ", "Min.   :11.00  ", "1st Qu.:13.75  ",
"Median :26.50  ", "Mean   :25.20  ", "3rd Qu.:34.25  ", "Max.   :41.00  ",
"Min.   : 5.0  ", "1st Qu.: 9.0  ", "Median :17.5  ", "Mean   :18.2  ",
"3rd Qu.:26.0  ", "Max.   :37.0  "), .Dim = c(6L, 4L), .Dimnames = list(
    c("", "", "", "", "", ""), c("     Date", "Max_TemperatureF",
    "Mean_TemperatureF", "Min_TemperatureF")), class = "table")

I just got temperature data, but if you'd like, you can also get other information (like humidity, cloud cover, etc) by changing the opt_all_columns flag to TRUE.

Hope that Helps!

Edit: Looking at your code you have station_type ="KARB" Did you mean that to be station_id?


问:
Is there a Google DFP api to check whether an ad units is active or not?
Is there a Google DFP api to check whether an ad unit is active or not ?

Any suggestions are appreciated! Thanks

答:
It depends on what you mean by "whether an ad unit is active or not". In general it's best to be as descriptive as posible in questions and to include what you've already tried, it saves time in the answers. I'll do my best.

If you're trying to debug whether it was properly loaded on the site, then I'd suggest you debug using the DoubleClick Publisher Console, which you can activate by adding ?googfc to the end of the URL. In there you can check which ad units are called and their status, and you can also follow the execution on the History tab inside the console.

You could also use the Google Publisher Toolbar chrome extension, which has some more information on the ad being rendered, the line item, etc.

Moreover, you could set up an event listener and render information to the developer console.

```<code>googletag.pubads().addEventListener('slotRenderEnded', function(event) {
        console.info(event);
    }
});
</code>```

This code should be included inside the googlgoogletag.cmd.push(function() {}) and below the slot definitions (e.g.: the method defineSlot()).

However, if you want to do is programatically check if an ad unit is active prior to calling it or defining it, then I think you should rephrase the question to be a bit more specific.

Body:
It depends on what you mean by "whether an ad unit is active or not". In general it's best to be as descriptive as posible in questions and to include what you've already tried, it saves time in the answers. I'll do my best.

If you're trying to debug whether it was properly loaded on the site, then I'd suggest you debug using the DoubleClick Publisher Console, which you can activate by adding ?googfc to the end of the URL. In there you can check which ad units are called and their status, and you can also follow the execution on the History tab inside the console.

You could also use the Google Publisher Toolbar chrome extension, which has some more information on the ad being rendered, the line item, etc.

Moreover, you could set up an event listener and render information to the developer console.

googletag.pubads().addEventListener('slotRenderEnded', function(event) {
        console.info(event);
    }
});

This code should be included inside the googlgoogletag.cmd.push(function() {}) and below the slot definitions (e.g.: the method defineSlot()).

However, if you want to do is programatically check if an ad unit is active prior to calling it or defining it, then I think you should rephrase the question to be a bit more specific.


问:
vDSP fft computation good practice
In order to compute the FFT with Accelerate framework, I see a lot of people using (the old way I guess) fft_zrip instead of the recommended one by Apple in the vDSP documentation DSP_DFT_Execute.

Is there any reason why DSP_DFT_Execute is so under used?

答: Actually for real-to-complex FFT both vDSP_fft_zrip and DSP_DFT_Execute  require data in split even-odd format.

Title: vDSP fft computation good practice


问:
WordPress Button triggered ajax request
So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.

My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code

```<code>echo '<button id="ZapisPrace">Save</button>
<script>
jQuery("#ZapisPrace").click(function($){
    var data={
        action: "addToDB",
        info: "nomz"
    };
    jQuery.post(ajaxurl,data,function(response){
    alert("Response was "+ response);
    });
});
</script>';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
    echo '<script>console.log("AAA")</script>';
    wp_die();
}
</code>```

Using current version of WP so variable ajaxurl is pointing to the

/wordpress/wp-admin/admin-ajax.php

No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why?
Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.

PS: I am supposed to use the WP way of using ajax.

答:
Change php code as follows.</p>

```<code>add_action('wp_ajax_addToDB','addToDB');
function addToDB(){
    echo "AAA";
    wp_die();
}
</code>```

Title: WordPress Button triggered ajax request

Body:
So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.

My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code

echo '<button id="ZapisPrace">Save</button>
';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
    echo '';
    wp_die();
}

Using current version of WP so variable ajaxurl is pointing to the

/wordpress/wp-admin/admin-ajax.php

No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why?
Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.

PS: I am supposed to use the WP way of using ajax.

Body:
Change php code as follows.

add_action('wp_ajax_addToDB','addToDB');
function addToDB(){
    echo "AAA";
    wp_die();
}


问:
Python matcher not matching
I'm trying to write a very simple regex script in python that matches all lowercase characters, but the matcher is returning "None"

Here's my code:

```<code>p = re.compile('[a-z]+')
print(p.match('This is a test'))
p
</code>```

答:
match starts matching at the beginning of a string. Your string starts with a capital letter, so it doesn't match it and gives up.

Perhaps you wanted findall?

```<code>>>> p = re.compile('[a-z]+')
>>> print(p.findall('This is a test'))
['his', 'is', 'a', 'test']
</code>```

Title: Python matcher not matching

Body:
I'm trying to write a very simple regex script in python that matches all lowercase characters, but the matcher is returning "None"

Here's my code:

p = re.compile('[a-z]+')
print(p.match('This is a test'))
p

Body:
match starts matching at the beginning of a string. Your string starts with a capital letter, so it doesn't match it and gives up.

Perhaps you wanted findall?

>>> p = re.compile('[a-z]+')
>>> print(p.findall('This is a test'))
['his', 'is', 'a', 'test']


问:
How to add values in a 2d matrix with same first index (c++)
I have a set of values stored in a 2d matrix.  I want to create separate totals for the values which have the same first index.  Here's a short example:

```<code>typedef int matrix [9][9];
matrix sampleMatrix;

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   for (int j = 0; j < 9; j++){
        //here's where I'm stuck
        //if i = 1, then total all values with i = 1 etc.
        if(sampleMatrix[i]){
        int sum = sum + sampleMatrix[i][j];
        }
        std::cout << i << " Total: " << sum << std::endl;
   }

}
</code>```

Thanks for any help.

答: Build a integer array of the length 9 like int sums [9] and initialize each entry with 0. In your double for loop, for every sampleMatrix [i][j] entry, add it to the corresponding entry of the sums array, like sums [i] += sampleMatrix [i][j]</p>

Body:
I have a set of values stored in a 2d matrix.  I want to create separate totals for the values which have the same first index.  Here's a short example:

typedef int matrix [9][9];
matrix sampleMatrix;

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   for (int j = 0; j < 9; j++){
        //here's where I'm stuck
        //if i = 1, then total all values with i = 1 etc.
        if(sampleMatrix[i]){
        int sum = sum + sampleMatrix[i][j];
        }
        std::cout << i << " Total: " << sum << std::endl;
   }

}

Thanks for any help.


问:
Azure Site Recovery - REST API, Powershell and Automation
Has anyone come up with a complete solution to protect and replicate VMs from on-prem (either VMware or HyperV) to Azure using either the REST API or the Powershell module?

I recently completed a POC with ASR and was able to replicate a couple dozen VMs associated with three different applications.  I replicated out of VMware and into Azure.  I was able to failover and failback successfully.

I did all of the POC work using the GUI (portal.azure.com).  Now I have to figure out how to protect ~2000 VMs and there is no way that I am going to do that with the GUI.  But the MS documentation has me running in circles.

(https://learn.microsoft.com/en-us/azure/site-recovery/)

It would be very helpful if any of you can share the sequence of steps to protect and replicate a VM.  The MS documentation does not lay out how the various components (fabrics, protection policies, protection containers, protection items, etc.) are related to each other.

I do not need specific syntax.  The documentation does a passable job of detailing the syntax.  I could use some guidance on the task sequence.

If it helps to understand the bigger picture, my intention is to use a System Center Orchestrator runbook to ingest a CSV list of VMs, parse that out into input for the Azure REST API / Powershell, and then enable protection.

Thanks in advance for any assistance or guidance that you are able to provide.

答:
You can find recovery service API documentation here:

https://learn.microsoft.com/en-us/rest/api/recoveryservices/

When you have one definition put in place(manually from portal), you may also be able to study it from resource.azure.com to see how properties are composited. *not all resource available thru this portal

After that, you should be able to create template for either REST call or Resource Manager, depending on preference.


问:
How to check the password from an EditView?
I use an EditText with android:password="true" to let the user type the password. Then I want to compare the password with a hard coded password when the user presses a button.

But I can't compare the password with a String "mypassword". Here is the code I use to check the password:

```<code>EditText pw = (EditText) findViewById(R.id.pwdTxt);
if(pw.getText().equals("mypassword")) {
    Intent i = new Intent(LoginActivity.this, LinkpageActivity.class);
    startActivity(i);
} else {
    // Wrong password
}
</code>```

The comparison pw.getText().equals("mypassword") returns false even if I type the correct password. How should I check the password from an EditText?

答:
Maybe you could try</p>

```<code>pw.getText().toString().equals("mypassword")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I use an EditText with android:password="true" to let the user type the password. Then I want to compare the password with a hard coded password when the user presses a button.

But I can't compare the password with a String "mypassword". Here is the code I use to check the password:

EditText pw = (EditText) findViewById(R.id.pwdTxt);
if(pw.getText().equals("mypassword")) {
    Intent i = new Intent(LoginActivity.this, LinkpageActivity.class);
    startActivity(i);
} else {
    // Wrong password
}

The comparison pw.getText().equals("mypassword") returns false even if I type the correct password. How should I check the password from an EditText?

Body:
Maybe you could try

pw.getText().toString().equals("mypassword")


问:
All nodejs functions asyncronously running?
I was trying to learn about async/promises/callbacks/js modules/etc... However, when I was trying to run a simple module which only required a file, and ran a function that only returned the parameter back, node was not outputting the result correctly. By this I mean that it would only sometimes return the value, and sometimes not.

I am pretty new so I could be wrong, but from what I understand this is async in node(?). But while researching I was only finding functions which do things like load, wait, timeout, etc. in lists for things that use async. But it seems that everything I run in node, no matter how simple runs with async and will not consistently output values? Here is an example of what I ran and recieved in the node console:

```<code>> function test(input){
... return input;
... }
> test('a')

> test('a')
'a'
>
> test(5)

> test(5)
5
>
</code>```

Like I said, I was working on learning about a few things, but it started by looking into modules, so I was also wondering what a common 'pattern'(?) for handling this is, when exporting modules. Thanks.

Edit:

I'm not sure if I made it very clear, but for the most part I was really just wondering why a function as simple as this wouldn't be working, when the only functions I have seen people talk about async with are functions that are obviously waiting, in a sense. Not simple functions like this. I havent tried putting a callback with this yet, but I assume that works. I just didn't think you needed them for functions as simple as this?

答:
This is how the same input in the Node REPL works for me:

```<code>> function test(input){
... return input;
... }
undefined
> test('a')
'a'
> test('a')
'a'
> test(5)
5
> test(5)
5
>
</code>```

The test() function is not asynchronous in your example. It returns the value synchronously. The REPL session that you included doesn't seem rea, though, as your function definition should return undefined like in my example.

To answer your question: Not all of Node functions have to be asynchronous. Every function that simply return a value is synchronous - like e.g. Math.sin() etc.

For a better understanding of all this, take a look at this answer that shows examples of both synchronous and asynchronous functions, explaining the order of execution step by step:

Node.js: Asynchronous Callback Execution. Is this Zalgo?

Body:
I was trying to learn about async/promises/callbacks/js modules/etc... However, when I was trying to run a simple module which only required a file, and ran a function that only returned the parameter back, node was not outputting the result correctly. By this I mean that it would only sometimes return the value, and sometimes not.

I am pretty new so I could be wrong, but from what I understand this is async in node(?). But while researching I was only finding functions which do things like load, wait, timeout, etc. in lists for things that use async. But it seems that everything I run in node, no matter how simple runs with async and will not consistently output values? Here is an example of what I ran and recieved in the node console:

> function test(input){
... return input;
... }
> test('a')

> test('a')
'a'
>
> test(5)

> test(5)
5
>

Like I said, I was working on learning about a few things, but it started by looking into modules, so I was also wondering what a common 'pattern'(?) for handling this is, when exporting modules. Thanks.

Edit:

I'm not sure if I made it very clear, but for the most part I was really just wondering why a function as simple as this wouldn't be working, when the only functions I have seen people talk about async with are functions that are obviously waiting, in a sense. Not simple functions like this. I havent tried putting a callback with this yet, but I assume that works. I just didn't think you needed them for functions as simple as this?

Body:
This is how the same input in the Node REPL works for me:

> function test(input){
... return input;
... }
undefined
> test('a')
'a'
> test('a')
'a'
> test(5)
5
> test(5)
5
>

The test() function is not asynchronous in your example. It returns the value synchronously. The REPL session that you included doesn't seem rea, though, as your function definition should return undefined like in my example.

To answer your question: Not all of Node functions have to be asynchronous. Every function that simply return a value is synchronous - like e.g. Math.sin() etc.

For a better understanding of all this, take a look at this answer that shows examples of both synchronous and asynchronous functions, explaining the order of execution step by step:

Node.js: Asynchronous Callback Execution. Is this Zalgo?


问:
jQuery - Detect value change which use .val() function
We all know that use the val() will not trigger the change event, so we also use .trigger('change') behind the val().

But the problem is that someone write the val() did't with trigger() and it's a external file that I can't edit it.

So, how can I detect value change through some code same like below:

```<code>$('.elem').on('change', function(){
   // do something
});
</code>```

答:
```<code>var originalValFn = jQuery.fn.val;

function getErrorObject(){
    try { throw Error('') } catch(err) { return err; }
}

jQuery.fn.val = function() {
    if ($(this).hasClass( "element" )) {
        var err = getErrorObject();
        var caller_line = err.stack.split("\n")[4];
        var index = caller_line.indexOf("at ");
        var clean = caller_line.slice(index+2, caller_line.length);

        console.log(clean);
        console.log(arguments);
    }
    originalValFn.apply( this, arguments );
};
</code>```

Body:
We all know that use the val() will not trigger the change event, so we also use .trigger('change') behind the val().

But the problem is that someone write the val() did't with trigger() and it's a external file that I can't edit it.

So, how can I detect value change through some code same like below:

$('.elem').on('change', function(){
   // do something
});


问:
To draw some points by using QImage, QWidget.update() is too slow, Is there more faster way?
I'm trying to draw a point on the window by using QImage, and update the position of this point as fast as possible(less than 1ms every update). I've wrote the code below and run it, but the result is it's too slow(about 50ms every update). I searched the bottleneck and found the cause of this slowness is calling QWidget.update() takes too long. So I figured out as long as using Widget.update() it won't be faster. So I think I need another way. Is there any faster way to do this? All of the codes and the result are the following.

result:

qimageBehaviorForStackOverflowQuestion.pro

```<code>######################################################################
# Automatically generated by qmake (3.1) Wed Mar 29 15:18:09 2017
######################################################################

TEMPLATE = app
TARGET = qimageBehaviorForStackOverflowQuestion
INCLUDEPATH += .
QT += widgets

# Input
HEADERS += qimageBehaviorForStackOverflowQuestion.h
SOURCES += qimageBehaviorForStackOverflowQuestion.cpp
</code>```

qimageBehaviorForStackOverflowQuestion.h

```<code>#include <iostream>
#include <QApplication>
#include <QWidget>
#include <QTimer>
#include <QPainter>
#include <QPushButton>
#include <QImage>
#include <QTime>

class MyWidget : public QWidget {
  Q_OBJECT
 private:
  QImage *image;
  int px, py;
  uchar d[100*100*4];
  QTimer *timer;
  QTime time;
public:
  MyWidget();
  void paintEvent(QPaintEvent * event);
public slots:
  void doPaint();
};
</code>```

qimageBehaviorForStackOverflowQuestion.cpp

```<code>#include "qimageBehaviorForStackOverflowQuestion.h"

int my_counter = 0;

MyWidget::MyWidget() : QWidget(0), px(0), py(0){
  image = new QImage(d, 100, 100, QImage::Format_ARGB32);
  for(int cnt = 0, a, r, g, b; cnt < 100*100*4;){
    a = 255; //alpha
    r = 0;   //red
    g = 0;   //green
    b = 0;   //blue

    d[cnt] = b; cnt++;
    d[cnt] = g; cnt++;
    d[cnt] = r; cnt++;
    d[cnt] = a; cnt++;
  }
  // connect QTimer.timeout to my doPaint method
  timer = new QTimer();
  connect(timer, SIGNAL(timeout()), this, SLOT(doPaint()));
  timer->start(1);
};

void MyWidget::doPaint(){
  // manipulate the positions of the points
  if(px < 100){
    int cnt = 0, b = 255, g = 255, r = 255, a = 255;
    d[4 * px + cnt] = b; cnt++;
    d[4 * px + cnt] = g; cnt++;
    d[4 * px + cnt] = r; cnt++;
    d[4 * px + cnt] = a; cnt++;
    px++;
  }
  // update the window
  update();
};

void MyWidget::paintEvent(QPaintEvent * event){
    QPainter painter(this);
    painter.drawImage(0, 0, *image);
}

int main(int argc, char *argv[]){
  QApplication app(argc, argv);
  MyWidget *widget = new MyWidget();
  widget->show();
  return app.exec();
}
</code>```

答:
After googling couple of hours, I found more faster way. It becomes incredibly very fast(once 20FPS is now about 500FPS).What I'm using now is QGraphicsView Framework and QPixmap and QGraphicsPixmapItem. However I don't know this is the right or efficient way, if it isn't please correct me. And if you know there is more faster way please let me know. Any way I show you the code. I hope it could help someone who fight same problem.

qgraphicsSceneExample.h

```<code>    #include <iostream>
    #include <QApplication>
    #include <QGraphicsView>
    #include <QGraphicsScene>
    #include <QGraphicsItem>
    #include <QTimer>
    #include <QPainter>
    #include <QPushButton>
    #include <QImage>
    #include <QTime>
    #include <QStyleOptionGraphicsItem>
    #include <QWidget>
    #include <QPixmap>
    #include <QGraphicsPixmapItem>

    class MyView : public QGraphicsView {
        Q_OBJECT
    private:
        QGraphicsScene *scene;
        QImage *image;
        QPixmap *pixmap;
        QGraphicsPixmapItem *gpixmapItem;
        int px, py;
        uchar d[100*100*4];
        QTimer *timer;
        QTime time;
    public:
        MyView();
        //void paintEvent(QPaintEvent * event);
    public slots:
        void doPaint();
    };
</code>```

qgraphicsSceneExample.cpp

```<code>#include "qgraphicsSceneExample.h"

int my_counter = 0;

MyView::MyView() : px(0), py(0){

    image = new QImage(d, 100, 100, QImage::Format_ARGB32);
    for(int cnt = 0, a, r, g, b; cnt < 100*100*4;){
        a = 255; //alpha
        r = 0;   //red
        g = 0;   //green
        b = 0;   //blue

        d[cnt] = b; cnt++;
        d[cnt] = g; cnt++;
        d[cnt] = r; cnt++;
        d[cnt] = a; cnt++;
    }

    // connect QTimer.timeout to my doPaint method
    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(doPaint()));
    scene = new QGraphicsScene(0);
    pixmap = new QPixmap(QPixmap::fromImage(*image));
    gpixmapItem = scene->addPixmap(*pixmap);
    this->setScene(scene);

    timer->start(1);
};

void MyView::doPaint(){
    // manipulate the positions of the points
    if(px < 100){
        int cnt = 0, b = 255, g = 255, r = 255, a = 255;
        d[4 * px + cnt] = b; cnt++;
        d[4 * px + cnt] = g; cnt++;
        d[4 * px + cnt] = r; cnt++;
        d[4 * px + cnt] = a; cnt++;
        px++;
    }
    pixmap = new QPixmap(QPixmap::fromImage(*image));
    gpixmapItem->setPixmap(*pixmap);
    std::cout << my_counter++ << "\n";
};

int main(int argc, char *argv[]){
    QApplication app(argc, argv);
    MyView *myView = new MyView();
    myView->show();
    return app.exec();
}
</code>```

Body:
I'm trying to draw a point on the window by using QImage, and update the position of this point as fast as possible(less than 1ms every update). I've wrote the code below and run it, but the result is it's too slow(about 50ms every update). I searched the bottleneck and found the cause of this slowness is calling QWidget.update() takes too long. So I figured out as long as using Widget.update() it won't be faster. So I think I need another way. Is there any faster way to do this? All of the codes and the result are the following.

result:

qimageBehaviorForStackOverflowQuestion.pro

######################################################################
# Automatically generated by qmake (3.1) Wed Mar 29 15:18:09 2017
######################################################################

TEMPLATE = app
TARGET = qimageBehaviorForStackOverflowQuestion
INCLUDEPATH += .
QT += widgets

# Input
HEADERS += qimageBehaviorForStackOverflowQuestion.h
SOURCES += qimageBehaviorForStackOverflowQuestion.cpp

qimageBehaviorForStackOverflowQuestion.h

#include <iostream>
#include <QApplication>
#include <QWidget>
#include <QTimer>
#include <QPainter>
#include <QPushButton>
#include <QImage>
#include <QTime>

class MyWidget : public QWidget {
  Q_OBJECT
 private:
  QImage *image;
  int px, py;
  uchar d[100*100*4];
  QTimer *timer;
  QTime time;
public:
  MyWidget();
  void paintEvent(QPaintEvent * event);
public slots:
  void doPaint();
};

qimageBehaviorForStackOverflowQuestion.cpp

#include "qimageBehaviorForStackOverflowQuestion.h"

int my_counter = 0;

MyWidget::MyWidget() : QWidget(0), px(0), py(0){
  image = new QImage(d, 100, 100, QImage::Format_ARGB32);
  for(int cnt = 0, a, r, g, b; cnt < 100*100*4;){
    a = 255; //alpha
    r = 0;   //red
    g = 0;   //green
    b = 0;   //blue

    d[cnt] = b; cnt++;
    d[cnt] = g; cnt++;
    d[cnt] = r; cnt++;
    d[cnt] = a; cnt++;
  }
  // connect QTimer.timeout to my doPaint method
  timer = new QTimer();
  connect(timer, SIGNAL(timeout()), this, SLOT(doPaint()));
  timer->start(1);
};

void MyWidget::doPaint(){
  // manipulate the positions of the points
  if(px < 100){
    int cnt = 0, b = 255, g = 255, r = 255, a = 255;
    d[4 * px + cnt] = b; cnt++;
    d[4 * px + cnt] = g; cnt++;
    d[4 * px + cnt] = r; cnt++;
    d[4 * px + cnt] = a; cnt++;
    px++;
  }
  // update the window
  update();
};

void MyWidget::paintEvent(QPaintEvent * event){
    QPainter painter(this);
    painter.drawImage(0, 0, *image);
}

int main(int argc, char *argv[]){
  QApplication app(argc, argv);
  MyWidget *widget = new MyWidget();
  widget->show();
  return app.exec();
}

Body:
After googling couple of hours, I found more faster way. It becomes incredibly very fast(once 20FPS is now about 500FPS).What I'm using now is QGraphicsView Framework and QPixmap and QGraphicsPixmapItem. However I don't know this is the right or efficient way, if it isn't please correct me. And if you know there is more faster way please let me know. Any way I show you the code. I hope it could help someone who fight same problem.

qgraphicsSceneExample.h

    #include <iostream>
    #include <QApplication>
    #include <QGraphicsView>
    #include <QGraphicsScene>
    #include <QGraphicsItem>
    #include <QTimer>
    #include <QPainter>
    #include <QPushButton>
    #include <QImage>
    #include <QTime>
    #include <QStyleOptionGraphicsItem>
    #include <QWidget>
    #include <QPixmap>
    #include <QGraphicsPixmapItem>

    class MyView : public QGraphicsView {
        Q_OBJECT
    private:
        QGraphicsScene *scene;
        QImage *image;
        QPixmap *pixmap;
        QGraphicsPixmapItem *gpixmapItem;
        int px, py;
        uchar d[100*100*4];
        QTimer *timer;
        QTime time;
    public:
        MyView();
        //void paintEvent(QPaintEvent * event);
    public slots:
        void doPaint();
    };

qgraphicsSceneExample.cpp

#include "qgraphicsSceneExample.h"

int my_counter = 0;

MyView::MyView() : px(0), py(0){

    image = new QImage(d, 100, 100, QImage::Format_ARGB32);
    for(int cnt = 0, a, r, g, b; cnt < 100*100*4;){
        a = 255; //alpha
        r = 0;   //red
        g = 0;   //green
        b = 0;   //blue

        d[cnt] = b; cnt++;
        d[cnt] = g; cnt++;
        d[cnt] = r; cnt++;
        d[cnt] = a; cnt++;
    }

    // connect QTimer.timeout to my doPaint method
    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(doPaint()));
    scene = new QGraphicsScene(0);
    pixmap = new QPixmap(QPixmap::fromImage(*image));
    gpixmapItem = scene->addPixmap(*pixmap);
    this->setScene(scene);

    timer->start(1);
};

void MyView::doPaint(){
    // manipulate the positions of the points
    if(px < 100){
        int cnt = 0, b = 255, g = 255, r = 255, a = 255;
        d[4 * px + cnt] = b; cnt++;
        d[4 * px + cnt] = g; cnt++;
        d[4 * px + cnt] = r; cnt++;
        d[4 * px + cnt] = a; cnt++;
        px++;
    }
    pixmap = new QPixmap(QPixmap::fromImage(*image));
    gpixmapItem->setPixmap(*pixmap);
    std::cout << my_counter++ << "\n";
};

int main(int argc, char *argv[]){
    QApplication app(argc, argv);
    MyView *myView = new MyView();
    myView->show();
    return app.exec();
}


问:
unable to update textview immideately
i'm making a translation app in which i want to update a textview but it is not doing as i want.

```<code>final audioTranslate at[] = new audioTranslate[1];
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_translate);
    tv = (TextView) findViewById(R.id.textView11);
    spokentext = (TextView) findViewById(R.id.textView12);
    translatedtext = (TextView) findViewById(R.id.textView13);
    at[0] = this;
    start = (Button) findViewById(R.id.Start);
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Button b = (Button) v;
            if (b.getText().toString().equals("Start")) {
                //code
            }
            else{
                tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                b.setText("Wait");
                b.setEnabled(false);
                transfer();
            }
        }
    });
}

void transfer() {
    Thread t = new Thread() {
        public void run() {
            //socket connection
            //it is giving exception on below line too.
            //Only the original thread that created a view hierarchy can touch its views.
            //java.lang.RuntimeException
            at[0].spokentext.setText(spoken);
        }
    };
t.start();
}
</code>```

this is my layout file for reference:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_audio_translate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="diverse.technologies.transcriber.audioTranslate">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <Button
                android:text="Start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/Start" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:gravity="center_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView11"
                android:textColor="@color/colorAccent"
                android:textSize="24sp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView12"
                android:textSize="26sp"
                android:fontFamily="serif-monospace"
                android:textStyle="normal|bold" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView13"
                android:textSize="24sp"/>
        </TableRow>

    </TableLayout>
</ScrollView>

</RelativeLayout>
</code>```

I'm not getting what is wrong with above exception i'm getting. i'm using the object of the view that is having the textview. please help.

答:
Normal worker threads cannot modify UI elements like TextView. Run the code at[0].spokentext.setText(spoken); inside UI thread. In side your run method write

```<code>runOnUiThread(new Runnable() {
                @Override
                public void run() {//Your code}}
</code>```

However I do not recommend this type of native java coding. Use a Handler or AsyncTask

Title: unable to update textview immideately

Body:
i'm making a translation app in which i want to update a textview but it is not doing as i want.

final audioTranslate at[] = new audioTranslate[1];
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_translate);
    tv = (TextView) findViewById(R.id.textView11);
    spokentext = (TextView) findViewById(R.id.textView12);
    translatedtext = (TextView) findViewById(R.id.textView13);
    at[0] = this;
    start = (Button) findViewById(R.id.Start);
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Button b = (Button) v;
            if (b.getText().toString().equals("Start")) {
                //code
            }
            else{
                tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                b.setText("Wait");
                b.setEnabled(false);
                transfer();
            }
        }
    });
}

void transfer() {
    Thread t = new Thread() {
        public void run() {
            //socket connection
            //it is giving exception on below line too.
            //Only the original thread that created a view hierarchy can touch its views.
            //java.lang.RuntimeException
            at[0].spokentext.setText(spoken);
        }
    };
t.start();
}

this is my layout file for reference:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_audio_translate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="diverse.technologies.transcriber.audioTranslate">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <Button
                android:text="Start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/Start" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:gravity="center_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView11"
                android:textColor="@color/colorAccent"
                android:textSize="24sp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView12"
                android:textSize="26sp"
                android:fontFamily="serif-monospace"
                android:textStyle="normal|bold" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView13"
                android:textSize="24sp"/>
        </TableRow>

    </TableLayout>
</ScrollView>

</RelativeLayout>

I'm not getting what is wrong with above exception i'm getting. i'm using the object of the view that is having the textview. please help.

Body:
Normal worker threads cannot modify UI elements like TextView. Run the code at[0].spokentext.setText(spoken); inside UI thread. In side your run method write

runOnUiThread(new Runnable() {
                @Override
                public void run() {//Your code}}

However I do not recommend this type of native java coding. Use a Handler or AsyncTask


问:
Tool to generate a GUI (WinForms or WPF) from a class
Say we've got a class like

```<code>public class Doer
{
    public int Timeout {get;set;}
    public string DoIt(string input)
    {
        string toReturn;
        // Do something that involves a Timeout
        return toReturn;
    }
}
</code>```

Is there a tool that would create a Form or Control for prototyping this class? The GUI might have a NumericUpDown control with a label of "Timeout" and a GroupBox with a TextBox for "input" and a button labeled "DoIt" with an eventhandler that calls Doer.DoIt with the Text property of the input TextBox and puts the response in another TextBox.

答:
Looks a lot like Naked Objects are a good avenue to research. (Hanselminutes podcast.)

Briefly:

The naked objects pattern is defined
  by three principles:

All business logic should be encapsulated onto the domain objects.
  This principle is not unique to naked
  objects: it is just a strong
  commitment to encapsulation.

The user interface should be a direct representation of the domain
  objects, with all user actions
  consisting, explicitly, of creating or
  retrieving domain objects and/or
  invoking methods on those objects.
  This principle is also not unique to
  naked objects: it is just a specific
  interpretation of an object-oriented
  user interface (OOUI). The original
  idea in the naked objects pattern
  arises from the combination of these
  two, to form the third principle:

The user interface should be created 100% automatically from the
  definition of the domain objects. This
  may be done using several different
  technologies, including source code
  generation; implementations of the
  naked objects pattern to date have
  favoured the technology of reflection.
  The naked objects pattern was first
  described formally in Richard Pawson's
  PhD thesis1 which includes a
  thorough investigation of various
  antecedents and inspirations for the
  pattern including, for example, the
  Morphic user interface. Naked Objects
  is commonly contrasted with the
  model-view-controller pattern.
  However, the published version of
  Pawson's thesis (see References)
  contains a foreword by Trygve
  Reenskaug, who first formulated the
  model-view-controller pattern,
  suggesting that naked objects is
  closer to the original intent of
  model-view-controller than many of the
  subsequent interpretations and
  implementations.

Body:
Say we've got a class like

public class Doer
{
    public int Timeout {get;set;}
    public string DoIt(string input)
    {
        string toReturn;
        // Do something that involves a Timeout
        return toReturn;
    }
}

Is there a tool that would create a Form or Control for prototyping this class? The GUI might have a NumericUpDown control with a label of "Timeout" and a GroupBox with a TextBox for "input" and a button labeled "DoIt" with an eventhandler that calls Doer.DoIt with the Text property of the input TextBox and puts the response in another TextBox.


问:
ASP.Net 4.5 - Web Method Does Not Get Called From JQuery
I have set break points in the C# code and the web method is not invoked. I should see four rows returned from the database.

I do not get any errors - the only thing I see in the console is an error on the the length (in the javascript for loop ie i < data.d.length).

Relevant Code

TestApp.aspx.cs

```<code>    namespace WebApplication1
{
    public class User
    {
        public int?   TestID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

    public partial class TestApp : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static User[] Get()
        {
            try
            {
                List<User> details = FetchData("sp_LoadData", null);
                return details.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
</code>```

TestApp.aspx

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestApp.aspx.cs" Inherits="WebApplication1.TestApp" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
    <script src="TestApp.js"></script>
</head>
<body>
    <form id="form1">

                        <table id="example" class="display" cellspacing="1" width="100%" border="1">
                            <thead style="border: solid thin;">
                                <tr>
                                    <th>First name</th>
                                    <th>Last name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Delete</th>
                                </tr>
                            </thead>
                        </table>
</code>```

TestApp.js

```<code>$(document).ready(function () {
    BindGrid();

function BindGrid() {
    var t = $('#example').DataTable();
    t.rows().remove().draw();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestApp.aspx/Get",
        data: "{}",
        dataType: "json",

        success: function (data) {
            for (var i = 0; i < data.d.length; i++) {
                //debugger;
                t.row.add([
                            '<a class="table-edit" onclick="showRecord(' + data.d[i].TestID + ');">' + data.d[i].FirstName + '</a>',
                            data.d[i].LastName,
                            data.d[i].Email,
                            data.d[i].Phone,
                            '<button type="button" onclick="deleteRecord(' + data.d[i].TestID + ');">Delete</button>'
                ]).draw(false);
            }
        },
        error: function (result) {
            debugger;
            alert("Error");
        }
    });
};
</code>```

答:
I suspect that since you're passing in an empty object .NET is looking for a function defined like Get(object) not Get(). Try removing the below from your ajax call: </p>

```<code>   data: "{}",
   dataType: "json",
</code>```

Body:
I have set break points in the C# code and the web method is not invoked. I should see four rows returned from the database.

I do not get any errors - the only thing I see in the console is an error on the the length (in the javascript for loop ie i < data.d.length).

Relevant Code

TestApp.aspx.cs

    namespace WebApplication1
{
    public class User
    {
        public int?   TestID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

    public partial class TestApp : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static User[] Get()
        {
            try
            {
                List<User> details = FetchData("sp_LoadData", null);
                return details.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

TestApp.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestApp.aspx.cs" Inherits="WebApplication1.TestApp" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1">

                                    First name
                                    Last name
                                    Email
                                    Phone
                                    Delete

TestApp.js

$(document).ready(function () {
    BindGrid();

function BindGrid() {
    var t = $('#example').DataTable();
    t.rows().remove().draw();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestApp.aspx/Get",
        data: "{}",
        dataType: "json",

        success: function (data) {
            for (var i = 0; i < data.d.length; i++) {
                //debugger;
                t.row.add([
                            '' + data.d[i].FirstName + '',
                            data.d[i].LastName,
                            data.d[i].Email,
                            data.d[i].Phone,
                            '<button type="button" onclick="deleteRecord(' + data.d[i].TestID + ');">Delete</button>'
                ]).draw(false);
            }
        },
        error: function (result) {
            debugger;
            alert("Error");
        }
    });
};

Body:
I suspect that since you're passing in an empty object .NET is looking for a function defined like Get(object) not Get(). Try removing the below from your ajax call:

   data: "{}",
   dataType: "json",


问:
How do I keep all data in a td side by side fixed height
I am trying to put all these three data side by side. Like the second row last column. but after the first column (within php loop) 3rd and 4th elements get to lower line.
screenshot

here is what I have tried (included style in line.

```<code><?php while ($each_row = mysqli_fetch_assoc($table_data)){ ?>
                        <tr style="border: 1px solid black; ">
                            <td style="border: 1px solid black;"><?php echo $i; ?></td>
                            <td style="border: 1px solid black;"><?php echo $each_row["roll"]; ?></td>
                            <td style="border: 1px solid black;"><?php echo $each_row["name"]; ?></td>
                            <td style="border: 1px solid black; text-align:center;"><?php echo $each_row["present"]; ?></td>
                            <td style="border: 1px solid black; width: 300px;">
                                    <a href="attendence.php?change=present&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Present</button></a>
                                    <a href="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Absent</button></a>
                                    <form class="" style="width: 100px;" action="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>" method="post">
                                        <input style="width: 50px;" type="text" name="late" value="0">
                                        <input style="width: 50px;" type="submit" name="" value="Late">
                                    </form>
                            </td>
                        </tr>
      <?php } ?>
</code>```

答:
You may want to try the following structure. Consider using single <form> tag outside the main
 and also consider not using the  anchor around the <button>.

```<code><form method="post">
    <table style="width: 100%">
        <?php while ($each_row = mysqli_fetch_assoc($table_data)){ ?>
        <tr style="border: 1px solid black;">
            <td style="border: 1px solid black;">1</td>
            <td style="border: 1px solid black;">2</td>
            <td style="border: 1px solid black;">3</td>
            <td style="border: 1px solid black; text-align:center;">4</td>
            <td style="border: 1px solid black; width: 300px;">
                <a href="#YourUrlHere"><!--CONSIDER REMOVING THIS ANCHOR-->
                    <button type="button" name="button">Present</button>
                </a><!--CONSIDER REMOVING THIS ANCHOR-->
                <a href="#YourUrlHere"><!--CONSIDER REMOVING THIS ANCHOR-->
                    <button type="button" name="button">Absent</button>
                </a><!--CONSIDER REMOVING THIS ANCHOR-->
                <input style="width: 50px;" type="text" name="late" value="0">
                <input style="width: 50px;" type="submit" name="" value="Late">
            </td>
        </tr>
        <?php } ?>
    </table>
</form>
</code>```

https://jsfiddle.net/ksrgnmcm/#&togetherjs=Nl81IM2PG7

Hope it helps somehow.

Body:
I am trying to put all these three data side by side. Like the second row last column. but after the first column (within php loop) 3rd and 4th elements get to lower line.
screenshot

here is what I have tried (included style in line.

<?php while ($each_row = mysqli_fetch_assoc($table_data)){ ?>

                            <?php echo $i; ?>
                            <?php echo $each_row["roll"]; ?>
                            <?php echo $each_row["name"]; ?>
                            <?php echo $each_row["present"]; ?>

                                    <a href="attendence.php?change=present&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Present</button>
                                    <a href="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Absent</button>
                                    <form class="" style="width: 100px;" action="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>" method="post">
                                        <input style="width: 50px;" type="text" name="late" value="0">
                                        <input style="width: 50px;" type="submit" name="" value="Late">
                                    </form>

      <?php } ?>

Body:
You may want to try the following structure. Consider using single <form> tag outside the main <table> and also consider not using the <a> anchor around the <button>.

<form method="post">
    <table style="width: 100%">
        <?php while ($each_row = mysqli_fetch_assoc($table_data)){ ?>
        <tr style="border: 1px solid black;">
            <td style="border: 1px solid black;">1</td>
            <td style="border: 1px solid black;">2</td>
            <td style="border: 1px solid black;">3</td>
            <td style="border: 1px solid black; text-align:center;">4</td>
            <td style="border: 1px solid black; width: 300px;">
                <a href="#YourUrlHere"><!--CONSIDER REMOVING THIS ANCHOR-->
                    <button type="button" name="button">Present</button>
                </a><!--CONSIDER REMOVING THIS ANCHOR-->
                <a href="#YourUrlHere"><!--CONSIDER REMOVING THIS ANCHOR-->
                    <button type="button" name="button">Absent</button>
                </a><!--CONSIDER REMOVING THIS ANCHOR-->
                <input style="width: 50px;" type="text" name="late" value="0">
                <input style="width: 50px;" type="submit" name="" value="Late">
            </td>
        </tr>
        <?php } ?>
    </table>
</form>

https://jsfiddle.net/ksrgnmcm/#&togetherjs=Nl81IM2PG7

Hope it helps somehow.


问:
Servlet Mapping issue when called from two different folders
File 1:  public_html/eval.jsp

File 2:  public_html/m/eval.jsp

File 1 form action:

```<code>action="submitEval"
</code>```

File 2 form action:

```<code> action="../submitEval
</code>```

web.xml:

```<code><servlet>
  <servlet-name>submitEval</servlet-name>
  <servlet-class>submitPackage.submitEval</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>submitEval</servlet-name>
  <url-pattern>submitEval</url-pattern>
</servlet-mapping>
</code>```

Getting complaints of 404s when using the /m/ version of eval.jsp.  Not able to recreate but I figure if they are getting a 404 it would most likely have to do with my servlet mapping, any thoughts?

答:
Since i cant post it in the comment so i'm posting it as an answer.The only time i have seen or used  such mapping without any leading "/" is "*.anyString",and to test your mapping,i also went and tried the mapping which you are doing here,

```<code><servlet>
    <servlet-name>Demo</servlet-name>
    <servlet-class>coo.Demo</servlet-class>\
    </servlet>

    <servlet-mapping>
        <servlet-name>Demo</servlet-name>
        <url-pattern>Demo</url-pattern>
        </servlet-mapping>
</code>```

but i'm getting java.lang.IllegalArgumentException: Invalid <url-pattern> Demo in servlet mapping.But adding "/" or "*.Demo" fixes it as expected.
So i'm curious why is it working for you but not for me.

Body:
File 1:  public_html/eval.jsp

File 2:  public_html/m/eval.jsp

File 1 form action:

action="submitEval"

File 2 form action:

 action="../submitEval

web.xml:

<servlet>
  <servlet-name>submitEval</servlet-name>
  <servlet-class>submitPackage.submitEval</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>submitEval</servlet-name>
  <url-pattern>submitEval</url-pattern>
</servlet-mapping>

Getting complaints of 404s when using the /m/ version of eval.jsp.  Not able to recreate but I figure if they are getting a 404 it would most likely have to do with my servlet mapping, any thoughts?

Body:
Since i cant post it in the comment so i'm posting it as an answer.The only time i have seen or used  such mapping without any leading "/" is "*.anyString",and to test your mapping,i also went and tried the mapping which you are doing here,

<servlet>
    <servlet-name>Demo</servlet-name>
    <servlet-class>coo.Demo</servlet-class>\
    </servlet>

    <servlet-mapping>
        <servlet-name>Demo</servlet-name>
        <url-pattern>Demo</url-pattern>
        </servlet-mapping>

but i'm getting java.lang.IllegalArgumentException: Invalid <url-pattern> Demo in servlet mapping.But adding "/" or "*.Demo" fixes it as expected.
So i'm curious why is it working for you but not for me.


问:
How to treat COM references with methods that use ref sbyte in C#
I have the following IDL definition for a method in my native ATL COM project:

```<code>[id(1)] HRESULT Create([in] CHAR* a, [out] Details* b);
</code>```

I have added a reference to my COM object from my C# project and it has generated the stub for this function for me, which I need to call:

```<code>void Create(ref sbyte a, out SampleNativeLib.Details b)
</code>```

I would have expected the library to let me use a string as the ref sbyte a parameter on this function.

How can I call the Create method it has generated? Are there any alternatives to have it accept the ref sbyte a parameter as a string instead?

答:
You'll need to add the string attribute. This ensures that the CHAR pointer is treated as a string:

```<code>[id(1)] HRESULT Create([in, string] CHAR* a, [out] Details* b);
</code>```

Body:
I have the following IDL definition for a method in my native ATL COM project:

[id(1)] HRESULT Create([in] CHAR* a, [out] Details* b);

I have added a reference to my COM object from my C# project and it has generated the stub for this function for me, which I need to call:

void Create(ref sbyte a, out SampleNativeLib.Details b)

I would have expected the library to let me use a string as the ref sbyte a parameter on this function.

How can I call the Create method it has generated? Are there any alternatives to have it accept the ref sbyte a parameter as a string instead?

Body:
You'll need to add the string attribute. This ensures that the CHAR pointer is treated as a string:

[id(1)] HRESULT Create([in, string] CHAR* a, [out] Details* b);


问:
Sending a POST request with Volley to PHP Script
Im trying to send POST request with Volley from Android App to PHP script hosted on my server. When i get the response code i get Code 200 Successfull but $_POST in PHP script is empty.

My android Request code:

```<code>try {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = getResources().getString(R.string.web_login);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("hello", "world");
        jsonBody.put("username", username);
        final String mRequestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("LOG_VOLLEY", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("LOG_VOLLEY", error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "text/plain; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");

                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                    return null;
                }
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString = "";
                if (response != null) {

                    try {
                            responseString = new String(response.data, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));

            }
        };

        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

This code works fine, but when i get the response header it contains the next PHP Error:

Undefined index: username

Here is my php Script:

```<code><?php

//Get post data from Android App
$name = $_POST['username'];

if (isset($name)){
    $data = "OK";
    header('Content-Type: text/plain');
    echo $data;
}

?>
</code>```

What am I doing wrong?

答:
POST parameters should be sent from getParams().

Try:

```<code> try {
        final HashMap<String, String> params = new HashMap<>();
        params.put("username", username);

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = getResources().getString(R.string.web_login);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("hello", "world");
        jsonBody.put("username", username);
        final String mRequestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("LOG_VOLLEY", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("LOG_VOLLEY", error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "text/plain; charset=utf-8";
            }

            {
                @Override
                protected Map<String, String> getParams ()throws AuthFailureError {
                return params;
            }

                @Override
                public byte[] getBody ()throws AuthFailureError {
                try {
                    return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");

                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                    return null;
                }
            }

                @Override
                protected Response<String> parseNetworkResponse (NetworkResponse response){
                String responseString = "";
                if (response != null) {

                    try {
                        responseString = new String(response.data, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));

            }
            }

            ;

            requestQueue.add(stringRequest);
        }catch(JSONException e){
            e.printStackTrace();
        }
</code>```

Body:
Im trying to send POST request with Volley from Android App to PHP script hosted on my server. When i get the response code i get Code 200 Successfull but $_POST in PHP script is empty.

My android Request code:

try {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = getResources().getString(R.string.web_login);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("hello", "world");
        jsonBody.put("username", username);
        final String mRequestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("LOG_VOLLEY", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("LOG_VOLLEY", error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "text/plain; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");

                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                    return null;
                }
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString = "";
                if (response != null) {

                    try {
                            responseString = new String(response.data, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));

            }
        };

        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }

This code works fine, but when i get the response header it contains the next PHP Error:

Undefined index: username

Here is my php Script:

<?php

//Get post data from Android App
$name = $_POST['username'];

if (isset($name)){
    $data = "OK";
    header('Content-Type: text/plain');
    echo $data;
}

?>

What am I doing wrong?

Body:
POST parameters should be sent from getParams().

Try:

 try {
        final HashMap<String, String> params = new HashMap<>();
        params.put("username", username);

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = getResources().getString(R.string.web_login);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("hello", "world");
        jsonBody.put("username", username);
        final String mRequestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("LOG_VOLLEY", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("LOG_VOLLEY", error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "text/plain; charset=utf-8";
            }

            {
                @Override
                protected Map<String, String> getParams ()throws AuthFailureError {
                return params;
            }

                @Override
                public byte[] getBody ()throws AuthFailureError {
                try {
                    return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");

                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                    return null;
                }
            }

                @Override
                protected Response<String> parseNetworkResponse (NetworkResponse response){
                String responseString = "";
                if (response != null) {

                    try {
                        responseString = new String(response.data, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));

            }
            }

            ;

            requestQueue.add(stringRequest);
        }catch(JSONException e){
            e.printStackTrace();
        }


问:
DeserializeObject not working with object type
I am having trouble with my serializing and deserializing.
The below code has the List object record as a list while serializing however when deserializing it doesn't work.

Each Tag Parameter is of type object

```<code>TreeViewCollection = new ObservableCollection<TreeViewItem>()
        {
            new TreeViewItem()
            {
                Header = "Suite 1"
            },
            new TreeViewItem()
            {
                Header = "Suite 2",
                Nodes = new ObservableCollection<TreeViewItem>()
                {
                    new TreeViewItem()
                    {
                        Header = "Case 1"
                    }
                }
            },
            new TreeViewItem()
            {
                Header = "Suite 2",
                Nodes = new ObservableCollection<TreeViewItem>()
                {
                    new TreeViewItem()
                    {
                        Header = "Case 2",
                        Tag = new List<ListViewItem>()
                        {
                            new ListViewItem()
                            {
                                Tag = new ActionObject()
                                {
                                    Command = "Command",
                                    Target = "Target",
                                    Value = "Value",
                                    Comment = "Comment"
                                }
                            }
                        }
                    },
                    new TreeViewItem()
                    {
                        Header = "Case 3"
                    }
                }
            }
        };

        string serializedJson = JsonConvert.SerializeObject(TreeViewCollection, Formatting.Indented, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects,
            TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
        });

        var deserializedObject = JsonConvert.DeserializeObject<ObservableCollection<TreeViewItem>>(serializedJson, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects,
            TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
        });

        TreeViewCollection = deserializedObject;
</code>```

However it comes out as JSON and not a List() object

```<code>{[
  {
    "$type": "RFA.Models.Items.ListViewItem, RFA",
    "ID": "0b9661f0-87f1-41f4-85cb-620dc1f49bb3",
    "Name": null,
    "Tag": {
      "$type": "RFA.Models.Objects.ActionObject, RFA",
      "Command": "Command",
      "Target": "Target",
      "Value": "Value",
      "Comment": "Comment"
    }
  }
]}
</code>```

How can I get json deserialization to work with object types

Requested TreeviewItem class :

```<code>public partial class TreeViewItem
{
    #region Private Variables

    private string _header;
    private object _tag;
    private ObservableCollection<TreeViewItem> _nodes;

    #endregion
    #region Properties

    public string Header
    {
        get { return _header; }
        set
        {
            if (value == _header) return;
            _header = value;
            OnPropertyChanged();
        }
    }
    public object Tag
    {
        get { return _tag; }
        set
        {
            if (value == _tag) return;
            _tag = value;
            OnPropertyChanged();
        }
    }
    public ObservableCollection<TreeViewItem> Nodes
    {
        get { return _nodes; }
        set
        {
            if (Equals(value, _nodes)) return;
            _nodes = value;
            OnPropertyChanged();
        }
    }
    #endregion
}
</code>```

答:
Your problem is that you are assigning a new List<ListViewItem>() value to an object Tag property, then serializing and deserializing with TypeNameHandling = TypeNameHandling.Objects.  As explained in the Newtonsoft docs this enumeration has the following meanings:

```<code>None      0   Do not include the .NET type name when serializing types.
Objects   1   Include the .NET type name when serializing into a JSON object structure.
Arrays    2   Include the .NET type name when serializing into a JSON array structure.
All       3   Always include the .NET type name when serializing.
Auto      4   Include the .NET type name when the type of the object being serialized is not the same as its declared type. Note that this doesn't include the root serialized object by default. To include the root object's type name in JSON you must specify a root type object with SerializeObject(Object, Type, JsonSerializerSettings) or Serialize(JsonWriter, Object, Type).
</code>```

By using TypeNameHandling.Objects you omit the type information for your List<ListViewItem> collection, and thus, when serialized and deserialized, your Tag gets turned into a LINQ-to-JSON JArray.

Instead, I recommend using TypeNameHandling.Auto.  This includes type information only when necessary - i.e., when the declared type of a property value or collection item does not match the actual, observed type.  Using this will cause type information to be emitted for your object Tag property but not for, say, your ObservableCollection<TreeViewItem> Nodes property which is fully typed.

Alternatively, if you can add Newtonsoft attributes to your model, you can mark the Tag property with [JsonProperty(TypeNameHandling = TypeNameHandling.All)]:

```<code>[JsonProperty(TypeNameHandling = TypeNameHandling.All)]
public object Tag { get; set; }
</code>```

If you unconditionally require type information for your objects even when not needed for deserialization and cannot add Newtonsoft attributes to your model, you could use TypeNameHandling.All - but I don't really recommend this setting because it unconditionally emits type information for collections even when not necessary.  This can cause problems down the road if, for instance, you decide to change the type of a collection from List<T> to ObservableCollection<T>.  If you do, you'll need to strip out the collection type information during deserialization with something like IgnoreCollectionTypeConverter as shown in this answer.  (Unfortunately, TypeNameHandling.Auto | TypeNameHandling.Objects seems not to be implemented.)

Finally, when using TypeNameHandling, do take note of this caution from the Newtonsoft docs:

TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than None.

For a discussion of why this may be necessary, see TypeNameHandling caution in Newtonsoft Json.

Body:
I am having trouble with my serializing and deserializing.
The below code has the List object record as a list while serializing however when deserializing it doesn't work.

Each Tag Parameter is of type object

TreeViewCollection = new ObservableCollection<TreeViewItem>()
        {
            new TreeViewItem()
            {
                Header = "Suite 1"
            },
            new TreeViewItem()
            {
                Header = "Suite 2",
                Nodes = new ObservableCollection<TreeViewItem>()
                {
                    new TreeViewItem()
                    {
                        Header = "Case 1"
                    }
                }
            },
            new TreeViewItem()
            {
                Header = "Suite 2",
                Nodes = new ObservableCollection<TreeViewItem>()
                {
                    new TreeViewItem()
                    {
                        Header = "Case 2",
                        Tag = new List<ListViewItem>()
                        {
                            new ListViewItem()
                            {
                                Tag = new ActionObject()
                                {
                                    Command = "Command",
                                    Target = "Target",
                                    Value = "Value",
                                    Comment = "Comment"
                                }
                            }
                        }
                    },
                    new TreeViewItem()
                    {
                        Header = "Case 3"
                    }
                }
            }
        };

        string serializedJson = JsonConvert.SerializeObject(TreeViewCollection, Formatting.Indented, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects,
            TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
        });

        var deserializedObject = JsonConvert.DeserializeObject<ObservableCollection<TreeViewItem>>(serializedJson, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects,
            TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
        });

        TreeViewCollection = deserializedObject;

However it comes out as JSON and not a List() object

{[
  {
    "$type": "RFA.Models.Items.ListViewItem, RFA",
    "ID": "0b9661f0-87f1-41f4-85cb-620dc1f49bb3",
    "Name": null,
    "Tag": {
      "$type": "RFA.Models.Objects.ActionObject, RFA",
      "Command": "Command",
      "Target": "Target",
      "Value": "Value",
      "Comment": "Comment"
    }
  }
]}

How can I get json deserialization to work with object types

Requested TreeviewItem class :

public partial class TreeViewItem
{
    #region Private Variables

    private string _header;
    private object _tag;
    private ObservableCollection<TreeViewItem> _nodes;

    #endregion
    #region Properties

    public string Header
    {
        get { return _header; }
        set
        {
            if (value == _header) return;
            _header = value;
            OnPropertyChanged();
        }
    }
    public object Tag
    {
        get { return _tag; }
        set
        {
            if (value == _tag) return;
            _tag = value;
            OnPropertyChanged();
        }
    }
    public ObservableCollection<TreeViewItem> Nodes
    {
        get { return _nodes; }
        set
        {
            if (Equals(value, _nodes)) return;
            _nodes = value;
            OnPropertyChanged();
        }
    }
    #endregion
}

Body:
Your problem is that you are assigning a new List<ListViewItem>() value to an object Tag property, then serializing and deserializing with TypeNameHandling = TypeNameHandling.Objects.  As explained in the Newtonsoft docs this enumeration has the following meanings:

None      0   Do not include the .NET type name when serializing types.
Objects   1   Include the .NET type name when serializing into a JSON object structure.
Arrays    2   Include the .NET type name when serializing into a JSON array structure.
All       3   Always include the .NET type name when serializing.
Auto      4   Include the .NET type name when the type of the object being serialized is not the same as its declared type. Note that this doesn't include the root serialized object by default. To include the root object's type name in JSON you must specify a root type object with SerializeObject(Object, Type, JsonSerializerSettings) or Serialize(JsonWriter, Object, Type).

By using TypeNameHandling.Objects you omit the type information for your List<ListViewItem> collection, and thus, when serialized and deserialized, your Tag gets turned into a LINQ-to-JSON JArray.

Instead, I recommend using TypeNameHandling.Auto.  This includes type information only when necessary - i.e., when the declared type of a property value or collection item does not match the actual, observed type.  Using this will cause type information to be emitted for your object Tag property but not for, say, your ObservableCollection<TreeViewItem> Nodes property which is fully typed.

Alternatively, if you can add Newtonsoft attributes to your model, you can mark the Tag property with [JsonProperty(TypeNameHandling = TypeNameHandling.All)]:

[JsonProperty(TypeNameHandling = TypeNameHandling.All)]
public object Tag { get; set; }

If you unconditionally require type information for your objects even when not needed for deserialization and cannot add Newtonsoft attributes to your model, you could use TypeNameHandling.All - but I don't really recommend this setting because it unconditionally emits type information for collections even when not necessary.  This can cause problems down the road if, for instance, you decide to change the type of a collection from List<T> to ObservableCollection<T>.  If you do, you'll need to strip out the collection type information during deserialization with something like IgnoreCollectionTypeConverter as shown in this answer.  (Unfortunately, TypeNameHandling.Auto | TypeNameHandling.Objects seems not to be implemented.)

Finally, when using TypeNameHandling, do take note of this caution from the Newtonsoft docs:

TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than None.

For a discussion of why this may be necessary, see TypeNameHandling caution in Newtonsoft Json.


问:
How to make a method pop first in java fluent interface?
This is my first asking, so sorry if I messed something.
I have a task to implement a Mail, using Java fluent interface.
I must have fields: From, To, Subject.

The problem is, I can not make "From" to appear as first and only.
Example:
MailBuilder builder = new MailBuilder();
builder.from("Stiliyan").to("Alexander").subject("Welcome aboard");

But when I type the first dot "." all of them appears. (eg builder.to("a").from("b")..)

So in short: builder.(HERE MUST APPEAR ONLY "from").to("No worries")..."

Here is MailBuilder.java

So here after "." must appear ONLY from method

答:
Then your declared return type of each of the builder methods cannot be the same. You can still return the same builder instance though. For example:

```<code>interface IFromBuilder {
    IToBuilder from(String from);
}

interface IToBuilder {
    IMailBuilder to(String to);
}

interface IMailBuilder {
    Mail build();
}

class MailBuilder implements IFromBuilder, IToBuilder, IMailBuilder {

    private String from;
    private String to;

    @Override
    public IToBuilder from(String from) {
        this.from = from;
        return this;
    }

    @Override
    public IMailBuilder to(String to) {
        this.to = to;
        return this;
    }

    @Override
    public Mail build() {
        return new Mail(from, to);
    }
}

class Mail {
    private final String from;
    private final String to;

    public Mail(String from, String to) {
        this.from = from;
        this.to = to;
    }

    public static IFromBuilder newBuilder() {
        return new MailBuilder();
    }
}

public class Demo {
    public static void main(String[] args) {
        Mail mail = Mail.newBuilder().from("sender@a.com").to("receiver@b.com").build();
    }
}
</code>```

Body:
Then your declared return type of each of the builder methods cannot be the same. You can still return the same builder instance though. For example:

interface IFromBuilder {
    IToBuilder from(String from);
}

interface IToBuilder {
    IMailBuilder to(String to);
}

interface IMailBuilder {
    Mail build();
}

class MailBuilder implements IFromBuilder, IToBuilder, IMailBuilder {

    private String from;
    private String to;

    @Override
    public IToBuilder from(String from) {
        this.from = from;
        return this;
    }

    @Override
    public IMailBuilder to(String to) {
        this.to = to;
        return this;
    }

    @Override
    public Mail build() {
        return new Mail(from, to);
    }
}

class Mail {
    private final String from;
    private final String to;

    public Mail(String from, String to) {
        this.from = from;
        this.to = to;
    }

    public static IFromBuilder newBuilder() {
        return new MailBuilder();
    }
}

public class Demo {
    public static void main(String[] args) {
        Mail mail = Mail.newBuilder().from("sender@a.com").to("receiver@b.com").build();
    }
}


问:
Eclipse IDE project directory structure help [Java]
I have been learning Java and have had no problem with projects in which multiple .java files were in the same Default Package.
I am now trying to separate code and create folders for images, but everything I have tried has failed.

How do I properly add folders for images and other classes, and properly set the path to it?
All paths should be relative to the project, I know that much ;_;

Here's a link to a picture of my IDE and error message from program output:

http://img262.imageshack.us/img262/8415/directory.png

Thanks!!

答: Try giving src/Textures/Crate.png  as the path to the FileInputStream constructor.


问:
Using psycopg2 or other python module within Visual Code
I am using Visual Code and wanted to script some Python code that connects to a database. Psycopg2 seems to be the perfect library for just that. So I had in my settings.json file:

```<code>{
    "python.linting.pylintEnabled": true,
    "python.autoComplete.extraPaths": [
    "c:/OSGeo4W64/apps/python27",
    "C:/OSGeo4W64/apps/Python27/Lib/site-packages/psycopg2"
    ],
    "python.pythonPath": "C:/OSGeo4W64/bin/python.exe"

}
</code>```

I still get the error

'no module named psycopg2'

on the first line in my code: import psycopg2.

答:
Or psycopg2 is install but not in the right place you can check where it is with this method :

How do I find the location of Python module sources?

or as have said bernie you don't have psycopg2you can check this way:

https://askubuntu.com/questions/588390/how-do-i-check-whether-a-module-is-installed-or-not-in-python

in this case in your terminal do : pip install psycopg2or if you use anaconda conda install -c anaconda psycopg2=2.7.1

Body:
I am using Visual Code and wanted to script some Python code that connects to a database. Psycopg2 seems to be the perfect library for just that. So I had in my settings.json file:

{
    "python.linting.pylintEnabled": true,
    "python.autoComplete.extraPaths": [
    "c:/OSGeo4W64/apps/python27",
    "C:/OSGeo4W64/apps/Python27/Lib/site-packages/psycopg2"
    ],
    "python.pythonPath": "C:/OSGeo4W64/bin/python.exe"

}

I still get the error

'no module named psycopg2'

on the first line in my code: import psycopg2.


问:
Why am I getting error when enum type variable is initialized in file scope?
I am unable to understand the situation when I try to initialize the enum variable as global, i.e., outside of any scope. For example if I try to compile below code:

```<code>#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

card = club;
int main()
{
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}
</code>```

Following compilation errors happen:

```<code>prog.c:9:1: warning: data definition has no type or storage class
card = club;
^
prog.c:9:1: warning: type defaults to 'int' in declaration of 'card' [Wimplicit-int]
prog.c:9:1: error: conflicting types for 'card'
prog.c:8:3: note: previous declaration of 'card' was here
} card;
  ^
</code>```

But when I put the initialization within the main() scope , no error occurs like the code below:

```<code>#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

int main()
{
    card = club;
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}
</code>```

Output is :

```<code>Size of enum variable = 4 bytes
</code>```

答:
Your first declares a global variable named club of type enum suit, however you cannot initialize a global variable on another line outside of a function - you must do it on the same line, like so:

```<code>enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card = club;
</code>```

I feel your code would be more readable if you moved the enum club definition away from the variable declaration:

```<code>enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
};

enum suit card = club;
</code>```

The extra enum keyword is because C (unlike C++) has a different namespace for each kind of type - so you can have enum foo and struct foo in the same project without the names colliding because enum and struct type names exist in different namespaces.

(I'm personally not a fan of using typedef - but feel free to go with that if you choose).

Body:
I am unable to understand the situation when I try to initialize the enum variable as global, i.e., outside of any scope. For example if I try to compile below code:

#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

card = club;
int main()
{
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}

Following compilation errors happen:

prog.c:9:1: warning: data definition has no type or storage class
card = club;
^
prog.c:9:1: warning: type defaults to 'int' in declaration of 'card' [Wimplicit-int]
prog.c:9:1: error: conflicting types for 'card'
prog.c:8:3: note: previous declaration of 'card' was here
} card;
  ^

But when I put the initialization within the main() scope , no error occurs like the code below:

#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

int main()
{
    card = club;
    printf("Size of enum variable = %d bytes", sizeof(card));
    return 0;
}

Output is :

Size of enum variable = 4 bytes

Body:
Your first declares a global variable named club of type enum suit, however you cannot initialize a global variable on another line outside of a function - you must do it on the same line, like so:

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card = club;

I feel your code would be more readable if you moved the enum club definition away from the variable declaration:

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
};

enum suit card = club;

The extra enum keyword is because C (unlike C++) has a different namespace for each kind of type - so you can have enum foo and struct foo in the same project without the names colliding because enum and struct type names exist in different namespaces.

(I'm personally not a fan of using typedef - but feel free to go with that if you choose).