问:
'ld: file not found' after changing product name in Xcode
I was working on my application and i started out with a really bad name. So i decided to change it. I did that like this.

At the top right corner i simply changed the name to what i want. and then i started getting the error as you can see there. Reveal in Log shows these details:

The main error says:

ld: file not found: /Users/.../XCode/DerivedData/...

答:
Real Issue

After changing the PRODUCT_NAME (as seen in the question) the erroneous reference to Host Application is the real cause of the issue.

Just select your Tests-Target and under the General-Tab select your updated Host Application.

Afterwards, building the project will work.


来源: stackexchange

问:
Why does this sierpinski triangle draw randomly and not following the code?
I needed to do one for my school assignment but this code draw randomly. I copied some Stack Overflow code but I don't understand the logic. Can someone explain it to me?

```<code>import turtle
def triangle(width,height):

    if height==0:

        for i in range(3):
            t.fd(width)
            t.left(120)
    else:

        triangle(width/2,height-1)
        t.fd(width/2)
        triangle(width/2,height-1)
        t.bk(width/2)
        t.left(60)
        t.fd(width/2)
        t.right(60)
        triangle(width/2,height-1)
        t.left(60)
        t.bk(width/2)
        t.right(60)

window = turtle.Screen()
t = turtle.Turtle()
triangle(100,2)
window.exitonclick()
</code>```

What does the first if statement do? Does the first if statement draw the last triangle or what? Where does it draw the triangle because it never drawed a triangle that size on the script. The only triangle that is the same size as 100x100x100 in width is the triangle outside which is made out a lot of small triangles.

The (height-1) 3 times in the function, that would make height negative 1? At height 0 it would draw a big triangle and there's no big triangle on the window that start from the width then go up and then back down. Also in the else statement the width is 25 because the triangle the statement above divided 100 by 2 and then after that divided the width(50) by 2 again?

答:
In my opinion, the way your code is naming the variable is very misleading.
Because when this code uses the variable height, it actually doesn't refer to the 'height of the triangle'. Instead, this height is an indicator of when to stop the recursion.

FYI, recursion is a procedure of function calling itself, like f(f(f(f()))).
On the example I gave just now, it is a recursion of 4 iteration, as the function f calls itself 4 times.

If the variable height passed to the triangle() was 0, the first if statement knows that it doesn't have to do any recursion, so it simply draws a single triangle of side 100.

```<code>if height==0:

        for i in range(3):
            t.fd(width)
            t.left(120)
</code>```

Now if the height variable was 1, it calls three new triangle function with each height variable 0, and each side 50.

```<code>else:

        triangle(width/2,height-1) #notice how height is reduced by one
        t.fd(width/2)
        triangle(width/2,height-1)
        t.bk(width/2)
        t.left(60)
        t.fd(width/2)
        t.right(60)
        triangle(width/2,height-1)
        t.left(60)
        t.bk(width/2)
        t.right(60)
</code>```

so it draws 3 smaller triangles.

With height variable 2, imagine that each of the three triangles also calls another 3 triangles (so there will be total of 9 triangles of each side 25).

Hope this made the everything a little clearer :)

ContentLicense: CC BY-SA 4.0

Body:
I needed to do one for my school assignment but this code draw randomly. I copied some Stack Overflow code but I don't understand the logic. Can someone explain it to me?

import turtle
def triangle(width,height):

    if height==0:

        for i in range(3):
            t.fd(width)
            t.left(120)
    else:

        triangle(width/2,height-1)
        t.fd(width/2)
        triangle(width/2,height-1)
        t.bk(width/2)
        t.left(60)
        t.fd(width/2)
        t.right(60)
        triangle(width/2,height-1)
        t.left(60)
        t.bk(width/2)
        t.right(60)

window = turtle.Screen()
t = turtle.Turtle()
triangle(100,2)
window.exitonclick()

What does the first if statement do? Does the first if statement draw the last triangle or what? Where does it draw the triangle because it never drawed a triangle that size on the script. The only triangle that is the same size as 100x100x100 in width is the triangle outside which is made out a lot of small triangles.

The (height-1) 3 times in the function, that would make height negative 1? At height 0 it would draw a big triangle and there's no big triangle on the window that start from the width then go up and then back down. Also in the else statement the width is 25 because the triangle the statement above divided 100 by 2 and then after that divided the width(50) by 2 again?

Body:
In my opinion, the way your code is naming the variable is very misleading.
Because when this code uses the variable height, it actually doesn't refer to the 'height of the triangle'. Instead, this height is an indicator of when to stop the recursion.

FYI, recursion is a procedure of function calling itself, like f(f(f(f()))).
On the example I gave just now, it is a recursion of 4 iteration, as the function f calls itself 4 times.

If the variable height passed to the triangle() was 0, the first if statement knows that it doesn't have to do any recursion, so it simply draws a single triangle of side 100.

if height==0:

        for i in range(3):
            t.fd(width)
            t.left(120)

Now if the height variable was 1, it calls three new triangle function with each height variable 0, and each side 50.

else:

        triangle(width/2,height-1) #notice how height is reduced by one
        t.fd(width/2)
        triangle(width/2,height-1)
        t.bk(width/2)
        t.left(60)
        t.fd(width/2)
        t.right(60)
        triangle(width/2,height-1)
        t.left(60)
        t.bk(width/2)
        t.right(60)

so it draws 3 smaller triangles.

With height variable 2, imagine that each of the three triangles also calls another 3 triangles (so there will be total of 9 triangles of each side 25).

Hope this made the everything a little clearer :)


问:
Start background process/daemon from CGI script
I'm trying to launch a background process from a CGI scripts.  Basically, when a form is submitted the CGI script will indicate to the user that his or her request is being processed, while the background script does the actual processing (because the processing tends to take a long time.)  The problem I'm facing is that Apache won't send the output of the parent CGI script to the browser until the child script terminates.

I've been told by a colleague that what I want to do is impossible because there is no way to prevent Apache from waiting for the entire process tree of a CGI script to die.  However, I've also seen numerous references around the web to a "double fork" trick which is supposed to do the job.  The trick is described succinctly in this Stack Overflow answer, but I've seen similar code elsewhere.

Here's a short script I wrote to test the double-fork trick in Python:

```<code>import os
import sys

if os.fork():
    print 'Content-type: text/html\n\n Done'
    sys.exit(0)

if os.fork():
    os.setsid()
    sys.exit(0)

# Second child
os.chdir("/")
sys.stdout.close()
sys.stderr.close()
sys.stdin.close()

f = open('/tmp/lol.txt', 'w')

while 1:
     f.write('test\n')
</code>```

If I run this from the shell, it does exactly what I'd expect: the original script and first descendant die, and the second descendant keeps running until it's killed manually.  But if I access it through CGI, the page won't load until I kill the second descendant or Apache kills it because of the CGI timeout.  I've also tried replacing the second sys.exit(0) with os._exit(0), but there is no difference.

What am I doing wrong?

答:
I think there are two issues: setsid is in the wrong place and doing buffered IO operations in one of the transient children:

```<code>if os.fork():
  print "success"
  sys.exit(0)

if os.fork():
  os.setsid()
  sys.exit()
</code>```

You've got the original process (grandparent, prints "success"), the middle parent, and the grandchild ("lol.txt").

The os.setsid() call is being performed in the middle parent after the grandchild has been spawned. The middle parent can't influence the grandchild's session after the grandchild has been created. Try this:

```<code>print "success"
sys.stdout.flush()
if os.fork():
    sys.exit(0)
os.setsid()
if os.fork():
    sys.exit(0)
</code>```

This creates a new session before spawning the grandchild. Then the middle parent dies, leaving the session without a process group leader, ensuring that any calls to open a terminal will fail, making sure there's never any blocking on terminal input or output, or sending unexpected signals to the child.

Note that I've also moved the success to the grandparent; there's no guarantee of which child will run first after calling fork(2), and you run the risk that the child would be spawned, and potentially try to write output to standard out or standard error, before the middle parent could have had a chance to write success to the remote client.

In this case, the streams are closed quickly, but still, mixing standard IO streams among multiple processes is bound to give difficulty: keep it all in one process, if you can.

Edit I've found a strange behavior I can't explain:

```<code>#!/usr/bin/python

import os
import sys
import time

print "Content-type: text/plain\r\n\r\npid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())
sys.stdout.flush()

if os.fork():
    print "\nfirst fork pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())
    sys.exit(0)

os.setsid()

print "\nafter setsid pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())

sys.stdout.flush()

if os.fork():
    print "\nsecond fork pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())
    sys.exit(0)

#os.sleep(1) # comment me out, uncomment me, notice following line appear and dissapear
print "\nafter second fork pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())
</code>```

The last line, after second fork pid, only appears when the os.sleep(1) call is commented out. When the call is left in place, the last line never appears in the browser. (But otherwise all the content is printed to the browser.)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to launch a background process from a CGI scripts.  Basically, when a form is submitted the CGI script will indicate to the user that his or her request is being processed, while the background script does the actual processing (because the processing tends to take a long time.)  The problem I'm facing is that Apache won't send the output of the parent CGI script to the browser until the child script terminates.

I've been told by a colleague that what I want to do is impossible because there is no way to prevent Apache from waiting for the entire process tree of a CGI script to die.  However, I've also seen numerous references around the web to a "double fork" trick which is supposed to do the job.  The trick is described succinctly in this Stack Overflow answer, but I've seen similar code elsewhere.

Here's a short script I wrote to test the double-fork trick in Python:

import os
import sys

if os.fork():
    print 'Content-type: text/html\n\n Done'
    sys.exit(0)

if os.fork():
    os.setsid()
    sys.exit(0)

# Second child
os.chdir("/")
sys.stdout.close()
sys.stderr.close()
sys.stdin.close()

f = open('/tmp/lol.txt', 'w')

while 1:
     f.write('test\n')

If I run this from the shell, it does exactly what I'd expect: the original script and first descendant die, and the second descendant keeps running until it's killed manually.  But if I access it through CGI, the page won't load until I kill the second descendant or Apache kills it because of the CGI timeout.  I've also tried replacing the second sys.exit(0) with os._exit(0), but there is no difference.

What am I doing wrong?

Body:
I think there are two issues: setsid is in the wrong place and doing buffered IO operations in one of the transient children:

if os.fork():
  print "success"
  sys.exit(0)

if os.fork():
  os.setsid()
  sys.exit()

You've got the original process (grandparent, prints "success"), the middle parent, and the grandchild ("lol.txt").

The os.setsid() call is being performed in the middle parent after the grandchild has been spawned. The middle parent can't influence the grandchild's session after the grandchild has been created. Try this:

print "success"
sys.stdout.flush()
if os.fork():
    sys.exit(0)
os.setsid()
if os.fork():
    sys.exit(0)

This creates a new session before spawning the grandchild. Then the middle parent dies, leaving the session without a process group leader, ensuring that any calls to open a terminal will fail, making sure there's never any blocking on terminal input or output, or sending unexpected signals to the child.

Note that I've also moved the success to the grandparent; there's no guarantee of which child will run first after calling fork(2), and you run the risk that the child would be spawned, and potentially try to write output to standard out or standard error, before the middle parent could have had a chance to write success to the remote client.

In this case, the streams are closed quickly, but still, mixing standard IO streams among multiple processes is bound to give difficulty: keep it all in one process, if you can.

Edit I've found a strange behavior I can't explain:

#!/usr/bin/python

import os
import sys
import time

print "Content-type: text/plain\r\n\r\npid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())
sys.stdout.flush()

if os.fork():
    print "\nfirst fork pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())
    sys.exit(0)

os.setsid()

print "\nafter setsid pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())

sys.stdout.flush()

if os.fork():
    print "\nsecond fork pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())
    sys.exit(0)

#os.sleep(1) # comment me out, uncomment me, notice following line appear and dissapear
print "\nafter second fork pid: " + str(os.getpid()) + "\nppid: " + str(os.getppid())

The last line, after second fork pid, only appears when the os.sleep(1) call is commented out. When the call is left in place, the last line never appears in the browser. (But otherwise all the content is printed to the browser.)


问:
Python pathlib.Path - how do I get just a platform independent file separator as a string?
I am creating a format string that is different based on class, that is used to generate a filename by a generic class method. I'm using the Python 3.4+ pathlib.Path module for object-oriented file I/O.

In building this string, the path separator is missing, and rather than just put the windows version in, I want to add a platform independent file separator.

I searched the pathlib docs, and answers here about this, but all the examples assume I'm building a Path object, not a string. The pathlib functions will add the correct separator in any string outputs, but those are actual paths - so it won't work.

Besides something hacky like writing a string and parsing it to figure out what the separator is, is there a way to directly get the current, correct file separator string?

Prefer an answer using pathlib.Path, rather than os or shutil packages.

Here's what the code looks like:

In the constructor:

    self.outputdir = Path('drive:\\dir\\file')
    self.indiv_fileformatstr = str(self.outputdir) + '{}_new.m'
```

<p>In the final method used:</p>

<pre class="lang-py prettyprint-override"><code>    indiv_filename = Path(self.indiv_fileformatstr.format(topic))
</code>```

This leaves out the file separator

答: The platform-independent separator is in pathlib.os.sep

Body:
I am creating a format string that is different based on class, that is used to generate a filename by a generic class method. I'm using the Python 3.4+ pathlib.Path module for object-oriented file I/O.

In building this string, the path separator is missing, and rather than just put the windows version in, I want to add a platform independent file separator.

I searched the pathlib docs, and answers here about this, but all the examples assume I'm building a Path object, not a string. The pathlib functions will add the correct separator in any string outputs, but those are actual paths - so it won't work.

Besides something hacky like writing a string and parsing it to figure out what the separator is, is there a way to directly get the current, correct file separator string?

Prefer an answer using pathlib.Path, rather than os or shutil packages.

Here's what the code looks like:

In the constructor:

    self.outputdir = Path('drive:\\dir\\file')
    self.indiv_fileformatstr = str(self.outputdir) + '{}_new.m'

In the final method used:

    indiv_filename = Path(self.indiv_fileformatstr.format(topic))

This leaves out the file separator


问:
How to modify a low level driver in order to make it AUTOSAR compliant?
I wrote a low level driver for a CAN module,and now I have to modify it in order to make it AUTOSAR compliant. I've looked through the layered software architecture, SWS and SRS CAN documents available on autosar.org but the whole thing is over my head.
I don't know how to approach this problem. What do you think would be a good starting point / strategy?

I should mention that I am new to this field. I've had this job for 4 months and in college I studied electronics engineering. Also, at my job I am the only one in this department. I get directions from time to time from a superior, so I don't really have someone who can help me when I get stuck.

答: AUTOSAR specification includes coding guidelines (likewise as i.e. MISRA-C, see i.e. https://blog.parasoft.com/breaking-down-the-autosar-coding-guidelines-for-adaptive-autosar) that have to be obeyed In MISRA-C i.e. some pointer operations are considered as critical for security and so are not allowed and also  recursions are not allowed because the limited control of the recursion depth (stack smashing,...)


问:
Balanced Branching Algorithm
So I am doing a school task that looks like this

and I have absolutely no idea where to even start. Could someone point me in the right direction?

My idea of a starting point would be to calculate the discrepancy value of the root node first (the absolute value of the sum of the leaf values given) and then (somehow) check if there exists a discrepancy value higher than the root value, if not, the root value is the minimum possible discrepancy of the input. Am I on the right track? Currently I can't seem to get any further than this.

Important note: The tree that is built must "respect" the given order
  of the values.  For instance if the input is (5, 0, 0, -5) you are not
  allowed to build your tree by first combining the first and the last
  items into a tree.  More formally: at every internal node, the input
  values appearing as leaves in the left subtree of that node must all
  come before the input values appearing as leaves in the right subtree.

Thanks!

答:
For a given set a[1]...a[n], each corresponding to a leaf node, it is clear that the discrepancy of every tree is lower bounded by:

```<code>B(x[]) = max (abs(x[1]),...,abs(x[n]), abs(sum))
</code>```

Where sum, the sum of all x[i], corresponds to the weight of the root node of every tree build from the x[i].

The goal here is simply to show that it is always possible to build a tree, the discrepancy of which is equal to this lower bound.

It is realized in two steps.

In a first step, if two adjacent nodes have different signs, we simply merge them. This corresponds by replacing these two nodes by a new node, the weight of which is the sum of the two weights. The absolute value of this weight is less than the maximum of the absolute values of the two input weights, therefore less than the bound. We reiterate this process until we only get nodes (a new set), the weights of which have all the same sign.

In a second step, we have to manage a set, derived from the initial one, where all weights have the same sign. The maximum node of all trees that can be created from it correspond to the top one, the weight of which is equal to the sum of all weights of current active nodes, which is equal to the sum of the initial set. This sum corresponds to a value less or equal than the lower bound.

Finally, we obtain a tree, the weights of which are all less or equal to the lower bound.

Example:

```<code>-1 -5 4 -2      -> merge -5 and 4
-1 -1 -2        -> all signs equal, 2nd step: the maximum node of this sub-array correspond to the sum -4
</code>```

It is interesting to note that we obtain the same result by applying the rule in a different order:

```<code>-1 -5 4 -2      -> merge 4 and -2
-1 -5 2         -> merge -5 and 2
-1 -3           -> all signs equal, 2nd step: sum equals -4
</code>```

Title: Balanced Branching Algorithm

Body:
For a given set a[1]...a[n], each corresponding to a leaf node, it is clear that the discrepancy of every tree is lower bounded by:

B(x[]) = max (abs(x[1]),...,abs(x[n]), abs(sum))

Where sum, the sum of all x[i], corresponds to the weight of the root node of every tree build from the x[i].

The goal here is simply to show that it is always possible to build a tree, the discrepancy of which is equal to this lower bound.

It is realized in two steps.

In a first step, if two adjacent nodes have different signs, we simply merge them. This corresponds by replacing these two nodes by a new node, the weight of which is the sum of the two weights. The absolute value of this weight is less than the maximum of the absolute values of the two input weights, therefore less than the bound. We reiterate this process until we only get nodes (a new set), the weights of which have all the same sign.

In a second step, we have to manage a set, derived from the initial one, where all weights have the same sign. The maximum node of all trees that can be created from it correspond to the top one, the weight of which is equal to the sum of all weights of current active nodes, which is equal to the sum of the initial set. This sum corresponds to a value less or equal than the lower bound.

Finally, we obtain a tree, the weights of which are all less or equal to the lower bound.

Example:

-1 -5 4 -2      -> merge -5 and 4
-1 -1 -2        -> all signs equal, 2nd step: the maximum node of this sub-array correspond to the sum -4

It is interesting to note that we obtain the same result by applying the rule in a different order:

-1 -5 4 -2      -> merge 4 and -2
-1 -5 2         -> merge -5 and 2
-1 -3           -> all signs equal, 2nd step: sum equals -4


问:
How to dynamically change part of string's color with SpannableBuilder
I am formatting strings dynamically, as the following example from Android documentation:

```<code><string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
</code>```

Then I set values like this:

```<code>var text = getString(R.string.welcome_messages, username, mailCount)
</code>```

How can I set the green color for username and red for mailCount?

I need it to work for multiple locales, too. So I can't just hardcoded positions myself.

Previously I split this string into 4 parts and then could easily use SpannableBuilder to change colors.

HTML and CDATA are not appropriate. We need to keep the same strings for Android and iOS.

答:
Declare string

```<code><string name="string_formatted"><![CDATA[ Hello, <font color=#145A14> %1$s!</font> You have %2$d new messages]]></string>
</code>```

In Activity

```<code>TextView tv = findViewById(R.id.mytext);
tv.setText(Html.fromHtml(getString(R.string.html_formatted,"XYZ", 5)));
</code>```

Body:
I am formatting strings dynamically, as the following example from Android documentation:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

Then I set values like this:

var text = getString(R.string.welcome_messages, username, mailCount)

How can I set the green color for username and red for mailCount?

I need it to work for multiple locales, too. So I can't just hardcoded positions myself.

Previously I split this string into 4 parts and then could easily use SpannableBuilder to change colors.

HTML and CDATA are not appropriate. We need to keep the same strings for Android and iOS.

Body:
Declare string

<string name="string_formatted"><![CDATA[ Hello, <font color=#145A14> %1$s!</font> You have %2$d new messages]]></string>

In Activity

TextView tv = findViewById(R.id.mytext);
tv.setText(Html.fromHtml(getString(R.string.html_formatted,"XYZ", 5)));


问:
How do I make @WebMvcTest pickup WebMvcConfigurer classes from custom starters?
I'm building a custom starter library which registers an ObjectMapper in a WebMvcConfigurer class. One of the settings on this ObjectMapper is an Instant serialization format.

When I use @SpringBootTest with @AutoConfigureMockMvc the configured ObjectMapper is picked up, and everything works as expected. However the same assertions using @WebMvcTest fail. It seems like the WebMvcConfigurer class is not being picked up in the @WebMvcTest autoconfiguration, although the docs state that it should be picked up.

Is there a way to extend the autoconfiguration for WebMvcTest's without having to resort to putting @Import with every @WebMvcTest annotation?

code example

答:
Similar to what you have done to include your starter’s configuration in the main auto-configuration, you can include a configuration class in a particular test slice by adding an entry to spring.factories. In this case, you should use the key org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc.

If you look at the Spring Boot source code you can see that this is how Boot’s Jackson auto-configuration is included, for example.


问:
Hiding Report Columns in Crystal Reports
My gut is no, but if there's a Crystal Guru out there that knows better here's my question.  I have a report with 12 columns.  At times the report needs to be run for a crowd that doesn't have the "need to know" on a couple of the columns.  The specific column(s) to hide can change from time to time depending on the circumstances.

Is there a way to give the end user of the report the ability to toggle columns on or off without me having to hand code all the different options.

答: So, the answer is.  Set up a boolean parameter for each column.  Then place that parameter in the suppress formula of each column.  That allows the end user to uncheck any columns they do not want to appear in the final report.</p>


问:
CXF 2.2.12: How to turn off schema validation on the client side
I would like to turn off schema validation for JAXB-bound messages.  I am dealing with the client-side CXF code (WSDL first generation).  I have tried using

```<code><jaxws:client name="{http://apache.org/hello_world_soap_http}SoapPort"
    createdFromAPI="true">
    <jaxws:properties>
        <entry key="schema-validation-enabled" value="true" />
    </jaxws:properties>
</jaxws:client>
</code>```

Without success (see reference CXF FAQ ).  I've had difficulty finding a programmatic way of settings this property.  I've also explored short-circuiting CXF and accessing the parser, unmarshaller, etc.

Thanks for your help.

答:
```<code>@SchemaValidation(type = SchemaValidation.SchemaValidationType.NONE)
public EndpointImpl endpoint(Bus bus, DirectConnectService accountServiceEndpoint) {
  }
</code>```

put this validation in your endpoint configuration class

Body:
I would like to turn off schema validation for JAXB-bound messages.  I am dealing with the client-side CXF code (WSDL first generation).  I have tried using

<jaxws:client name="{http://apache.org/hello_world_soap_http}SoapPort"
    createdFromAPI="true">
    <jaxws:properties>
        <entry key="schema-validation-enabled" value="true" />
    </jaxws:properties>
</jaxws:client>

Without success (see reference CXF FAQ ).  I've had difficulty finding a programmatic way of settings this property.  I've also explored short-circuiting CXF and accessing the parser, unmarshaller, etc.

Thanks for your help.

Body:
@SchemaValidation(type = SchemaValidation.SchemaValidationType.NONE)
public EndpointImpl endpoint(Bus bus, DirectConnectService accountServiceEndpoint) {
  }

put this validation in your endpoint configuration class


问:
How do i validate settings using the project manager generated My.Settings in VB.Net?
The code below does not work, the error says the method ValidateSettings does not have a signature compatable with delgate 'Delgate Sub SettingChangingEventHandler(sender as Object, e as SettingChangingEventArgs)'

This error shows up when hovering over [...] AddressOf ValidateSettings

```<code>    Private Sub ValidateSettings(sender As Object, e As SettingChangingEventArgs)

    End Sub

    Private Sub frm_Settings_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        AddHandler My.Settings.SettingChanging, AddressOf ValidateSettings
        PropertyGrid_Settings.SelectedObject = My.Settings
        CenterToParent()
    End Sub
</code>```

Im using this tutorial

答:
The solution was to add Imports System.Configuration to the class, as pointed out by a comment on the original post.

```<code>Imports System.Configuration
Public Class frm_Settings

    Private Sub ValidateSettings(sender As Object, e As SettingChangingEventArgs)
        'validation and notifying user
        MsgBox(e.NewValue)
    End Sub

    Private Sub frm_Settings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler My.Settings.SettingChanging, AddressOf ValidateSettings
        PropertyGrid_Settings.SelectedObject = My.Settings

        CenterToParent()
    End Sub
</code>```

Body:
The code below does not work, the error says the method ValidateSettings does not have a signature compatable with delgate 'Delgate Sub SettingChangingEventHandler(sender as Object, e as SettingChangingEventArgs)'

This error shows up when hovering over [...] AddressOf ValidateSettings

    Private Sub ValidateSettings(sender As Object, e As SettingChangingEventArgs)

    End Sub

    Private Sub frm_Settings_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        AddHandler My.Settings.SettingChanging, AddressOf ValidateSettings
        PropertyGrid_Settings.SelectedObject = My.Settings
        CenterToParent()
    End Sub

Im using this tutorial

Body:
The solution was to add Imports System.Configuration to the class, as pointed out by a comment on the original post.

Imports System.Configuration
Public Class frm_Settings

    Private Sub ValidateSettings(sender As Object, e As SettingChangingEventArgs)
        'validation and notifying user
        MsgBox(e.NewValue)
    End Sub

    Private Sub frm_Settings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler My.Settings.SettingChanging, AddressOf ValidateSettings
        PropertyGrid_Settings.SelectedObject = My.Settings

        CenterToParent()
    End Sub


问:
TypeError: Cannot read property 'rocket_name' of undefined -- Even though it is defined
I'm using the SpaceX API to build a personal project. I'm using React Router to dynamically load components, rather than refreshing the whole website.

Here is my LaunchDetails component where I'm trying to output some data:

```<code>import React, { Component } from 'react'

class LaunchDetail extends Component {
  state = {
    launch: []
  }

  async componentDidMount () {
    try {
      const res = await fetch(`https://api.spacexdata.com/v3/launches/${this.props.match.params.flight_number}`)
      const data = await res.json()
      this.setState({
        launch: data,
        rocket: data.rocket
      })
    } catch (e) {
      console.log(e)
    }
  }

  render () {
    const { launch, rocket } = this.state

    console.log(rocket)

    return (
      <div>
        <div>
          <h1>{launch.mission_name}</h1>
          <p>SpaceX Flight Number: {launch.flight_number}</p>
          <p>Launched: {launch.launch_year}</p>
          <p>Rocket: {rocket.rocket_name}, {rocket.rocket_type}</p>
        </div>
      </div>
    )
  }
}

export default LaunchDetail
</code>```

Data one level deep like launch.mission_name is displaying correctly... However, when I try and go down another level, say, rocket.rocket_name (eg: launch.rocket.rocket_name), it throws the above error.

What is strange is that this works in another component, but that is using a different end point (all the data) and I'm mapping through it. Not sure if the way I'm calling the data in this component is to blame or not...

Does anyone have any idea why this could be happening?

EDIT: I've updated the code to be simpler after receiving some comments, error still persists:

```<code>import React, { Component } from 'react'

class LaunchDetail extends Component {
  state = {
    launch: []
  }

  async componentDidMount () {
    try {
      const res = await fetch(`https://api.spacexdata.com/v3/launches/${this.props.match.params.flight_number}`)
      const data = await res.json()
      this.setState({
        launch: data
      })
    } catch (e) {
      console.log(e)
    }
  }

  render () {
    const { launch } = this.state

    return (
      <div>
        <div>
          <h1>{launch.mission_name}</h1>
          <p>SpaceX Flight Number: {launch.flight_number}</p>
          <p>Launched: {launch.launch_year}</p>
          <p>Rocket: {launch.rocket.rocket_name}, {launch.rocket_type}</p>
        </div>
      </div>
    )
  }
}

export default LaunchDetail
</code>```

答:
From here you can find that the react lifecycle methods go in the following order.

componentWillMount --> render --> componentDidMount

You have initialized state with

state = {
  launch: []
}
```

So on the first render, state.rocket will be undefined.

To fix this, either initialise state.rocket or change componentDidMount to componentWillMount
With the former being prefered.

Note componentWillMount is deprecated in version 17.

After OP's edit. You are still initializing launch to []

On the first render launch.rocket will be undefined. Therefore launch.rocket.rocket_name will throw an error.

Either initialise launch to have a rocket field. Or do something like

(launch.rocket || {}).rocket_name, or something else to check that rocket is defined before accessing rocket_name.

Body:
I'm using the SpaceX API to build a personal project. I'm using React Router to dynamically load components, rather than refreshing the whole website.

Here is my LaunchDetails component where I'm trying to output some data:

import React, { Component } from 'react'

class LaunchDetail extends Component {
  state = {
    launch: []
  }

  async componentDidMount () {
    try {
      const res = await fetch(`https://api.spacexdata.com/v3/launches/${this.props.match.params.flight_number}`)
      const data = await res.json()
      this.setState({
        launch: data,
        rocket: data.rocket
      })
    } catch (e) {
      console.log(e)
    }
  }

  render () {
    const { launch, rocket } = this.state

    console.log(rocket)

    return (

{launch.mission_name}

SpaceX Flight Number: {launch.flight_number}

Launched: {launch.launch_year}

Rocket: {rocket.rocket_name}, {rocket.rocket_type}

    )
  }
}

export default LaunchDetail

Data one level deep like launch.mission_name is displaying correctly... However, when I try and go down another level, say, rocket.rocket_name (eg: launch.rocket.rocket_name), it throws the above error.

What is strange is that this works in another component, but that is using a different end point (all the data) and I'm mapping through it. Not sure if the way I'm calling the data in this component is to blame or not...

Does anyone have any idea why this could be happening?

EDIT: I've updated the code to be simpler after receiving some comments, error still persists:

import React, { Component } from 'react'

class LaunchDetail extends Component {
  state = {
    launch: []
  }

  async componentDidMount () {
    try {
      const res = await fetch(`https://api.spacexdata.com/v3/launches/${this.props.match.params.flight_number}`)
      const data = await res.json()
      this.setState({
        launch: data
      })
    } catch (e) {
      console.log(e)
    }
  }

  render () {
    const { launch } = this.state

    return (

{launch.mission_name}

SpaceX Flight Number: {launch.flight_number}

Launched: {launch.launch_year}

Rocket: {launch.rocket.rocket_name}, {launch.rocket_type}

    )
  }
}

export default LaunchDetail

Body:
From here you can find that the react lifecycle methods go in the following order.

componentWillMount --> render --> componentDidMount

You have initialized state with

state = {
  launch: []
}

So on the first render, state.rocket will be undefined.

To fix this, either initialise state.rocket or change componentDidMount to componentWillMount
With the former being prefered.

Note componentWillMount is deprecated in version 17.

After OP's edit. You are still initializing launch to []

On the first render launch.rocket will be undefined. Therefore launch.rocket.rocket_name will throw an error.

Either initialise launch to have a rocket field. Or do something like

(launch.rocket || {}).rocket_name, or something else to check that rocket is defined before accessing rocket_name.


问:
jquery or js select the first class of an element
I have 3 anchors with 3 divs
The anchors are like that:

```<code><a class="home sharedClass">home</a>

<a class="about sharedClass">about</a>

<a class="contact sharedClass">contact</a>
</code>```

When I click one of them I get the contents of the corresponding div which its id is the same as the first class (home, about or contact)

I have a little jQuery code that has to select the right class But the result is an alert telling the name of theClass:

```<code>$('a.sharedClass').click(function(){

    var theClass = $(this).attr('class[0]');

    alert(theClass)

});
</code>```

The problem is that this function returns "undefined". How to fix this?

Thanks.

答:
why not just get the text then you don't even need the class</p>

```<code>$('a.sharedClass').click(function(){

    alert(this.text)

});
</code>```

Body:
I have 3 anchors with 3 divs
The anchors are like that:

home

about

contact

When I click one of them I get the contents of the corresponding div which its id is the same as the first class (home, about or contact)

I have a little jQuery code that has to select the right class But the result is an alert telling the name of theClass:

$('a.sharedClass').click(function(){

    var theClass = $(this).attr('class[0]');

    alert(theClass)

});

The problem is that this function returns "undefined". How to fix this?

Thanks.

Body:
why not just get the text then you don't even need the class

$('a.sharedClass').click(function(){

    alert(this.text)

});


问:
Firebase: keep values assigned in observeSingleEvent
I am reading data from Firebase Database in Swift, then want to use length in later in function, however I lost the assignment done in with: closure. AKA the two print(length!) print different values. How can I remember this assignment whether it be a workaround to closures in Swift or way to save save value with a Firebase call.</p>

```<code>var length:Int? = 1
        ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
                print(length!)
            })
        print(length!)
</code>```

答:
To use your length property in the same class, just declare it in the class like so:

```<code>var length: Int?

override func viewDidLoad() {
    //...
}
</code>```

To use your length property in other classes, consider making the property global:

```<code>public struct GlobalProperties {

    static var length: Int?

}
</code>```

Assign value in closure:

```<code>ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
            let value = snapshot.value as? NSDictionary
            length = (value?["AcademicBuildingsLength"] as? Int ?? 0)

            // Assign value to length property
            self.length = length //if value is used within this class
            GlobalProperties.length = length //if value is used elsewhere
        })
</code>```

Btw. The reason your print statements prints different values is because the bottom print is executed before the asynchronous firebase function is finished. You should grab the length value only inside the closure.

Body:
I am reading data from Firebase Database in Swift, then want to use length in later in function, however I lost the assignment done in with: closure. AKA the two print(length!) print different values. How can I remember this assignment whether it be a workaround to closures in Swift or way to save save value with a Firebase call.

var length:Int? = 1
        ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
                print(length!)
            })
        print(length!)

Body:
To use your length property in the same class, just declare it in the class like so:

var length: Int?

override func viewDidLoad() {
    //...
}

To use your length property in other classes, consider making the property global:

public struct GlobalProperties {

    static var length: Int?

}

Assign value in closure:

ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
            let value = snapshot.value as? NSDictionary
            length = (value?["AcademicBuildingsLength"] as? Int ?? 0)

            // Assign value to length property
            self.length = length //if value is used within this class
            GlobalProperties.length = length //if value is used elsewhere
        })

Btw. The reason your print statements prints different values is because the bottom print is executed before the asynchronous firebase function is finished. You should grab the length value only inside the closure.


问:
Bootstrap Carousel Wont Start Cycle Automaticly
I've been working on my carousel and it seems to be working now.

It start cycling, but not before I've hovored my cursor once over it. How do I make it start cycle automaticly, so people doesn't have to hover the carousel.

Heres my code:

```<code><div id="slider" class="carousel slide">
 <div class="carousel-inner">
  <div class="item active">
   <img src="img/slide1.jpg" id="picture">
   <div class="carousel-caption">
   <center><h4>ADD TEXT LATER</h4>
   <p>ADD TEXT LATER</p></center>
  </div>
 </div>
 <div class="item">
  <img src="img/slide2.jpg" id="picture">
  <div class="carousel-caption">
  <center><h4>ADD TEXT LATER</h4>
  <p>ADD TEXT LATER</p></center>
 </div>
</div>
 <div class="item">
  <img src="img/slide3.png" id="picture">
  <div class="carousel-caption">
  <center><h4>ADD TEXT LATER</h4>
  <p>ADD TEXT LATER</p></center>
 </div>
</div>
  <div class="item">
  <img src="img/slide4.png" id="picture">
  <div class="carousel-caption">
  <center><h4>ADD TEXT LATER</h4>
  <p>ADD TEXT LATER</p></center>
 </div>
</div>
</div>

<a class="carousel-control left"href="#slider" data-slide="prev">‹</a>
<a class="carousel-control right"href="#slider" data-slide="next">›</a>
</div>

<script>
$('.carousel').carousel({
  interval: 1000
})
</script>

<script src="js/bootstrap-carousel.jss"></script>
</code>```

答:
I had to add delay for carousel starting function. For some reason it did not start after routing to another page view.

This is what did the trick for me:

```<code><script>
setTimeout(function() {
  $('.carousel').carousel();
}, 3000);
</script>
</code>```

Body:
I've been working on my carousel and it seems to be working now.

It start cycling, but not before I've hovored my cursor once over it. How do I make it start cycle automaticly, so people doesn't have to hover the carousel.

Heres my code:

ADD TEXT LATER

ADD TEXT LATER

ADD TEXT LATER

ADD TEXT LATER

ADD TEXT LATER

ADD TEXT LATER

ADD TEXT LATER

ADD TEXT LATER

‹
›

Body:
I had to add delay for carousel starting function. For some reason it did not start after routing to another page view.

This is what did the trick for me:

<script>
setTimeout(function() {
  $('.carousel').carousel();
}, 3000);
</script>


问:
Multiple variables in .htaccess
i want to make my URL become from this:
www.mysite.com/index.php?area=test1&par=test2
to this:
www.mysite.com/test1/test2

my .htaccess look like that:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*?)/?$ /index.php?area=$1 [L]
DirectoryIndex index.php
</code>```

i get only the area variable, and dont know how to continue from here.

答:
why not simply pass all to php like

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]
</code>```

than process it in php

```<code>var_dump($_SERVER);//parse all info you want
</code>```

Title: Multiple variables in .htaccess

Body:
i want to make my URL become from this:
www.mysite.com/index.php?area=test1&par=test2
to this:
www.mysite.com/test1/test2

my .htaccess look like that:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*?)/?$ /index.php?area=$1 [L]
DirectoryIndex index.php

i get only the area variable, and dont know how to continue from here.

Body:
why not simply pass all to php like

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

than process it in php

var_dump($_SERVER);//parse all info you want


问:
Making Link Description point to Link Reference in IMPORTXML statement
I am scraping FINVIZ financial data using the google sheets IMPORTXML function, specifically:

=IMPORTXML("http://finviz.com/quote.ashx?t="&B1,"//table[@id='news-table']/tr")

Against the following source:

```<code><table width="100%" cellpadding="1" cellspacing="0" border="0" id="news-table" class="fullview-news-outer">
    <tr>
        <td width="130" align="right" style="white-space:nowrap">Feb-15-20 03:58PM  </td>
        <td align="left"><a href="https://finance.yahoo.com/news/u-evacuate-citizens-quarantined-ship-043646253.html" target="_blank" class="tab-link-news">U.S. Woman From Cruise Falls Ill as 2,200 Head Home: Virus Update</a> <span style="color:#aa6dc0;font-size:9px">Bloomberg</span></td>
    </tr>
    <tr>
        <td width="130" align="right">03:41PM  </td>
        <td align="left"><a href="https://www.marketwatch.com/story/afraid-of-sky-high-stock-valuations-consider-this-deep-value-strategy-2020-02-12?siteid=yhoof2&yptr=yahoo" target="_blank" class="tab-link-news">Afraid of sky-high stock valuations? Consider this deep value strategy</a> <span style="color:#aa6dc0;font-size:9px">MarketWatch</span></td>
    </tr>
    <tr>
        <td width="130" align="right">10:47AM  </td>
        <td align="left"><a href="https://www.marketwatch.com/story/if-you-could-buy-only-one-stock-for-5g-and-artificial-intelligence-this-would-be-it-2020-02-14?siteid=yhoof2&yptr=yahoo" target="_blank" class="tab-link-news">If you could buy only one stock for 5G and artificial intelligence, this would be it</a> <span style="color:#aa6dc0;font-size:9px">MarketWatch</span></td>
    </tr>
</table>
</code>```

Hence, if I choose the stock ticker for Apple (AAPL) then the XPATH component of the IMPORTXML call above returns the following:

Question: How do I modify the XPATH component to make the news description clickable to its HREF?

I DO NOT want the URL to replace the news - just the news to point to its destination such that clicking the news takes me to the link.

答:
try:

```<code>=ARRAYFORMULA({INDEX(IMPORTXML("http://finviz.com/quote.ashx?t="&B1,
 "//table[@id='news-table']/tr"),,1),
 HYPERLINK(IMPORTXML("http://finviz.com/quote.ashx?t="&B1,
 "//table[@id='news-table']/tr//a/@href"),
 INDEX(IMPORTXML("http://finviz.com/quote.ashx?t="&B1,
 "//table[@id='news-table']/tr"),,2))})
</code>```

Body:
I am scraping FINVIZ financial data using the google sheets IMPORTXML function, specifically:

=IMPORTXML("http://finviz.com/quote.ashx?t="&B1,"//table[@id='news-table']/tr")

Against the following source:

        Feb-15-20 03:58PM
        U.S. Woman From Cruise Falls Ill as 2,200 Head Home: Virus Update Bloomberg

        03:41PM
        Afraid of sky-high stock valuations? Consider this deep value strategy MarketWatch

        10:47AM
        If you could buy only one stock for 5G and artificial intelligence, this would be it MarketWatch

Hence, if I choose the stock ticker for Apple (AAPL) then the XPATH component of the IMPORTXML call above returns the following:

Question: How do I modify the XPATH component to make the news description clickable to its HREF?

I DO NOT want the URL to replace the news - just the news to point to its destination such that clicking the news takes me to the link.

Body:
try:

=ARRAYFORMULA({INDEX(IMPORTXML("http://finviz.com/quote.ashx?t="&B1,
 "//table[@id='news-table']/tr"),,1),
 HYPERLINK(IMPORTXML("http://finviz.com/quote.ashx?t="&B1,
 "//table[@id='news-table']/tr//a/@href"),
 INDEX(IMPORTXML("http://finviz.com/quote.ashx?t="&B1,
 "//table[@id='news-table']/tr"),,2))})


问:
How to programmatically discover the JPA implementation and SQL dialect being used by Spring Boot?
I know it is possible to change the JPA implementation in use by Spring Boot, the default is to use Hibernate, but it's also possible to user others, like EclipseLink. It is possible to find, at application runtime, which JPA implementation is being used, and also discover which SQL dialect is currently in use (like MySQL, PostgreSQL, Oracle)?</p>

答: Another possible solution would be to inspect the JDBC string from the application.yml file :-)</p>


问:
How to Display Real Time variables node.js with express
So , I have been try to display my variables "pares", "impares" ,"ninguno" in real time as the image below I used app.get and inside that a response.write to print de varibles, but the problem is if I want the varaibles to update, I need to reload the page everytime, is there anyway to print them in real time?,enter image description here</p>

```<code>var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var reload = require('reload');
var http = require('http');
var server = http.createServer(app);

var impares = 0;
var pares = 0;
var ninguno =0;

app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());

app.post('/arduino', function(request, response) {
    console.log("Arduino asking data");
    var stringInform = (Object.keys(request.body)).toString();
    var stringA = stringInform.split("|");
    var dato1= parseInt(stringA[0],10);
    var dato2 = parseInt(stringA[1],10);
    response.send('Hello Arduino');
    Parimpar(dato1,dato2);
    response.end();
    console.log(dato1);
    console.log(dato2);
    console.log(ninguno);
});

 app.get('/arduino', function(request, response) {
    response.write('PARES:'+ pares + ' '+ 'IMPARES:' + impares + ' ' + 'NINGUNO:'+ ninguno);
    response.end();
});

app.listen(8080);

function Parimpar(c,i)
{
    if (c%2 == 0  && i%2 == 0)
    {
        pares = pares +1;
    //  return pares;
    }
    else if (c%2 != 0 && i%2 != 0)
    {
        impares = impares + 1;
        //return impares;
    }
    else
    {
        ninguno = ninguno +1 ;
        //return ninguno;
    }

}
</code>```

答:
You Can Use Web-sockets To Emit Events When The Values Are Updated . The Easier Way Is to Setup A socket.io webserver and emit values to all the connected values.
Check Out https://socket.io/</p>

Body:
So , I have been try to display my variables "pares", "impares" ,"ninguno" in real time as the image below I used app.get and inside that a response.write to print de varibles, but the problem is if I want the varaibles to update, I need to reload the page everytime, is there anyway to print them in real time?,enter image description here

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var reload = require('reload');
var http = require('http');
var server = http.createServer(app);

var impares = 0;
var pares = 0;
var ninguno =0;

app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());

app.post('/arduino', function(request, response) {
    console.log("Arduino asking data");
    var stringInform = (Object.keys(request.body)).toString();
    var stringA = stringInform.split("|");
    var dato1= parseInt(stringA[0],10);
    var dato2 = parseInt(stringA[1],10);
    response.send('Hello Arduino');
    Parimpar(dato1,dato2);
    response.end();
    console.log(dato1);
    console.log(dato2);
    console.log(ninguno);
});

 app.get('/arduino', function(request, response) {
    response.write('PARES:'+ pares + ' '+ 'IMPARES:' + impares + ' ' + 'NINGUNO:'+ ninguno);
    response.end();
});

app.listen(8080);

function Parimpar(c,i)
{
    if (c%2 == 0  && i%2 == 0)
    {
        pares = pares +1;
    //  return pares;
    }
    else if (c%2 != 0 && i%2 != 0)
    {
        impares = impares + 1;
        //return impares;
    }
    else
    {
        ninguno = ninguno +1 ;
        //return ninguno;
    }

}


问:
Is notifications height adjustable to any value?
I know the recommended layout_height for small notifications is 64dp, but I want the notifications to be a little bigger (for example to be 128dp). Is notifications height adjustable to any value or it has to be exactly 64dp to make it look good on all devices without problems?

I use FCM to send notifications.

答:
By default, the height of the collapsed notification layout is fixed at 64dp, The only way to make it larger than that size is to make it expandable by using NotificationCompat.BigPictureStyle. You can see the example here:

```<code>var notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setSmallIcon(R.drawable.new_post)
    .setContentTitle(imageTitle)
    .setContentText(imageDescription)
    .setStyle(NotificationCompat.BigPictureStyle()
            .bigPicture(myBitmap))
    .build()
</code>```

However, according to this source, expanded notification layouts are limited to 256dp. There is no way to exceed this amount.

Body:
By default, the height of the collapsed notification layout is fixed at 64dp, The only way to make it larger than that size is to make it expandable by using NotificationCompat.BigPictureStyle. You can see the example here:

var notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setSmallIcon(R.drawable.new_post)
    .setContentTitle(imageTitle)
    .setContentText(imageDescription)
    .setStyle(NotificationCompat.BigPictureStyle()
            .bigPicture(myBitmap))
    .build()

However, according to this source, expanded notification layouts are limited to 256dp. There is no way to exceed this amount.


问:
Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT
This post is in continuation of JPA How to get the value from database after persist

When I execute the following I am getting following exception, how can I resolve this?

```<code>Not allowed to create transaction on shared EntityManager - use Spring
transactions or EJB CMT
</code>```

DAOImpl code

```<code>public void create(Project project) {
        entityManager.persist(project);
        entityManager.getTransaction().commit();
        project = entityManager.find(Project.class, project.getProjectId());
        entityManager.refresh(project);
        System.out.println("Id    -- " + project.getProjectId());
            System.out.println("no -- " + project.getProjectNo());
    }
</code>```

applicationContext.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="DataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="scott" />
        <property name="password" value="tiger" />
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@myserver:1521:ORCL" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="DataSource" />
        <property name="packagesToScan" value="test.entity" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
            </bean>
        </property>
    </bean>

    <context:component-scan base-package="test.net" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

     <context:annotation-config/>

</beans>
</code>```

答: You need to remove the statement entityManager.getTransaction().begin() and annotate the method using @Transactional? which enables transaction handling by Spring.

Body:
This post is in continuation of JPA How to get the value from database after persist

When I execute the following I am getting following exception, how can I resolve this?

Not allowed to create transaction on shared EntityManager - use Spring
transactions or EJB CMT

DAOImpl code

public void create(Project project) {
        entityManager.persist(project);
        entityManager.getTransaction().commit();
        project = entityManager.find(Project.class, project.getProjectId());
        entityManager.refresh(project);
        System.out.println("Id    -- " + project.getProjectId());
            System.out.println("no -- " + project.getProjectNo());
    }

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="DataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="scott" />
        <property name="password" value="tiger" />
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@myserver:1521:ORCL" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="DataSource" />
        <property name="packagesToScan" value="test.entity" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
            </bean>
        </property>
    </bean>

    <context:component-scan base-package="test.net" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

     <context:annotation-config/>

</beans>


问:
Django Channels __init__() got an unexpected keyword argument 'scope'
I have been trying to set up a basic Django Channels project based on the tutorial, but I am getting this error. I used the Django python shell to test if Redis is working and it is. I am running Daphne with 'Daphne my_project.asgi:application. I could not find any similar questions or documentation on the problem. Please let me know if you need to see any other parts of my code. Any help is greatly appreciated!</p>

```<code>consumers.py

from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
import json

class TestConsumer(WebsocketConsumer):

def connect(self):
    self.group_name = 'test'

    async_to_sync(self.channel_layer.group_add)(
        self.group_name,
        self.channel_name
    )

    self.accept()

def disconnect(self, close_code):
    async_to_sync(self.channel_layer.group_discard)(
        self.group_name,
        self.channel_name
    )

def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']

    async_to_sync(self.channel_layer.group_send)(
        self.group_name,
        {
            'type': 'chat_message',
            'message': message
        }
    )

def chat_message(self, event):
    message = event['message']

    self.send(text_data=json.dumps({
        'message' : message
    }))

project routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import main.routing
import sockets.routing

application = ProtocolTypeRouter
({
    'websocket' : AuthMiddlewareStack(
        URLRouter(
            sockets.routing.websocket_urlpatterns
        )
    )
})

asgi.py

import os
import django
from channels.routing import get_default_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'socialapp.settings')
django.setup()
application = get_default_application()

project settings

ASGI_APPLICATION = 'socialapp.routing.application'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}
</code>```

答: Try double checking you logic as the files look fine: when i saw this, i had erroneously passed my uwsgi.application to daphne instead of the asgi.application

Body:
I have been trying to set up a basic Django Channels project based on the tutorial, but I am getting this error. I used the Django python shell to test if Redis is working and it is. I am running Daphne with 'Daphne my_project.asgi:application. I could not find any similar questions or documentation on the problem. Please let me know if you need to see any other parts of my code. Any help is greatly appreciated!

consumers.py

from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
import json

class TestConsumer(WebsocketConsumer):

def connect(self):
    self.group_name = 'test'

    async_to_sync(self.channel_layer.group_add)(
        self.group_name,
        self.channel_name
    )

    self.accept()

def disconnect(self, close_code):
    async_to_sync(self.channel_layer.group_discard)(
        self.group_name,
        self.channel_name
    )

def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']

    async_to_sync(self.channel_layer.group_send)(
        self.group_name,
        {
            'type': 'chat_message',
            'message': message
        }
    )

def chat_message(self, event):
    message = event['message']

    self.send(text_data=json.dumps({
        'message' : message
    }))

project routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import main.routing
import sockets.routing

application = ProtocolTypeRouter
({
    'websocket' : AuthMiddlewareStack(
        URLRouter(
            sockets.routing.websocket_urlpatterns
        )
    )
})

asgi.py

import os
import django
from channels.routing import get_default_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'socialapp.settings')
django.setup()
application = get_default_application()

project settings

ASGI_APPLICATION = 'socialapp.routing.application'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}


问:
Returning Boolean value error when traversing a list
I am trying to find if a list is a strictly increasing sequenced if 1 and only 1 element from it is removed.  This works for some lists but does not work for others when there isn't any apparent difference between the lists.  And for large lists, it exceeds the execution time limit.  This is my code:

```<code>def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        new_seq = sequence.copy()
        del new_seq[i]

        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            output = True
        else:
            output = False

    return output
</code>```

I'm creating a copy of the input list.  Then, I'm removing the element i and then returning True or False depending on whether the list is a strictly increasing sequence.  I am creating the copy of the list inside the for-loop to make sure that I am removing only one element.  These are some of the test runs where the code does not return the appropriate value:

```<code>Input:
sequence: [10, 1, 2, 3, 4, 5]
Output: false
Expected Output: true

Input:
sequence: [1, 2, 5, 3, 5]
Output: false
Expected Output: true
</code>```

And in this test case, the code exceeds the execution time limit:

```<code>Input:
sequence: [-9996, -9995, -9994, -9993, -9991, -9989, -9987, -9986, -9985, -9983, -9982, -9980, -9978, -9977, -9976, -9975, -9974, -9972, -9968, -9966, -9965, -9961, -9957, -9956, -9955, -9954, -9952, -9948, -9942, -9939, -9938, -9936, -9935, -9932, -9931, -9927, -9925, -9923, -9922, -9921, -9920, -9919, -9918, -9908, -9905, -9902, -9901, -9900, -9899, -9897, -9896, -9894, -9888, -9886, -9880, -9878, -9877, -9876, -9874, -9872, -9871, -9870, -9869, -9868, -9867, -9865, -9857, -9856, -9855, -9854, -9853, -9852, -9851, -9849, -9848, -9846, -9845, -9843, -9842, -9841, -9840, -9837, -9834, -9828, -9826, -9824, -9823, -9820, -9816, -9814, -9812, -9811, -9810, -9809, -9807, -9806, -9804, -9803, -9801, -9800]
Output: undefined
Expected Output: false
</code>```

答:
Your loop will always overwrite (with returning False or True) the previous result in each iteration. So it actually "forgets" about any violation in the previous iteration. Only the last iteration determines the output, so your algorithm is wrong.

Secondly, even if you would fix that error (by exiting the loop if the new list is not sorted), this algorithm represents a time complexity of O(n²), because in each iteration:

a copy of the list is made with .copy()

a del is performed, requiring a shift of all values that follow it

a new copy of the list is made with new_seq[1:]

zip is called, creating yet another list

all is called, iterating that new list

All of these actions are killing the performance.

Instead you should only perform one iteration over the list, and solve the problem without any nested iterations. One clue is that you don't actually have to perform the removal of the element. You only need to check the situation as if it were removed.

An efficient algorithm only needs to look at three values: the currently iterated value, and the two preceding values. If those three are not in order, you can determine which one should be removed, but only represent that removal in those three variables (keep the list untouched):

```<code>def almostIncreasingSequence(sequence):
    beforePrev = prev = float('-inf')
    allowExceptions = True

    for curr in sequence:
        if curr <= prev: # Order is not maintained:
            if not allowExceptions: # It's not the first time
                return False
            allowExceptions = False
            # Decide whether to skip the current or previous value
            if curr > beforePrev:
                prev = curr;
        else: # Normal case: keep track of two preceding values
            beforePrev, prev = prev, curr
    return True
</code>```

Explanation

Three list values are kept in separate memory during the traversal of the list: curr, prev and beforePrev. The latter two lag behind the curr value. So at each iteration, curr gets the current list value, and at the end of the iteration, we shift the values: beforePrev ← prev ← curr. So essentially, these three values correspond to the 3 most recently visited values -- at least when there is no anomaly in the list.

So let's say at a certain moment you find an anomaly: you find a position where curr <= prev, i.e. where the sequence is not strictly increasing; then it is clear one of the values has to be removed: either curr or prev should be removed to have any hope that the list can be "fixed".

It could be that the algorithm had already decided that a value had to be removed at an earlier iteration (allowExceptions is False): but we are only allowed to remove one value from the list, so in that case we decide that there is no solution and return False

But if this was the first time we got into this situation, then we should decide whether to identify curr or prev as offending value. We may assume that beforePrev and prev are in the correct order (we verified that in the preceding iteration), so there really are only two possibilities left for the relative ordering of beforePrev prev and curr: either curr > beforePrev, or not.

If curr > beforePrev, then those two are placed in a good ordering relative to each other, so if we would remove prev from between those two, we would restore that part of the list into an increasing ordering.

If curr <= beforePrev, then they are not in a good ordering relative to each  other, so we should remove curr to restore the increasing ordering.

To save time we will not actually perform the removal of the chosen item from the list: we will just apply the result of that removal to the variables beforePrev, prev, and curr, so that in the next iteration they have values as if the list had one item removed:

As we removed an element, beforePrev should remain the same in the next iteration of the loop: so we don't touch its value, like we would normally do.

If we remove prev, then the new prev becomes what curr is now. If we remove curr, there is nothing to do: prev also remains the same for the next iteration, and curr will get its new value any way at the start of the next iteration.

Because we "deleted" an item we also set allowExceptions to False, so that we know that we are not allowed to perform a second deletion.

Remains to say that at the first iteration, we don't really have a beforePrev and prev, so we set them to -infinity, so that in a first iteration there will be no decision to delete yet.

Body:
I am trying to find if a list is a strictly increasing sequenced if 1 and only 1 element from it is removed.  This works for some lists but does not work for others when there isn't any apparent difference between the lists.  And for large lists, it exceeds the execution time limit.  This is my code:

def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        new_seq = sequence.copy()
        del new_seq[i]

        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            output = True
        else:
            output = False

    return output

I'm creating a copy of the input list.  Then, I'm removing the element i and then returning True or False depending on whether the list is a strictly increasing sequence.  I am creating the copy of the list inside the for-loop to make sure that I am removing only one element.  These are some of the test runs where the code does not return the appropriate value:

Input:
sequence: [10, 1, 2, 3, 4, 5]
Output: false
Expected Output: true

Input:
sequence: [1, 2, 5, 3, 5]
Output: false
Expected Output: true

And in this test case, the code exceeds the execution time limit:

Input:
sequence: [-9996, -9995, -9994, -9993, -9991, -9989, -9987, -9986, -9985, -9983, -9982, -9980, -9978, -9977, -9976, -9975, -9974, -9972, -9968, -9966, -9965, -9961, -9957, -9956, -9955, -9954, -9952, -9948, -9942, -9939, -9938, -9936, -9935, -9932, -9931, -9927, -9925, -9923, -9922, -9921, -9920, -9919, -9918, -9908, -9905, -9902, -9901, -9900, -9899, -9897, -9896, -9894, -9888, -9886, -9880, -9878, -9877, -9876, -9874, -9872, -9871, -9870, -9869, -9868, -9867, -9865, -9857, -9856, -9855, -9854, -9853, -9852, -9851, -9849, -9848, -9846, -9845, -9843, -9842, -9841, -9840, -9837, -9834, -9828, -9826, -9824, -9823, -9820, -9816, -9814, -9812, -9811, -9810, -9809, -9807, -9806, -9804, -9803, -9801, -9800]
Output: undefined
Expected Output: false

Body:
Your loop will always overwrite (with returning False or True) the previous result in each iteration. So it actually "forgets" about any violation in the previous iteration. Only the last iteration determines the output, so your algorithm is wrong.

Secondly, even if you would fix that error (by exiting the loop if the new list is not sorted), this algorithm represents a time complexity of O(n²), because in each iteration:

a copy of the list is made with .copy()

a del is performed, requiring a shift of all values that follow it

a new copy of the list is made with new_seq[1:]

zip is called, creating yet another list

all is called, iterating that new list

All of these actions are killing the performance.

Instead you should only perform one iteration over the list, and solve the problem without any nested iterations. One clue is that you don't actually have to perform the removal of the element. You only need to check the situation as if it were removed.

An efficient algorithm only needs to look at three values: the currently iterated value, and the two preceding values. If those three are not in order, you can determine which one should be removed, but only represent that removal in those three variables (keep the list untouched):

def almostIncreasingSequence(sequence):
    beforePrev = prev = float('-inf')
    allowExceptions = True

    for curr in sequence:
        if curr <= prev: # Order is not maintained:
            if not allowExceptions: # It's not the first time
                return False
            allowExceptions = False
            # Decide whether to skip the current or previous value
            if curr > beforePrev:
                prev = curr;
        else: # Normal case: keep track of two preceding values
            beforePrev, prev = prev, curr
    return True

Explanation

Three list values are kept in separate memory during the traversal of the list: curr, prev and beforePrev. The latter two lag behind the curr value. So at each iteration, curr gets the current list value, and at the end of the iteration, we shift the values: beforePrev ← prev ← curr. So essentially, these three values correspond to the 3 most recently visited values -- at least when there is no anomaly in the list.

So let's say at a certain moment you find an anomaly: you find a position where curr <= prev, i.e. where the sequence is not strictly increasing; then it is clear one of the values has to be removed: either curr or prev should be removed to have any hope that the list can be "fixed".

It could be that the algorithm had already decided that a value had to be removed at an earlier iteration (allowExceptions is False): but we are only allowed to remove one value from the list, so in that case we decide that there is no solution and return False

But if this was the first time we got into this situation, then we should decide whether to identify curr or prev as offending value. We may assume that beforePrev and prev are in the correct order (we verified that in the preceding iteration), so there really are only two possibilities left for the relative ordering of beforePrev prev and curr: either curr > beforePrev, or not.

If curr > beforePrev, then those two are placed in a good ordering relative to each other, so if we would remove prev from between those two, we would restore that part of the list into an increasing ordering.

If curr <= beforePrev, then they are not in a good ordering relative to each  other, so we should remove curr to restore the increasing ordering.

To save time we will not actually perform the removal of the chosen item from the list: we will just apply the result of that removal to the variables beforePrev, prev, and curr, so that in the next iteration they have values as if the list had one item removed:

As we removed an element, beforePrev should remain the same in the next iteration of the loop: so we don't touch its value, like we would normally do.

If we remove prev, then the new prev becomes what curr is now. If we remove curr, there is nothing to do: prev also remains the same for the next iteration, and curr will get its new value any way at the start of the next iteration.

Because we "deleted" an item we also set allowExceptions to False, so that we know that we are not allowed to perform a second deletion.

Remains to say that at the first iteration, we don't really have a beforePrev and prev, so we set them to -infinity, so that in a first iteration there will be no decision to delete yet.


问:
Conditional subquery in where clause
I'm trying to create a query with conditional logic where I only calculate revenue for the most recent records by each month using a datetime column (start_date), but only if there are multiple records in that month from the same account_id.

Here's a basic example of the schema after I join two tables (full schema in sqlfiddle link).

```<code>| account_id | plan_id | start_date           | plan_interval | price |
|------------|---------|----------------------|---------------|-------|
| 1          | 1       | 2018-01-03T14:52:13Z | month         | 39    |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999   |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99    |
</code>```

In the above example, I would only like to include rows 1 and 3 in my output, as it's the one record from account_id 1 in January and the most recent of two records for account_id 1 in February.

```<code>SELECT
MONTH(start_date) AS month,
SUM(CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12 END) AS mrr
FROM subscriptions
  JOIN plans
  ON plans.id = subscriptions.plan_id
WHERE Year(start_date) = 2018 AND
  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END
GROUP BY month
ORDER BY month ASC;
</code>```

The case statement in the subquery above does not seem to work in doing this. It returns the data without filtering out records when the first condition is met.

Here is an example: sqlfiddle

答:
In your case, the WHERE statement does not work because the CASE statement will always return a boolean.

```<code>  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END
</code>```

Another approach to what you are building would involve using a subquery to order the columns the way you want within the groups.

```<code>SELECT
  account_id,
  month,
  CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12
  END AS mrr
FROM (
  SELECT *, MONTH(start_date) AS month
  FROM subscriptions
  INNER JOIN plans ON plans.id = subscriptions.plan_id
  ORDER BY account_id, start_date DESC
) sq
GROUP BY account_id, month
</code>```

This works because selecting columns in a GROUP BY will automatically take the first row that is returned by the subquery for a given group of columns.

Title: Conditional subquery in where clause

Body:
I'm trying to create a query with conditional logic where I only calculate revenue for the most recent records by each month using a datetime column (start_date), but only if there are multiple records in that month from the same account_id.

Here's a basic example of the schema after I join two tables (full schema in sqlfiddle link).

| account_id | plan_id | start_date           | plan_interval | price |
|------------|---------|----------------------|---------------|-------|
| 1          | 1       | 2018-01-03T14:52:13Z | month         | 39    |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999   |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99    |

In the above example, I would only like to include rows 1 and 3 in my output, as it's the one record from account_id 1 in January and the most recent of two records for account_id 1 in February.

SELECT
MONTH(start_date) AS month,
SUM(CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12 END) AS mrr
FROM subscriptions
  JOIN plans
  ON plans.id = subscriptions.plan_id
WHERE Year(start_date) = 2018 AND
  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END
GROUP BY month
ORDER BY month ASC;

The case statement in the subquery above does not seem to work in doing this. It returns the data without filtering out records when the first condition is met.

Here is an example: sqlfiddle

Body:
In your case, the WHERE statement does not work because the CASE statement will always return a boolean.

  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END

Another approach to what you are building would involve using a subquery to order the columns the way you want within the groups.

SELECT
  account_id,
  month,
  CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12
  END AS mrr
FROM (
  SELECT *, MONTH(start_date) AS month
  FROM subscriptions
  INNER JOIN plans ON plans.id = subscriptions.plan_id
  ORDER BY account_id, start_date DESC
) sq
GROUP BY account_id, month

This works because selecting columns in a GROUP BY will automatically take the first row that is returned by the subquery for a given group of columns.


问:
Calling a function by adding an onclick event through innerHTML inside react class
How to call a function by add an onclick event in react class through innerHTML

```<code>document.getElementById('activeEmployeesTableContent').innerHTML = `
                                    <tr>
                                      <td>${res.data.empId}</td>
                                      <td><button onclick = ${this.fun}>CLICK</button></td>
                                    </tr>
                                  `;
</code>```

The above code is not working but i must use innerHTML to add the code dynamically into the table body

```<code>  componentDidMount(){
     axios.post('http://localhost:5000/employeesRetrieval')
      .then( res => {
          document.getElementById('activeEmployeesTableContent').innerHTML = `
                                  <tr>
                                    <td>${res.data.empId}</td>
                                    <td><button onclick = ${this.fun(res.data.empid)}>CLICK</button></td>
                                  </tr>`;
      }).catch( err => {
        console.log(err);
      });
  }
</code>```

答: react is totally different thing, you cannot add react in plain html.</p>

Body:
How to call a function by add an onclick event in react class through innerHTML

document.getElementById('activeEmployeesTableContent').innerHTML = `

                                      ${res.data.empId}
                                      <button onclick = ${this.fun}>CLICK</button>

                                  `;

The above code is not working but i must use innerHTML to add the code dynamically into the table body

  componentDidMount(){
     axios.post('http://localhost:5000/employeesRetrieval')
      .then( res => {
          document.getElementById('activeEmployeesTableContent').innerHTML = `

                                    ${res.data.empId}
                                    <button onclick = ${this.fun(res.data.empid)}>CLICK</button>

`;
      }).catch( err => {
        console.log(err);
      });
  }


问:
Sorting an array of objects using a well known dynamicSort function, but getting this error: "Comparison method violates its general contract"
I am generating an array of calendar events and then (using code I got from user 'Cooper') I am deduplicating the list to create a new array: dedList

```<code>// This code creates a deduplicated array (dedList) from my array 'events' (parts of this code are from Cooper on StackOverflow... and I don't really understand it all)
var dedList=[];
var obj={eA:[]};
for(var i=0;i<events.length;i++) {
  var key=events[i].getTitle() + events[i].getDescription();
  if(!obj.hasOwnProperty(key)) {
    obj[key]={
      title: events[i].getTitle(),
      description: events[i].getDescription(),
      guest_list: events[i].getGuestList(),
      guests: events[i].getGuestList().length,
      start: events[i].getStartTime(),
      end: events[i].getEndTime(),
      recurs: events[i].isRecurringEvent(),
      duration: "",
      creator: events[i].getCreators(),
      color: events[i].getColor() ,
      copies: 0,
      category: "",
    };
    obj.eA.push(key);
  }else{
    obj[key].copies+=1; //count the copies
  }
}
for(var i=0;i<obj.eA.length;i++) {
  dedList.push(obj[obj.eA[i]]);
}
</code>```

This is working perfectly, but I'm using some well shared code to sort dedList by "category" and it's generating error I've never seen before: "Comparison method violates its general contract." Here's the line causing the error, followed by the function I am using:

```<code>dedList.sort(dynamicSort("category")); // this line generates the error

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}
</code>```

Any suggestions? I'm pretty new to google scripting so I don't completely understand how the dynamicSort function works, and that is making it hard for me to debug the error. Thanks!

MCVE:

```<code>function sortTest() {
  var arr = [];
  for (i = 0; i < 50; ++i) {
    arr.push({ a: '' }, {}, { a: {} });
  }
  Logger.log(arr.sort(dynamicSort('a')));
}
function dynamicSort(property) {
    var sortOrder = 1;
    return function (a,b) {
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}
</code>```

Engine: Rhino (Old)

Error:

Comparison method violates its general contract

答:
Thanks for all the help. The code I posted works fine; the problem was that I had another function that was changing some category values to "undefined". I fixed this and my problem went away, and my array is sorting perfectly now.

I was going to delete this post, but the MCVE added by @TheMaster may still be relevant? I'll leave it for now.

Body:
I am generating an array of calendar events and then (using code I got from user 'Cooper') I am deduplicating the list to create a new array: dedList

// This code creates a deduplicated array (dedList) from my array 'events' (parts of this code are from Cooper on StackOverflow... and I don't really understand it all)
var dedList=[];
var obj={eA:[]};
for(var i=0;i<events.length;i++) {
  var key=events[i].getTitle() + events[i].getDescription();
  if(!obj.hasOwnProperty(key)) {
    obj[key]={
      title: events[i].getTitle(),
      description: events[i].getDescription(),
      guest_list: events[i].getGuestList(),
      guests: events[i].getGuestList().length,
      start: events[i].getStartTime(),
      end: events[i].getEndTime(),
      recurs: events[i].isRecurringEvent(),
      duration: "",
      creator: events[i].getCreators(),
      color: events[i].getColor() ,
      copies: 0,
      category: "",
    };
    obj.eA.push(key);
  }else{
    obj[key].copies+=1; //count the copies
  }
}
for(var i=0;i<obj.eA.length;i++) {
  dedList.push(obj[obj.eA[i]]);
}

This is working perfectly, but I'm using some well shared code to sort dedList by "category" and it's generating error I've never seen before: "Comparison method violates its general contract." Here's the line causing the error, followed by the function I am using:

dedList.sort(dynamicSort("category")); // this line generates the error

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        var result = (a[property]  b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

Any suggestions? I'm pretty new to google scripting so I don't completely understand how the dynamicSort function works, and that is making it hard for me to debug the error. Thanks!

MCVE:

function sortTest() {
  var arr = [];
  for (i = 0; i < 50; ++i) {
    arr.push({ a: '' }, {}, { a: {} });
  }
  Logger.log(arr.sort(dynamicSort('a')));
}
function dynamicSort(property) {
    var sortOrder = 1;
    return function (a,b) {
        var result = (a[property]  b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

Engine: Rhino (Old)

Error:

Comparison method violates its general contract


问:
Error when creating Directory and creating files using touch in UNIX
I am trying to create a directory structure in Unix. I made the directory using mkdir command with -p option but when i use "touch" to create files i get hit with the "No such file or directory error"

The code i tried .

```<code>mkdir -p livingthings{birds/{flyingbirds,nonflyingbirds},plants,animals/{mammals,reptiles}}
touch livingthings/{birds/{flyingbirds/{stork,eagle,eider},nonflyingbirds/{kiwi,ostrich,penguin}},plants/{carrot,cabbage,daisy},animals/{mammals/{jaguar,dog,tiger},reptiles/{alligator,skink,turtle}}}
</code>```

This is the error which pops out

Help much appreciated.

UPDATE :
After adding the "/" i get one error now that is telling

```<code>touch: cannot touch 'livingthings/animals/reptiles/turtle': No such file or directory .:
</code>```

答: The issue is you missed the slash after livingthings in mkdir -p livingthings/{birds..... not mkdir -p livingthings{birds.... Because of this it creates a directory named livingthingsbirds instead of livingthings/birds. But then in your touch command u r using livingthings/ so thats why it cant find that directory.</p>

Body:
I am trying to create a directory structure in Unix. I made the directory using mkdir command with -p option but when i use "touch" to create files i get hit with the "No such file or directory error"

The code i tried .

mkdir -p livingthings{birds/{flyingbirds,nonflyingbirds},plants,animals/{mammals,reptiles}}
touch livingthings/{birds/{flyingbirds/{stork,eagle,eider},nonflyingbirds/{kiwi,ostrich,penguin}},plants/{carrot,cabbage,daisy},animals/{mammals/{jaguar,dog,tiger},reptiles/{alligator,skink,turtle}}}

This is the error which pops out

Help much appreciated.

UPDATE :
After adding the "/" i get one error now that is telling

touch: cannot touch 'livingthings/animals/reptiles/turtle': No such file or directory .:


问:
Regex for find multiline form data (php)
I try (without success) to make a regex for find a  submit button even if button code is in one two or more lines.

I use now this patter

/<(button|input)(.*type=['\"](submit|button)['\"].*)?>/i

and works fine if the button code is in one line

<input type="submit" name="mybutton" class="button_class" value="Submit" title="Click Me" />

I want to make it work if my button code look like

<input type="submit" name="mybutton"

class="button_class" value="Submit"

title="Click Me" />

Thanks

答:
Don't use a regular expression to parse HTML.

RegEx match open tags except XHTML self-contained tags

Learn xpath, and use a parser.

EDIT Added some code to insert before.

```<code>    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $x = new DOMXPath($dom);
    foreach($x->query("//input[@type='submit']") as $node)
    {
         $newNode = $dom->createElement("img");
         $newNode->setAttribute("src","/loading.gif");
         $node->insertBefore($node);
    }
    $output = $dom->saveHTML();
</code>```

Body:
Don't use a regular expression to parse HTML.

RegEx match open tags except XHTML self-contained tags

Learn xpath, and use a parser.

EDIT Added some code to insert before.

    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $x = new DOMXPath($dom);
    foreach($x->query("//input[@type='submit']") as $node)
    {
         $newNode = $dom->createElement("img");
         $newNode->setAttribute("src","/loading.gif");
         $node->insertBefore($node);
    }
    $output = $dom->saveHTML();


问:
How to cocatinate rows from 2 files in bash
I have 2 files:
nodes.txt

```<code>node1
node2
node3
</code>```

descriptions.txt

```<code>Description1
Description2
Description3
</code>```

How can I make loop and get output as a concatenate rows of 2 files?

output.txt

```<code>node1 Description1
node2 Description2
node3 Description3
</code>```

答:
```<code>paste -d' ' nodes.txt descriptions.txt
</code>```

Body:
I have 2 files:
nodes.txt

node1
node2
node3

descriptions.txt

Description1
Description2
Description3

How can I make loop and get output as a concatenate rows of 2 files?

output.txt

node1 Description1
node2 Description2
node3 Description3

Body: paste -d' ' nodes.txt descriptions.txt


问:
How to specify version label in CircleCI deployments to AWS ElasticBeanStalk
I am using Circle CI to deploy my java application to elasticbeanstalk.

But I am not able to specify a version for my release. the release label looks like app-1234-staging-1234-1234 is there any way that I can specify an application version, like myapp.4.0.

答:
Finally found the answer, It was an easy one. You can pass the label along with the deploy command</p>

```<code>eb deploy -l "RELEASE-VERSION-4.0.1"
</code>```

Body:
Finally found the answer, It was an easy one. You can pass the label along with the deploy command

eb deploy -l "RELEASE-VERSION-4.0.1"