问:
TypeError: 'str' object does not support item assignment while trying to create a nested dictionary
i have several lists that im trying to iterate through and create a nested dictionary based off of a key(date in this case) . The lists are from a dataframe here's how am doing it but am getting the error above.
The idea is to get the values for 'total' and 'volume' for each type of bread for each date in the 'dates' list. The order of the lists is consistent and they have equal length. Any idea why this is happening?
The goal is to analyze/visualize the sales performance from 2018 to date
I have an idea that a nested dictionary might not be the best solutions so any better idea is welcome.

my data structure:

```<code> ID      Created At                 Description                   Order No  Qnty StockID Price  Total  Date
233535  2020-05-30 19:12:17+03:00   SLICED ROUND TOP WHITE BREAD    71231   285 FG003   36.0    10260.0 2020-05-30
233537  2020-05-30 19:12:17+03:00   SLICED ROUND TOP BROWN BREAD    71231   15  FG004   36.0    540.0   2020-05-30
233529  2020-05-30 19:11:18+03:00   SLICED ROUND TOP WHITE BREAD    71229   90  FG003   36.0    3240.0  2020-05-30
233531  2020-05-30 19:11:18+03:00   SLICED ROUND TOP BROWN BREAD    71229   10  FG004   36.0    360.0   2020-05-30

breads=[]
dates=[]
volumes=[]
totals=[]
for i, row in sales.iterrows():
    bread=row[2]
    breads.append(bread)
    vol=row[4]
    volumes.append(vol)
    total=row[-2]
    totals.append(total)
    date=row[-1]
    dates.append(date)

from collections import defaultdict

sku_vol_total_by_date=defaultdict(dict)
for i in range(len(dates)):
    date=dates[i]
    bread=breads[i]
    volume=volumes[i]
    total=totals[i]
    if date not in sku_vol_total_by_date.keys():
        sku_vol_total_by_date[date]=date
        sku_vol_total_by_date[date][volume]=volume
        sku_vol_total_by_date[date][total]=total
    else:
        sku_vol_total_by_date[date][bread][volume]+=volume
        sku_vol_total_by_date[date][bread][total]+=total

sku_vol_total_by_date
</code>```

答:
There is a problem in the way you try to implement nested dictionaries.

First of all, you are using sku_vol_total_by_date=defaultdict(dict), which is a defaultdict whose values are regular dicts, so you would not be able to use more than one nesting depth. However, there is a deeper problem with the way you use the dictionary.

Defaultdicts work by filling missing entries with a default value, based on the defaultdict's type, in your case, a dict. So the following will work, even though you never added an entry for the key "test":

```<code>sku_vol_total_by_date=defaultdict(dict)
print(sku_vol_total_by_date["test"])  # will print the empty dict {}
</code>```

However, if you add a key/value pair manually to your defaultdict, it will use whatever value you supply:

```<code>sku_vol_total_by_date=defaultdict(dict)
sku_vol_total_by_date["test"] = "test_string"
print(sku_vol_total_by_date["test"])  # will print "test_string"
</code>```

Since you explicitly add a string value to your dictionary, python will ignore the fact that you have defined the default value to be dict, and accept whatever you put into the dictionary.

The problem occurs when you start nesting. In the previous example, the dictionary contains a key/value pair "test": "test_string".

So if you do this, it will fail with the error message you have given:

```<code>sku_vol_total_by_date["test"]["new_test"] = "new_test_string"
</code>```

The expression sku_vol_total_by_date["test"] is the same as "test_string", so you are basically trying to write

```<code>"test_string"["new_test"] = "new_test_string"
</code>```

And this is interpreted in python as something similar to mystring[3] = "x", which is not allowed for strings.

So, where to go from here? Nested defaultdicts are described here: Nested defaultdict of defaultdict

Reading your code, I get the impression that nested dictionaries are not the solution to your problem though. It's hard to say what a good solution it without knowing exactly how your data is structured. I would assume that you want to group all the "volume" numbers that belong to the same "date", and do the same with the "total" numbers.

A hint to get you on your way, as this looks like a homework exercise and I don't want to give away the answer: grouping values can be done with a defaultdict(int), and you may need separate dictionaries for your "volume" and "total" values. Try to research some examples about defaultdicts and how they are usually used.

Body:
i have several lists that im trying to iterate through and create a nested dictionary based off of a key(date in this case) . The lists are from a dataframe here's how am doing it but am getting the error above.
The idea is to get the values for 'total' and 'volume' for each type of bread for each date in the 'dates' list. The order of the lists is consistent and they have equal length. Any idea why this is happening?
The goal is to analyze/visualize the sales performance from 2018 to date
I have an idea that a nested dictionary might not be the best solutions so any better idea is welcome.

my data structure:

 ID      Created At                 Description                   Order No  Qnty StockID Price  Total  Date
233535  2020-05-30 19:12:17+03:00   SLICED ROUND TOP WHITE BREAD    71231   285 FG003   36.0    10260.0 2020-05-30
233537  2020-05-30 19:12:17+03:00   SLICED ROUND TOP BROWN BREAD    71231   15  FG004   36.0    540.0   2020-05-30
233529  2020-05-30 19:11:18+03:00   SLICED ROUND TOP WHITE BREAD    71229   90  FG003   36.0    3240.0  2020-05-30
233531  2020-05-30 19:11:18+03:00   SLICED ROUND TOP BROWN BREAD    71229   10  FG004   36.0    360.0   2020-05-30

breads=[]
dates=[]
volumes=[]
totals=[]
for i, row in sales.iterrows():
    bread=row[2]
    breads.append(bread)
    vol=row[4]
    volumes.append(vol)
    total=row[-2]
    totals.append(total)
    date=row[-1]
    dates.append(date)

from collections import defaultdict

sku_vol_total_by_date=defaultdict(dict)
for i in range(len(dates)):
    date=dates[i]
    bread=breads[i]
    volume=volumes[i]
    total=totals[i]
    if date not in sku_vol_total_by_date.keys():
        sku_vol_total_by_date[date]=date
        sku_vol_total_by_date[date][volume]=volume
        sku_vol_total_by_date[date][total]=total
    else:
        sku_vol_total_by_date[date][bread][volume]+=volume
        sku_vol_total_by_date[date][bread][total]+=total

sku_vol_total_by_date

Body:
There is a problem in the way you try to implement nested dictionaries.

First of all, you are using sku_vol_total_by_date=defaultdict(dict), which is a defaultdict whose values are regular dicts, so you would not be able to use more than one nesting depth. However, there is a deeper problem with the way you use the dictionary.

Defaultdicts work by filling missing entries with a default value, based on the defaultdict's type, in your case, a dict. So the following will work, even though you never added an entry for the key "test":

sku_vol_total_by_date=defaultdict(dict)
print(sku_vol_total_by_date["test"])  # will print the empty dict {}

However, if you add a key/value pair manually to your defaultdict, it will use whatever value you supply:

sku_vol_total_by_date=defaultdict(dict)
sku_vol_total_by_date["test"] = "test_string"
print(sku_vol_total_by_date["test"])  # will print "test_string"

Since you explicitly add a string value to your dictionary, python will ignore the fact that you have defined the default value to be dict, and accept whatever you put into the dictionary.

The problem occurs when you start nesting. In the previous example, the dictionary contains a key/value pair "test": "test_string".

So if you do this, it will fail with the error message you have given:

sku_vol_total_by_date["test"]["new_test"] = "new_test_string"

The expression sku_vol_total_by_date["test"] is the same as "test_string", so you are basically trying to write

"test_string"["new_test"] = "new_test_string"

And this is interpreted in python as something similar to mystring[3] = "x", which is not allowed for strings.

So, where to go from here? Nested defaultdicts are described here: Nested defaultdict of defaultdict

Reading your code, I get the impression that nested dictionaries are not the solution to your problem though. It's hard to say what a good solution it without knowing exactly how your data is structured. I would assume that you want to group all the "volume" numbers that belong to the same "date", and do the same with the "total" numbers.

A hint to get you on your way, as this looks like a homework exercise and I don't want to give away the answer: grouping values can be done with a defaultdict(int), and you may need separate dictionaries for your "volume" and "total" values. Try to research some examples about defaultdicts and how they are usually used.


来源: stackexchange

问:
Pure Java alternative to database / cache for storing records
I have created an application sold to customers, some of which are hardware manufacturers with fixed constraints (slow CPU). The app has to be in java, so that it can be easily installed as a single package.

The application is multithreaded and maintains audio records. In this particular case all we have is INSERT SOMEDATA FOR RECORD, each record representing an audio file (and this can be done by different threads), and then later on we have SELECT SOMEDATA WHERE IDS in (x, y, z) by an single thread, then 3rd step is we actually DELETE all the data in this table.

The main constraint is cpu, slow single cpu. Memory is also a constraint, but only in that the application is designed so it can process an unlimited number of files, and so even if had lots of memory would eventually run out if all stored in memory rather than utilizing the disk.

In my Java application I started off using the H2 database to store all my data. But the software has to run on some slow single cpu servers so I want to reduce the cpu cycles used, and one area I want to look again is the database.

In many cases I am inserting data into database simply for the purposes of keeping the data off the heap otherwise would run out of memory, then later on we retrieve the data, we never have to UPDATE the data.

So I considered using a cache like ehCache but that has two problems:

It doesn't guarantee the data will not be thrown away (If the cache gets full)

I can only retrieve records one at a time, whereas with relational database I can retrieve a batch of records, this looks like a potential bottleneck.

What is an alternative that solves these issues ?

答:
Relational databases like Oracle are decades old (41 years), can you imagine how many CPU cycles were available back then? Based on research from 1970 and well understood by professionals, tested, documented, reliable, consistent (checksums), maintainable (backups with zero data loss), performant if used correctly (all kinds of indexes), accessible securely over the network, scalable, etc but apparently Not Invented Here.

Nowadays there are even many free Open Source databases like PostgreSQL that have very modest requirements and the potential to easily implement new requirements in the future (which is hard to predict) and with some effort interchangeable with other databases (JDBC, JPA)

But yes, there is some overhead but typically hardware is cheaper than changing your architecture late in the project and CPU cycles are not an expensive resource anymore (think raspberry pi, smartphones, etc)

ContentLicense: CC BY-SA 4.0


问:
Python Pandas Data not aligned correctly
I am building a dataframe from a directory of text files that contain memory readings. I am giving the column the name Memory.

But when the data gets imported there is a column of zeros, the column with the memory readings that I want, and the Memory column has an NaN by each entry (not a number, I presume):

output:

```<code>***Memory Data Frame:
            0 Memory
0   1843260.0    NaN
0   7706164.0    NaN
0   7904828.0    NaN
0   7706164.0    NaN
0   7706172.0    NaN
0   7648524.0    NaN
0   7648524.0    NaN
0   7706172.0    NaN
0   7706164.0    NaN
0   7904828.0    NaN
0   7706172.0    NaN
0   7648524.0    NaN
0   7706172.0    NaN
0  16075888.0    NaN
0   7904672.0    NaN
0   7904680.0    NaN
0   7904672.0    NaN
0   7904680.0    NaN
0  16075880.0    NaN
0   7904672.0    NaN
***
</code>```

I'm not sure why the data is misaligned with a row of all zeros, the memory readings are floats with a trailing .0, or why there's a row of NaN in the Memory column. Here is my most recent code.

code:

```<code># Create the memory dataframe
column_names = ["Memory"]
memory_df = pd.DataFrame(columns = column_names)
memory_df.astype('int32').dtypes
temp_df = pd.DataFrame(columns = column_names)
temp_df.astype('int32').dtypes
print(f"Reading text files into the Memory DF")
for filename in filelist:
    print(f"Adding filename: {filename}")
    filename = text_path + filename
    temp_df = pd.read_csv(filename, delim_whitespace=True, header=None)
    temp_df.astype('int32').dtypes
    memory_df = memory_df.append(temp_df)
</code>```

How can I ingest the data with JUST one Memory column with the memory readings shown as integers with no trailing .0?

答:
The all zeroes and misalignment are just a misunderstanding of the form of data by pandas and your computer. To get your desired result, one must extract all the memory values and place them in a new dataframe. To remove the trailing zeroes, change the type to integer. Code to do this below:</p>

```<code>memory = df['0']
new_df = pd.Dataframe(memory)
new_df.astype('int32').dtypes
</code>```

Body:
I am building a dataframe from a directory of text files that contain memory readings. I am giving the column the name Memory.

But when the data gets imported there is a column of zeros, the column with the memory readings that I want, and the Memory column has an NaN by each entry (not a number, I presume):

output:

***Memory Data Frame:
            0 Memory
0   1843260.0    NaN
0   7706164.0    NaN
0   7904828.0    NaN
0   7706164.0    NaN
0   7706172.0    NaN
0   7648524.0    NaN
0   7648524.0    NaN
0   7706172.0    NaN
0   7706164.0    NaN
0   7904828.0    NaN
0   7706172.0    NaN
0   7648524.0    NaN
0   7706172.0    NaN
0  16075888.0    NaN
0   7904672.0    NaN
0   7904680.0    NaN
0   7904672.0    NaN
0   7904680.0    NaN
0  16075880.0    NaN
0   7904672.0    NaN
***

I'm not sure why the data is misaligned with a row of all zeros, the memory readings are floats with a trailing .0, or why there's a row of NaN in the Memory column. Here is my most recent code.

code:

# Create the memory dataframe
column_names = ["Memory"]
memory_df = pd.DataFrame(columns = column_names)
memory_df.astype('int32').dtypes
temp_df = pd.DataFrame(columns = column_names)
temp_df.astype('int32').dtypes
print(f"Reading text files into the Memory DF")
for filename in filelist:
    print(f"Adding filename: {filename}")
    filename = text_path + filename
    temp_df = pd.read_csv(filename, delim_whitespace=True, header=None)
    temp_df.astype('int32').dtypes
    memory_df = memory_df.append(temp_df)

How can I ingest the data with JUST one Memory column with the memory readings shown as integers with no trailing .0?

Body:
The all zeroes and misalignment are just a misunderstanding of the form of data by pandas and your computer. To get your desired result, one must extract all the memory values and place them in a new dataframe. To remove the trailing zeroes, change the type to integer. Code to do this below:

memory = df['0']
new_df = pd.Dataframe(memory)
new_df.astype('int32').dtypes


问:
How can I add a mouse over event to this function?
I am working on a slideshow / carousel in HTML with vanilla JS controlling the changing of the slides. I am happy with the current functionality, but I would like the slideshow to pause if the user hovers over the gallery. I understand that I could do this by clearing the timeout function, but I am stuck on how to integrate that into the current function. I am trying to add this functionality to the 'showSlides' function.

HTML

```<code><div class="galleryImages">
            <div class="numbertext">1 / 2</div>
            <img src="./assets/images/1.jpg" style="width: 100%;" />
          </div>

          <div class="galleryImages">
            <div class="numbertext">2 / 2</div>
            <img src="./assets/images/2.jpg" style="width: 100%;" />
          </div>

          <!-- Next and previous buttons -->
          <a class="prev" onclick="plusSlides(-1)">❮</a>
          <a class="next" onclick="plusSlides(1)">❯</a>
        </div>
</code>```

JS

```<code>var slideIndex = 0;
showSlides();

// Next/previous controls
function plusSlides(n) {
  changeSlides((slideIndex += n));
}
// automatically show slides and change the slide at the set timeout
function showSlides() {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  let gallery = document.getElementById("gallery");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {
    slideIndex = 1;
  }
  slides[slideIndex - 1].style.display = "block";
  setTimeout(showSlides, 5000); // Change image every 5 seconds
}
// change the slides based on the user input on the prev and next buttons
function changeSlides(n) {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  if (n > slides.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = slides.length;
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex - 1].style.display = "block";
}
</code>```

答:
In showSlides() set

```<code>gallery.addEventListener('mouseover', function() {
    // stop timeout here
});

gallery.addEventListener('mouseout', function() {
    // restart automatic slides change
});
</code>```

EDIT: as showSlides() is executed many times you'll need to remove event listeners, or refactor your code, so that those listeners are set once at the beginning only.

Body:
I am working on a slideshow / carousel in HTML with vanilla JS controlling the changing of the slides. I am happy with the current functionality, but I would like the slideshow to pause if the user hovers over the gallery. I understand that I could do this by clearing the timeout function, but I am stuck on how to integrate that into the current function. I am trying to add this functionality to the 'showSlides' function.

HTML

1 / 2

2 / 2

          ❮
          ❯

JS

var slideIndex = 0;
showSlides();

// Next/previous controls
function plusSlides(n) {
  changeSlides((slideIndex += n));
}
// automatically show slides and change the slide at the set timeout
function showSlides() {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  let gallery = document.getElementById("gallery");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {
    slideIndex = 1;
  }
  slides[slideIndex - 1].style.display = "block";
  setTimeout(showSlides, 5000); // Change image every 5 seconds
}
// change the slides based on the user input on the prev and next buttons
function changeSlides(n) {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  if (n > slides.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = slides.length;
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex - 1].style.display = "block";
}

Body:
In showSlides() set

gallery.addEventListener('mouseover', function() {
    // stop timeout here
});

gallery.addEventListener('mouseout', function() {
    // restart automatic slides change
});

EDIT: as showSlides() is executed many times you'll need to remove event listeners, or refactor your code, so that those listeners are set once at the beginning only.


问:
How to Convert a variable in drtn format to time format in R
I have a variable in drtn format that looks like this:

f <- structure(c(223, 35, 3, 16, 2, 183, 95, 146, 38, 30), class = "difftime", units = "secs")

```<code>< drtn> 223 secs, 35 secs, 3 secs, 16 secs, 2 secs, 183 secs, 95 secs, 146 secs, 38 secs
</code>```

I want to convert it to a time format like HMS or 00:00:00.

I want to avoid using the as_date function as this will provide the date in addition to the time but I am just looking for it to be in the HMS format similar to this:

```<code>< time> 00:03:43, 00:00:35, 00:00:03, 00:00:16, 00:00:02, 00:03:03, 00:01:35
...
</code>```

Thank you for your Help!

Body:
I have a variable in drtn format that looks like this:

f <- structure(c(223, 35, 3, 16, 2, 183, 95, 146, 38, 30), class = "difftime", units = "secs")

< drtn> 223 secs, 35 secs, 3 secs, 16 secs, 2 secs, 183 secs, 95 secs, 146 secs, 38 secs

I want to convert it to a time format like HMS or 00:00:00.

I want to avoid using the as_date function as this will provide the date in addition to the time but I am just looking for it to be in the HMS format similar to this:

< time> 00:03:43, 00:00:35, 00:00:03, 00:00:16, 00:00:02, 00:03:03, 00:01:35
...

Thank you for your Help!

Body:
One option is to convert the seconds to period and change it to hms

library(lubridate)
hms::hms(seconds_to_period(df1$col1))
#00:03:43
#00:00:35
#00:00:03
#00:00:16
#00:00:02
#00:03:03
#00:01:35
#00:02:26
#00:00:38

Or with dplyr

library(dplyr)
library(data.table)
df1 %>%
   mutate(col2 = as.ITime(hms::hms(seconds_to_period(col1))))
# A tibble: 9 x 2
#  col1     col2
#  <drtn>   <ITime>
#1 223 secs 00:03:43
#2  35 secs 00:00:35
#3   3 secs 00:00:03
#4  16 secs 00:00:16
#5   2 secs 00:00:02
#6 183 secs 00:03:03
#7  95 secs 00:01:35
#8 146 secs 00:02:26
#9  38 secs 00:00:38

data

df1 <- tibble(col1 = as.difftime(c(223, 35, 3, 16, 2, 183, 95, 146, 38), units = "secs"))


问:
Getting Exception thrown for glViewport(0, 0, framebufferWidth, framebufferHight);

#include "list.h"

int main()
{
    //INIT GLFW
    glfwInit();

    //CREATE WINDOW

    const int WINDOW_WIDTH = 640;
    const int WINDOW_HEIGHT = 480;
    int framebufferWidth = 0;
    int framebufferHight = 0;

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH,WINDOW_HEIGHT,"Title", NULL, NULL);

    glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHight);

    glViewport(0, 0, framebufferWidth, framebufferHight);

    glfwMakeContextCurrent(window);//IMPORTIANT!!

    //INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
    glewExperimental = GL_TRUE;

    >//Error

    if (glewInit() != GLEW_OK)
    {
        std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
        glfwTerminate();
    }

    //MAIN LOOP
    while (glfwWindowShouldClose(window))
    {
        //UPDATE INPUT ---

        //UPDATE ---

        //DRAW ---
        //Clear

        //Draw

        //End Draw
    }

    //END OF PROGAM
    glfwTerminate();

    return 0;
}
```

glViewport(0, 0, framebufferWidth, framebufferHight); is giving me

Unhandled exception at >0x00007FF704D6E7D9 in OpenzGL4.exe: 0xC0000005: Access violation reading >location >0x0000000000000348.

when I run it.

答:
In addition to what Rabbid76 already wrote in his answer, there is another problem in your code:

```<code>glViewport(0, 0, framebufferWidth, framebufferHight);

glfwMakeContextCurrent(window);//IMPORTIANT!!

//INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
glewExperimental = GL_TRUE;

>//Error

if (glewInit() != GLEW_OK) {
    std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
    glfwTerminate(); }
</code>```

Since you use the GLEW OpenGL loader, every gl...() Function name is actually remapped as a preprocessor macro to a function pointer, and glewInit will query all those function pointers (and that needs an active OpenGL context, so it can't be done before the glfwMakeContextCurrent). So it is not enough to move the glViewport after the glfwMakeContextCurrent, you must also move it after glewInit.

And there is a second issue with this code: the glewExperimental =  GL_TRUE is an evil hack for a bug in GLEW 1.x with OpenGL core profiles, and it's use can't be discouraged enough. Just update to GLEW 2.x or another loader which is compatible with OpenGL core profile contexts.

Body:
#include "list.h"

int main()
{
    //INIT GLFW
    glfwInit();

    //CREATE WINDOW

    const int WINDOW_WIDTH = 640;
    const int WINDOW_HEIGHT = 480;
    int framebufferWidth = 0;
    int framebufferHight = 0;

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH,WINDOW_HEIGHT,"Title", NULL, NULL);

    glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHight);

    glViewport(0, 0, framebufferWidth, framebufferHight);

    glfwMakeContextCurrent(window);//IMPORTIANT!!

    //INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
    glewExperimental = GL_TRUE;

    >//Error

    if (glewInit() != GLEW_OK)
    {
        std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
        glfwTerminate();
    }

    //MAIN LOOP
    while (glfwWindowShouldClose(window))
    {
        //UPDATE INPUT ---

        //UPDATE ---

        //DRAW ---
        //Clear

        //Draw

        //End Draw
    }

    //END OF PROGAM
    glfwTerminate();

    return 0;
}

glViewport(0, 0, framebufferWidth, framebufferHight); is giving me

Unhandled exception at >0x00007FF704D6E7D9 in OpenzGL4.exe: 0xC0000005: Access violation reading >location >0x0000000000000348.

when I run it.

Body:
In addition to what Rabbid76 already wrote in his answer, there is another problem in your code:

glViewport(0, 0, framebufferWidth, framebufferHight);

glfwMakeContextCurrent(window);//IMPORTIANT!!

//INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
glewExperimental = GL_TRUE;

>//Error

if (glewInit() != GLEW_OK) {
    std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
    glfwTerminate(); }

Since you use the GLEW OpenGL loader, every gl...() Function name is actually remapped as a preprocessor macro to a function pointer, and glewInit will query all those function pointers (and that needs an active OpenGL context, so it can't be done before the glfwMakeContextCurrent). So it is not enough to move the glViewport after the glfwMakeContextCurrent, you must also move it after glewInit.

And there is a second issue with this code: the glewExperimental =  GL_TRUE is an evil hack for a bug in GLEW 1.x with OpenGL core profiles, and it's use can't be discouraged enough. Just update to GLEW 2.x or another loader which is compatible with OpenGL core profile contexts.


问:
My preferences aren't 'sticking'
I'm trying to create a settings section for my app. I have a res/xml/settings.xml:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
  <ListPreference
    android:key="numberOfYears"
    android:title="Number of Years to Read the Bible"
    android:summary="How many years would you like to take to read through the reading plan?"
    android:entries="@array/numberOfYears"
    android:entryValues="@array/numberOfYears"
    android:dialogTitle="How Many Years?"
    />
  <CheckBoxPreference android:key="ignoreDates"
    android:title="Ignore Dates"
    android:summary="Would you like to use the dates in the plan?"
  />
</PreferenceScreen>
</code>```

I have a class called Preferences which extends PreferenceActivity and contains the following:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
}
</code>```

I wasn't sure if this was required but I also added the following to my main activity:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, PREFS_MENU, Menu.NONE, "Preferences");
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.d(TAG, "Menu Item: " + item.getItemId());
    switch (item.getItemId()) {
    case PREFS_MENU :
        startActivity(new Intent(this, Preferences.class));
        return true;
    }
    return false;
}
</code>```

This seems to work in that I get a "Preferences" menu which, when selected, launches my preferences.  However, when I select anything the values don't seem to stick.  My understanding was that the android:key was enough for the system to set the chosen values in the default shared preferences - is this not the case?

What am I missing?

答:
Not sure if I did this correctly and I would love to have inputs or another best or better practices as well.

I made my PreferenceActivity class also implements OnSharedPreferenceChangeListener, and have these methods implemented like this:

```<code>@Override
protected void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
    // TODO Auto-generated method stub
    Preference pref = findPreference(arg1);
    if (pref instanceof ListPreference) {
        ListPreference listPref = (ListPreference)pref;
        pref.setSummary(listPref.getEntry());
    }
    else {
        pref.setSummary(arg0.getString(arg1, pref.getSummary().toString()));
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: My preferences aren't 'sticking'

Body:
I'm trying to create a settings section for my app. I have a res/xml/settings.xml:

 <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
  <ListPreference
    android:key="numberOfYears"
    android:title="Number of Years to Read the Bible"
    android:summary="How many years would you like to take to read through the reading plan?"
    android:entries="@array/numberOfYears"
    android:entryValues="@array/numberOfYears"
    android:dialogTitle="How Many Years?"
    />
  <CheckBoxPreference android:key="ignoreDates"
    android:title="Ignore Dates"
    android:summary="Would you like to use the dates in the plan?"
  />
</PreferenceScreen>

I have a class called Preferences which extends PreferenceActivity and contains the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
}

I wasn't sure if this was required but I also added the following to my main activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, PREFS_MENU, Menu.NONE, "Preferences");
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.d(TAG, "Menu Item: " + item.getItemId());
    switch (item.getItemId()) {
    case PREFS_MENU :
        startActivity(new Intent(this, Preferences.class));
        return true;
    }
    return false;
}

This seems to work in that I get a "Preferences" menu which, when selected, launches my preferences.  However, when I select anything the values don't seem to stick.  My understanding was that the android:key was enough for the system to set the chosen values in the default shared preferences - is this not the case?

What am I missing?

Body:
Not sure if I did this correctly and I would love to have inputs or another best or better practices as well.

I made my PreferenceActivity class also implements OnSharedPreferenceChangeListener, and have these methods implemented like this:

@Override
protected void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
    // TODO Auto-generated method stub
    Preference pref = findPreference(arg1);
    if (pref instanceof ListPreference) {
        ListPreference listPref = (ListPreference)pref;
        pref.setSummary(listPref.getEntry());
    }
    else {
        pref.setSummary(arg0.getString(arg1, pref.getSummary().toString()));
    }
}

ContentLicense: CC BY-SA 3.0


问:
HeapFree is crashing
Summary:

I have VBA code that collects lots of info and writes it out into one or more worksheets. To improve perf writing lots of info into sheets, I created a class that acts kind of like a buffered copy/paste stream: the caller sends it CSV format strings which it buffers in memory until the buffer is full; when full, it pastes into a sheet, clears the buffer and continues.

Initially, I used Global memory, but then saw on MSDN a recommendation to use Heap rather than Global or Local due to less overhead. So now I'm using Heap.

I'm in the process of adapting everything for 64-bit Office. After doing all the PtrSafe stuff, I can run the code. But now Excel crashes when HeapFree() is called.

Question: Why is it crashing, and what do I need to change to avoid it?

Details:

I've come up with the following that is a minimized sample that repro's the crash: there's a module with a sub I can run for the repro, and the class. This doesn't do the buffering; every call to .SendText will put the text on the clipboard and paste into the active cell.

First the module. This has the following declare statements

```<code>' memory APIs
Public Const HEAP_ZERO_MEMORY = &H8

Declare PtrSafe Function GetProcessHeap Lib "kernel32" () As LongPtr 'returns HANDLE
Declare PtrSafe Function HeapAlloc Lib "kernel32" (ByVal hHeap As LongPtr, ByVal dwFlags As Long, ByVal dwBytes As LongPtr) As LongPtr 'returns HANDLE
Declare PtrSafe Function HeapFree Lib "kernel32" (ByVal hHeap As LongPtr, ByVal dwFlags As Long, lpMem As Any) As Long 'returns BOOL

Declare PtrSafe Function lstrcpy Lib "kernel32" Alias "lstrcpyW" (ByVal lpDestString As Any, ByVal lpSrcString As Any) As LongPtr 'returns HANDLE

' clipboard APIs
Public Const CF_UNICODETEXT = 13

Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hwnd As LongPtr) As Long 'returns BOOL
Declare PtrSafe Function EmptyClipboard Lib "user32" () As Long 'returns BOOL
Declare PtrSafe Function CloseClipboard Lib "user32" () As Long 'returns BOOL
Declare PtrSafe Function SetClipboardData Lib "user32" (ByVal wFormat As Long, ByVal hMem As LongPtr) As LongPtr   'returns HANDLE
</code>```

Then the sub:

```<code>Private Sub TestMemoryBugRepro()
    Dim s As String
    Dim clip As clsHeapBugRepro

    s = Chr(34) & "a" & vbLf & "b" & Chr(34) & ",c" & vbCrLf & "d" & vbTab & ",e" & vbCrLf

    Set clip = New clsHeapBugRepro
    clip.Initialize &H100
    clip.SendText s

    'Crash happens during the following
    Set clip = Nothing
End Sub
</code>```

Now the class. The crash occurs during Class_Terminate() when HeapFree is called.

```<code>Option Explicit

Private m_hHeap As LongPtr 'handle to the process heap
Private m_hMem As LongPtr 'handle to memory
Private m_pMem As LongPtr 'pointer to locked memory
Private m_cbMem As Long 'size of the memory buffer
Private m_BytesWritten As Long '

'**************************************
'  Event procedures

Private Sub Class_Initialize()
    m_hHeap = GetProcessHeap()
End Sub

Private Sub Class_Terminate()
    If m_hMem <> 0 And m_hHeap <> 0 Then
        HeapFree m_hHeap, 0, m_hMem       'CRASH OCCURS HERE
    End If
End Sub

'**************************************
'  Public methods

Public Function Initialize(Optional bufferSize As Long = &H8000) As Boolean
    Initialize = False
    m_BytesWritten = 0

    If m_hHeap <> 0 Then
        m_cbMem = bufferSize
        m_hMem = HeapAlloc(m_hHeap, (HEAP_ZERO_MEMORY), m_cbMem)
    End If
    If m_hMem <> 0 Then Initialize = True
End Function

Public Function SendText(text As String) As Boolean
    Dim nStrLen As Long

    nStrLen = LenB(text) + 2&
    Debug.Assert nStrLen < (m_cbMem + m_BytesWritten)

    m_pMem = m_hMem 'in lieu of locking heap memory
    lstrcpy m_pMem, StrPtr(text)
    m_pMem = 0 'in lieu of unlocking heap memory
    m_BytesWritten = m_BytesWritten + nStrLen

    DoEvents

    OpenClipboard 0&
    EmptyClipboard
    SetClipboardData CF_UNICODETEXT, m_hMem
    CloseClipboard

    ActiveCell.PasteSpecial
    DoEvents

    SendText = True
End Function
</code>```

答:
There's an issue in how you're calling HeapFree, but your real issue is that you shouldn't be using HeapAlloc/HeapFree at all.

Memory allocated by HeapAlloc is not movable, whereas SetClipboardData requires it to be moveable.

Another consideration is that SetClipboardData transfers the ownership of the memory to the system, which means you should not free it yourself. (The application may not write to or free the data once ownership has been transferred to the system.)

So, I would try to rewrite your logic using GlobalAlloc, not HeapAlloc, and don't try to free memory after it is put on the clipboard.

Now, there was an issue in how you were calling HeapFree, if you were going to use it. HeapFree wants the pointer returned by HeapAlloc.

You were instead passing a pointer to that pointer, because you declared the third argument of HeapFree As Any, which means ByRef As Any.

Either redeclare the argument ByVal As LongPtr / ByVal As Any, e.g.:

Declare PtrSafe Function HeapFree Lib "kernel32" (ByVal hHeap As LongPtr, _
                                                  ByVal dwFlags As Long,
                                                  ByVal lpMem As LongPtr) As Long 'returns BOOL
```

<p>or specify <code>ByVal</code> when calling it:</p>

<pre class="lang-vb prettyprint-override"><code>HeapFree m_hHeap, 0, ByVal m_hMem
</code>```

Title: HeapFree is crashing

Body:
Summary:

I have VBA code that collects lots of info and writes it out into one or more worksheets. To improve perf writing lots of info into sheets, I created a class that acts kind of like a buffered copy/paste stream: the caller sends it CSV format strings which it buffers in memory until the buffer is full; when full, it pastes into a sheet, clears the buffer and continues.

Initially, I used Global memory, but then saw on MSDN a recommendation to use Heap rather than Global or Local due to less overhead. So now I'm using Heap.

I'm in the process of adapting everything for 64-bit Office. After doing all the PtrSafe stuff, I can run the code. But now Excel crashes when HeapFree() is called.

Question: Why is it crashing, and what do I need to change to avoid it?

Details:

I've come up with the following that is a minimized sample that repro's the crash: there's a module with a sub I can run for the repro, and the class. This doesn't do the buffering; every call to .SendText will put the text on the clipboard and paste into the active cell.

First the module. This has the following declare statements

' memory APIs
Public Const HEAP_ZERO_MEMORY = &H8

Declare PtrSafe Function GetProcessHeap Lib "kernel32" () As LongPtr 'returns HANDLE
Declare PtrSafe Function HeapAlloc Lib "kernel32" (ByVal hHeap As LongPtr, ByVal dwFlags As Long, ByVal dwBytes As LongPtr) As LongPtr 'returns HANDLE
Declare PtrSafe Function HeapFree Lib "kernel32" (ByVal hHeap As LongPtr, ByVal dwFlags As Long, lpMem As Any) As Long 'returns BOOL

Declare PtrSafe Function lstrcpy Lib "kernel32" Alias "lstrcpyW" (ByVal lpDestString As Any, ByVal lpSrcString As Any) As LongPtr 'returns HANDLE

' clipboard APIs
Public Const CF_UNICODETEXT = 13

Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hwnd As LongPtr) As Long 'returns BOOL
Declare PtrSafe Function EmptyClipboard Lib "user32" () As Long 'returns BOOL
Declare PtrSafe Function CloseClipboard Lib "user32" () As Long 'returns BOOL
Declare PtrSafe Function SetClipboardData Lib "user32" (ByVal wFormat As Long, ByVal hMem As LongPtr) As LongPtr   'returns HANDLE

Then the sub:

Private Sub TestMemoryBugRepro()
    Dim s As String
    Dim clip As clsHeapBugRepro

    s = Chr(34) & "a" & vbLf & "b" & Chr(34) & ",c" & vbCrLf & "d" & vbTab & ",e" & vbCrLf

    Set clip = New clsHeapBugRepro
    clip.Initialize &H100
    clip.SendText s

    'Crash happens during the following
    Set clip = Nothing
End Sub

Now the class. The crash occurs during Class_Terminate() when HeapFree is called.

Option Explicit

Private m_hHeap As LongPtr 'handle to the process heap
Private m_hMem As LongPtr 'handle to memory
Private m_pMem As LongPtr 'pointer to locked memory
Private m_cbMem As Long 'size of the memory buffer
Private m_BytesWritten As Long '

'**************************************
'  Event procedures

Private Sub Class_Initialize()
    m_hHeap = GetProcessHeap()
End Sub

Private Sub Class_Terminate()
    If m_hMem <> 0 And m_hHeap <> 0 Then
        HeapFree m_hHeap, 0, m_hMem       'CRASH OCCURS HERE
    End If
End Sub

'**************************************
'  Public methods

Public Function Initialize(Optional bufferSize As Long = &H8000) As Boolean
    Initialize = False
    m_BytesWritten = 0

    If m_hHeap <> 0 Then
        m_cbMem = bufferSize
        m_hMem = HeapAlloc(m_hHeap, (HEAP_ZERO_MEMORY), m_cbMem)
    End If
    If m_hMem <> 0 Then Initialize = True
End Function

Public Function SendText(text As String) As Boolean
    Dim nStrLen As Long

    nStrLen = LenB(text) + 2&
    Debug.Assert nStrLen < (m_cbMem + m_BytesWritten)

    m_pMem = m_hMem 'in lieu of locking heap memory
    lstrcpy m_pMem, StrPtr(text)
    m_pMem = 0 'in lieu of unlocking heap memory
    m_BytesWritten = m_BytesWritten + nStrLen

    DoEvents

    OpenClipboard 0&
    EmptyClipboard
    SetClipboardData CF_UNICODETEXT, m_hMem
    CloseClipboard

    ActiveCell.PasteSpecial
    DoEvents

    SendText = True
End Function

Body:
There's an issue in how you're calling HeapFree, but your real issue is that you shouldn't be using HeapAlloc/HeapFree at all.

Memory allocated by HeapAlloc is not movable, whereas SetClipboardData requires it to be moveable.

Another consideration is that SetClipboardData transfers the ownership of the memory to the system, which means you should not free it yourself. (The application may not write to or free the data once ownership has been transferred to the system.)

So, I would try to rewrite your logic using GlobalAlloc, not HeapAlloc, and don't try to free memory after it is put on the clipboard.

Now, there was an issue in how you were calling HeapFree, if you were going to use it. HeapFree wants the pointer returned by HeapAlloc.

You were instead passing a pointer to that pointer, because you declared the third argument of HeapFree As Any, which means ByRef As Any.

Either redeclare the argument ByVal As LongPtr / ByVal As Any, e.g.:

Declare PtrSafe Function HeapFree Lib "kernel32" (ByVal hHeap As LongPtr, _
                                                  ByVal dwFlags As Long,
                                                  ByVal lpMem As LongPtr) As Long 'returns BOOL

or specify ByVal when calling it:

HeapFree m_hHeap, 0, ByVal m_hMem


问:
How do you call functions from a Windows Runtime Component (c#) in a UWP app written in c#?
I have created a UWP app for Windows 10 using Visual Studio 2019 that I want to utilize a library of functions when a button is clicked.
Here is the template I selected when creating my UWP app.

I chose to write the library using a Windows runtime component written in c# thinking it would be easily imported into my UWP app to where I could call the functions when a button is clicked on the UI. The Windows Runtime component will eventually need to be portable to other software which is why I am creating these two separately. The library has to have the ability to read/write to a USB port which is why I didn't chose Class library template. The class library doesn't allow you to import "System.IO.Ports", but the Windows runtime component does. I have very basic code in my library at the moment so if the Windows runtime component is not what I should be using please offer other suggestions.

I have seen tutorials calling functions from a component in JavaScript, but couldn't find any showing how to call functions from my Windows Runtime Component in a UWP App written in C#.

Project Directory showing where I would like to call these functions.

UI created with XAML

答:
VS2010: Use namespace from another project within the solution?

^^ Figured out I just needed to add reference of Windows Runtime Component to my UWP App.


问:
Apply js function to all inputs within a panel on an aspx form
I have a c# WebForms application where I add an onkeydown event to all of the textboxes within a panel in the Page_Load event:

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        foreach (var txt in panel1.Controls.OfType<TextBox>())
        {
            txt.Attributes.Add("onkeydown", "capsLock(event);");
        }
    }
</code>```

The above works as expected.  All of the textboxes within panel1 have onkeydown.  Here's an example:

```<code><input name="ctl00$MainContent$txtFrom" type="text" id="MainContent_txtFrom" class="form-control" onkeydown="capsLock(event);">
</code>```

Here is the capsLock function I copied from w3:

```<code>function capsLock() {
            var input = document.getElementById("MainContent_txtFrom");
            var text = document.getElementById("capslockdiv");
            input.addEventListener("keydown", function (event) {
                if (event.getModifierState("CapsLock")) {
                    text.style.display = "block";
                } else {
                    text.style.display = "none"
                }
            })
        };
</code>```

The above works just as expected for MainContent_txtFrom.  However, instead of adding each control to the function, I would prefer to apply it to all input elements.  I attempted changing var input to use getElementsByTagName("input"), but of course that didn't work.  How can I achieve this?

答:
Don't you already have an event attached to each input from the code in Page_Load. You should change your function capsLock to take in the event parameter as it is being set currently, then there is no need to find the element and add the event again.</p>

```<code> function capsLock(event) {
  var text = document.getElementById("capslockdiv");
  if (event.getModifierState("CapsLock")) {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}
</code>```

Body:
I have a c# WebForms application where I add an onkeydown event to all of the textboxes within a panel in the Page_Load event:

protected void Page_Load(object sender, EventArgs e)
    {
        foreach (var txt in panel1.Controls.OfType<TextBox>())
        {
            txt.Attributes.Add("onkeydown", "capsLock(event);");
        }
    }

The above works as expected.  All of the textboxes within panel1 have onkeydown.  Here's an example:

<input name="ctl00$MainContent$txtFrom" type="text" id="MainContent_txtFrom" class="form-control" onkeydown="capsLock(event);">

Here is the capsLock function I copied from w3:

function capsLock() {
            var input = document.getElementById("MainContent_txtFrom");
            var text = document.getElementById("capslockdiv");
            input.addEventListener("keydown", function (event) {
                if (event.getModifierState("CapsLock")) {
                    text.style.display = "block";
                } else {
                    text.style.display = "none"
                }
            })
        };

The above works just as expected for MainContent_txtFrom.  However, instead of adding each control to the function, I would prefer to apply it to all input elements.  I attempted changing var input to use getElementsByTagName("input"), but of course that didn't work.  How can I achieve this?

Body:
Don't you already have an event attached to each input from the code in Page_Load. You should change your function capsLock to take in the event parameter as it is being set currently, then there is no need to find the element and add the event again.

 function capsLock(event) {
  var text = document.getElementById("capslockdiv");
  if (event.getModifierState("CapsLock")) {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}


问:
Listview doesn't get updated when selected property changes in code
I have a simple demo application which shows a list and edit box shows the selected property. If I change the property in edit boxes, the list gets updated. But if I modify the same in code (cmmand handler) it doesn't get updated. Why is that?

```<code><StackPanel>
        <ListView  Margin="10" Name="myListView" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="First Name" Width="200" DisplayMemberBinding="{Binding FirstName}" />
                    <GridViewColumn Header="Last Name" Width="200" DisplayMemberBinding="{Binding LastName}" />
                </GridView>
            </ListView.View>
        </ListView>
        <TextBox Text="{Binding SelectedPerson.FirstName, UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="Update" Command="{Binding CmdUpdate}"/>
    </StackPanel>
</code>```

My ViewModel class is here

```<code>   class SimpleListViewModel : Notifier
    {
        private ObservableCollection<Person> _persons;
        public ObservableCollection<Person> Persons
        {
            get
            {
                return _persons;
            }
            set
            {
                _persons = value; //
                OnPropertyChanged("Persons");
            }
        }

        private Person _selectedPerson;

        public Person SelectedPerson
        {
            get { return _selectedPerson; }
            set
            {
                _selectedPerson = value;
                OnPropertyChanged("SelectedPerson");
            }
        }

        public RelayCommand CmdUpdate { get; private set; }

        public SimpleListViewModel()
        {
            var albert = new Person() { FirstName = "Albert", LastName = "Einstein" };
            var bruno = new Person() { FirstName = "Bruno", LastName = "Latour" };
            var charles = new Person() { FirstName = "Charles", LastName = "Darwin" };
            var newton = new Person() { FirstName = "Isaac", LastName = "Newton" };
            var hawking = new Person() { FirstName = "Stephen", LastName = "Hawking" };

            _persons = new ObservableCollection<Person>() { albert, bruno, charles, newton, hawking };

            CmdUpdate = new RelayCommand(OnCmdUpdate, IsCmdUpdateEnabled);
        }

        private bool IsCmdUpdateEnabled(object obj)
        {
            return true;
        }

        private void OnCmdUpdate(object obj)
        {
            //MessageBox.Show(SelectedPerson.FirstName);
            SelectedPerson.FirstName += " CHANGED"; // listview NOT getting updated
        }
    };
</code>```

答:
The answer is that when the data is updated via data binding and the Binding.Source is not a DependencyProperty, the binding engine will use reflection to to resolve the source property and then create a ValueChanged handler in case the Binding.Source doesn't implement INotifyPropertyChanged (which seems to be the true for Person). This will create a static reference to the source object, which is known to be a potential memory leak. The TextBox.Text property does all the work, since it is a DependencyProperty (remember that the Binding.Target must be a DependencyProperty). But if you omit the binding engine and manipulate the property directly and the class of this property doesn't implement INotifyPropertyChanged and doesn't raise the PropertyChanged event, the bindings that reference this manipulated property won't get notified about the manipulation.

To solve this Person must implement INotifyPropertyChanged and the Person.FirstName property must raise the INotifyPropertyChanged.PropertyChnaged event.

It is highly recommended to implement properties of every DependencyObject that are either Binding.Source or Binding.Target as DependencyProperty. This will result in the best performance.

If the Binding.Source is not a DependencyObject, it must implement INotifyPropertyChanged. If it doesn't, the performance impact will be significantly worse. See Microsoft Docs: Optimizing Performance: Data Binding.

Body:
I have a simple demo application which shows a list and edit box shows the selected property. If I change the property in edit boxes, the list gets updated. But if I modify the same in code (cmmand handler) it doesn't get updated. Why is that?

<StackPanel>
        <ListView  Margin="10" Name="myListView" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="First Name" Width="200" DisplayMemberBinding="{Binding FirstName}" />
                    <GridViewColumn Header="Last Name" Width="200" DisplayMemberBinding="{Binding LastName}" />
                </GridView>
            </ListView.View>
        </ListView>
        <TextBox Text="{Binding SelectedPerson.FirstName, UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="Update" Command="{Binding CmdUpdate}"/>
    </StackPanel>

My ViewModel class is here

   class SimpleListViewModel : Notifier
    {
        private ObservableCollection<Person> _persons;
        public ObservableCollection<Person> Persons
        {
            get
            {
                return _persons;
            }
            set
            {
                _persons = value; //
                OnPropertyChanged("Persons");
            }
        }

        private Person _selectedPerson;

        public Person SelectedPerson
        {
            get { return _selectedPerson; }
            set
            {
                _selectedPerson = value;
                OnPropertyChanged("SelectedPerson");
            }
        }

        public RelayCommand CmdUpdate { get; private set; }

        public SimpleListViewModel()
        {
            var albert = new Person() { FirstName = "Albert", LastName = "Einstein" };
            var bruno = new Person() { FirstName = "Bruno", LastName = "Latour" };
            var charles = new Person() { FirstName = "Charles", LastName = "Darwin" };
            var newton = new Person() { FirstName = "Isaac", LastName = "Newton" };
            var hawking = new Person() { FirstName = "Stephen", LastName = "Hawking" };

            _persons = new ObservableCollection<Person>() { albert, bruno, charles, newton, hawking };

            CmdUpdate = new RelayCommand(OnCmdUpdate, IsCmdUpdateEnabled);
        }

        private bool IsCmdUpdateEnabled(object obj)
        {
            return true;
        }

        private void OnCmdUpdate(object obj)
        {
            //MessageBox.Show(SelectedPerson.FirstName);
            SelectedPerson.FirstName += " CHANGED"; // listview NOT getting updated
        }
    };


问:
Django OAuth Toolkit invalid_grant error
I have a bit of a problem, I have a django application that is using Django OAuth Toolkit and I can't  get the access token from the server when using Authorization Code flow. Implicit flow works fine. I haven't find anything regarding my problem on stack so I'm really sorry if this is a duplicate of another question.

I can authorize with this url and get the request come back, if i understand it correctly the request token is past in the code param.

http://mydomain.se/o/authorize?scope=read+write&state=kalle&redirect_uri=mycallbakurls&response_type=code&client_id=myclientid

when i then try to do a post to http://mydomain.se/o/token/
with:

```<code>grant_type = authorization_code
code = code from authorize call
client_id = my clientId
client_secret = my client secret
redirect_uri = my callback url
</code>```

i get "error" : "invalid_grant" back.

Can someone please point me in the right direction what the problem can be?

Best regards Markus

答: Check to verify that you set your details correctly. For instance in my case my client_id was wrong.

Body:
I have a bit of a problem, I have a django application that is using Django OAuth Toolkit and I can't  get the access token from the server when using Authorization Code flow. Implicit flow works fine. I haven't find anything regarding my problem on stack so I'm really sorry if this is a duplicate of another question.

I can authorize with this url and get the request come back, if i understand it correctly the request token is past in the code param.

http://mydomain.se/o/authorize?scope=read+write&state=kalle&redirect_uri=mycallbakurls&response_type=code&client_id=myclientid

when i then try to do a post to http://mydomain.se/o/token/
with:

grant_type = authorization_code
code = code from authorize call
client_id = my clientId
client_secret = my client secret
redirect_uri = my callback url

i get "error" : "invalid_grant" back.

Can someone please point me in the right direction what the problem can be?

Best regards Markus


问:
ReactNative & Expo: Trouble incrementing/decrementing to cycle through an Array
I am attempting to cycle through sound objects in an Array, using an index value that begins at 0 and increments/decrements depending on whether I press next or back.

This is for a music player for react-native using the Expo//expo-av library. I'll include all relevant code.

State I have in my Context file:

```<code>const initialState = {
  startMusic: () => null,
  stopMusic: () => null,
  soundObject: null,
  isPlaying: false,
  currentIndex: 0,
}
useState()
const [soundObject, setSoundObject] = useState(initialState.soundObject)
const [isPlaying, setIsPlaying] = useState(initialState.isPlaying)
const [currentIndex, setCurrentIndex] = useState(initialState.currentIndex)
</code>```

Start Music function

```<code>const startMusic = async () => {
    try {
      const songToPlay = songs[currentIndex].song
      const source = songs[currentIndex].path

      await songToPlay.loadAsync(source)
      await songToPlay.playAsync()
      setSoundObject(songToPlay)
      setIsPlaying(true)
      return new Promise(resolve => {      // I made this promise when I was setting a loop to play through music.  May not need this anymore
        songToPlay.setOnPlaybackStatusUpdate(playbackStatus => {
          if (playbackStatus.didJustFinish) {
            console.log("Song finished")
            resolve()
          }
        })
      })
    } catch (error) {
      console.log(`Error: ${error}`)
      return
    }
  }
</code>```

And finally, the handler functions that are supposed to cycle through songs:

```<code>const handlePreviousTrack = async () => {
    if (soundObject) {
      await soundObject.stopAsync()
      await soundObject.unloadAsync()
      // setSoundObject(null)
      let newIndex = currentIndex

      newIndex < songs.length - 1 ? newIndex-- : (newIndex = 0)

      setCurrentIndex(newIndex)
      startMusic()

      console.log(currentIndex)
    }
  }

  const handleNextTrack = async () => {
    if (soundObject) {
      await soundObject.stopAsync()
      await soundObject.unloadAsync()
      // setSoundObject(null)
      let newIndex = currentIndex

      newIndex < songs.length - 1 ? newIndex++ : (newIndex = 0)

      setCurrentIndex(newIndex)
      startMusic()

      console.log(currentIndex)
    }
  }
</code>```

Cycling through next/previous does not go in order.
Sometimes it works, sometimes previous goes to the next song, sometimes pressing next just replays the first song.

Am I manipulating the state via currentIndex incorrectly?

答:
I don't see anything alarmingly wrong in the above code by quickly looking through it.  One suggestion I would have is to take your startMusic() call out of your two handleTrack methods and instead just have them set index state as they are doing.

Instead add a useEffect that will fire every time the index changes and put your startMusic() in that useEffect.

It would look something like this:

```<code>useEffect(() => {
   ... (other logic)
   startMusic()
}, [currentIndex])
</code>```

This will ensure startMusic will only get called after the currentIndex state has been changed and not be called too soon etc.  If not it may make it easier to track down when the state is changing regardless

Body:
I am attempting to cycle through sound objects in an Array, using an index value that begins at 0 and increments/decrements depending on whether I press next or back.

This is for a music player for react-native using the Expo//expo-av library. I'll include all relevant code.

State I have in my Context file:

const initialState = {
  startMusic: () => null,
  stopMusic: () => null,
  soundObject: null,
  isPlaying: false,
  currentIndex: 0,
}
useState()
const [soundObject, setSoundObject] = useState(initialState.soundObject)
const [isPlaying, setIsPlaying] = useState(initialState.isPlaying)
const [currentIndex, setCurrentIndex] = useState(initialState.currentIndex)

Start Music function

const startMusic = async () => {
    try {
      const songToPlay = songs[currentIndex].song
      const source = songs[currentIndex].path

      await songToPlay.loadAsync(source)
      await songToPlay.playAsync()
      setSoundObject(songToPlay)
      setIsPlaying(true)
      return new Promise(resolve => {      // I made this promise when I was setting a loop to play through music.  May not need this anymore
        songToPlay.setOnPlaybackStatusUpdate(playbackStatus => {
          if (playbackStatus.didJustFinish) {
            console.log("Song finished")
            resolve()
          }
        })
      })
    } catch (error) {
      console.log(`Error: ${error}`)
      return
    }
  }

And finally, the handler functions that are supposed to cycle through songs:

const handlePreviousTrack = async () => {
    if (soundObject) {
      await soundObject.stopAsync()
      await soundObject.unloadAsync()
      // setSoundObject(null)
      let newIndex = currentIndex

      newIndex < songs.length - 1 ? newIndex-- : (newIndex = 0)

      setCurrentIndex(newIndex)
      startMusic()

      console.log(currentIndex)
    }
  }

  const handleNextTrack = async () => {
    if (soundObject) {
      await soundObject.stopAsync()
      await soundObject.unloadAsync()
      // setSoundObject(null)
      let newIndex = currentIndex

      newIndex < songs.length - 1 ? newIndex++ : (newIndex = 0)

      setCurrentIndex(newIndex)
      startMusic()

      console.log(currentIndex)
    }
  }

Cycling through next/previous does not go in order.
Sometimes it works, sometimes previous goes to the next song, sometimes pressing next just replays the first song.

Am I manipulating the state via currentIndex incorrectly?

Body:
I don't see anything alarmingly wrong in the above code by quickly looking through it.  One suggestion I would have is to take your startMusic() call out of your two handleTrack methods and instead just have them set index state as they are doing.

Instead add a useEffect that will fire every time the index changes and put your startMusic() in that useEffect.

It would look something like this:

useEffect(() => {
   ... (other logic)
   startMusic()
}, [currentIndex])

This will ensure startMusic will only get called after the currentIndex state has been changed and not be called too soon etc.  If not it may make it easier to track down when the state is changing regardless


问:
Springboot mongo exception with Docker
I am new to docker and trying to connect a spring boot app with mongo db which is running on docker at port 27017. In my pom I have this:

```<code>        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
</code>```

I have not specified anything in application.properties. Below are logs from spring boot failure:

```<code>com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:67) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.8.2.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:579) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:339) ~[na:na]
    at java.base/java.net.Socket.connect(Socket.java:603) ~[na:na]
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.8.2.jar:na]
</code>```

And logs from mongodb(docker)

```<code>2020-05-30T00:31:55.387+0000 I  NETWORK  [listener] Listening on /tmp/mongodb-27017.sock
2020-05-30T00:31:55.388+0000 I  NETWORK  [listener] Listening on 0.0.0.0
2020-05-30T00:31:55.391+0000 I  NETWORK  [listener] waiting for connections on port 27017
2020-05-30T00:31:55.405+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index _id_ on ns config.system.sessions
2020-05-30T00:31:55.425+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: starting on config.system.sessions properties: { v: 2, key: { lastUse: 1 }, name: "lsidTTLIndex", ns: "config.system.sessions", expireAfterSeconds: 1800 } using method: Hybrid
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] build may temporarily use up to 200 megabytes of RAM
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: collection scan done. scanned 0 total records in 0 seconds
2020-05-30T00:31:55.429+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: inserted 0 keys from external sorter into index in 0 seconds
2020-05-30T00:31:55.431+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index lsidTTLIndex on ns config.system.sessions
2020-05-30T00:31:55.434+0000 I  SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: <unsharded>
2020-05-30T00:31:56.006+0000 I  SHARDING [ftdc] Marking collection local.oplog.rs as collection version: <unsharded>
</code>```

Can someone please help me out?

Thanks!

答: I was able to resolve this issue by getting the Windows 2004 version upgrade and then installing Docker Desktop for Windows(after uninstalling the Docker Toolbox legacy one, which was required for previous windows versions).</p>

Title: Springboot mongo exception with Docker

Body:
I am new to docker and trying to connect a spring boot app with mongo db which is running on docker at port 27017. In my pom I have this:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

I have not specified anything in application.properties. Below are logs from spring boot failure:

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:67) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.8.2.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:579) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:339) ~[na:na]
    at java.base/java.net.Socket.connect(Socket.java:603) ~[na:na]
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.8.2.jar:na]

And logs from mongodb(docker)

2020-05-30T00:31:55.387+0000 I  NETWORK  [listener] Listening on /tmp/mongodb-27017.sock
2020-05-30T00:31:55.388+0000 I  NETWORK  [listener] Listening on 0.0.0.0
2020-05-30T00:31:55.391+0000 I  NETWORK  [listener] waiting for connections on port 27017
2020-05-30T00:31:55.405+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index _id_ on ns config.system.sessions
2020-05-30T00:31:55.425+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: starting on config.system.sessions properties: { v: 2, key: { lastUse: 1 }, name: "lsidTTLIndex", ns: "config.system.sessions", expireAfterSeconds: 1800 } using method: Hybrid
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] build may temporarily use up to 200 megabytes of RAM
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: collection scan done. scanned 0 total records in 0 seconds
2020-05-30T00:31:55.429+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: inserted 0 keys from external sorter into index in 0 seconds
2020-05-30T00:31:55.431+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index lsidTTLIndex on ns config.system.sessions
2020-05-30T00:31:55.434+0000 I  SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: <unsharded>
2020-05-30T00:31:56.006+0000 I  SHARDING [ftdc] Marking collection local.oplog.rs as collection version: <unsharded>

Can someone please help me out?

Thanks!


问:
how to show only two text boxes at a time
how to show only two textbox only by next and previous button </p>

<p>this is my code,in this code when i click the next button show two textbox and aging when i click show the next two textbox..totally four textbox..i want only two text box per each click.......how can I achieve that ?

    </p>

```<code><script type="text/javascript">
var max=2;//highest number to go to
var currentIndex=0;
function Previous(){
  if(currentIndex>0){
    currentIndex--;
    postClick();
  }
}
function Next(){
  if(currentIndex<max){
    currentIndex++;
    document.getElementById("div").style.display="none"
    postClick();
  }
}
function postClick(){//whatever you want to happen goes here
  var sahan =new Array();
  sahan[currentIndex]==d;
  var d=document.getElementById("div");
  d.innerHTML+="<p><input type='text' name='name"+currentIndex+"[]'>";
  d.innerHTML+="<p><input type='text' name='topic"+currentIndex+"[]'>";
  form1.text1.value=currentIndex;
}
</script>

<form name="form1">
  <input type="button" value="Previous" onclick="Previous()"/>

  <input type="button" value="Next" onclick="Next()"/>

</form>
<div id="div"></div>
</body>
</html>
</code>```

答:
In the postClick() function, try to remove the first "+" on line 4, i.e.:

```<code>d.innerHTML="...";
</code>```

instead of

```<code>d.innerHTML+="...";
</code>```

Body:
how to show only two textbox only by next and previous button

this is my code,in this code when i click the next button show two textbox and aging when i click show the next two textbox..totally four textbox..i want only two text box per each click.......how can I achieve that ?

<form name="form1">
  <input type="button" value="Previous" onclick="Previous()"/>

  <input type="button" value="Next" onclick="Next()"/>

</form>

Body:
In the postClick() function, try to remove the first "+" on line 4, i.e.:

d.innerHTML="...";

instead of

d.innerHTML+="...";


问:
Django NoReverseMatch and wrong URL Pattern matching attempt
I am new to Django and trying to learn by creating a Blog App.

Now I ran into an error I am not able to solve. I tried everything and compared it to the tutorial I am following but it seems to be the same but for me it is not working.

So I have some posts which are listed on my feed page and when I want to click on the post title to get to the 'post-detail' page I am getting a NoReverseMatch Error because Django somehow tries to match with a wrong URL pattern, which is 'user-feed' but instead I am expecting to match with 'post-detail'.

Error Message:

```<code>Reverse for 'user-feed' with arguments '('',)' not found. 2 pattern(s) tried: ['feed/user/(?P<username>[^/]+)/$', 'user/(?P<username>[^/]+)/$']
</code>```

Feed.html:

```<code>{% for post in posts %}
        <article class="media content-section">
            <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
            <div class="media-body">
            <div class="article-metadata">
                <a class="mr-2" href="{% url 'user-feed' post.author.username %}">{{ post.author }}</a>
                <small class="text-muted">{{ post.date_posted|date:"d. F Y" }}</small>
            </div>
            <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
            </div>
        </article>
{% endfor %}
</code>```

My urls.py for my feed app looks as follows:

```<code>urlpatterns = [
    path('', login_required(PostListView.as_view()), name='feed-home'),
    path('user/<str:username>/', login_required(UserPostListView.as_view()), name='user-feed'),
    path('post/<int:pk>/', login_required(PostDetailView.as_view()), name='post-detail'),
    path('post/new/', login_required(PostCreateView.as_view()), name='post-create'),
    path('post/<int:pk>/update', login_required(PostUpdateView.as_view()), name='post-update'),
    path('post/<int:pk>/delete', login_required(PostDeleteView.as_view()), name='post-delete'),
    path('about/', views.about, name='feed-about'),
]
</code>```

My views.py looks like this:

```<code>class PostListView(ListView):
    model = Post
    template_name = 'feed/feed.html' # Replaces the original template src which is <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10

class UserPostListView(ListView):
    model = Post
    template_name = 'feed/user_feed.html' # Replaces the original template src which is <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

class PostDetailView(DetailView):
    model = Post

class PostCreateView(CreateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostUpdateView(UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    # Function to test whether the current user is the author of the post he wants to edit
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    # Function to test whether the current user is the author of the post he wants to delete
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
</code>```

My models.py looks as follows:

```<code>class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})
</code>```

Before this error occurred I deleted some old posts using the django admin page.

答:
I suspect it has a problem with this line:

```<code><a class="mr-2" href="{% url 'user-feed' post.author.username %}">{{ post.author }}</a>
</code>```

Most likely the post.author.username is not checking out, is it trying to access the author of one of the posts you deleted?

Body:
I am new to Django and trying to learn by creating a Blog App.

Now I ran into an error I am not able to solve. I tried everything and compared it to the tutorial I am following but it seems to be the same but for me it is not working.

So I have some posts which are listed on my feed page and when I want to click on the post title to get to the 'post-detail' page I am getting a NoReverseMatch Error because Django somehow tries to match with a wrong URL pattern, which is 'user-feed' but instead I am expecting to match with 'post-detail'.

Error Message:

Reverse for 'user-feed' with arguments '('',)' not found. 2 pattern(s) tried: ['feed/user/(?P<username>[^/]+)/$', 'user/(?P<username>[^/]+)/$']

Feed.html:

{% for post in posts %}

                {{ post.author }}
                {{ post.date_posted|date:"d. F Y" }}

{{ post.title }}

{{ post.content }}

{% endfor %}

My urls.py for my feed app looks as follows:

urlpatterns = [
    path('', login_required(PostListView.as_view()), name='feed-home'),
    path('user/<str:username>/', login_required(UserPostListView.as_view()), name='user-feed'),
    path('post/<int:pk>/', login_required(PostDetailView.as_view()), name='post-detail'),
    path('post/new/', login_required(PostCreateView.as_view()), name='post-create'),
    path('post/<int:pk>/update', login_required(PostUpdateView.as_view()), name='post-update'),
    path('post/<int:pk>/delete', login_required(PostDeleteView.as_view()), name='post-delete'),
    path('about/', views.about, name='feed-about'),
]

My views.py looks like this:

class PostListView(ListView):
    model = Post
    template_name = 'feed/feed.html' # Replaces the original template src which is <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10

class UserPostListView(ListView):
    model = Post
    template_name = 'feed/user_feed.html' # Replaces the original template src which is <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

class PostDetailView(DetailView):
    model = Post

class PostCreateView(CreateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostUpdateView(UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    # Function to test whether the current user is the author of the post he wants to edit
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    # Function to test whether the current user is the author of the post he wants to delete
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

My models.py looks as follows:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

Before this error occurred I deleted some old posts using the django admin page.

Body:
I suspect it has a problem with this line:

<a class="mr-2" href="{% url 'user-feed' post.author.username %}">{{ post.author }}</a>

Most likely the post.author.username is not checking out, is it trying to access the author of one of the posts you deleted?


问:
how to set rmse cost function in tensorflow
I have cost function in tensorflow.

```<code>activation = tf.add(tf.mul(X, W), b)
cost = (tf.pow(Y-y_model, 2)) # use sqr error for cost function
</code>```

I am trying out this example. How can I change it to rmse cost function?

答:
for who want to implement RMSE as a metric

```<code>rmse = tf.keras.metrics.RootMeanSquaredError()
</code>```

exapmle of how to use it

```<code>model.compile(optimizer=optimizer, loss='mean_squared_error',
              metrics=[rmse,'mae'])
</code>```

Body:
I have cost function in tensorflow.

activation = tf.add(tf.mul(X, W), b)
cost = (tf.pow(Y-y_model, 2)) # use sqr error for cost function

I am trying out this example. How can I change it to rmse cost function?

Body:
for who want to implement RMSE as a metric

rmse = tf.keras.metrics.RootMeanSquaredError()

exapmle of how to use it

model.compile(optimizer=optimizer, loss='mean_squared_error',
              metrics=[rmse,'mae'])


问:
How to get currency and currency symbol in flutter by country code?
I'm converting my app from Java(Android) to Flutter(Dart) and I can't find a method to get the currency from context or from a country code.

Code in Java:

```<code>String country = Locale.getDefault().getCountry();
String currency = Currency.getInstance(new Locale("", country)).getCurrencyCode();
</code>```

Code in Dart:

```<code>Locale locale = Localizations.localeOf(context);

String country = locale.countryCode;
</code>```

答:
after a long time of searching on this problem the only solution that solved my problem is USE A FONT THAT SUPPORT YOUR SYMBOLE.

this was my symbole "₺" and the font that supported it is "Roboto", you can specify a font for your text like this:

```<code>  Text('₺',
     style: TextStyle(
     fontFamily: 'Roboto',
      )),
</code>```

Body:
I'm converting my app from Java(Android) to Flutter(Dart) and I can't find a method to get the currency from context or from a country code.

Code in Java:

String country = Locale.getDefault().getCountry();
String currency = Currency.getInstance(new Locale("", country)).getCurrencyCode();

Code in Dart:

Locale locale = Localizations.localeOf(context);

String country = locale.countryCode;

Body:
after a long time of searching on this problem the only solution that solved my problem is USE A FONT THAT SUPPORT YOUR SYMBOLE.

this was my symbole "₺" and the font that supported it is "Roboto", you can specify a font for your text like this:

  Text('₺',
     style: TextStyle(
     fontFamily: 'Roboto',
      )),


问:
Incorrect results drawing horizontal and vertical lines to the LFB returned by VBE
I finally managed to draw a cyan pixel on the screen using the VESA BIOS Extensions (1920px * 1080px, 24bpp).

```<code>;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    lea eax, [esi]
    ;mov ecx, 0
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov ebx, 0x3296fa

    mov [edx], ebx
    ret
</code>```

I tried to draw a cyan horizontal line on the screen using a "for loop" this way:

```<code>mov edi, 1920
call drawLoop
jmp $

drawLoop:
    dec edi                                       ;decrease edi
    cmp edi, 0                                    ;is edi equal to zero?
    jl doneLoop                                   ;then return
    imul ebx, edi, 3                              ;multiply edi by three and save the result in ebx
    mov ecx, 0                                    ;y = 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel                                ;Draw it!
    jmp drawLoop                                  ;run this again

doneLoop:
    ret
</code>```

However, this doesn't work: it draws a green line instead.

When I try to draw a vertical line again with the draw/draw pixel code, it doesn't work either. It plots pixels with random colors everywhere. Here's how I use the DrawPixel function to draw a vertical line:

```<code>%include "../kernel/Services/Display/display.asm"

kernel:
    mov edi, 1080
    call drawLoop
    jmp $

drawLoop:
    dec edi
    cmp edi, 0
    jl doneLoop
    mov ecx, edi
    mov ebx, 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel
    jmp drawLoop

doneLoop:
    ret
</code>```

Any way to solve these problems?

答:
Let's start by re-writing the DrawPixel routine. Currently it's a bit of a mess!

There's no point in using the mul instruction that will clobber the EDX register needlessly. Better use a variant of imul.

And instead of using mov eax, 0 lea eax, [si] to load the EAX register, why don't you simply write mov eax, esi?

There's also an error to consider. Because you're working on a 24-bit true color screen, writing a whole dword (32 bits) will change part of an adjacent pixel.

```<code>;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

; IN (ebx,ecx,edx,esi) OUT () MOD (eax)
DrawPixel:
    mov     eax, esi                ; BytesPerScanLine
    imul    eax, ecx                ; BytesPerScanLine * Y
    add     eax, ebx                ; BytesPerScanLine * Y + X * 3
    mov     word [edx+eax], 0x96FA  ; Low word of RGB triplet
    mov     byte [edx+eax+2], 0x32  ; High byte of RGB triplet
    ret
</code>```

This new routine now only modifies the EAX register

The main part has problems of its own:

The mov esi, ModeInfoBlock + 10h will not retrieve the BytesPerScanLine info. For that to happen you would need movzx esi, word [ModeInfoBlock + 10h]

The loop uses 2 branches on every iteration. It's perfectly possible to write the loop with a single branch.

Next is my version of it. Because the new DrawPixel routine preserves all the registers (except EAX) great simplifications are possible:

```<code>    xor     ebx, ebx                         ; X = 0  -> EBX = X * 3
    xor     ecx, ecx                         ; Y = 0
    movzx   esi, word [ModeInfoBlock + 10h]  ; BytesPerScanLine
    mov     edx, [ModeInfoBlock + 28h]       ; PhysBasePtr
    call    drawLoop
    jmp     $

drawLoop:
    call    DrawPixel                        ; Modifies EAX
    add     ebx, 3                           ; Like X = X + 1
    cmp     ebx, 1920*3                      ; Length of the line is 1920 pixels
    jb      drawLoop
    ret
</code>```

My version draws this horizontal line from left to right. I believe it could be a tiny bit faster than drawing from the right to the left.

Instead of using a separate loop counter (EDI), I control the loop via the tripled-X coordinate. Amongst other benefits (like speed because cmpand jb pair up nicely) this relieves the pressure on register use.

Better horizontal and vertical line drawing routines

Especially for drawing horizontal and vertical lines, it is not a good idea to repeatedly call a DrawPixel routine. It's a waste of time to calculate the pixel's address over and over again. Below I show a couple routines specifically for these tasks.

I've added some extra changes:

You should not burden the main program with the technical details of addressing the video memory. Have the graphics routines retrieve the BytesPerScanLine and PhysBasePtr values.

The main program should deal with pixels at the (X,Y) level. That "times 3" stuff again is a technical detail that belongs to the graphics routines.

Hard coding the color in the drawing routines is very much not flexible.

```<code>; IN (eax,ebx,ecx,edx) OUT () MOD (eax)
; EAX = X
; EBX = Y
; ECX = Color
; EDX = Line length
HLine:
    push    edx
    push    edi
    movzx   edi, word [ModeInfoBlock + 10h]  ; BytesPerScanLine
    imul    edi, ebx                         ; BytesPerScanLine * Y
    imul    eax, 3                           ; X * 3
    add     edi, eax                         ; BytesPerScanLine * Y + X * 3
    add     edi, [ModeInfoBlock + 28h]       ; ... + PhysBasePtr
    mov     eax, ecx                         ; Color 24 bits
    shr     eax, 8
    imul    edx, 3                           ; Line length * 3
    add     edx, edi                         ; Address of the end of line
.a: mov     [edi], cx                        ; Low word of RGB triplet
    mov     [edi+2], ah                      ; High byte of RGB triplet
    add     edi, 3                           ; Like (X + 1)
    cmp     edi, edx
    jb      .a
    pop     edi
    pop     edx
    ret
</code>```

The above HLine routine draws a horizontal line from left to right.

```<code>; IN (eax,ebx,ecx,edx) OUT () MOD (eax)
; EAX = X
; EBX = Y
; ECX = Color
; EDX = Line length
VLine:
    push    edx
    push    esi
    push    edi
    movzx   esi, word [ModeInfoBlock + 10h]  ; BytesPerScanLine
    mov     edi, esi
    imul    edi, ebx                         ; BytesPerScanLine * Y
    imul    eax, 3                           ; X * 3
    add     edi, eax                         ; BytesPerScanLine * Y + X * 3
    add     edi, [ModeInfoBlock + 28h]       ; ... + PhysBasePtr
    mov     eax, ecx                         ; Color 24 bits
    shr     eax, 8
    imul    edx, esi                         ; Line length * BytesPerScanLine
    add     edx, edi                         ; Address of the end of line
.a: mov     [edi], cx                        ; Low word of RGB triplet
    mov     [edi+2], ah                      ; High byte of RGB triplet
    add     edi, esi                         ; Like (Y + 1)
    cmp     edi, edx
    jb      .a
    pop     edi
    pop     esi
    pop     edx
    ret
</code>```

The above VLine routine draws a vertical line from top to bottom.

This is how you could use these:

```<code>Main:
    xor     eax, eax                         ; X = 0
    xor     ebx, ebx                         ; Y = 0
    mov     ecx, 0x003296FA                  ; Color cyan
    mov     edx, 1920                        ; Line length
    call    HLine                            ; -> (EAX)
    mov     edx, 1080
    call    VLine                            ; -> (EAX)
    jmp     $
</code>```

Body:
I finally managed to draw a cyan pixel on the screen using the VESA BIOS Extensions (1920px * 1080px, 24bpp).

;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    lea eax, [esi]
    ;mov ecx, 0
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov ebx, 0x3296fa

    mov [edx], ebx
    ret

I tried to draw a cyan horizontal line on the screen using a "for loop" this way:

mov edi, 1920
call drawLoop
jmp $

drawLoop:
    dec edi                                       ;decrease edi
    cmp edi, 0                                    ;is edi equal to zero?
    jl doneLoop                                   ;then return
    imul ebx, edi, 3                              ;multiply edi by three and save the result in ebx
    mov ecx, 0                                    ;y = 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel                                ;Draw it!
    jmp drawLoop                                  ;run this again

doneLoop:
    ret

However, this doesn't work: it draws a green line instead.

When I try to draw a vertical line again with the draw/draw pixel code, it doesn't work either. It plots pixels with random colors everywhere. Here's how I use the DrawPixel function to draw a vertical line:

%include "../kernel/Services/Display/display.asm"

kernel:
    mov edi, 1080
    call drawLoop
    jmp $

drawLoop:
    dec edi
    cmp edi, 0
    jl doneLoop
    mov ecx, edi
    mov ebx, 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel
    jmp drawLoop

doneLoop:
    ret

Any way to solve these problems?

Body:
Let's start by re-writing the DrawPixel routine. Currently it's a bit of a mess!

There's no point in using the mul instruction that will clobber the EDX register needlessly. Better use a variant of imul.

And instead of using mov eax, 0 lea eax, [si] to load the EAX register, why don't you simply write mov eax, esi?

There's also an error to consider. Because you're working on a 24-bit true color screen, writing a whole dword (32 bits) will change part of an adjacent pixel.

;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

; IN (ebx,ecx,edx,esi) OUT () MOD (eax)
DrawPixel:
    mov     eax, esi                ; BytesPerScanLine
    imul    eax, ecx                ; BytesPerScanLine * Y
    add     eax, ebx                ; BytesPerScanLine * Y + X * 3
    mov     word [edx+eax], 0x96FA  ; Low word of RGB triplet
    mov     byte [edx+eax+2], 0x32  ; High byte of RGB triplet
    ret

This new routine now only modifies the EAX register

The main part has problems of its own:

The mov esi, ModeInfoBlock + 10h will not retrieve the BytesPerScanLine info. For that to happen you would need movzx esi, word [ModeInfoBlock + 10h]

The loop uses 2 branches on every iteration. It's perfectly possible to write the loop with a single branch.

Next is my version of it. Because the new DrawPixel routine preserves all the registers (except EAX) great simplifications are possible:

    xor     ebx, ebx                         ; X = 0  -> EBX = X * 3
    xor     ecx, ecx                         ; Y = 0
    movzx   esi, word [ModeInfoBlock + 10h]  ; BytesPerScanLine
    mov     edx, [ModeInfoBlock + 28h]       ; PhysBasePtr
    call    drawLoop
    jmp     $

drawLoop:
    call    DrawPixel                        ; Modifies EAX
    add     ebx, 3                           ; Like X = X + 1
    cmp     ebx, 1920*3                      ; Length of the line is 1920 pixels
    jb      drawLoop
    ret

My version draws this horizontal line from left to right. I believe it could be a tiny bit faster than drawing from the right to the left.

Instead of using a separate loop counter (EDI), I control the loop via the tripled-X coordinate. Amongst other benefits (like speed because cmpand jb pair up nicely) this relieves the pressure on register use.

Better horizontal and vertical line drawing routines

Especially for drawing horizontal and vertical lines, it is not a good idea to repeatedly call a DrawPixel routine. It's a waste of time to calculate the pixel's address over and over again. Below I show a couple routines specifically for these tasks.

I've added some extra changes:

You should not burden the main program with the technical details of addressing the video memory. Have the graphics routines retrieve the BytesPerScanLine and PhysBasePtr values.

The main program should deal with pixels at the (X,Y) level. That "times 3" stuff again is a technical detail that belongs to the graphics routines.

Hard coding the color in the drawing routines is very much not flexible.

; IN (eax,ebx,ecx,edx) OUT () MOD (eax)
; EAX = X
; EBX = Y
; ECX = Color
; EDX = Line length
HLine:
    push    edx
    push    edi
    movzx   edi, word [ModeInfoBlock + 10h]  ; BytesPerScanLine
    imul    edi, ebx                         ; BytesPerScanLine * Y
    imul    eax, 3                           ; X * 3
    add     edi, eax                         ; BytesPerScanLine * Y + X * 3
    add     edi, [ModeInfoBlock + 28h]       ; ... + PhysBasePtr
    mov     eax, ecx                         ; Color 24 bits
    shr     eax, 8
    imul    edx, 3                           ; Line length * 3
    add     edx, edi                         ; Address of the end of line
.a: mov     [edi], cx                        ; Low word of RGB triplet
    mov     [edi+2], ah                      ; High byte of RGB triplet
    add     edi, 3                           ; Like (X + 1)
    cmp     edi, edx
    jb      .a
    pop     edi
    pop     edx
    ret

The above HLine routine draws a horizontal line from left to right.

; IN (eax,ebx,ecx,edx) OUT () MOD (eax)
; EAX = X
; EBX = Y
; ECX = Color
; EDX = Line length
VLine:
    push    edx
    push    esi
    push    edi
    movzx   esi, word [ModeInfoBlock + 10h]  ; BytesPerScanLine
    mov     edi, esi
    imul    edi, ebx                         ; BytesPerScanLine * Y
    imul    eax, 3                           ; X * 3
    add     edi, eax                         ; BytesPerScanLine * Y + X * 3
    add     edi, [ModeInfoBlock + 28h]       ; ... + PhysBasePtr
    mov     eax, ecx                         ; Color 24 bits
    shr     eax, 8
    imul    edx, esi                         ; Line length * BytesPerScanLine
    add     edx, edi                         ; Address of the end of line
.a: mov     [edi], cx                        ; Low word of RGB triplet
    mov     [edi+2], ah                      ; High byte of RGB triplet
    add     edi, esi                         ; Like (Y + 1)
    cmp     edi, edx
    jb      .a
    pop     edi
    pop     esi
    pop     edx
    ret

The above VLine routine draws a vertical line from top to bottom.

This is how you could use these:

Main:
    xor     eax, eax                         ; X = 0
    xor     ebx, ebx                         ; Y = 0
    mov     ecx, 0x003296FA                  ; Color cyan
    mov     edx, 1920                        ; Line length
    call    HLine                            ; -> (EAX)
    mov     edx, 1080
    call    VLine                            ; -> (EAX)
    jmp     $