问:
how do I see if two values are not equal in APL?
Writing an APL function- how do I check to see if two values are not equal?
I tried like this:

```<code> :If (rowValue ≠ columnValue)
</code>```

but that gives me a LengthError.
Thank you!

答:
Just use ≢.

Note that many browser engines have a rendering bug which means that the Unicode character ≢ U+2262 "Not identical to" renders as "Identical to" ≡ followed by a slash / like ≢ . This is a single character (and displays correctly in all text editor that I have come across).

It should look like this: <img src="https://i.stack.imgur.com/FpyGw.png" alt="≢">

Body:
Writing an APL function- how do I check to see if two values are not equal?
I tried like this:

 :If (rowValue ≠ columnValue)

but that gives me a LengthError.
Thank you!


来源: stackexchange

问:
Advice/ on how to plot side by side histograms with line graph going through in ggplot2
I'm currently finishing off my Masters project and need to include some graphics for the write-up. Without boring you too much, I have some data which is associated with AR(1) parameters ranging from 0.1 to 0.9 by 0.1 increments. As such I thought of doing a faceted histogram like the one below (worry not about the hideous fruit salad of colours, it will not be used).

I used this code.

```<code>ggplot(opt_lens_geom,aes(x=l_1024,fill=factor(rho))) + geom_histogram()+coord_flip()+facet_grid(.~rho,scales = "free_x")
</code>```

I also would like to draw a trend line for the median values since the AR(1) parameter is continuous. In a later iteration I deleted the padding and made it "look" like it was one graph, but I have had issues with the endpoints matching up since each facet is a separate graphical device. Can anyone give me some advice on how to do this? I am not particularly partial to the faceting so if it is not needed I do away with it.

I will try and upload sample data, but all simulating 100 values for each of the 9 rhos would work just to get it started like:

```<code>opt_lens_geom <- data.frame(rho= rep(seq(0.1,0.9,by=0.1),each=100),l_1024=rnorm(900))
</code>```

答:
You might consider ggridges. I've assumed here that you want a median value for each value of rho.

```<code>library(ggplot2)
library(ggridges)
library(dplyr)

set.seed(1001)
opt_lens_geom <- data.frame(rho = rep(seq(0.1, 0.9, by = 0.1), each = 100),
                            l_1024 = rnorm(900))

opt_lens_geom %>%
  mutate(rho_f = factor(rho)) %>%
  ggplot(aes(l_1024, rho_f)) +
  stat_density_ridges(quantiles = 2, quantile_lines = TRUE)
</code>```

Result. You can add scale = 1 as a parameter to stat_density_ridges if you don't like the amount of overlap.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently finishing off my Masters project and need to include some graphics for the write-up. Without boring you too much, I have some data which is associated with AR(1) parameters ranging from 0.1 to 0.9 by 0.1 increments. As such I thought of doing a faceted histogram like the one below (worry not about the hideous fruit salad of colours, it will not be used).

I used this code.

ggplot(opt_lens_geom,aes(x=l_1024,fill=factor(rho))) + geom_histogram()+coord_flip()+facet_grid(.~rho,scales = "free_x")

I also would like to draw a trend line for the median values since the AR(1) parameter is continuous. In a later iteration I deleted the padding and made it "look" like it was one graph, but I have had issues with the endpoints matching up since each facet is a separate graphical device. Can anyone give me some advice on how to do this? I am not particularly partial to the faceting so if it is not needed I do away with it.

I will try and upload sample data, but all simulating 100 values for each of the 9 rhos would work just to get it started like:

opt_lens_geom <- data.frame(rho= rep(seq(0.1,0.9,by=0.1),each=100),l_1024=rnorm(900))

Body:
You might consider ggridges. I've assumed here that you want a median value for each value of rho.

library(ggplot2)
library(ggridges)
library(dplyr)

set.seed(1001)
opt_lens_geom <- data.frame(rho = rep(seq(0.1, 0.9, by = 0.1), each = 100),
                            l_1024 = rnorm(900))

opt_lens_geom %>%
  mutate(rho_f = factor(rho)) %>%
  ggplot(aes(l_1024, rho_f)) +
  stat_density_ridges(quantiles = 2, quantile_lines = TRUE)

Result. You can add scale = 1 as a parameter to stat_density_ridges if you don't like the amount of overlap.


问:
How to get window (like dialog, popupmenu...)
I'm working on library and it should find out if non-activity window (e.g. dialog, popupmenu....) is on the screen. I tried this...

```<code>((Activity)context).getWindow()
</code>```

but it always return main activity window, not what I want.

Is there any way to get Window on the screen or activated?

答:
Your code is getting the window of the activity because you are calling the getWindow() method on your activity object.

Instead ((Activity)context).getWindow() try dialog.getWindow()

Body:
I'm working on library and it should find out if non-activity window (e.g. dialog, popupmenu....) is on the screen. I tried this...

((Activity)context).getWindow()

but it always return main activity window, not what I want.

Is there any way to get Window on the screen or activated?


问:
How to test a className with the Jest and React testing library
I am totally new to JavaScript testing and am working in a new codebase. I would like to write a test that is checking for a className on the element. I am working with Jest and React Testing Library. Below I have a test that will render a button based on the variant prop. It also contains a className and I would like to test that.

```<code>it('Renders with a className equal to the variant', () => {
    const { container } = render(<Button variant="default" />)
    expect(container.firstChild) // Check for className here
})
</code>```

I tried to google for a property like Enzyme has with hasClass, but I couldn't find anything. How can I solve this with the current libraries (React Testing Library and Jest)?

答:
You need to understand the philosophy behind react-testing-library to understand what you can do and what you can't do with it;

The goal behind react-testing-library is for the tests to avoid including implementation details of your components and rather focus on writing tests that give you the confidence for which they are intended.

So querying element by classname is not aligned with the react-testing-library philosophy as it includes implementation details. The classname is actual the implementation detail of an element and is not something the end user will see, and it is subjected to change at anytime in the lifecycle of the element.

So instead of searching element by what user cannot see, and something that can change at anytime, just try to search by using something that the user can see, such as text, label or something that will remain constant in the life cycle of the element like data-id.

So to answer your question, it is not advised to test classname and hence you cannot do that with react-testing-library. Try with other test libraries such as Enzyme or react-dom test utils.

Body:
I am totally new to JavaScript testing and am working in a new codebase. I would like to write a test that is checking for a className on the element. I am working with Jest and React Testing Library. Below I have a test that will render a button based on the variant prop. It also contains a className and I would like to test that.

it('Renders with a className equal to the variant', () => {
    const { container } = render(<Button variant="default" />)
    expect(container.firstChild) // Check for className here
})

I tried to google for a property like Enzyme has with hasClass, but I couldn't find anything. How can I solve this with the current libraries (React Testing Library and Jest)?


问:
Manually calculate AUC
How can I obtain the AUC value having fpr and tpr? Fpr and tpr are just 2 floats obtained from these formulas:

```<code>my_fpr = fp / (fp + tn)
my_tpr = tp / (tp + fn)
my_roc_auc = auc(my_fpr, my_tpr)
</code>```

I know this can't pe possible, because fpr and tpr are just some floats and they need to be arrays, but I can't figure it out how to do that so. I also know that I can compute AUC this way:

```<code>y_predict_proba = model.predict_proba(X_test)
probabilities = np.array(y_predict_proba)[:, 1]
fpr, tpr, _ = roc_curve(y_test, probabilities)
roc_auc = auc(fpr, tpr)
</code>```

but I want to avoid using predict_proba for some reasons. So my question is: how can I obtain AUC having fp, tp, fn, tn, fpr, tpr? In other words, is it possible to obtain AUC without roc_curve?

答:
Yes, it is possible to obtain the AUC without calling roc_curve.

You first need to create the ROC (Receiver Operating Characteristics) curve. To be able to use the ROC curve, your classifier should be able to rank examples such that the ones with higher rank are more likely to be positive (e.g. fraudulent). As an example, Logistic Regression outputs probabilities, which is a score that you can use for ranking.
The ROC curve is created by plotting the True Positive Pate (TPR) against the False Positive Rate (FPR) at various threshold settings. As an example:

The model performance is determined by looking at the area under the ROC curve (or AUC)

You can find here the more detailed explanation.

Title: Manually calculate AUC

Body:
How can I obtain the AUC value having fpr and tpr? Fpr and tpr are just 2 floats obtained from these formulas:

my_fpr = fp / (fp + tn)
my_tpr = tp / (tp + fn)
my_roc_auc = auc(my_fpr, my_tpr)

I know this can't pe possible, because fpr and tpr are just some floats and they need to be arrays, but I can't figure it out how to do that so. I also know that I can compute AUC this way:

y_predict_proba = model.predict_proba(X_test)
probabilities = np.array(y_predict_proba)[:, 1]
fpr, tpr, _ = roc_curve(y_test, probabilities)
roc_auc = auc(fpr, tpr)

but I want to avoid using predict_proba for some reasons. So my question is: how can I obtain AUC having fp, tp, fn, tn, fpr, tpr? In other words, is it possible to obtain AUC without roc_curve?


问:
Redis vs Aerospike usecases?
After going through couple of resources on Google and stack overflow(mentioned below) , I have got high level understanding when to use what but
got couple of questions too

My Understanding :

When used as pure in-memory  memory databases both have comparable performance. But for big data where complete complete dataset
can not be fit in memory or even if it can be fit (but it increases the cost), AS(aerospike) can be the good fit as it provides
the mode where indexes can be kept in memory and data in SSD. I believe performance will be bit degraded(compared to completely in memory
db though the way AS handles the read/write from SSD , it makes it fast then traditional disk I/O) but saves the cost and provide performance
then complete data on disk. So when complete data can be fit in memory both can be
equally good but when memory is constraint AS can be good case. Is that right ?

Also it is said that AS provided rich and easy to set up clustering feature whereas some of clustering  features in redis needs to be
handled at application. Is it still hold good or  it was true till couple of years back(I believe so as I see redis also provides clustering
feature) ?

How is aerospike different from other key-value nosql databases?

What are the use cases where Redis is preferred to Aerospike?

答:
Your assumption in (1) is off, because it applies to (mostly) synthetic situations where all data fits in memory. What happens when you have a system that grows to many terabytes or even petabytes of data? Would you want to try and fit that data in a very expensive, hard to manage fully in-memory system containing many nodes?  A modern machine can store a lot more SSD/NVMe drives than memory. If you look at the new i3en instance family type from Amazon EC2, the i3en.24xl has 768G of RAM and 60TB of NVMe storage (8 x 7.5TB). That kind of machine works very well with Aerospike, as it only stores the indexes in memory. A very large amount of data can be stored on a small cluster of such dense nodes, and perform exceptionally well.

Aerospike is used in the real world in clusters that have grown to hundreds of terabytes or even petabytes of data (tens to hundreds of billions of objects), serving millions of operations per-second, and still hitting sub-millisecond to single digit millisecond latencies. See https://www.aerospike.com/summit/ for several talks on that topic.

Another aspect affecting (1) is the fact that the performance of a single instance of Redis is misleading if in-reality you'll be deployed on multiple servers, each with multiple instances of Redis on them. Redis isn't a distributed database as Aerospike is - it requires application-side sharding (which becomes a bit of a clustering and horizontal scaling nightmare) or a separate proxy, which often ends up being the bottleneck. It's great that a single shard can do a million operations per-second, but if the proxy can't handle the combined throughput, and competes with shards for CPU and memory, there's more to the performance at scale picture than just in-memory versus data on SSD.

Unless you're looking at a tiny amount of objects or a small amount of data that isn't likely to grow, you should probably compare the two for yourself with a proof-of-concept test.

Title: Redis vs Aerospike usecases?


问:
PIXI how to completely remove a sprite
I'm trying to completely remove a sprite from my game(acting as a death). All I could find online was:

```<code>sprite.parent.removeChild(sprite);
</code>```

When I did this, the sprite stops rendering, but i'm pretty sure the sprite is still there, and my collisions are still being detected and it's causing lot's of problems. How do i completely remove the sprite from the scene?

答:
An entity gets deleted in javascript when there are no references pointing to it and GC (garbage collector) runs. Thus, to fully delete sprite you need to unlink it from everything.

If you have for example a SpriteContainer and within it you did

```<code>mySprite = new PIXI.Sprite(myTexture)
this.addChild(mySprite)
</code>```

then you need to both use removeChild as you did, but also clear the mySprite reference.

Now please consider that GC runs are managed by the browser engine, so you might actually need to wait for a while before you see the sprite gone from memory.

And if you referenced it in chrome console, this too is a reference to the sprite and it won't get removed if you have it open.

To confirm the Sprite gets deleted, use browser's developer's tool, take a memory snapshot before and after deletion, and use a built-in comparision tool. If you see a delta of -1 for Sprite (and optionally also its Texture and BaseTexture), you're good. You can also manually call GC within developers' tools.

Note: a PIXI.Sprite displays a Texture. Removal of Sprite does not necessarily cause removal of the Texture. PIXI has its own GC which will take care of abandoned textures, but if your object gets created and deleted often, it is better to keep the texture in memory so it doesn't cause stutter when loading up. To also clear contents of the sprite, please refer to destroy method, as documented here: http://pixijs.download/dev/docs/PIXI.Sprite.html

Title: PIXI how to completely remove a sprite

Body:
I'm trying to completely remove a sprite from my game(acting as a death). All I could find online was:

sprite.parent.removeChild(sprite);

When I did this, the sprite stops rendering, but i'm pretty sure the sprite is still there, and my collisions are still being detected and it's causing lot's of problems. How do i completely remove the sprite from the scene?

Body:
An entity gets deleted in javascript when there are no references pointing to it and GC (garbage collector) runs. Thus, to fully delete sprite you need to unlink it from everything.

If you have for example a SpriteContainer and within it you did

mySprite = new PIXI.Sprite(myTexture)
this.addChild(mySprite)

then you need to both use removeChild as you did, but also clear the mySprite reference.

Now please consider that GC runs are managed by the browser engine, so you might actually need to wait for a while before you see the sprite gone from memory.

And if you referenced it in chrome console, this too is a reference to the sprite and it won't get removed if you have it open.

To confirm the Sprite gets deleted, use browser's developer's tool, take a memory snapshot before and after deletion, and use a built-in comparision tool. If you see a delta of -1 for Sprite (and optionally also its Texture and BaseTexture), you're good. You can also manually call GC within developers' tools.

Note: a PIXI.Sprite displays a Texture. Removal of Sprite does not necessarily cause removal of the Texture. PIXI has its own GC which will take care of abandoned textures, but if your object gets created and deleted often, it is better to keep the texture in memory so it doesn't cause stutter when loading up. To also clear contents of the sprite, please refer to destroy method, as documented here: http://pixijs.download/dev/docs/PIXI.Sprite.html


问:
A in-place recursive solution to reverse a string
I am learning recursion basics from leetcode's featured tutorial Recursion I

The first exercise is to  reverse a string Reverse String - LeetCode

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

```<code>Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
</code>```

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
```
</blockquote>

<p>The accepted solution is </p>

<pre class="lang-py prettyprint-override"><code>
class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        #base case
        if len(s) <= 1:
            return s
        #recur case
        elif len(s) >= 2:
            n=len(s)
            return self.reverseString(s[n//2:])+self.reverseString(s[:n//2])
</code>```

Two Problem with the solution:

1, Not modify in-place

2, It's expensive to recursively slicing a string.

As the first step to improve it, introduced parameters lo and hi to store index

class Solution:
    def reverseString(self, s, lo=0, hi=None):
        """
        :type s: str
        :rtype: None
        """
        if hi == None:
            hi = len(s)
      #base case
        if hi <= 1:
            return s

        #recur case
        elif hi >= 2:
            mid = hi // 2
            left = self.reverseString(s, lo, mid)
            right = self.reverseString(s, mid, hi)
            return left + right
```

It report error

　RecursionError: maximum recursion depth exceeded in comparison

Ran 1 test in 0.005s

Ｗhat' s the problem?

答:
Here is in place solution for this problem:</p>

```<code>class Solution(object):
    def reverseString(self, s, left=0, right=0):
        if right == 0:
            right = len(s) - 1

        if left >= right:
            return

        temp = s[right]
        s[right] = s[left]
        s[left] = temp
        self.reverseString(s, left+1, right -1)
</code>```

Body:
I am learning recursion basics from leetcode's featured tutorial Recursion I

The first exercise is to  reverse a string Reverse String - LeetCode

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

The accepted solution is

class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        #base case
        if len(s) <= 1:
            return s
        #recur case
        elif len(s) >= 2:
            n=len(s)
            return self.reverseString(s[n//2:])+self.reverseString(s[:n//2])

Two Problem with the solution:

1, Not modify in-place

2, It's expensive to recursively slicing a string.

As the first step to improve it, introduced parameters lo and hi to store index

class Solution:
    def reverseString(self, s, lo=0, hi=None):
        """
        :type s: str
        :rtype: None
        """
        if hi == None:
            hi = len(s)
      #base case
        if hi <= 1:
            return s

        #recur case
        elif hi >= 2:
            mid = hi // 2
            left = self.reverseString(s, lo, mid)
            right = self.reverseString(s, mid, hi)
            return left + right

It report error

　RecursionError: maximum recursion depth exceeded in comparison

Ran 1 test in 0.005s

Ｗhat' s the problem?

Body:
Here is in place solution for this problem:

class Solution(object):
    def reverseString(self, s, left=0, right=0):
        if right == 0:
            right = len(s) - 1

        if left >= right:
            return

        temp = s[right]
        s[right] = s[left]
        s[left] = temp
        self.reverseString(s, left+1, right -1)


问:
Why do I not have to define the variable in a for loop using range(), but I do have to in a while loop in Python?
I have the following code using a for loop:

```<code>    total = 0
    for num in range(101):
       total = total + num
       print(total)
</code>```

Now the same result using a while loop:

```<code>    num = 0
    total = 0
    while num <= 99:
         num = num + 1
         total = total + num
         print(total)
</code>```

Why is it that I do not have to define num in the first case, but I do have to define it in the second? Are they both not variables?

答:
I'd like to approach this question from a slightly different perspective.

If we look at the official Python grammar specification, we can see that (approximately speaking), a while statement takes a test, while a for statement takes an exprlist and testlist.

Conceptually, then, we can understand that a while statement needs one thing: an expression that it can repeatedly evaluate.

On the other hand, a for statement needs two: a collection of expressions to be evaluated, as well as a number of names to bind the results of those evaluations to.

With this in mind, it makes sense that a while statement would not automatically create a temporary variable, since it can accept literals too. Conversely, a for statement must bind to some names.

(Strictly speaking, it is valid, in terms of Python grammar, to put a literal where you would expect a name in a for statement, but contextually that wouldn't make sense, so the language prohibits it.)

Body:
I have the following code using a for loop:

    total = 0
    for num in range(101):
       total = total + num
       print(total)

Now the same result using a while loop:

    num = 0
    total = 0
    while num <= 99:
         num = num + 1
         total = total + num
         print(total)

Why is it that I do not have to define num in the first case, but I do have to define it in the second? Are they both not variables?


问:
Intent is not working for moving fragment to activity
I'm having trouble moving intent class fragment to activity. I'm trying to send intent from one Fragment to another Activity.
Here is the code:

```<code>        Intent intent = new Intent(getActivity(), MainActivity.class);
        getActivity().startActivity(intent);
</code>```

Here is my Manifest File

```<code>    <activity android:name=".activities.MainActivity"
        android:supportsPictureInPicture="true"
        android:resizeableActivity="true"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustNothing"
        android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"/>
</code>```

but it's not working for me and on another side, I have done some RND but all are same for me.
How can I Solve the issue
Thanks In Advance.

答:
remove this android:launchMode="singleTask"
which looks like this

```<code><activity android:name=".activities.MainActivity"
        android:supportsPictureInPicture="true"
        android:resizeableActivity="true"
        android:windowSoftInputMode="adjustNothing"
        android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"/>
</code>```

if your current activity is mainactivity and you are launching it again , it will not work because launchmode is set to single task in manifest

Solution :- remove this tag

android:launchMode="singleTask"

Body:
I'm having trouble moving intent class fragment to activity. I'm trying to send intent from one Fragment to another Activity.
Here is the code:

        Intent intent = new Intent(getActivity(), MainActivity.class);
        getActivity().startActivity(intent);

Here is my Manifest File

    <activity android:name=".activities.MainActivity"
        android:supportsPictureInPicture="true"
        android:resizeableActivity="true"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustNothing"
        android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"/>

but it's not working for me and on another side, I have done some RND but all are same for me.
How can I Solve the issue
Thanks In Advance.

Body:
remove this android:launchMode="singleTask"
which looks like this

<activity android:name=".activities.MainActivity"
        android:supportsPictureInPicture="true"
        android:resizeableActivity="true"
        android:windowSoftInputMode="adjustNothing"
        android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"/>

if your current activity is mainactivity and you are launching it again , it will not work because launchmode is set to single task in manifest

Solution :- remove this tag

android:launchMode="singleTask"


问:
How to restore a modified file in geany on linux?
I have modified a file (personal file) and I saved the modification, now I want to restore the file to its last status before the modification, is it possible? how?</p>

答:
If you have just overwritten the file (Ctrl+S) and haven't yet quit Geany, you can just Ctrl+Z to the desired document state and save that file version.

If you have already quit Geany after that and haven't set up back up in Geany before, I am afraid that by means of Geany you cannot restore the file to the previous state.

Read this article about how to set up back up in Geany. Basically you can go to Edit -> Preferences -> Various (read the manual and the link above before changing these preferences) and:

disable use_atomic_file_saving (disabled by default)

enable use_gio_unsafe_file_saving (enabled by default)

enable gio_unsafe_save_backup (disabled by default)

This will always keep the previous version of the file (as a hidden file with ~ attached to its name) next to original.

Or you can install/enable the Save Actions Geany plugin and enable the Auto Save and Backup Copy options to automatically save files at a certain time interval and to keep a copy of previous file versions.

ContentLicense: CC BY-SA 3.0


问:
Send excel files from micro to micro
I am trying to establish a communication between two micros, where the first one receives a petition from the frontend and contacts with another micro, which creates an excel file and sends it back to the first micro, starting the download of the file.

First, I tried to print a simple String response to check the communication between micros and that worked correctly, but the same thing for files didn't work.

Here is the code that I am following:
For Controller A:

```<code>
    @GetMapping(path="/test")
    public void getEntities2(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ResponseEntity<Workbook> responseEntity = new RestTemplate()
                .getForEntity("http://localhost:8080/proceso/excel", Workbook.class);
        assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));
        response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
        Workbook workbook = responseEntity.getBody();
        workbook.write(response.getOutputStream());
        workbook.close();
    }

</code>```

The second Controller (Excel file generator):

```<code>
@GetMapping(path="/excel")
    public ResponseEntity<Workbook> test3(HttpServletResponse response) throws Exception {
        HashMap<String, ArrayList<String>> test = new HashMap<String, ArrayList<String>>();
        Workbook workbook =  CreateExcel.excelCreator(test);

        Workbook responseFile = workbook;
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "test.xls")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(responseFile);
    }

</code>```

And then the following error appears:

```<code>org.springframework.web.client.HttpClientErrorException$NotAcceptable: 406 null
</code>```

I just want to receive the file in the first controller and download the Excel from localhost. Is there any way to do it? Thanks all.

答:
I discovered the problem. The excel file is a octet-stream file so it needs to be received as a byte[] array. This is the Controller A:

```<code>    @GetMapping(path="/")
public ResponseEntity<byte[]> getEntities() throws IOException {
ResponseEntity<byte[]> responseEntity = new RestTemplate()
.getForEntity("http://localhost:8080/excel", byte[].class);
assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));

return responseEntity;
}
</code>```

And Controller B:

```<code>@GetMapping(path="/excel")
public void getExcel(HttpServletResponse response) throws Exception {

Iterable<InstancesAggregate> list = instancesAggregate.myfindAll(); //Creating a list
HashMap<String, ArrayList<String>> test = CreateExcel.setExcelProceso(list);
Workbook workbook =  CreateExcel.excelCreator(test);
response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
   workbook.write(response.getOutputStream());
   workbook.close();

}
</code>```

This works fine for me, hope someone find the info useful.

Title: Send excel files from micro to micro

Body:
I am trying to establish a communication between two micros, where the first one receives a petition from the frontend and contacts with another micro, which creates an excel file and sends it back to the first micro, starting the download of the file.

First, I tried to print a simple String response to check the communication between micros and that worked correctly, but the same thing for files didn't work.

Here is the code that I am following:
For Controller A:

    @GetMapping(path="/test")
    public void getEntities2(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ResponseEntity<Workbook> responseEntity = new RestTemplate()
                .getForEntity("http://localhost:8080/proceso/excel", Workbook.class);
        assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));
        response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
        Workbook workbook = responseEntity.getBody();
        workbook.write(response.getOutputStream());
        workbook.close();
    }

The second Controller (Excel file generator):

@GetMapping(path="/excel")
    public ResponseEntity<Workbook> test3(HttpServletResponse response) throws Exception {
        HashMap<String, ArrayList<String>> test = new HashMap<String, ArrayList<String>>();
        Workbook workbook =  CreateExcel.excelCreator(test);

        Workbook responseFile = workbook;
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "test.xls")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(responseFile);
    }

And then the following error appears:

org.springframework.web.client.HttpClientErrorException$NotAcceptable: 406 null

I just want to receive the file in the first controller and download the Excel from localhost. Is there any way to do it? Thanks all.

Body:
I discovered the problem. The excel file is a octet-stream file so it needs to be received as a byte[] array. This is the Controller A:

    @GetMapping(path="/")
public ResponseEntity<byte[]> getEntities() throws IOException {
ResponseEntity<byte[]> responseEntity = new RestTemplate()
.getForEntity("http://localhost:8080/excel", byte[].class);
assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));

return responseEntity;
}

And Controller B:

@GetMapping(path="/excel")
public void getExcel(HttpServletResponse response) throws Exception {

Iterable<InstancesAggregate> list = instancesAggregate.myfindAll(); //Creating a list
HashMap<String, ArrayList<String>> test = CreateExcel.setExcelProceso(list);
Workbook workbook =  CreateExcel.excelCreator(test);
response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
   workbook.write(response.getOutputStream());
   workbook.close();

}

This works fine for me, hope someone find the info useful.


问:
Show all atributes on one element with python and xml
As you can see on the XML code, every pais has his idiomas with the tag idioma and each of them has his attribute which I am not able to show. I just get the first on each one of them but not all.

The XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paises SYSTEM "Paises_DTD.dtd">
<paises>
    <pais id="p1">
        <nombre>España</nombre>
        <habitantes>46423034</habitantes>
        <extension unidad="km2">504645</extension>
        <gobierno tipo="monarquia" fecha="1978"/>
        <idiomas>
            <idioma nombre="castellano"/>
            <idioma nombre="catalan"/>
            <idioma nombre="euskera"/>
            <idioma nombre="gallego"/>
        </idiomas>
    </pais>
    <pais id="p2">
        <nombre>Irán</nombre>
        <habitantes>79853900</habitantes>
        <extension unidad="km2">1648195</extension>
        <gobierno tipo="republica_islamica" fecha="1979"/>
        <idiomas>
            <idioma nombre="persa"/>
        </idiomas>
    </pais>
    <pais id="p3">
        <nombre>Alemania</nombre>
        <habitantes>81292400</habitantes>
        <extension unidad="km2">357168</extension>
        <gobierno tipo="republica_federal" fecha="1990"/>
        <idiomas>
            <idioma nombre="aleman"/>
        </idiomas>
    </pais>
    <pais id="p4">
        <nombre>Estados Unidos de América</nombre>
        <habitantes>316017000</habitantes>
        <extension unidad="km2">9371174</extension>
        <gobierno tipo="republica_federal"/>
        <idiomas>
            <idioma nombre="ingles"/>
        </idiomas>
    </pais>
    <pais id="p5">
        <nombre>Líbano</nombre>
        <habitantes>6006668</habitantes>
        <extension unidad="km2">10400200</extension>
        <gobierno tipo="republica_parlamentaria"/>
        <idiomas>
            <idioma nombre="árabe"/>
            <idioma nombre="francés"/>
            <idioma nombre="armenio"/>
            <idioma nombre="español"/>
            <idioma nombre="portugués"/>
        </idiomas>
    </pais>
    <pais id="p6">
        <nombre>Madagascar</nombre>
        <habitantes>24430325</habitantes>
        <extension unidad="km2">5870410</extension>
        <gobierno tipo="republica"/>
        <idiomas>
            <idioma nombre="malgache"/>
            <idioma nombre="francés"/>
        </idiomas>
    </pais>
</paises>
</code>```

I'm showing the code I tried here which just shows me one attribute from the element idioma:

```<code>from lxml import etree

doc = etree.parse('Paises_XML.xml')
raiz=doc.getroot()
paises=doc.findall("pais")

print("""
    DATOS SOBRE IDIOMAS EN CADA PAIS

    1- España
    2- Irán
    3- Alemania
    4- EEUU
    5- Libano
    6- Madagascar
    7- Salir
    """)

valid_choices = ["1", "2", "3", "4", "5", "6"]

while True:
    eleccion=input("Introduzca un número referente a un país de la lista observable: ")

    if eleccion in valid_choices:
        index = int(eleccion) - 1
        print("")
        print (paises[index].find("nombre").text)
        print (paises[index].find("idiomas/idioma").attrib)
    elif eleccion== "7":
        print("")
        print("¡Hasta pronto!")
        break
    else:
        print("Opción no válida, elija un número del 1 al 6 para mostrar la información del país correspondiente")
</code>```

It was supposed to show all attributes from idioma on each pais, but I don't get how to do it so that's why I come here

答:
You should loop over the 'idiomas'. See the code below.  </p>

<p>(56331871.xml is the data you have posted)</p>

```<code>from lxml import etree

doc = etree.parse('56331871.xml')
raiz = doc.getroot()
paises = doc.findall("pais")

print("""
    DATOS SOBRE IDIOMAS EN CADA PAIS

    1- España
    2- Irán
    3- Alemania
    4- EEUU
    5- Libano
    6- Madagascar
    7- Salir
    """)

valid_choices = ["1", "2", "3", "4", "5", "6"]

while True:
    eleccion = input("Introduzca un número referente a un país de la lista observable: ")

    if eleccion in valid_choices:
        index = int(eleccion) - 1
        print("")
        print(paises[index].find("nombre").text)
        idiomas = paises[index].findall("idiomas/idioma")
        for idioma in idiomas:
            print(idioma.attrib)
    elif eleccion == "7":
        print("")
        print("¡Hasta pronto!")
        break
    else:
        print("Opción no válida, elija un número del 1 al 6 para mostrar la información del país correspondiente")
</code>```

Body:
As you can see on the XML code, every pais has his idiomas with the tag idioma and each of them has his attribute which I am not able to show. I just get the first on each one of them but not all.

The XML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paises SYSTEM "Paises_DTD.dtd">
<paises>
    <pais id="p1">
        <nombre>España</nombre>
        <habitantes>46423034</habitantes>
        <extension unidad="km2">504645</extension>
        <gobierno tipo="monarquia" fecha="1978"/>
        <idiomas>
            <idioma nombre="castellano"/>
            <idioma nombre="catalan"/>
            <idioma nombre="euskera"/>
            <idioma nombre="gallego"/>
        </idiomas>
    </pais>
    <pais id="p2">
        <nombre>Irán</nombre>
        <habitantes>79853900</habitantes>
        <extension unidad="km2">1648195</extension>
        <gobierno tipo="republica_islamica" fecha="1979"/>
        <idiomas>
            <idioma nombre="persa"/>
        </idiomas>
    </pais>
    <pais id="p3">
        <nombre>Alemania</nombre>
        <habitantes>81292400</habitantes>
        <extension unidad="km2">357168</extension>
        <gobierno tipo="republica_federal" fecha="1990"/>
        <idiomas>
            <idioma nombre="aleman"/>
        </idiomas>
    </pais>
    <pais id="p4">
        <nombre>Estados Unidos de América</nombre>
        <habitantes>316017000</habitantes>
        <extension unidad="km2">9371174</extension>
        <gobierno tipo="republica_federal"/>
        <idiomas>
            <idioma nombre="ingles"/>
        </idiomas>
    </pais>
    <pais id="p5">
        <nombre>Líbano</nombre>
        <habitantes>6006668</habitantes>
        <extension unidad="km2">10400200</extension>
        <gobierno tipo="republica_parlamentaria"/>
        <idiomas>
            <idioma nombre="árabe"/>
            <idioma nombre="francés"/>
            <idioma nombre="armenio"/>
            <idioma nombre="español"/>
            <idioma nombre="portugués"/>
        </idiomas>
    </pais>
    <pais id="p6">
        <nombre>Madagascar</nombre>
        <habitantes>24430325</habitantes>
        <extension unidad="km2">5870410</extension>
        <gobierno tipo="republica"/>
        <idiomas>
            <idioma nombre="malgache"/>
            <idioma nombre="francés"/>
        </idiomas>
    </pais>
</paises>

I'm showing the code I tried here which just shows me one attribute from the element idioma:

from lxml import etree

doc = etree.parse('Paises_XML.xml')
raiz=doc.getroot()
paises=doc.findall("pais")

print("""
    DATOS SOBRE IDIOMAS EN CADA PAIS

    1- España
    2- Irán
    3- Alemania
    4- EEUU
    5- Libano
    6- Madagascar
    7- Salir
    """)

valid_choices = ["1", "2", "3", "4", "5", "6"]

while True:
    eleccion=input("Introduzca un número referente a un país de la lista observable: ")

    if eleccion in valid_choices:
        index = int(eleccion) - 1
        print("")
        print (paises[index].find("nombre").text)
        print (paises[index].find("idiomas/idioma").attrib)
    elif eleccion== "7":
        print("")
        print("¡Hasta pronto!")
        break
    else:
        print("Opción no válida, elija un número del 1 al 6 para mostrar la información del país correspondiente")

It was supposed to show all attributes from idioma on each pais, but I don't get how to do it so that's why I come here

Body:
You should loop over the 'idiomas'. See the code below.

(56331871.xml is the data you have posted)

from lxml import etree

doc = etree.parse('56331871.xml')
raiz = doc.getroot()
paises = doc.findall("pais")

print("""
    DATOS SOBRE IDIOMAS EN CADA PAIS

    1- España
    2- Irán
    3- Alemania
    4- EEUU
    5- Libano
    6- Madagascar
    7- Salir
    """)

valid_choices = ["1", "2", "3", "4", "5", "6"]

while True:
    eleccion = input("Introduzca un número referente a un país de la lista observable: ")

    if eleccion in valid_choices:
        index = int(eleccion) - 1
        print("")
        print(paises[index].find("nombre").text)
        idiomas = paises[index].findall("idiomas/idioma")
        for idioma in idiomas:
            print(idioma.attrib)
    elif eleccion == "7":
        print("")
        print("¡Hasta pronto!")
        break
    else:
        print("Opción no válida, elija un número del 1 al 6 para mostrar la información del país correspondiente")


问:
How to Convert Tuple to Dictionary?
i'm using Python 2.5 and Win XP. i have a tuple as below:

```<code>>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>
</code>```

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq

答:
There is another way to do it, without using any imports.

A simple list comprehension (temp):

```<code>>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>> temp = [[int(c) for c in b.split(":")] for b in a[1].strip('{}').split(",")]
>>> a_dict = dict(temp)
>>> a_dict[1]
2
>>> a_dict[2]
4
</code>```

Title: How to Convert Tuple to Dictionary?

Body:
i'm using Python 2.5 and Win XP. i have a tuple as below:

>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq

Body:
There is another way to do it, without using any imports.

A simple list comprehension (temp):

>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>> temp = [[int(c) for c in b.split(":")] for b in a[1].strip('{}').split(",")]
>>> a_dict = dict(temp)
>>> a_dict[1]
2
>>> a_dict[2]
4


问:
How to submit form in a web page using python?
I’m doing my homework. I have built  a local web service.what should I do for submitting form with python?

I want to log in my local web service with python and a data dictionary.

Here is my local Web verification：

def signin():
    if request.form['username']=='root' and request.form['password']=='1234':
        return '
Login successfully
'
    return '
Login failed
'
```

答:
Since you are using python3 you can use 'mechanicalsoup' library for this.
Have a look at to this example.Hope it will be helpful.</p>

```<code>import mechanicalsoup  #importing the library

browser = mechanicalsoup.StatefulBrowser()
browser.open("http://example.com/")

browser.select_form('form[action="/post"]') #selecting the form.
browser["name"] = "Name"
browser["email"] = "example@mail.com" #filling the fields in the form.

response = browser.submit_selected()
</code>```

Body:
Since you are using python3 you can use 'mechanicalsoup' library for this.
Have a look at to this example.Hope it will be helpful.

import mechanicalsoup  #importing the library

browser = mechanicalsoup.StatefulBrowser()
browser.open("http://example.com/")

browser.select_form('form[action="/post"]') #selecting the form.
browser["name"] = "Name"
browser["email"] = "example@mail.com" #filling the fields in the form.

response = browser.submit_selected()


问:
Can't bind to 'ngModel' since it isn't a known property of 'ng-toggle'
I want to use the Angular ng-toggle component.

I'm using lazy loading, i'm importing the NgToggleModule in my lazy loading Module. Without the use of [(ngModule)]="cat.enable" the component renders correctly.

dispomap.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DispomapComponent } from './dispomap.component';
import { DispomapSettingsComponent } from './dispomap-settings/dispomap-settings.component';
import { Routes, RouterModule } from '@angular/router';
import { DispmapService } from './Service/dispmap.service';
import { NgToggleModule } from '@nth-cloud/ng-toggle';

const routes: Routes = [
...
  {
      path: 'settings',
      data: {
          title: 'Settings'
      },
      component: DispomapSettingsComponent,
  }
];

@NgModule({
  declarations: [DispomapComponent, DispomapSettingsComponent],
  imports: [
    CommonModule,
    NgToggleModule,
    RouterModule.forChild(routes),
  ],
  providers: [ DispmapService ]
})
export class DispomapModule { }

```

<p>dispomap-settings.component.ts</p>

<pre class="lang-js prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
import { DispmapService } from '../Service/dispmap.service';
import { IDispoMapCategoryInfo } from '../Models/IDispoMapCategoryInfo';

@Component({
  selector: 'app-dispomap-settings',
  templateUrl: './dispomap-settings.component.html',
  styleUrls: ['./dispomap-settings.component.scss']
})
export class DispomapSettingsComponent implements OnInit {

  CategoryInfos: IDispoMapCategoryInfo[];
  constructor(private dispomapService: DispmapService) { }

  ngOnInit() {
    this.dispomapService.GetCategories().subscribe(ci => {
      this.CategoryInfos = ci;
    });
  }

}
</code>```

dispomap-settings.component.html

        <ng-toggle onColor="primary" offColor="secondary" [(ngModel)]="cat.enabled"></ng-toggle>

{{cat.label}}

{{cat.order}}

{{cat.trucks}}

```

<p>Google Chrome Console Error:</p>

<pre class="lang-html prettyprint-override"><code>ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ng-toggle'.
1. If 'ngModel' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("yInfos">
    <div class="col-2 col-md-1">
        <ng-toggle onColor="primary" offColor="secondary" [ERROR ->][(ngModel)]="cat.enabled"></ng-toggle>
      </div>
    <div class="col-6 col-md-4">{{cat.label}}</di"): ng:///DispomapModule/DispomapSettingsComponent.html@3:58
Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ng-toggle'.
1. If 'ngModel' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("yInfos">
    <div class="col-2 col-md-1">
        <ng-toggle onColor="primary" offColor="secondary" [ERROR ->][(ngModel)]="cat.enabled"></ng-toggle>
      </div>
    <div class="col-6 col-md-4">{{cat.label}}</di"): ng:///DispomapModule/DispomapSettingsComponent.html@3:58
    at syntaxError (compiler.js:2430)
    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (compiler.js:20605)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (compiler.js:26171)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (compiler.js:26158)
    at compiler.js:26101
    at Set.forEach (<anonymous>)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (compiler.js:26101)
    at compiler.js:26011
    at Object.then (compiler.js:2421)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:26010)
    at resolvePromise (zone.js:831)
    at resolvePromise (zone.js:788)
    at zone.js:892
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
</code>```

答:
That is because FormsModule is not part of your module.

In order to use two-way data binding in your component, you will need to  import FormsModule into your module.

```<code>import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
//.. other imports

@NgModule({
  imports: [
    FormsModule,
    // other imports
  ]
</code>```

Body:
I want to use the Angular ng-toggle component.

I'm using lazy loading, i'm importing the NgToggleModule in my lazy loading Module. Without the use of [(ngModule)]="cat.enable" the component renders correctly.

dispomap.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DispomapComponent } from './dispomap.component';
import { DispomapSettingsComponent } from './dispomap-settings/dispomap-settings.component';
import { Routes, RouterModule } from '@angular/router';
import { DispmapService } from './Service/dispmap.service';
import { NgToggleModule } from '@nth-cloud/ng-toggle';

const routes: Routes = [
...
  {
      path: 'settings',
      data: {
          title: 'Settings'
      },
      component: DispomapSettingsComponent,
  }
];

@NgModule({
  declarations: [DispomapComponent, DispomapSettingsComponent],
  imports: [
    CommonModule,
    NgToggleModule,
    RouterModule.forChild(routes),
  ],
  providers: [ DispmapService ]
})
export class DispomapModule { }

dispomap-settings.component.ts

import { Component, OnInit } from '@angular/core';
import { DispmapService } from '../Service/dispmap.service';
import { IDispoMapCategoryInfo } from '../Models/IDispoMapCategoryInfo';

@Component({
  selector: 'app-dispomap-settings',
  templateUrl: './dispomap-settings.component.html',
  styleUrls: ['./dispomap-settings.component.scss']
})
export class DispomapSettingsComponent implements OnInit {

  CategoryInfos: IDispoMapCategoryInfo[];
  constructor(private dispomapService: DispmapService) { }

  ngOnInit() {
    this.dispomapService.GetCategories().subscribe(ci => {
      this.CategoryInfos = ci;
    });
  }

}

dispomap-settings.component.html

        <ng-toggle onColor="primary" offColor="secondary" [(ngModel)]="cat.enabled"></ng-toggle>

{{cat.label}}

{{cat.order}}

{{cat.trucks}}

Google Chrome Console Error:

ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ng-toggle'.
1. If 'ngModel' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("yInfos">

        <ng-toggle onColor="primary" offColor="secondary" [ERROR ->][(ngModel)]="cat.enabled"></ng-toggle>

{{cat.label}}</di"): ng:///DispomapModule/DispomapSettingsComponent.html@3:58
Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ng-toggle'.
1. If 'ngModel' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("yInfos">

        <ng-toggle onColor="primary" offColor="secondary" [ERROR ->][(ngModel)]="cat.enabled"></ng-toggle>

{{cat.label}}</di"): ng:///DispomapModule/DispomapSettingsComponent.html@3:58
    at syntaxError (compiler.js:2430)
    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (compiler.js:20605)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (compiler.js:26171)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (compiler.js:26158)
    at compiler.js:26101
    at Set.forEach (<anonymous>)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (compiler.js:26101)
    at compiler.js:26011
    at Object.then (compiler.js:2421)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:26010)
    at resolvePromise (zone.js:831)
    at resolvePromise (zone.js:788)
    at zone.js:892
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)

Body:
That is because FormsModule is not part of your module.

In order to use two-way data binding in your component, you will need to  import FormsModule into your module.

import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
//.. other imports

@NgModule({
  imports: [
    FormsModule,
    // other imports
  ]


问:
Watermark / hint / placeholder text in TextBox?
How can I put some text into a TextBox which will be removed automatically when the user types something in it?

答:
simplest Way to WaterMark Of TextBox </p>

```<code> <Window.Resources>
    <Style x:Key="MyWaterMarkStyle" TargetType="{x:Type TextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <Border Background="White" BorderBrush="#FF7D8683" BorderThickness="1"/>
                        <ScrollViewer x:Name="PART_ContentHost" Margin="5,0,0,0" VerticalAlignment="Center" />
                        <Label Margin="5,0,0,0" x:Name="WaterMarkLabel" Content="{TemplateBinding Tag}" VerticalAlignment="Center"
                           Visibility="Collapsed" Foreground="Gray" FontFamily="Arial"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="Text" Value=""/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Visibility" TargetName="WaterMarkLabel" Value="Visible"/>
                        </MultiTrigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Foreground" Value="DimGray"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
</code>```

<p>and  add textbox StaticResource style </p>

```<code>  <TextBox
                Style="{StaticResource MyWaterMarkStyle}"
                Tag="Search Category"
                Grid.Row="0"
                Text="{Binding CategorySearch,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                TextSearch.Text="Search Category"
                >
</code>```

OwnerDisplayName: mehdi

Body:
simplest Way to WaterMark Of TextBox

 <Window.Resources>
    <Style x:Key="MyWaterMarkStyle" TargetType="{x:Type TextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <Border Background="White" BorderBrush="#FF7D8683" BorderThickness="1"/>
                        <ScrollViewer x:Name="PART_ContentHost" Margin="5,0,0,0" VerticalAlignment="Center" />
                        <Label Margin="5,0,0,0" x:Name="WaterMarkLabel" Content="{TemplateBinding Tag}" VerticalAlignment="Center"
                           Visibility="Collapsed" Foreground="Gray" FontFamily="Arial"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="Text" Value=""/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Visibility" TargetName="WaterMarkLabel" Value="Visible"/>
                        </MultiTrigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Foreground" Value="DimGray"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

and  add textbox StaticResource style

  <TextBox
                Style="{StaticResource MyWaterMarkStyle}"
                Tag="Search Category"
                Grid.Row="0"
                Text="{Binding CategorySearch,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                TextSearch.Text="Search Category"
                >


问:
ExtJS Grid slow with 3000+ records
I am using ExtJS Grid and its getting pretty slow with 3000+ records. Sorting takes about 4 seconds.

I am thinking maybe to use pagination in my table. However after reading the documentation, I am still a bit unsure about how pagination works in extjs. Does this pull data from the server each time u turn a page? I would prefer that wasn't the case. I would prefer the 3000 records are saved in the browser and then what is rendered is just a portion of those rows.

Also I am using Extjs version 4.2.1. If I upgrade to version 5. will I get some performance improvements?

答:
You can keep your data in the LocalStorage. It allows you to have the data stored in the browser. You'll need a data model which you fill with data from XML and store in the browser. The next time you just check if the data is stored and download it if not.
The Ext Grid will work with these data well.

It works for me.

Title: ExtJS Grid slow with 3000+ records


问:
Sinon spy callCount returns 0
I can't seem to get my test working. I have a simple mixin like so:

```<code>export const mixin = superclass => class mixin extends superclass {
  constructor() {
    super();
    this.addEventListener('do-it', this.doIt);
  }

  doIt() {
    console.log('did it');
  }
};
</code>```

And a simple test as well:

```<code>describe('mixin', () => {
  it('should call doIt', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const el = new TestElement();
    const spy = sinon.spy(el, 'doIt');

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.callCount).to.equal(1);
  });
});
</code>```

https://jsfiddle.net/nbuLhvkd/

It logs did it but the spy's callCount value is 0. If I do const spy = sinon.spy(console, 'log');, the spy's callCount is 1. What's the correct way of spying for instance methods?

答:
It is likely that your 'dispatchEvent' call is asynchronous, therefore the callCount is indeed 0 since it is executed synchronously.
Otherwise your syntax is good - as your test on console call prooved.</p>

Title: Sinon spy callCount returns 0

Body:
I can't seem to get my test working. I have a simple mixin like so:

export const mixin = superclass => class mixin extends superclass {
  constructor() {
    super();
    this.addEventListener('do-it', this.doIt);
  }

  doIt() {
    console.log('did it');
  }
};

And a simple test as well:

describe('mixin', () => {
  it('should call doIt', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const el = new TestElement();
    const spy = sinon.spy(el, 'doIt');

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.callCount).to.equal(1);
  });
});

https://jsfiddle.net/nbuLhvkd/

It logs did it but the spy's callCount value is 0. If I do const spy = sinon.spy(console, 'log');, the spy's callCount is 1. What's the correct way of spying for instance methods?


问:
Why are the react-router component props not including history?
I'm loving v4 but in 4.1.2 this keeps tripping me up when using the browser router:

With a component in a Route component I have these props passed in: {computedMatch, location, path} although the documentation tells me to expect {match, location, history} which is what I get with the hash router.

To get the history passed in I have to use the withRouter wrapper which feels very clunky because the relevant component is the component prop to a Route component.

The documentation sounds right to me. Is this a bug?

答:
You can get access to {match, location, history} if you use Route as

```<code><Route path="/" component={myComponent}
</code>```

In above code you will have match location and history accessible inside myComponent.

Or else you have to use withRouter

Body:
You can get access to {match, location, history} if you use Route as

<Route path="/" component={myComponent}

In above code you will have match location and history accessible inside myComponent.

Or else you have to use withRouter


问:
Why does `<input type='date' />` and `<input type='time' />` have onchange issues in Firefox? Or am I missing something?
It seems that Firefox desktop only runs a change Event upon focus, which does not occur from simply closing <input type='date' /> or <input type='time' />. Somehow this problem is not reproducible using Stack Overflow, even with Firefox (If you know why...do tell). But if you run the code on localhost, using Firefox, you will see it seems to work every other time. I believe this is because Firefox will refocus on a previously focused Element when the page is reloaded.

So, what do I mean by "work"? When you hit the close button, if the value is === '', that should get console.log()ed, as you can see from the code I wrote below. Sometimes it does not get logged and the value changes back to empty, so it doesn't work. Change Event fails to fire using Firefox Quantum 67.0 (64-bit).

//<![CDATA[
/* external.js */
var doc, bod, I, DateTime; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
I = function(id){
  return doc.getElementById(id);
}
DateTime = function(dateElement, timeElement, dateInstance){
  var t = this;
  this.dateElement = dateElement; this.timeElement = timeElement;
  this.date = dateInstance instanceof Date ? dateInstance : new Date;
  this.dateValue = function(dateInstance){
    if(dateInstance instanceof Date)this.date = dateInstance;
    var dt = this.date;
    return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
  }
  this.showDate = function(dateInstance){
    this.dateElement.value = this.dateValue(dateInstance);
    return this;
  }
  this.timeValue = function(dateInstance){
    if(dateInstance instanceof Date)this.date = dateInstance;
    var dt = this.date;
    return dt.getHours().toString().replace(/^(\d)$/, '0$1')+':'+dt.getMinutes().toString().replace(/^(\d)$/, '0$1');
  }
  this.showTime = function(dateInstance){
    this.timeElement.value = this.timeValue(dateInstance);
    return this;
  }
  this.showDate().showTime();
  this.dateChange = function(changeFunc, noDateFunc){
    this.dateElement.onchange = function(){
      var v = this.value;
      if(v === ''){
        console.log("t.dateElement.value === ''");
        if(noDateFunc)t.showDate(noDateFunc(t));
      }
      else{
        var s = t.timeElement.value;
        if(s === '')s = t.timeValue(new Date);
        t.date = new Date(v+' '+s);
      }
      changeFunc(t.date, t);
    }
    return this;
  }
  this.timeChange = function(changeFunc, noTimeFunc){
    this.timeElement.onchange = function(){
      var v = this.value;
      if(v === ''){
        console.log("t.timeElement.value === ''");
        if(noTimeFunc)t.showTime(noTimeFunc(t));
      }
      else{
        var s = t.dateElement.value;
        if(s === '')s = t.dateValue(new Date);
        t.date = new Date(s+' '+v);
      }
      changeFunc(t.date, t);
    }
    return this;
  }
}
var hourTest = function(){
    return new Date(Date.now()+3600000);
  }
var dt = new DateTime(I('edit_date'), I('edit_time'), hourTest());
dt.dateChange(function(dateResult){
  console.log(dateResult.toString());
}, hourTest).timeChange(function(timeResult){
  console.log(timeResult.toString());
}, hourTest);
}); // end load
//]]>```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* external.js */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#content{
  padding:7px;
}
label,input{
  font:22px Tahoma, Geneva, sans-serif;
}
label{
  display:block; height:26px; font-weight:bold; margin:7px 0 4px; float:left;
}
input{
   width:100%; height:38px; background:#fff; color:#000; padding:5px; border:1px solid #0b0; float:left;
}</code>```

    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />

    Notify Date<input class='yes' id='edit_date' type='date' />
    Notify Time<input class='yes' id='edit_time' type='time' />

```

Is there any way to guarantee that a change Event occurred, because it seems without focusing on the date or time, it may just decide not to fire?

答:
I'm not sure if what you're seeing is a bug or not, but if you can't figure out a solution to the issue with the change event, you could try listening for the input event instead.

The input event is fired every time the value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.

From OP's comments, to fix the issue, change these lines from:

```<code>this.dateElement.onchange = function(){
</code>```

```<code>this.timeElement.onchange = function(){
</code>```

to:

```<code>this.dateElement.oninput = function(){
</code>```

```<code>this.timeElement.oninput = function(){
</code>```

Body:
It seems that Firefox desktop only runs a change Event upon focus, which does not occur from simply closing <input type='date' /> or <input type='time' />. Somehow this problem is not reproducible using Stack Overflow, even with Firefox (If you know why...do tell). But if you run the code on localhost, using Firefox, you will see it seems to work every other time. I believe this is because Firefox will refocus on a previously focused Element when the page is reloaded.

So, what do I mean by "work"? When you hit the close button, if the value is === '', that should get console.log()ed, as you can see from the code I wrote below. Sometimes it does not get logged and the value changes back to empty, so it doesn't work. Change Event fails to fire using Firefox Quantum 67.0 (64-bit).

//<![CDATA[
/* external.js */
var doc, bod, I, DateTime; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
I = function(id){
  return doc.getElementById(id);
}
DateTime = function(dateElement, timeElement, dateInstance){
  var t = this;
  this.dateElement = dateElement; this.timeElement = timeElement;
  this.date = dateInstance instanceof Date ? dateInstance : new Date;
  this.dateValue = function(dateInstance){
    if(dateInstance instanceof Date)this.date = dateInstance;
    var dt = this.date;
    return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
  }
  this.showDate = function(dateInstance){
    this.dateElement.value = this.dateValue(dateInstance);
    return this;
  }
  this.timeValue = function(dateInstance){
    if(dateInstance instanceof Date)this.date = dateInstance;
    var dt = this.date;
    return dt.getHours().toString().replace(/^(\d)$/, '0$1')+':'+dt.getMinutes().toString().replace(/^(\d)$/, '0$1');
  }
  this.showTime = function(dateInstance){
    this.timeElement.value = this.timeValue(dateInstance);
    return this;
  }
  this.showDate().showTime();
  this.dateChange = function(changeFunc, noDateFunc){
    this.dateElement.onchange = function(){
      var v = this.value;
      if(v === ''){
        console.log("t.dateElement.value === ''");
        if(noDateFunc)t.showDate(noDateFunc(t));
      }
      else{
        var s = t.timeElement.value;
        if(s === '')s = t.timeValue(new Date);
        t.date = new Date(v+' '+s);
      }
      changeFunc(t.date, t);
    }
    return this;
  }
  this.timeChange = function(changeFunc, noTimeFunc){
    this.timeElement.onchange = function(){
      var v = this.value;
      if(v === ''){
        console.log("t.timeElement.value === ''");
        if(noTimeFunc)t.showTime(noTimeFunc(t));
      }
      else{
        var s = t.dateElement.value;
        if(s === '')s = t.dateValue(new Date);
        t.date = new Date(s+' '+v);
      }
      changeFunc(t.date, t);
    }
    return this;
  }
}
var hourTest = function(){
    return new Date(Date.now()+3600000);
  }
var dt = new DateTime(I('edit_date'), I('edit_time'), hourTest());
dt.dateChange(function(dateResult){
  console.log(dateResult.toString());
}, hourTest).timeChange(function(timeResult){
  console.log(timeResult.toString());
}, hourTest);
}); // end load
//]]>

/* external.js */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#content{
  padding:7px;
}
label,input{
  font:22px Tahoma, Geneva, sans-serif;
}
label{
  display:block; height:26px; font-weight:bold; margin:7px 0 4px; float:left;
}
input{
   width:100%; height:38px; background:#fff; color:#000; padding:5px; border:1px solid #0b0; float:left;
}

    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />

    Notify Date<input class='yes' id='edit_date' type='date' />
    Notify Time<input class='yes' id='edit_time' type='time' />

Is there any way to guarantee that a change Event occurred, because it seems without focusing on the date or time, it may just decide not to fire?

Body:
I'm not sure if what you're seeing is a bug or not, but if you can't figure out a solution to the issue with the change event, you could try listening for the input event instead.

The input event is fired every time the value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.

From OP's comments, to fix the issue, change these lines from:

this.dateElement.onchange = function(){

this.timeElement.onchange = function(){

to:

this.dateElement.oninput = function(){

this.timeElement.oninput = function(){


问:
Computing the first k powers of matrix in R
If I want to compute the first k powers (say, k = 10) of some matrix A, using matrix.power from the matrixcalc package, would I really need to write A2 <- matrix.power(A, 2), A3 <- matrix.power(A, 3), ..., A10 <- matrix.power(A, 10)? It seems a bit tedious to me, but I tried to avoid loops, which I understand is recommended in R, because it is not efficient. Would I be able to do some magic with apply functions? Basically, I would need the sum of some specific entry from all the powers of the matrix A up to a k.

答:
An option is lapply

```<code>library(matrixcalc)
lst1 <- lapply(2:100, matrix.power, x = A)
</code>```

and then get the sum with Reduce

```<code>Reduce(`+`, lst1)
</code>```

Body:
An option is lapply

library(matrixcalc)
lst1 <- lapply(2:100, matrix.power, x = A)

and then get the sum with Reduce

Reduce(`+`, lst1)


问:
How to create new User with password on MongoDB and connect from NodeJS application
I need some help with setting up my NodeJS application to connect with the MongoDB with credentials.

I'm confused with creating user on the admin database, or on the database I will store my documents, and then connecting to it from my application.

So, let's say I have this MongoDB service running on localhost port 27017 and my database is called myAmazingApp. I want to create a user with Read/Write permissions on this now empty database and set user userApp and password passwordApp.

I'm using Mongoose on NodeJS.

My question includes where and how I must create this User/Role/whatever on MongoDB.

By the way, right now this is my connection string

mongodb://userApp:passwordApp@localhost:27017/myAmazingApp and I am connecting with mongoose.connect.

It gives me Authentication failed

答:
Log into the mongo shell via terminal

```<code>user@ubuntu:~$ mongo
</code>```

and switch to admin DB

```<code>> use admin
</code>```

Create a user with the "userAdminAnyDatabase" role, which grants the privilege to create other users on any existing database.

```<code>> db.createUser(
  {
    user: "adminUser",
    pwd: "adminPwd",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
</code>```

Disconnect from the mongo shell

You need to enable authentication in mongod configuration file. Open /etc/mongod.conf or /etc/mongodb.conf

```<code>security:
    authorization: "disabled"
</code>```

change it to

```<code>security:
    authorization: "enabled"
</code>```

Restart mongodb service

```<code>user@ubuntu:~$ sudo service mongodb restart
</code>```

or

```<code>user@ubuntu:~$ sudo service mongod restart
</code>```

Connect and authenticate as the user administrator

```<code>user@ubuntu:~$ mongo admin
> db.auth("adminUser", "adminPwd")
1
</code>```

Create additional users as needed

```<code>> use myAmazingApp
> db.createUser(
  {
    user: "userApp",
    pwd: "passwordApp",
    roles: [ { role: "readWrite", db: "myAmazingApp" } ]
  }
)
</code>```

While connecting mongoose you can pass it in the connection URI or as options

```<code>mongoose.connect('mongodb://userApp:passwordApp@localhost:27017/myAmazingApp');
</code>```

or

```<code>mongoose.connect('mongodb://localhost:27017/myAmazingApp', {useNewUrlParser: true, user: "userApp", pass: "user:passwordApp"});
</code>```

Body:
Log into the mongo shell via terminal

user@ubuntu:~$ mongo

and switch to admin DB

> use admin

Create a user with the "userAdminAnyDatabase" role, which grants the privilege to create other users on any existing database.

> db.createUser(
  {
    user: "adminUser",
    pwd: "adminPwd",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

Disconnect from the mongo shell

You need to enable authentication in mongod configuration file. Open /etc/mongod.conf or /etc/mongodb.conf

security:
    authorization: "disabled"

change it to

security:
    authorization: "enabled"

Restart mongodb service

user@ubuntu:~$ sudo service mongodb restart

or

user@ubuntu:~$ sudo service mongod restart

Connect and authenticate as the user administrator

user@ubuntu:~$ mongo admin
> db.auth("adminUser", "adminPwd")
1

Create additional users as needed

> use myAmazingApp
> db.createUser(
  {
    user: "userApp",
    pwd: "passwordApp",
    roles: [ { role: "readWrite", db: "myAmazingApp" } ]
  }
)

While connecting mongoose you can pass it in the connection URI or as options

mongoose.connect('mongodb://userApp:passwordApp@localhost:27017/myAmazingApp');

or

mongoose.connect('mongodb://localhost:27017/myAmazingApp', {useNewUrlParser: true, user: "userApp", pass: "user:passwordApp"});


问:
How to disable setOnItemClickListener?
I've defined setOnItemClickListener for my View object and I need to disable during some calculations in the application. How to disable it?

答:
This should work:</p>

```<code>yourView.setOnItemClickListener(null);
</code>```

Title: How to disable setOnItemClickListener?

Body:
This should work:

yourView.setOnItemClickListener(null);


问:
How to pass arguments to methods inside class components in React?
I am working on a react project. I was trying to pass item.id as the argument to the event handler. But I don't know how to send the value as the argument and how to access the value in the method. The program I was doing is shown below. Can someone help me to solve this issue?</p>

```<code>class ItemList extends React.Component {
  constructor(props) {
    super(props);

    this.onClick = this.onClick.bind(this);
  }

  render() {
    return <div>
      {this.props.items.map(item =>
        <button key={item.id} item={item} onClick={this.onClick} />
      )}
    </div>;
  }

  onClick(itemId) {
    console.log('Clicked item:', itemId);
  }
}
</code>```

答:
```<code>render() {
    return <div>
      {this.props.items.map(item =>
        <button key={item.id} item={item} onClick={()=>{this.onClick(item.id)}} />
      )}
    </div>;
  }

  onClick(itemId) {
    console.log('Clicked item:', itemId);
  }
</code>```

you can use {()=>{...}}

NOTICE

If you write code like this onClick={this.onClick(item.id)},
It will be executed immediately when they are rendered.

so, you should keep wrapping them like this onClick={()=>{ ... }}

Body:
I am working on a react project. I was trying to pass item.id as the argument to the event handler. But I don't know how to send the value as the argument and how to access the value in the method. The program I was doing is shown below. Can someone help me to solve this issue?

class ItemList extends React.Component {
  constructor(props) {
    super(props);

    this.onClick = this.onClick.bind(this);
  }

  render() {
    return

      {this.props.items.map(item =>
        <button key={item.id} item={item} onClick={this.onClick} />
      )}

;
  }

  onClick(itemId) {
    console.log('Clicked item:', itemId);
  }
}

Body:
render() {
    return <div>
      {this.props.items.map(item =>
        <button key={item.id} item={item} onClick={()=>{this.onClick(item.id)}} />
      )}
    </div>;
  }

  onClick(itemId) {
    console.log('Clicked item:', itemId);
  }

you can use {()=>{...}}

NOTICE

If you write code like this onClick={this.onClick(item.id)},
It will be executed immediately when they are rendered.

so, you should keep wrapping them like this onClick={()=>{ ... }}


问:
Highlighting modified lines in Eclipse
In netbeans, if I open a file which is under version control the lines which are modified are highlighted in the left. (green for new lines and blue for modified lines)

Is it possible to get a similar effect in Eclipse?

答:
In Eclipse by using its Quick Diff feature. This is easy to do:

Go to Window -> Preferences -> General -> Editors -> Text Editors ->
Quick Diff. This is the dialog from where it can be configured.

Turn on Quick Diff, by enabling the option Enable quick diff.

Choose the version control system for which Quick Diff is needed
from the dropdown Use this reference source. Git, SVN and CVS should
be present here. Mercurial appears if the MercurialEclipse plugin is
installed.

The overview ruler is the ruler to the right of the scrollbar in the
editor. If you would like to see the uncommitted lines to be marked
on it, enable the option Show differences in overview ruler.

Choose Apply and OK. Close all editor windows and reopen the source
file that you want in the editor.

You should be able to see the newly added, modified or deleted lines marked in colors in the left bar on which line numbers are usually displayed. The colors used are the ones set in the Quick Diff dialog (see above steps). You can also view these uncommitted locations marked along the overview ruler on the right.

ContentLicense: CC BY-SA 2.5

Title: Highlighting modified lines in Eclipse


问:
Matplotlib Plotting using AWS-EMR jupyter notebook
I am attempting to plot data using Matplotlib within a jupyter notebook on an AWS-EMR instance. Matplotlib must be installed via a bootstrap action at instance start-up, which I have done successfully. I have also successfully installed Pandas in this way (and used it for various things in my notebook). The typical %matplotlib inline does not work. (In fact, it appears that NO magic commands work on AWS-EMR notebooks. I suspect AWS has disabled these or it has something to do with the notebooks being "serverless.")

I have tried:

installing matplotlib==2.0.2 and using magic command %matplotlib inline (as mentioned above, magic commands seem not to work at all)

installing matplotlib==1.5, installing ipympl, and using import ipympl. I don't receive errors using this method when trying to .show() a plot, but neither does a plot show up. The cell runs in the notebook with no plot appearing. As far as I can tell, .show() does nothing.

答:
EDIT:

Check Parag Chaudhari's answer for plotting in spark mode.

Tested on release label:emr-5.21.0

There is no %matplotlib magic in spark magic kernel in EMR notebook. Type %%help to see all supported magics.

pyspark kernel send REST requests to remote EMR cluster via Livy. So plotting work on spark cluster doesn't make much sense. Do data processing using pyspark kernel in a distributed way and then perform plot work in %%local mode.

Try to start the cell with %%local and then run your code

```<code>%%local
%matplotlib inline
<some code to plot charts>
</code>```

Body:
EDIT:

Check Parag Chaudhari's answer for plotting in spark mode.

Tested on release label:emr-5.21.0

There is no %matplotlib magic in spark magic kernel in EMR notebook. Type %%help to see all supported magics.

pyspark kernel send REST requests to remote EMR cluster via Livy. So plotting work on spark cluster doesn't make much sense. Do data processing using pyspark kernel in a distributed way and then perform plot work in %%local mode.

Try to start the cell with %%local and then run your code

%%local
%matplotlib inline
<some code to plot charts>


问:
Fortran: Short form for "do loop"
Hey there,
I have a code like that:

```<code>write (filehandle,'(5e14.6)')
     &    (((my_array(i,j,k,1),i=istart,iend,istep),j=jstart,jend,jstep),k=kstart,kend,kstep)
</code>```

is this a short form for a "do-loop"? I couldn't find anything about it on google...
Furthermore, I'm getting an error:

forrtl: severe (71): integer divide by
  zero Image              PC

  Routine            Line        Source
  libpthread.so.0    00007F473F0D892B
  Unknown               Unknown  Unknown
  libguide.so        00007F473F3CC20E
  Unknown               Unknown  Unknown

when executing the program (program is parallelized with OpenMP) about THIS line (removing the line removes the error-msg). What could be the cause about it?
Thanks!

答:
Those are referred to as implicit or implied do-loops.

I don't see any division by zero in that statement, could it be one of the surrounding lines?

Title: Fortran: Short form for "do loop"

Body:
Hey there,
I have a code like that:

write (filehandle,'(5e14.6)')
     &    (((my_array(i,j,k,1),i=istart,iend,istep),j=jstart,jend,jstep),k=kstart,kend,kstep)

is this a short form for a "do-loop"? I couldn't find anything about it on google...
Furthermore, I'm getting an error:

forrtl: severe (71): integer divide by
  zero Image              PC

  Routine            Line        Source
  libpthread.so.0    00007F473F0D892B
  Unknown               Unknown  Unknown
  libguide.so        00007F473F3CC20E
  Unknown               Unknown  Unknown

when executing the program (program is parallelized with OpenMP) about THIS line (removing the line removes the error-msg). What could be the cause about it?
Thanks!


问:
How to Update value by dynamic field Name using sql select query
I am passing dynamic column name base that column name  to Update the value and below i my table

```<code>Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar
</code>```

Example1

```<code>Declare @ColumnName varchar(100), @Id int

set @ColumnName='City'
set @Id=20
set @value='Hyderabad'

update set ____ Table_CandidateInfo where ID=@Id
</code>```

my output should like below Table_CandidateInfo, Hyderabad City updated base on Id and Column name

```<code>Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Hyderabad
</code>```

Column name is dynamic some time @ColumnName='Name' so name value should update

Yesterday i have asked for get data base on column value that working fine but now i need to update

How to get value by dynamic field Name using sql select query

答:
Well, since you can't parameterize identifiers in SQL, your only option would be to use dynamic SQL for such things.

However, please note that the code that creates and execute the dynamic SQL statement needs to be written in such a way it would prevent SQL injection attacks.

The rule is quite simple - what you can't parameterize must be white-listed.

So basically, you can do something like this:

```<code>CREATE PROCEDURE UpdateCandidateInfo
(
     @ColumnName sysname,
     @Id int,
     @value sql_Variant
)

AS

IF EXISTS
(
    SELECT 1
    FROM information_schema.columns
    WHERE Table_Name = 'Table_CandidateInfo'
    AND Column_Name = @ColumnName
)

BEGIN

    DECLARE @Sql nvarchar(4000) = N'Update Table_CandidateInfo SET '+ QUOTENAME(@ColumnName) + N' = @Value WHERE Id = @Id';

    DECLARE @Params nvarchar(4000) = N'@Value sql_Variant, @Id int'

    EXEC sp_ExecuteSql @Sql, @Params, @Value, @Id
END

GO
</code>```

Please note that the code was written directly here and therefor untested - there might be mistakes in it but that's the general idea.

sysname is a system data type which is used by SQL server for all identifiers. It's basically an alias to nvarchar(128), except it's non-nullable.

sql_variant is a special data type which can be used to hold different data types inside.

use QUOTENAME to enable the use of column names containing spaces, dots, or that are reserved keywords.

Body:
I am passing dynamic column name base that column name  to Update the value and below i my table

Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar

Example1

Declare @ColumnName varchar(100), @Id int

set @ColumnName='City'
set @Id=20
set @value='Hyderabad'

update set ____ Table_CandidateInfo where ID=@Id

my output should like below Table_CandidateInfo, Hyderabad City updated base on Id and Column name

Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Hyderabad

Column name is dynamic some time @ColumnName='Name' so name value should update

Yesterday i have asked for get data base on column value that working fine but now i need to update

How to get value by dynamic field Name using sql select query

Body:
Well, since you can't parameterize identifiers in SQL, your only option would be to use dynamic SQL for such things.

However, please note that the code that creates and execute the dynamic SQL statement needs to be written in such a way it would prevent SQL injection attacks.

The rule is quite simple - what you can't parameterize must be white-listed.

So basically, you can do something like this:

CREATE PROCEDURE UpdateCandidateInfo
(
     @ColumnName sysname,
     @Id int,
     @value sql_Variant
)

AS

IF EXISTS
(
    SELECT 1
    FROM information_schema.columns
    WHERE Table_Name = 'Table_CandidateInfo'
    AND Column_Name = @ColumnName
)

BEGIN

    DECLARE @Sql nvarchar(4000) = N'Update Table_CandidateInfo SET '+ QUOTENAME(@ColumnName) + N' = @Value WHERE Id = @Id';

    DECLARE @Params nvarchar(4000) = N'@Value sql_Variant, @Id int'

    EXEC sp_ExecuteSql @Sql, @Params, @Value, @Id
END

GO

Please note that the code was written directly here and therefor untested - there might be mistakes in it but that's the general idea.

sysname is a system data type which is used by SQL server for all identifiers. It's basically an alias to nvarchar(128), except it's non-nullable.

sql_variant is a special data type which can be used to hold different data types inside.

use QUOTENAME to enable the use of column names containing spaces, dots, or that are reserved keywords.


问:
Why does interface error is given when Realm Object is extended to model class.?
I am creating realm Database. Created the model and extended with RealmObject. It gives me error that

Cannot be cast to io.realm.FooRealmProxyInterface.

答: Got the answer. Just add Open keyword in Model class so that all classes of realm object can access that model class.</p>


问:
Sonar failure in gradle5 with SourceSetOutput.getClassesDir not found
I am getting an error while running sonarqube on gradle 5, the error I am getting is

```<code>What went wrong:
 org.gradle.api.tasks.SourceSetOutput.getClassesDir()Ljava/io/File;

Try:
Run with --info or --debug option to get more log output. Run with     --scan to get full insights.

Exception is:
java.lang.NoSuchMethodError:
    org.gradle.api.tasks.SourceSetOutput.getClassesDir()Ljava/io/File;
at    org.sonarqube.gradle.SonarQubePlugin.configureSourceDirsAndJavaClasspath(SonarQubePlugin.java:169)
at    org.sonarqube.gradle.SonarQubePlugin.lambda$configureForJava$1(SonarQubePlugin.java:104)
</code>```

I tried downgrading the gradle version to 4.0 and found out the issue, now it is showing

```<code>:sonarqube
Gradle now uses separate output directories for each JVM language, but this build assumes a single directory for all classes from a source set. This behaviour has been deprecated and is scheduled to be removed in Gradle 5.0
    at     org.gradle.api.internal.tasks.DefaultSourceSetOutput.getClassesDir(DefaultSourceSetOutput.java:79)
at    org.gradle.api.internal.tasks.DefaultSourceSetOutput_Decorated.getClassesDir(Unknown Source)
at  org.sonarqube.gradle.SonarQubePlugin.configureSourceDirsAndJavaClasspath(SonarQubePlugin.java:169)
</code>```

Gradle configurations present in my code is as below,

```<code>sonarqube {

    properties {
        property "sonar.jacoco.reportPath", "${project.buildDir}/jacoco/test.exec"
        property "sonar.exclusions", "**/generated-*/**/*"
        property "sonar.sources", "src/main/java"
        property "sonar.tests", "src/test/java"
        //property "sonar.java.binaries", "${project.buildDir}/classes/main/"
    }
}
</code>```

I believe the issue can be fixed by either adding an expected property to the sonarqube property list or explicitly setting the source directory. Can anyone please advice on how to do that?

答: Not a complete solution, I migrated my build script to kotlin, and this helped me.</p>

Body:
I am getting an error while running sonarqube on gradle 5, the error I am getting is

What went wrong:
 org.gradle.api.tasks.SourceSetOutput.getClassesDir()Ljava/io/File;

Try:
Run with --info or --debug option to get more log output. Run with     --scan to get full insights.

Exception is:
java.lang.NoSuchMethodError:
    org.gradle.api.tasks.SourceSetOutput.getClassesDir()Ljava/io/File;
at    org.sonarqube.gradle.SonarQubePlugin.configureSourceDirsAndJavaClasspath(SonarQubePlugin.java:169)
at    org.sonarqube.gradle.SonarQubePlugin.lambda$configureForJava$1(SonarQubePlugin.java:104)

I tried downgrading the gradle version to 4.0 and found out the issue, now it is showing

:sonarqube
Gradle now uses separate output directories for each JVM language, but this build assumes a single directory for all classes from a source set. This behaviour has been deprecated and is scheduled to be removed in Gradle 5.0
    at     org.gradle.api.internal.tasks.DefaultSourceSetOutput.getClassesDir(DefaultSourceSetOutput.java:79)
at    org.gradle.api.internal.tasks.DefaultSourceSetOutput_Decorated.getClassesDir(Unknown Source)
at  org.sonarqube.gradle.SonarQubePlugin.configureSourceDirsAndJavaClasspath(SonarQubePlugin.java:169)

Gradle configurations present in my code is as below,

sonarqube {

    properties {
        property "sonar.jacoco.reportPath", "${project.buildDir}/jacoco/test.exec"
        property "sonar.exclusions", "**/generated-*/**/*"
        property "sonar.sources", "src/main/java"
        property "sonar.tests", "src/test/java"
        //property "sonar.java.binaries", "${project.buildDir}/classes/main/"
    }
}

I believe the issue can be fixed by either adding an expected property to the sonarqube property list or explicitly setting the source directory. Can anyone please advice on how to do that?