问:
Asterisk-java for AMI not working correctly
I am an absolute newbee in asterisk. I am trying to use asterisk-java for event listening through AMI. I am currently using the version 11.2.1 asterisk. When I tries to compiles the code as

```<code>javac -cp asterisk-java-0.3.jar HelloEvents.java
</code>```

it complets successfully. But when I try to execute the file, I give the following error.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: HelloEvents
Caused by: java.lang.ClassNotFoundException: HelloEvents
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    Could not find the main class: HelloEvents. Program will exit.
</code>```

the code is

```<code>import java.io.IOException;

import org.asteriskjava.manager.AuthenticationFailedException;

import org.asteriskjava.manager.ManagerConnection;
import org.asteriskjava.manager.ManagerConnectionFactory;
import org.asteriskjava.manager.ManagerEventListener;
import org.asteriskjava.manager.TimeoutException;
import org.asteriskjava.manager.action.StatusAction;
import org.asteriskjava.manager.event.ManagerEvent;

public class HelloEvents implements ManagerEventListener
{
    private ManagerConnection managerConnection;

    public HelloEvents() throws IOException
    {
        ManagerConnectionFactory factory = new ManagerConnectionFactory(
                "localhost", "manager", "password");

        this.managerConnection = factory.createManagerConnection();
    }

    public void run() throws IOException, AuthenticationFailedException,
            TimeoutException, InterruptedException
    {
        // register for events
        managerConnection.addEventListener(this);

        // connect to Asterisk and log in
        managerConnection.login();

        // request channel state
        managerConnection.sendAction(new StatusAction());

        // wait 10 seconds for events to come in
        Thread.sleep(10000);

        // and finally log off and disconnectaaaa
        managerConnection.logoff();
    }

    public void onManagerEvent(ManagerEvent event)
    {
        // just print received events
        System.out.println(event);
    }

    public static void main(String[] args) throws Exception
    {
        HelloEvents helloEvents;

        helloEvents = new HelloEvents();
        helloEvents.run();
    }
}
</code>```

答:
We can avoid adding class path every time while compiling or executing code. Now go to the location where jar file is located. Then run,

For linux :- export CLASSPATH=$CLASSPATH:asterisk-java-2.0.3.jar:.

For windows:- set CLASSPATH=$CLASSPATH:asterisk-java-2.0.3.jar:.

Now compile code by

javac HelloEvents.java

Execute it by java HelloEvents

Body:
I am an absolute newbee in asterisk. I am trying to use asterisk-java for event listening through AMI. I am currently using the version 11.2.1 asterisk. When I tries to compiles the code as

javac -cp asterisk-java-0.3.jar HelloEvents.java

it complets successfully. But when I try to execute the file, I give the following error.

Exception in thread "main" java.lang.NoClassDefFoundError: HelloEvents
Caused by: java.lang.ClassNotFoundException: HelloEvents
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    Could not find the main class: HelloEvents. Program will exit.

the code is

import java.io.IOException;

import org.asteriskjava.manager.AuthenticationFailedException;

import org.asteriskjava.manager.ManagerConnection;
import org.asteriskjava.manager.ManagerConnectionFactory;
import org.asteriskjava.manager.ManagerEventListener;
import org.asteriskjava.manager.TimeoutException;
import org.asteriskjava.manager.action.StatusAction;
import org.asteriskjava.manager.event.ManagerEvent;

public class HelloEvents implements ManagerEventListener
{
    private ManagerConnection managerConnection;

    public HelloEvents() throws IOException
    {
        ManagerConnectionFactory factory = new ManagerConnectionFactory(
                "localhost", "manager", "password");

        this.managerConnection = factory.createManagerConnection();
    }

    public void run() throws IOException, AuthenticationFailedException,
            TimeoutException, InterruptedException
    {
        // register for events
        managerConnection.addEventListener(this);

        // connect to Asterisk and log in
        managerConnection.login();

        // request channel state
        managerConnection.sendAction(new StatusAction());

        // wait 10 seconds for events to come in
        Thread.sleep(10000);

        // and finally log off and disconnectaaaa
        managerConnection.logoff();
    }

    public void onManagerEvent(ManagerEvent event)
    {
        // just print received events
        System.out.println(event);
    }

    public static void main(String[] args) throws Exception
    {
        HelloEvents helloEvents;

        helloEvents = new HelloEvents();
        helloEvents.run();
    }
}


来源: stackexchange

问:
Asking the user if they want to play again - code repeats anyway when I type "n"
Here is my code:

```<code>play = True

while play:
    #1 A company gives bonus of 5% to employees with year of service of more than 5 years.
    salary = float(input("Insert your salary "))
    bonus = float((salary * 0.05) + salary)
    yearOfService = int(input("Insert how many years you have worked "))

    if yearOfService > 5:
        print ("You now have $" + str(round(bonus,2)))
    else:
        print ("Sorry, but you need to have more than 5 years of service for a bonus.")

    #2 A school's grading system.
    score = float(input("Enter your score: "))
    print("Your score is " + str(score))
    grade = ""
    if score < 25:
        grade = "F"
    if score >= 25 and score <= 45:
        grade = "E"
    if score >= 45 and score <=50:
        grade = "D"
    if score >= 50 and score <= 60:
        grade = "C"
    if score >= 60 and score <= 80:
        grade = "B"
    if score > 80:
        grade = "A"
    print("Your grade is " + grade)

    #3 Weird/Not Weird
    for i in range(0,3):
        n = float(input("Enter integer: "))
        if n%2 == 1:
            print "Weird"
        if n%2 == 0 and n <= 2 and n >= 5:
            print "Not Weird"
        if n%2 == 0 and n <= 6 and n >= 20:
            print "Weird"
        if n%2 == 0 and n > 20:
            print "Not Weird"

    #4. In a given string "mississippi" count number of 's' and 'i'
    string = "mississippi"
    sCount = 0
    iCount = 0

    for i in string:
        if i == 's':
            sCount = sCount + 1
        if i == 'i':
            iCount = iCount + 1
    print( str(sCount) + " s's and " + str(iCount) + "i's")

    #5. Print "Hello World" 8 times
    f = 1
    while f <= 8:
        print("Hello World")
        f += 1

    again = input("Would you like to play again?")
    if again == "n":
        play = False
</code>```

However when I tested my code, everything looked good except when I typed "n" at the end, it just repeated anyways, even though I put "if again == "n": play = False" at the end, making it act useless in the code. How do I make the code stop when I type "n"? Thanks!

答:
Oh, this is a fun one.

First we need to look at line 36:

```<code>print "Weird"
</code>```

Because this did not cause an error, it means the code is running under Python 2.x. (It's clear from the rest of your code that you intend to use a 3.x version of Python, where this would have caused a syntax error.)

In 2.x, input interprets the input text as a Python expression in the current context; it's equivalent to making a call to eval() on the input text. (You do not want to do this.)

What happens is that because you have a variable n earlier in the program, the text n that you typed in evaluates to that variable's value (i.e., the weird or not-weird number from before). (If you had instead typed y for example, an exception would have been raised.)

Solution: You need to fix your print function calls, and then ensure that you use a Python 3.x interpreter for the code.

ContentLicense: CC BY-SA 4.0

Body:
Here is my code:

play = True

while play:
    #1 A company gives bonus of 5% to employees with year of service of more than 5 years.
    salary = float(input("Insert your salary "))
    bonus = float((salary * 0.05) + salary)
    yearOfService = int(input("Insert how many years you have worked "))

    if yearOfService > 5:
        print ("You now have $" + str(round(bonus,2)))
    else:
        print ("Sorry, but you need to have more than 5 years of service for a bonus.")

    #2 A school's grading system.
    score = float(input("Enter your score: "))
    print("Your score is " + str(score))
    grade = ""
    if score < 25:
        grade = "F"
    if score >= 25 and score <= 45:
        grade = "E"
    if score >= 45 and score <=50:
        grade = "D"
    if score >= 50 and score <= 60:
        grade = "C"
    if score >= 60 and score <= 80:
        grade = "B"
    if score > 80:
        grade = "A"
    print("Your grade is " + grade)

    #3 Weird/Not Weird
    for i in range(0,3):
        n = float(input("Enter integer: "))
        if n%2 == 1:
            print "Weird"
        if n%2 == 0 and n <= 2 and n >= 5:
            print "Not Weird"
        if n%2 == 0 and n <= 6 and n >= 20:
            print "Weird"
        if n%2 == 0 and n > 20:
            print "Not Weird"

    #4. In a given string "mississippi" count number of 's' and 'i'
    string = "mississippi"
    sCount = 0
    iCount = 0

    for i in string:
        if i == 's':
            sCount = sCount + 1
        if i == 'i':
            iCount = iCount + 1
    print( str(sCount) + " s's and " + str(iCount) + "i's")

    #5. Print "Hello World" 8 times
    f = 1
    while f <= 8:
        print("Hello World")
        f += 1

    again = input("Would you like to play again?")
    if again == "n":
        play = False

However when I tested my code, everything looked good except when I typed "n" at the end, it just repeated anyways, even though I put "if again == "n": play = False" at the end, making it act useless in the code. How do I make the code stop when I type "n"? Thanks!

Body:
Oh, this is a fun one.

First we need to look at line 36:

print "Weird"

Because this did not cause an error, it means the code is running under Python 2.x. (It's clear from the rest of your code that you intend to use a 3.x version of Python, where this would have caused a syntax error.)

In 2.x, input interprets the input text as a Python expression in the current context; it's equivalent to making a call to eval() on the input text. (You do not want to do this.)

What happens is that because you have a variable n earlier in the program, the text n that you typed in evaluates to that variable's value (i.e., the weird or not-weird number from before). (If you had instead typed y for example, an exception would have been raised.)

Solution: You need to fix your print function calls, and then ensure that you use a Python 3.x interpreter for the code.


问:
Applications using Decimal versus double . .
I wanted to see if folks were using decimal for financial applications instead of double.  I have seen lots of folks using double all over the place with unintended consequences . .

Do you see others making this mistake . . .

答:
I totally agree on correctness issues of floating point vs decimal mentioned above, but
many financial applications are performance critical.

In such cases you will consider to use float/double as decimal has great impact on performance in systems where decimal types are not supported in hardware. And still it is possible to wrap floating point types in higher level classes (e.g. Tax, Commission, Balance, Dividend, Quote, Tick, etc...) that represent domain model and encapsulate all rounding logic as well as valid operators on these types and their interactions.
And yes - in some projects I have implemented custom rounding functions to squeeze up to 20% more out of calculations compared to .NET or win32 methods.

Another thing to consider is whether you pass your objects out of process, as serializing decimals which are usually 4 integers and passing them over the wire is much more CPU intensive (esp if not supported) and results in significantly more bandwidth and larger memory footprint.

OwnerDisplayName: ak

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Sort list of alphanumeric strings
I have a list of strings, each of which will something like ';2234661;E3006345_2234661_FRONT_Image_Container;\n' that I need to sort. Each string will start with a semi-colon and different numbers, but I need them all to be sorted according to the image angle (ex. FRONT, BACK, LEFT) in a non-alphabetical order following this ranking:
FRONT
BACK
LEFT
RIGHT
INGREDIENTS
INSTRUCTIONS
INFO
NUTRITION
PRODUCT

Example Input:

```<code>[';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']
</code>```

Desired Output

```<code>[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']
</code>```

Here is my code, based off of the solution to a similar issue I found here on stackexchange. However, it returns the error "ValueError: substring not found

```<code>galleryImages = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

alphabet = 'FBLRINP'

newGallery = sorted(galleryImages, key=lambda word: [alphabet.index(c) for c in word])

print(newGallery)
</code>```

答:
```<code>my_list = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

# create a dictionary of the form {"FRONT": 0, "BACK": 1, …}
angle = { e: i for i, e in enumerate(['FRONT', 'BACK', 'LEFT', 'RIGHT', 'INGREDIENTS', 'INSTRUCTIONS', 'INFO', 'NUTRITION', 'PRODUCT']) }

my_list.sort(key=lambda x: angle[x.split(';')[2]], reverse=True)

print(my_list)
</code>```

Title: Sort list of alphanumeric strings

Body:
I have a list of strings, each of which will something like ';2234661;E3006345_2234661_FRONT_Image_Container;\n' that I need to sort. Each string will start with a semi-colon and different numbers, but I need them all to be sorted according to the image angle (ex. FRONT, BACK, LEFT) in a non-alphabetical order following this ranking:
FRONT
BACK
LEFT
RIGHT
INGREDIENTS
INSTRUCTIONS
INFO
NUTRITION
PRODUCT

Example Input:

[';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

Desired Output

[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']

Here is my code, based off of the solution to a similar issue I found here on stackexchange. However, it returns the error "ValueError: substring not found

galleryImages = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

alphabet = 'FBLRINP'

newGallery = sorted(galleryImages, key=lambda word: [alphabet.index(c) for c in word])

print(newGallery)


问:
Requesting /admin but return to the same page
Hello there i m looking to fix a problem i m working on django right now the issue is that when i try to go to the admin area login it returns me to the same index.html page
my code:

urls.py on main folder

```<code>from django.conf.urls import url,include
from django.contrib import admin
from first_app import views
urlpatterns = [
    url('',views.index,name="index"),
    url('first_app/',include('first_app.urls')),
    url('admin/', admin.site.urls)
]
</code>```

urls.py on first_app folder

```<code>urlpatterns = [
    url('',views.index,name="index")
]
</code>```

the views.py on first_app folder

```<code>def index(request):
    my_dic = {'insert_me':"Hello Jinja"}
    return render(request,'index.html',my_dic)
</code>```

index.html file

```<code>{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{% static 'css/style.css'%}">
    <title>Django  Page</title>
</head>
<body>
    <p>{{ insert_me}}</p>
    <h1>a picture </h1>
</body>
</html>
</code>```

答:
You are mixing up path with url, if you are using Django < 2.0, then use url with regex, like this:

```<code>from django.conf.urls import include, url

urlpatterns = [

    url(r'^admin/', include(admin.site.urls)),
    url(r'^first_app/', include('first_app.urls')),
    url(r'^*$', views.index, name='index'),
    ...
]
</code>```

And if you are using Django >= 2.0, then use like this:

```<code>from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('first_app/',include('first_app.urls')),
    path('',views.index,name="index"),
]
</code>```

More information can be found in documentation.

Body:
Hello there i m looking to fix a problem i m working on django right now the issue is that when i try to go to the admin area login it returns me to the same index.html page
my code:

urls.py on main folder

from django.conf.urls import url,include
from django.contrib import admin
from first_app import views
urlpatterns = [
    url('',views.index,name="index"),
    url('first_app/',include('first_app.urls')),
    url('admin/', admin.site.urls)
]

urls.py on first_app folder

urlpatterns = [
    url('',views.index,name="index")
]

the views.py on first_app folder

def index(request):
    my_dic = {'insert_me':"Hello Jinja"}
    return render(request,'index.html',my_dic)

index.html file

{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{% static 'css/style.css'%}">
    <title>Django  Page</title>

{{ insert_me}}

a picture

Body:
You are mixing up path with url, if you are using Django < 2.0, then use url with regex, like this:

from django.conf.urls import include, url

urlpatterns = [

    url(r'^admin/', include(admin.site.urls)),
    url(r'^first_app/', include('first_app.urls')),
    url(r'^*$', views.index, name='index'),
    ...
]

And if you are using Django >= 2.0, then use like this:

from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('first_app/',include('first_app.urls')),
    path('',views.index,name="index"),
]

More information can be found in documentation.


问:
Confusion on the use of synthetic events in React
I was learning React and came across the term Synthetic events and its benefits. I found out that there is a question Are there any advantages of React's synthetic events vs. addEventListener? which was asked before in the platform but confused me a bit thus decided to ask for clarification. Firstly, "Synthetic event is just a wrapper for normal events. They are there to provide a common interface between browser inconsistencies" so the question is what kind of inconsistencies browsers have that synthetic events aims to solve. Secondly, "Synthetic events are faster" the question is e.g say, we have onChange events for 5 inputs and onClick events for 3 buttons, is it true that thanks to synthetic events only one onChange and one onClick are attached to document.body and e.g when we click a button, listener is attached to the clicked button only when we click that button? </p>

答:
What kind of inconsistencies browsers have that synthetic event aims to solve.

React normalizes events so that they have consistent properties across different browsers.

For example MouseEvent.clientX may return a long or a double type.

is it true that thanks to synthetic events only one onChange and one onClick are attached to document.body and e.g when we click a button, the listener is attached to the clicked button only when we click that button

You can make an example and debug it in dev tools to validate it.


问:
How can I get and then add Staccato 222 font to my first website?
I want to make my first website. The logo of my company is written by Staccato 222 font. The only site I know to get fonts is google fonts, but Staccato is not available there. Could you recommend me a site where I can get the font Staccato 222? I want to add the font in a way everybody can see the same font i.e Stacatto 222. And how can I add it to my website?</p>

答:
one of the reasons is that font maybe is licensed and not an open font.
I've found on this website some codesnippets.

https://www.onlinewebfonts.com/download/977ee109edb851f6c4a2c401445c74ee

You should habe your font in some of the following formats woff, ttf, svg, eot.
Than you can use css to use them.

```<code>@font-face {
src: url('your font') format('woff|ttf|svg|eot|…');
font-family: name;
</code>```

}

Body:
one of the reasons is that font maybe is licensed and not an open font.
I've found on this website some codesnippets.

https://www.onlinewebfonts.com/download/977ee109edb851f6c4a2c401445c74ee

You should habe your font in some of the following formats woff, ttf, svg, eot.
Than you can use css to use them.

@font-face {
src: url('your font') format('woff|ttf|svg|eot|…');
font-family: name;

}


问:
Download Data from JSON $ajax
I am trying to download data off a server and return the data but, the function I made does not seem to return the downloaded data. It keeps returning the promise, can someone help me out?

Here is the output on console:

```<code>part3-main.js:9 data {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
part3-application.js:55 Downloading Data
part3-application.js:56 Downloaded Data
part3-application.js:58 parsee (994) [{…},...]
</code>```

```<code>var getAndParseData = function(){
  var download_data = $.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })
  .done(function(data){
    console.log('Downloading Data');
    console.log('Downloaded Data');
    parsed_data = JSON.parse(data);
    console.log('parsee', parsed_data);
    return parsed_data;
  });
  console.log(download_data);
  return download_data;
};
</code>```

答:
Because $.ajax returns a Promise, you must wait for it to resolve before you start working on the data it returns. You can do this inside .done():

$.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })
  .done(function(data) {
    let results = JSON.parse(data);
    console.log('Success!', data)
    // do stuff with results here
  })
  .fail(function(error) {
    console.log('something went wrong', error);
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Download Data from JSON $ajax

Body:
I am trying to download data off a server and return the data but, the function I made does not seem to return the downloaded data. It keeps returning the promise, can someone help me out?

Here is the output on console:

part3-main.js:9 data {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
part3-application.js:55 Downloading Data
part3-application.js:56 Downloaded Data
part3-application.js:58 parsee (994) [{…},...]

var getAndParseData = function(){
  var download_data = $.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })
  .done(function(data){
    console.log('Downloading Data');
    console.log('Downloaded Data');
    parsed_data = JSON.parse(data);
    console.log('parsee', parsed_data);
    return parsed_data;
  });
  console.log(download_data);
  return download_data;
};

Body:
Because $.ajax returns a Promise, you must wait for it to resolve before you start working on the data it returns. You can do this inside .done():

$.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })
  .done(function(data) {
    let results = JSON.parse(data);
    console.log('Success!', data)
    // do stuff with results here
  })
  .fail(function(error) {
    console.log('something went wrong', error);
  })

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Unable to run JUnit tests inside a Maven project in IntelliJ IDEA
I have a 3-year old Maven project that was working fine in IntelliJ IDEA 3 years ago. I'm trying to return to the project now, but I can't get JUnit tests to run anymore. There's nothing fancy with the tests themselves, it's really basic @Test and assertTrue stuff. I suspect the issue lies with my pom.xml file.

If I try to run tests with the original pom.xml file from 3 years ago, I get an error "No tests found". I tried to update my dependencies, and after updating I get a different error: java.lang.NoSuchMethodError: 'java.util.Optional org.junit.jupiter.api.extension.ExtensionContext.getTestInstanceLifecycle()'. It appears to be some kind of internal error from JUnit. I've spent 1 hour googling, and I've randomly tried different ways of setting up the dependencies, but nothing so far works.

How should a pom.xml file look in order to allow basic JUnit tests to be run in a Maven project in IntelliJ IDEA 2019.3.2 Community Edition?

Here is the pom.xml file from 3 years ago.

答:
All-in-all you should create a dependency on junit-jupiter-engine and not on the api (the engine will bring the api) and upgrade a version of surefire plugin that runs the tests:

```<code>    <dependencies>

        <!-- junit 5 -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.6.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
    ...
     <build>
        <plugins>

            <!-- Requires at least 2.22.0 otherwise junit 5 doesn't work-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M3</version>
            </plugin>
          ...
         </plugins>
   </build>
</code>```

You can find the working example of minimal setup (that is pretty close to you fairly basic pom.xml) in this tutorial

Body:
All-in-all you should create a dependency on junit-jupiter-engine and not on the api (the engine will bring the api) and upgrade a version of surefire plugin that runs the tests:

    <dependencies>

        <!-- junit 5 -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.6.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
    ...
     <build>
        <plugins>

            <!-- Requires at least 2.22.0 otherwise junit 5 doesn't work-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M3</version>
            </plugin>
          ...
         </plugins>
   </build>

You can find the working example of minimal setup (that is pretty close to you fairly basic pom.xml) in this tutorial


问:
Does extending class Queue into class Stack break Liskov Principle?
If I have class Queue

```<code>class Queue {
  pop () {
   return 'Last value of Array'
  }
}
</code>```

...and class Stack

```<code>class Stack extends Queue {
  @Override
  pop () {
   return 'First value of Array'
  }
}
</code>```

Is it breaking the Liskov Substitution Principle? Why?

答:
Yes, this violates the LSP because Stack is violating the contract of Queue. I suspect the comments are inverted in the examples: Queue should be FIFO, while Stack should be LIFO; but either way, the child and parent have opposite post-conditions for their respective pop() methods, so one cannot inherit from the other.

The post-condition of pop() from a Queue is that the oldest element is removed.

The post-condition of pop() from a Stack is that the newest element is removed.

Clearly these two conditions cannot be satisfied by the same method.

To use Java as an example, Queue has no pop() method and is not implemented by Stack.

Queue is implemented by Deque, which combines both Queue and Stack methods, but note how Deque is exhaustively documented to define different behaviors for the different sets of methods.

Body:
If I have class Queue

class Queue {
  pop () {
   return 'Last value of Array'
  }
}

...and class Stack

class Stack extends Queue {
  @Override
  pop () {
   return 'First value of Array'
  }
}

Is it breaking the Liskov Substitution Principle? Why?


问:
Best way to partial update nested object data in mongodb in node js
I have searched many questions on nested objects, but all I found where related to array[s].

I am looking for a updating simple nested object in mongoose.
Once created a document, I want to partially update basicDetails and agentDetail object.

Example schema :

```<code>    var applicationSchema = new Schema({
      title:  String,
      author: String,
      basicDetails:{
        appId:Number,
        fname:String,
        mname:String,
        lname:String
      },
      agentDetails:{
        agentName:String,
        bankName:String,
        bankCode:Number,
        agentCode:Number
      }
      comments: [{ body: String, date: Date }],
      createdDate: { type: Date, default: Date.now }
    })
</code>```

I Want to update only fname and last name from basicDetails,title, bankName and agentCode from agentDetails.
    Request is :

```<code>    {
      title:Update,
      basicDetails:{
        fname:Neeraj,
        lname:singh
      },
      agentDetails:{
        bankName:String,
        agentCode:Number
      }
    }
</code>```

There is no document for the same that I could find.

答:
Just use the dot notation</p>

```<code>db.collection.findOneAndUpdate(
   { // match your document }
   { $set: { "basicDetails.fname": newName, "agentDetails.title": newTitle } }
)
</code>```

Body:
I have searched many questions on nested objects, but all I found where related to array[s].

I am looking for a updating simple nested object in mongoose.
Once created a document, I want to partially update basicDetails and agentDetail object.

Example schema :

    var applicationSchema = new Schema({
      title:  String,
      author: String,
      basicDetails:{
        appId:Number,
        fname:String,
        mname:String,
        lname:String
      },
      agentDetails:{
        agentName:String,
        bankName:String,
        bankCode:Number,
        agentCode:Number
      }
      comments: [{ body: String, date: Date }],
      createdDate: { type: Date, default: Date.now }
    })

I Want to update only fname and last name from basicDetails,title, bankName and agentCode from agentDetails.
    Request is :

    {
      title:Update,
      basicDetails:{
        fname:Neeraj,
        lname:singh
      },
      agentDetails:{
        bankName:String,
        agentCode:Number
      }
    }

There is no document for the same that I could find.

Body:
Just use the dot notation

db.collection.findOneAndUpdate(
   { // match your document }
   { $set: { "basicDetails.fname": newName, "agentDetails.title": newTitle } }
)


问:
Javascript filter array by another array of filters
I have a filtersArray which is a bunch of {id, value} and I want to filter my data (also array of JSON objects) to get back only the elements that match all of the filters? Is there a better way to do this than iterating through the arrayOfFilters with each filter using a for loop and doing a filter on each criteria?

the data is an array of JSON objects - ie

```<code>[{formID:1234, name:"sam", email:"sam@gmail.com", status:"open", phone: "333-444-5555"},
 {formID:2155, name:"charlie", email:"charlie@gmail.com", status:"closed", phone: "888-323-1234"},...]
</code>```

and the filtersArray [{"status":"closed"}, {"name":"charlie"}, {"id":2155}...]

I have tried doing

```<code>for(var criteria in arrayOfFilters){
   this.data = this.data.filter( d => d.status === criteria.status)
                    .filter(d => d.name === criteria.name)
                    .filter(d => d.address === criteria.address)...
}
</code>```

it does not work real well since criteria is a JSON object like {"status":"closed"}, {"name":"charlie"}...

答:
If the idea is to find all items of source array that match (by all properties) with some item of filter array, you can go like that:

const srcArr = [{formID:1234,name:"sam",email:"sam@gmail.com",status:"open",phone:"333-444-5555"},{formID:2155,name:"charlie",email:"charlie@gmail.com",status:"closed",phone:"888-323-1234"}],
      filterArr = [{status:'closed', name:'charlie'}],
      result = srcArr.filter(srcItem =>
                  filterArr.some(filterItem =>
                    Object.entries(filterItem).every(([filterKey, filterValue]) =>
                      srcItem[filterKey] == filterValue)))

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {min-height:100%}</code>```

If your filter is a plain object, that's even more simple:

const srcArr = [{formID:1234,name:"sam",email:"sam@gmail.com",status:"open",phone:"333-444-5555"},{formID:2155,name:"charlie",email:"charlie@gmail.com",status:"closed",phone:"888-323-1234"}],
      filterObj = {name:'charlie', status:'closed'}
      result = srcArr.filter(srcItem =>
                Object.entries(filterObj).every(([filterKey, filterVal]) =>
                  srcItem[filterKey] == filterVal))

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {min-height:100%}</code>```

Body:
I have a filtersArray which is a bunch of {id, value} and I want to filter my data (also array of JSON objects) to get back only the elements that match all of the filters? Is there a better way to do this than iterating through the arrayOfFilters with each filter using a for loop and doing a filter on each criteria?

the data is an array of JSON objects - ie

[{formID:1234, name:"sam", email:"sam@gmail.com", status:"open", phone: "333-444-5555"},
 {formID:2155, name:"charlie", email:"charlie@gmail.com", status:"closed", phone: "888-323-1234"},...]

and the filtersArray [{"status":"closed"}, {"name":"charlie"}, {"id":2155}...]

I have tried doing

for(var criteria in arrayOfFilters){
   this.data = this.data.filter( d => d.status === criteria.status)
                    .filter(d => d.name === criteria.name)
                    .filter(d => d.address === criteria.address)...
}

it does not work real well since criteria is a JSON object like {"status":"closed"}, {"name":"charlie"}...

Body:
If the idea is to find all items of source array that match (by all properties) with some item of filter array, you can go like that:

const srcArr = [{formID:1234,name:"sam",email:"sam@gmail.com",status:"open",phone:"333-444-5555"},{formID:2155,name:"charlie",email:"charlie@gmail.com",status:"closed",phone:"888-323-1234"}],
      filterArr = [{status:'closed', name:'charlie'}],
      result = srcArr.filter(srcItem =>
                  filterArr.some(filterItem =>
                    Object.entries(filterItem).every(([filterKey, filterValue]) =>
                      srcItem[filterKey] == filterValue)))

console.log(result)

.as-console-wrapper {min-height:100%}

If your filter is a plain object, that's even more simple:

const srcArr = [{formID:1234,name:"sam",email:"sam@gmail.com",status:"open",phone:"333-444-5555"},{formID:2155,name:"charlie",email:"charlie@gmail.com",status:"closed",phone:"888-323-1234"}],
      filterObj = {name:'charlie', status:'closed'}
      result = srcArr.filter(srcItem =>
                Object.entries(filterObj).every(([filterKey, filterVal]) =>
                  srcItem[filterKey] == filterVal))

console.log(result)

.as-console-wrapper {min-height:100%}


问:
Functions f not in O(g) and g not in O(f)
The question is:

Show or disprove that for two functions f,g, if  f  is not in  O(g) then g is in O(f).

My counterexample:

```<code>Let f(n) be   f(n) = n^2 : if n is even
                  or n^4 : if n is odd

Let g(n) be   g(n) = n^3
</code>```

This is an example for f not in O(g) and g not in O(f).
Is my example wrong? If so, why?
Do you have any other examples?

答:
Your counterexample works. A proof might look like this:

Suppose f were O(g). Then there is a positive constant c and an n0 such that for n >= n0, f(n) <= c * g(n). Let n' be an odd integer greater than or equal to n0. Then we have n'^4 <= c * n'^3. Dividing both sides by n'^3 gives n' <= c. However, this cannot be true for all n' > n0; so there are even n greater than n0 for which the condition does not hold, a contradiction.

The proof the other way around is similar, except you divide both sides by n'^2.

I think the kind of counterexample you identified is a good one for this; a function that oscillates by an asymptotically increasing amount and a function that goes somewhere in the middle.

Body:
The question is:

Show or disprove that for two functions f,g, if  f  is not in  O(g) then g is in O(f).

My counterexample:

Let f(n) be   f(n) = n^2 : if n is even
                  or n^4 : if n is odd

Let g(n) be   g(n) = n^3

This is an example for f not in O(g) and g not in O(f).
Is my example wrong? If so, why?
Do you have any other examples?


问:
When I use printf it gives me "???"
When I use printf it gives me "???"

```<code>import java.util.Scanner;

public class Homework {

    public static void main(String[] args) {

        Scanner kbScanner=new Scanner(System.in);
            double m,c , m2 , c2;
            System.out.println("Enter the coefficients of the first line: ");
            m= kbScanner.nextDouble();
            c= kbScanner.nextDouble();
            System.out.printf("The first line equation is: y = %.1f x + %.1f  \n" , m,c );

    }

}
</code>```

OUTPUT:
Enter the coefficients of the first line:

1  2

The first line equation is: y = ??? x + ???

WHY? How can I fix it?

答:
What are m2 and c2 for?
Just set them to .1*m and .1*c respectively in your code, then set your formatting specifiers to %f.

Your class will look something like this.

```<code>import java.util.Scanner;

public class Homework {

    public static void main(String[] args) {

        Scanner kbScanner=new Scanner(System.in);
            double m,c , m2 , c2;
            System.out.println("Enter the coefficients of the first line: ");
            m= kbScanner.nextDouble();
            c= kbScanner.nextDouble();
            m2= .1 * m;
            c2= .1 * c;
            System.out.printf("The first line equation is: y = %f x + %f" , m,c );
</code>```

I think that should solve the issue. Good luck.

Title: When I use printf it gives me "???"

Body:
When I use printf it gives me "???"

import java.util.Scanner;

public class Homework {

    public static void main(String[] args) {

        Scanner kbScanner=new Scanner(System.in);
            double m,c , m2 , c2;
            System.out.println("Enter the coefficients of the first line: ");
            m= kbScanner.nextDouble();
            c= kbScanner.nextDouble();
            System.out.printf("The first line equation is: y = %.1f x + %.1f  \n" , m,c );

    }

}

OUTPUT:
Enter the coefficients of the first line:

1  2

The first line equation is: y = ??? x + ???

WHY? How can I fix it?

Body:
What are m2 and c2 for?
Just set them to .1*m and .1*c respectively in your code, then set your formatting specifiers to %f.

Your class will look something like this.

import java.util.Scanner;

public class Homework {

    public static void main(String[] args) {

        Scanner kbScanner=new Scanner(System.in);
            double m,c , m2 , c2;
            System.out.println("Enter the coefficients of the first line: ");
            m= kbScanner.nextDouble();
            c= kbScanner.nextDouble();
            m2= .1 * m;
            c2= .1 * c;
            System.out.printf("The first line equation is: y = %f x + %f" , m,c );

I think that should solve the issue. Good luck.


问:
iOS 13 - VNDocumentCameraViewController maximum number of Scans
Exporing the new VNDocumentCameraViewController I cannot find any delegate or property to set the maximum number of scans.

Does anybody have a workaround or any idea I can implement to limit the number of scans in one go?

答:
I had the same issue, and I'm trying other alternatives.
It's limited to  24 scans top. By default and it's not customizable</p>


问:
data boxes not displayed by gnuplot
I'd like to do a bar chart using gnuplot.

I used this settings

```<code>set style data boxes
set style fill solid
plot 'foo.dat' using 1:2:(1) linewidth 2
</code>```

with the content of foo.dat being

```<code>8 1
10 1
11 4
12 4
</code>```

gnuplot only displays the bars corresponding to the last two lines.

Why ?
Is there an other solution than adding "9 0" into my data file ?

Thank you in advance

答:
Your y-axis is probably autoscaled to [1:4]. Use e.g.

```<code>set yrange [0:*]
</code>```

Then the axis always starts at 0 but is autoscaled at the other end.

Title: data boxes not displayed by gnuplot

Body:
I'd like to do a bar chart using gnuplot.

I used this settings

set style data boxes
set style fill solid
plot 'foo.dat' using 1:2:(1) linewidth 2

with the content of foo.dat being

8 1
10 1
11 4
12 4

gnuplot only displays the bars corresponding to the last two lines.

Why ?
Is there an other solution than adding "9 0" into my data file ?

Thank you in advance

Body:
Your y-axis is probably autoscaled to [1:4]. Use e.g.

set yrange [0:*]

Then the axis always starts at 0 but is autoscaled at the other end.


问:
ModuleNotFoundError: py3k for PyInstaller + savReaderWriter
I want to use PyInstaller with module savReaderWriter. My code is very simple:

```<code>import savReaderWriter

print("hello world")
input("Press enter, to finish...")
</code>```

I was trying to use hidden import with appropriate module:

```<code>pyinstaller --clean --win-private-assemblies --upx-exclude=vcruntime140.dll --onedir --hidden-import="savReaderWriter" temp.py
</code>```

```<code>pyinstaller --clean --win-private-assemblies --upx-exclude=vcruntime140.dll --onedir --hidden-import="py3k" temp.py
</code>```

```<code>pyinstaller --clean --win-private-assemblies --upx-exclude=vcruntime140.dll --onedir --hidden-import="py3k" --hidden-import="savReaderWriter" temp.py
</code>```

But in all cases I have received the same error:

```<code>ModuleNotFoundError: No module named 'py3k'
</code>```

答:
I solved the issue by including the path of the savReaderWriter to the parameter.

```<code>pyinstaller -p "C:\PyProjects\test\venv\Lib\site-packages\savReaderWriter"; test.py
</code>```

Also, the real pain is when you trying to delete the module, an Error will occur because it is finding a non "UTF-8" character.

Body:
I want to use PyInstaller with module savReaderWriter. My code is very simple:

import savReaderWriter

print("hello world")
input("Press enter, to finish...")

I was trying to use hidden import with appropriate module:

pyinstaller --clean --win-private-assemblies --upx-exclude=vcruntime140.dll --onedir --hidden-import="savReaderWriter" temp.py

pyinstaller --clean --win-private-assemblies --upx-exclude=vcruntime140.dll --onedir --hidden-import="py3k" temp.py

pyinstaller --clean --win-private-assemblies --upx-exclude=vcruntime140.dll --onedir --hidden-import="py3k" --hidden-import="savReaderWriter" temp.py

But in all cases I have received the same error:

ModuleNotFoundError: No module named 'py3k'

Body:
I solved the issue by including the path of the savReaderWriter to the parameter.

pyinstaller -p "C:\PyProjects\test\venv\Lib\site-packages\savReaderWriter"; test.py

Also, the real pain is when you trying to delete the module, an Error will occur because it is finding a non "UTF-8" character.


问:
Duplicate output with arrays in python
I'm trying to gather the data from 6 stocks in the array, but when my API can find the data I want it to move to the next item but still selecting just 6.
I tried with this code and other variants but nothing seems to work. The output always duplicate one stock and I don't know why

```<code>portfolio = ['NVDA', 'SPCE', 'IMGN', 'SUMR', 'EXPE', 'PWM.V', 'SVMK', 'DXCM']
tt = 0
irange = 6;
for i in range(irange):
    try:
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+portfolio[tt])
        t = t.json()
    except Exception as e:
        print("Error calling API, waiting 70 seconds and trying again...")
        time.sleep(70)
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+portfolio[tt])
        t = t.json()
    try:
        coticker = t['ticker']
        coexchange = t['exchange']
        coname = t['name']
        codesc = t['ggroup']
        coipo = t['ipo']
        cosector = t['gsector']
        costate = t['state']
        coweburl = t['weburl']
    except Exception as e:
        print("Information not available")
        irange = irange+1
    print("THE TT IS:"+str(tt))
    tt = tt+1
    print("")
    print(coticker,coexchange,coname,codesc,coipo,cosector,costate,coweburl)

</code>```

This is the output:

THE TT IS:0

NVDA -- GATHERED DATA

Information not available

THE TT IS:1

NVDA -- GATHERED DATA

THE TT IS:2

IMGN -- GATHERED DATA

THE TT IS:3

SUMR -- GATHERED DATA

THE TT IS:4

EXPE -- GATHERED DATA

Information not available

THE TT IS:5

EXPE -- GATHERED DATA

As you can see, when there is no information available, it doesn't move to the next one, it repeats the same one. What's the mistake? Thanks in advance for your kind help.

答:
Put the line that prints the information inside the try block that sets all the variables. Otherwise, you'll print the variables from the previous stock.

To make it keep going past 6 items when you have failures, don't use range(irange). Loop over the entire list with for symbol in portfolio:, and use a variable to count the successful attempts. Then break out of the loop when you've printed 6 stocks.

I've changed the code to use if statements instead of try/except to handle empty responses.

```<code>portfolio = ['NVDA', 'SPCE', 'IMGN', 'SUMR', 'EXPE', 'PWM.V', 'SVMK', 'DXCM']
irange = 6
successes = 0
for symbol in portfolio:
    try:
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+symbol)
        t = t.json()
    except Exception as e:
        print("Error calling API, waiting 70 seconds and trying again...")
        time.sleep(70)
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+symbol)
        if t:
            t = t.json()
    if t:
        coticker = t['ticker']
        coexchange = t['exchange']
        coname = t['name']
        codesc = t['ggroup']
        coipo = t['ipo']
        cosector = t['gsector']
        costate = t['state']
        coweburl = t['weburl']
        print("")
        print(coticker,coexchange,coname,codesc,coipo,cosector,costate,coweburl)
        successes += 1
        if successes >= irange:
            break
    else:
        print("Information not available for "+symbol)
</code>```

Title: Duplicate output with arrays in python

Body:
I'm trying to gather the data from 6 stocks in the array, but when my API can find the data I want it to move to the next item but still selecting just 6.
I tried with this code and other variants but nothing seems to work. The output always duplicate one stock and I don't know why

portfolio = ['NVDA', 'SPCE', 'IMGN', 'SUMR', 'EXPE', 'PWM.V', 'SVMK', 'DXCM']
tt = 0
irange = 6;
for i in range(irange):
    try:
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+portfolio[tt])
        t = t.json()
    except Exception as e:
        print("Error calling API, waiting 70 seconds and trying again...")
        time.sleep(70)
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+portfolio[tt])
        t = t.json()
    try:
        coticker = t['ticker']
        coexchange = t['exchange']
        coname = t['name']
        codesc = t['ggroup']
        coipo = t['ipo']
        cosector = t['gsector']
        costate = t['state']
        coweburl = t['weburl']
    except Exception as e:
        print("Information not available")
        irange = irange+1
    print("THE TT IS:"+str(tt))
    tt = tt+1
    print("")
    print(coticker,coexchange,coname,codesc,coipo,cosector,costate,coweburl)

This is the output:

THE TT IS:0

NVDA -- GATHERED DATA

Information not available

THE TT IS:1

NVDA -- GATHERED DATA

THE TT IS:2

IMGN -- GATHERED DATA

THE TT IS:3

SUMR -- GATHERED DATA

THE TT IS:4

EXPE -- GATHERED DATA

Information not available

THE TT IS:5

EXPE -- GATHERED DATA

As you can see, when there is no information available, it doesn't move to the next one, it repeats the same one. What's the mistake? Thanks in advance for your kind help.

Body:
Put the line that prints the information inside the try block that sets all the variables. Otherwise, you'll print the variables from the previous stock.

To make it keep going past 6 items when you have failures, don't use range(irange). Loop over the entire list with for symbol in portfolio:, and use a variable to count the successful attempts. Then break out of the loop when you've printed 6 stocks.

I've changed the code to use if statements instead of try/except to handle empty responses.

portfolio = ['NVDA', 'SPCE', 'IMGN', 'SUMR', 'EXPE', 'PWM.V', 'SVMK', 'DXCM']
irange = 6
successes = 0
for symbol in portfolio:
    try:
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+symbol)
        t = t.json()
    except Exception as e:
        print("Error calling API, waiting 70 seconds and trying again...")
        time.sleep(70)
        t = requests.get('https://finnhub.io/api/v1/stock/profile?symbol='+symbol)
        if t:
            t = t.json()
    if t:
        coticker = t['ticker']
        coexchange = t['exchange']
        coname = t['name']
        codesc = t['ggroup']
        coipo = t['ipo']
        cosector = t['gsector']
        costate = t['state']
        coweburl = t['weburl']
        print("")
        print(coticker,coexchange,coname,codesc,coipo,cosector,costate,coweburl)
        successes += 1
        if successes >= irange:
            break
    else:
        print("Information not available for "+symbol)


问:
Using LINQ to fill a boolean with true or false based off of condition
I am performing a linq query to grab some data from the DB.

Here is my linq:

```<code>   var requests = (from job in db.JobRequest
                        join jobCode in db.Job on job.JobCode equals jobCode.PkJobCode
                        join jobParams in db.JobRequestParameter on job.PkJobRequestId equals jobParams.FkJobRequestId into jobRequestParameters
                        from jobParams in jobRequestParameters.DefaultIfEmpty()
                        select new Objects.JobRequest.JobRequest()
                        {
                            JobRequestId = job.PkJobRequestId,
                            JobType = job.FkJobType,
                            JobCode = job.JobCode,
                            Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                            IsRunning = job.Running,
                            Description = jobCode.BriefDescription,
                            HasParams = ???
                        }).ToList();
</code>```

The main 2 tables I am concerned with here are JobRequest and JobRequestParameters...

JobRequest table has 13 records (but not all jobs have parameters).

JobRequestParameters table only has 4 records. They are joined on by PkJobRequestId. JobRequestParameters has a pkJobParameterId IF and only IF the PkJobRequestID from the JobRequest table has parameters..

How can I modify this linq query to be similar to the SQL I have written below. I would like to be able to fill HasParams with a true if the pkJobParameterId exists, and a 1 if not. Below is my SQL

```<code>        SELECT
      job.pkJobRequestId,
      jobParams.pkJobParameterId,
      (CASE
        WHEN jobParams.pkJobParameterId IS NULL THEN 1
        ELSE 0
      END) AS HasParams
    FROM
      Job.JobRequest job INNER JOIN
      Reference.Job jobCode ON job.JobCode = jobCode.pkJobCode LEFT OUTER JOIN
      job.JobRequestParameter jobParams ON job.pkJobRequestId = jobParams.fkJobRequestId
</code>```

edit: I have tried this but my syntax is way off.

```<code>requests = (from job in db.JobRequest
                        join jobCode in db.Job on job.JobCode equals jobCode.PkJobCode
                        join jobParams in db.JobRequestParameter on job.PkJobRequestId equals jobParams.FkJobRequestId into jobRequestParameters
                        from jobParams in jobRequestParameters.DefaultIfEmpty()
                        select new { pkJobRequestId = job, pkJobParameterId = jobParams == null ? false : true} as blahblah
                        select new Objects.JobRequest.JobRequest()
                        {
                            JobRequestId = job.PkJobRequestId,
                            JobType = job.FkJobType,
                            JobCode = job.JobCode,
                            Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                            IsRunning = job.Running,
                            Description = jobCode.BriefDescription,
                            HasParameters = blahblah.PkJobParameterId == null ? true : false
                        }).ToList();
</code>```

答:
It might work, in your original code, to do something like:

```<code>HasParams = ((object)jobParams.FkJobRequestId) == null
</code>```

But usually when you try to represent LINQ queries as exact translations of their SQL, it ends up overcomplicated. LINQ is a lot more expressive, and can usually represent what you really want better than SQL can. I'd probably do something like this.

```<code>var requests = (from job in db.JobRequest
                    join jobCode in db.Job on job.JobCode equals jobCode.PkJobCode
                    select new Objects.JobRequest.JobRequest()
                    {
                        JobRequestId = job.PkJobRequestId,
                        JobType = job.FkJobType,
                        JobCode = job.JobCode,
                        Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                        IsRunning = job.Running,
                        Description = jobCode.BriefDescription,
                        HasParams = db.JobRequestParameter.Any(jobParams => job.PkJobRequestId == jobParams.FkJobRequestId)
                    }).ToList();
</code>```

If you have navigation properties set up on your object model, you can do even better:

```<code>var requests = (from job in db.JobRequest
                let jobCode = job.JobCodeEntity // or whatever your nav property is called
                select new Objects.JobRequest.JobRequest()
                    {
                        JobRequestId = job.PkJobRequestId,
                        JobType = job.FkJobType,
                        JobCode = job.JobCode,
                        Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                        IsRunning = job.Running,
                        Description = jobCode.BriefDescription,
                        HasParams = job.JobParams.Any()
                    }).ToList();
</code>```

Body:
I am performing a linq query to grab some data from the DB.

Here is my linq:

   var requests = (from job in db.JobRequest
                        join jobCode in db.Job on job.JobCode equals jobCode.PkJobCode
                        join jobParams in db.JobRequestParameter on job.PkJobRequestId equals jobParams.FkJobRequestId into jobRequestParameters
                        from jobParams in jobRequestParameters.DefaultIfEmpty()
                        select new Objects.JobRequest.JobRequest()
                        {
                            JobRequestId = job.PkJobRequestId,
                            JobType = job.FkJobType,
                            JobCode = job.JobCode,
                            Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                            IsRunning = job.Running,
                            Description = jobCode.BriefDescription,
                            HasParams = ???
                        }).ToList();

The main 2 tables I am concerned with here are JobRequest and JobRequestParameters...

JobRequest table has 13 records (but not all jobs have parameters).

JobRequestParameters table only has 4 records. They are joined on by PkJobRequestId. JobRequestParameters has a pkJobParameterId IF and only IF the PkJobRequestID from the JobRequest table has parameters..

How can I modify this linq query to be similar to the SQL I have written below. I would like to be able to fill HasParams with a true if the pkJobParameterId exists, and a 1 if not. Below is my SQL

        SELECT
      job.pkJobRequestId,
      jobParams.pkJobParameterId,
      (CASE
        WHEN jobParams.pkJobParameterId IS NULL THEN 1
        ELSE 0
      END) AS HasParams
    FROM
      Job.JobRequest job INNER JOIN
      Reference.Job jobCode ON job.JobCode = jobCode.pkJobCode LEFT OUTER JOIN
      job.JobRequestParameter jobParams ON job.pkJobRequestId = jobParams.fkJobRequestId

edit: I have tried this but my syntax is way off.

requests = (from job in db.JobRequest
                        join jobCode in db.Job on job.JobCode equals jobCode.PkJobCode
                        join jobParams in db.JobRequestParameter on job.PkJobRequestId equals jobParams.FkJobRequestId into jobRequestParameters
                        from jobParams in jobRequestParameters.DefaultIfEmpty()
                        select new { pkJobRequestId = job, pkJobParameterId = jobParams == null ? false : true} as blahblah
                        select new Objects.JobRequest.JobRequest()
                        {
                            JobRequestId = job.PkJobRequestId,
                            JobType = job.FkJobType,
                            JobCode = job.JobCode,
                            Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                            IsRunning = job.Running,
                            Description = jobCode.BriefDescription,
                            HasParameters = blahblah.PkJobParameterId == null ? true : false
                        }).ToList();

Body:
It might work, in your original code, to do something like:

HasParams = ((object)jobParams.FkJobRequestId) == null

But usually when you try to represent LINQ queries as exact translations of their SQL, it ends up overcomplicated. LINQ is a lot more expressive, and can usually represent what you really want better than SQL can. I'd probably do something like this.

var requests = (from job in db.JobRequest
                    join jobCode in db.Job on job.JobCode equals jobCode.PkJobCode
                    select new Objects.JobRequest.JobRequest()
                    {
                        JobRequestId = job.PkJobRequestId,
                        JobType = job.FkJobType,
                        JobCode = job.JobCode,
                        Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                        IsRunning = job.Running,
                        Description = jobCode.BriefDescription,
                        HasParams = db.JobRequestParameter.Any(jobParams => job.PkJobRequestId == jobParams.FkJobRequestId)
                    }).ToList();

If you have navigation properties set up on your object model, you can do even better:

var requests = (from job in db.JobRequest
                let jobCode = job.JobCodeEntity // or whatever your nav property is called
                select new Objects.JobRequest.JobRequest()
                    {
                        JobRequestId = job.PkJobRequestId,
                        JobType = job.FkJobType,
                        JobCode = job.JobCode,
                        Schedule = job.Schedule.AddMilliseconds(-job.Schedule.Millisecond),
                        IsRunning = job.Running,
                        Description = jobCode.BriefDescription,
                        HasParams = job.JobParams.Any()
                    }).ToList();


问:
Staying put on a frame label
I am trying to use buttons to jump to frame labels. They jump to the label just fine, but they won't stop when pressed again. Below is the code I am using to have the button rest when pressed again.</p>

```<code>getting_btn.addEventListener(MouseEvent.CLICK, gettingStarted);

function gettingStarted(evt:MouseEvent):void {
gotoAndPlay("ipad_in");
if (this.currentLabel == "ipad_rest"){
this.gotoAndStop("ipad_rest");
}
}
</code>```

答:
On the following line you are testing the frame name for "ipad_rest" but on the line before you set the frame to "ipad_in" so in effect the currentLabel will never be "ipad_rest"

```<code>gotoAndPlay("ipad_in");
if (this.currentLabel == "ipad_rest"){// will never be true
</code>```

Not tested but this should be about what you want it all depends on if "ipad_in" is still the active frame . You were vague on your description.

```<code>function gettingStarted(evt:MouseEvent):void {
  if (this.currentLabel == "ipad_in"){
    this.gotoAndStop("ipad_rest");
  }else{
    gotoAndPlay("ipad_in");
  }
}
</code>```

Title: Staying put on a frame label

Body:
I am trying to use buttons to jump to frame labels. They jump to the label just fine, but they won't stop when pressed again. Below is the code I am using to have the button rest when pressed again.

getting_btn.addEventListener(MouseEvent.CLICK, gettingStarted);

function gettingStarted(evt:MouseEvent):void {
gotoAndPlay("ipad_in");
if (this.currentLabel == "ipad_rest"){
this.gotoAndStop("ipad_rest");
}
}

Body:
On the following line you are testing the frame name for "ipad_rest" but on the line before you set the frame to "ipad_in" so in effect the currentLabel will never be "ipad_rest"

gotoAndPlay("ipad_in");
if (this.currentLabel == "ipad_rest"){// will never be true

Not tested but this should be about what you want it all depends on if "ipad_in" is still the active frame . You were vague on your description.

function gettingStarted(evt:MouseEvent):void {
  if (this.currentLabel == "ipad_in"){
    this.gotoAndStop("ipad_rest");
  }else{
    gotoAndPlay("ipad_in");
  }
}


问:
Preventing a
 from wrapping inside of a table
I have a table with two columns. One has some property names and the other has descriptions, including pre tags. I need the pre tags to not wrap and instead scroll to see overflow. I also need the first column to be sized based on the largest property name. I can't get the two to play nicely with each other.

For example I can get the first column to size based on the content but the pre won't scroll:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
pre {
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-content">
  <table border="0" class="config">
    <thead>
      <tr>
        <th>Property</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="config-name">name</td>
        <td class="config-description">

          <p>Foo bar talking about some random things related to our code here in the paragraph:</p>
          ```// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)```
     </td>
    </tr>
    </tbody>
  </table>
</div></code>```

I can also get the pre to scroll but then I can't get the first column to resize:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
table {
  table-layout: fixed;
  width: 100%;
}
th:first-of-type {
  width: 15%; /* Faking it here - the size of the first td/th should be based on the largest */
}
pre {
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-content">
  <table border="0" class="config">
    <thead>
      <tr>
        <th>Property</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="config-name">name</td>
        <td class="config-description">

          <p>Foo bar talking about some random things related to our code here in the paragraph:</p>
          ```// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)```
     </td>
    </tr>
    </tbody>
  </table>
</div></code>```

Any ideas how I can get both working while retaining a table layout? I know how to do it with other methods like grid and flexbox, that's not what I'm asking about.

答:
You can consisder width:0;min-width:100%; trick on the pre. The idea is that the width:0 will disable the contribution of pre on defining the width of the container then min-width:100% will force it to fill all the space:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}

th:first-of-type {
  white-space:nowrap;
}
pre {
  overflow: auto;
  width:0;
  min-width:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-content">
  <table border="0" class="config">
    <thead>
      <tr>
        <th>Property</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="config-name">name</td>
        <td class="config-description">

          <p>Foo bar talking about some random things related to our code here in the paragraph:</p>
          ```// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)```
     </td>
    </tr>
    </tbody>
  </table>
</div></code>```

Related question: How to match width of text to width of dynamically sized image?

Title: Preventing a <pre> from wrapping inside of a table

Body:
I have a table with two columns. One has some property names and the other has descriptions, including pre tags. I need the pre tags to not wrap and instead scroll to see overflow. I also need the first column to be sized based on the largest property name. I can't get the two to play nicely with each other.

For example I can get the first column to size based on the content but the pre won't scroll:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
pre {
  overflow: auto;
}

        Property
        Description

        name

Foo bar talking about some random things related to our code here in the paragraph:

// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)

I can also get the pre to scroll but then I can't get the first column to resize:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}
table {
  table-layout: fixed;
  width: 100%;
}
th:first-of-type {
  width: 15%; /* Faking it here - the size of the first td/th should be based on the largest */
}
pre {
  overflow: auto;
}

        Property
        Description

        name

Foo bar talking about some random things related to our code here in the paragraph:

// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)

Any ideas how I can get both working while retaining a table layout? I know how to do it with other methods like grid and flexbox, that's not what I'm asking about.

Body:
You can consisder width:0;min-width:100%; trick on the pre. The idea is that the width:0 will disable the contribution of pre on defining the width of the container then min-width:100% will force it to fill all the space:

.main-content {
  max-width: 800px;
  border: 1px solid red;
}

th:first-of-type {
  white-space:nowrap;
}
pre {
  overflow: auto;
  width:0;
  min-width:100%;
}

<div class="main-content">
  <table border="0" class="config">
    <thead>
      <tr>
        <th>Property</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="config-name">name</td>
        <td class="config-description">

          <p>Foo bar talking about some random things related to our code here in the paragraph:</p>
          <pre>// some really long code section here that should have its own scroll bar (and not wrap) some really long code section here that should have its own scroll bar (and not wrap)</pre>
     </td>
    </tr>
    </tbody>
  </table>
</div>

Related question: How to match width of text to width of dynamically sized image?


问:
Access the Resolve Value of a Promise
I have a promise that resolves a variable this.data in a Read Excel Service as shown below,

  parseExcel(excelFile): Promise<any>
  {
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(excelFile.target);
    if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onload = (e: any) =>
        {
          /* read workbook */
          const bstr: string = e.target.result;
          const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

          /* grab first sheet */
          const wsname: string = wb.SheetNames[0];
          const ws: XLSX.WorkSheet = wb.Sheets[wsname];

          /* save data */
          this.data = <AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
          console.log("BOM PARSE SERVICE LOG: " , this.data)
          resolve(this.data);
        };
        reader.readAsBinaryString(target.files[0]);
    })
}
```

<p>I am now trying to access the resolved array here</p>

<pre class="lang-js prettyprint-override"><code>async ReadExcel(event)
  {
    return new Promise<Object>((resolve, reject) =>
    {
      var excelContents = this.parser.parseExcel(event).then(function(value)
      {
        return value
      }
      console.log("New Quote Component Log: ", excelContents)
      //need var excelContents to only contain the array and not contain the value of the promise object
    }
  )}
}
</code>```

the log statement in the latter function brings me back this...

Is there a way that I can have the variable excelContents only take on the value of the array rather than the entire value of the promise?

答:
The problem in the ReadExcel function is that .then() always returns the Promise instance, not the actual resolve value.
So by doing let blabla = promise.then(v => {return v}), blabla variable will be the promise and to access the resolve value you'll have to do blabla.then(v => ...).

That's why when you console.log the excelContents variable, you see an object with two properties, state, representing the state of the promise, and value, wich is the resolve value.

I recommend, if you are using an async function as I see you do, to use async/await like this:

```<code>async ReadExcel(event)
  {
    return new Promise<Object>(async(resolve, reject) =>
    {
      try {
          var excelContents = await this.parser.parseExcel(event)
          console.log("New Quote Component Log: ", excelContents)
          //need var excelContents to only contain the array and not contain the value of the promise object
          resolve(excelContents)
      } catch(e) {
         reject(e)
      }
    }
  )}
}
</code>```

as await promiseReturningFunc() will return the resolve value.

Be careful of error handling, always use try/catch.

Also please notice that I added async to the promise handler.

Title: Access the Resolve Value of a Promise

Body:
I have a promise that resolves a variable this.data in a Read Excel Service as shown below,

  parseExcel(excelFile): Promise<any>
  {
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(excelFile.target);
    if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onload = (e: any) =>
        {
          /* read workbook */
          const bstr: string = e.target.result;
          const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

          /* grab first sheet */
          const wsname: string = wb.SheetNames[0];
          const ws: XLSX.WorkSheet = wb.Sheets[wsname];

          /* save data */
          this.data = <AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
          console.log("BOM PARSE SERVICE LOG: " , this.data)
          resolve(this.data);
        };
        reader.readAsBinaryString(target.files[0]);
    })
}

I am now trying to access the resolved array here

async ReadExcel(event)
  {
    return new Promise<Object>((resolve, reject) =>
    {
      var excelContents = this.parser.parseExcel(event).then(function(value)
      {
        return value
      }
      console.log("New Quote Component Log: ", excelContents)
      //need var excelContents to only contain the array and not contain the value of the promise object
    }
  )}
}

the log statement in the latter function brings me back this...

Is there a way that I can have the variable excelContents only take on the value of the array rather than the entire value of the promise?

Body:
The problem in the ReadExcel function is that .then() always returns the Promise instance, not the actual resolve value.
So by doing let blabla = promise.then(v => {return v}), blabla variable will be the promise and to access the resolve value you'll have to do blabla.then(v => ...).

That's why when you console.log the excelContents variable, you see an object with two properties, state, representing the state of the promise, and value, wich is the resolve value.

I recommend, if you are using an async function as I see you do, to use async/await like this:

async ReadExcel(event)
  {
    return new Promise<Object>(async(resolve, reject) =>
    {
      try {
          var excelContents = await this.parser.parseExcel(event)
          console.log("New Quote Component Log: ", excelContents)
          //need var excelContents to only contain the array and not contain the value of the promise object
          resolve(excelContents)
      } catch(e) {
         reject(e)
      }
    }
  )}
}

as await promiseReturningFunc() will return the resolve value.

Be careful of error handling, always use try/catch.

Also please notice that I added async to the promise handler.


问:
Getting non-zero data and positions from 2D array in Python
I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.

Is there any way that I can get the value and the position at the same time?

```<code>import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])

res = zip(*np.nonzero(groupMatrix))

print(list(res))
</code>```

The result I got is [(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

But I hope the result can show the position with value.

For example, (x, y, z): x, y represent the position and z represents the value at the point.

(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2).

Thank you for your help!!!

答:
If your arrays are small, like the one in your question, ndenumerate will  be readable and fast.  If your arrays are large, you should default to vectorized methods.

```<code>[(*i, j) for i, j in np.ndenumerate(arr) if j != 0]
</code>```

```<code>[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]
</code>```

Body:
I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.

Is there any way that I can get the value and the position at the same time?

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])

res = zip(*np.nonzero(groupMatrix))

print(list(res))

The result I got is [(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

But I hope the result can show the position with value.

For example, (x, y, z): x, y represent the position and z represents the value at the point.

(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2).

Thank you for your help!!!

Body:
If your arrays are small, like the one in your question, ndenumerate will  be readable and fast.  If your arrays are large, you should default to vectorized methods.

[(*i, j) for i, j in np.ndenumerate(arr) if j != 0]

[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]


问:
Sum last two records including last record of a group
In SQL Server 2017, how do I sum the last two records and show the last record in a single query?

```<code>CREATE TABLE Billing
(
    Customer CHAR(12),
    Month INT,
    Amount INT
)
GO

INSERT INTO Billing VALUES ('AAAA', 3, 5)
INSERT INTO Billing VALUES ('AAAA', 2, 0)
INSERT INTO Billing VALUES ('AAAA', 1, 2)
INSERT INTO Billing VALUES ('BBBB', 10, 0)
INSERT INTO Billing VALUES ('BBBB', 12, 1)
INSERT INTO Billing VALUES ('BBBB', 11, 0)
INSERT INTO Billing VALUES ('BBBB', 13, 6)
</code>```

Expected output:

```<code>Customer   Total Last 2 Bills   Last Bill
-----------------------------------------
AAAA                         5          5
BBBB                         7          6
</code>```

I tried using SUM with LAST_VALUE with ORDER BY

答:
You can use window functions:

```<code>select customer, (prev_amount + amount), amount
from (select b.*,
             lag(amount) over (partition by customer order by month) as prev_amount,
             lead(month) over (partition by customer order by month) as next_month
      from billing b
     ) b
where next_month is null;
</code>```

If you want to ignore values of 0, then filter:

```<code>select customer, (coalesce(prev_amount, 0) + amount), amount
from (select b.*,
             lag(amount) over (partition by customer order by month) as prev_amount,
             lead(month) over (partition by customer order by month) as next_month
      from billing b
      where amount <> 0
     ) b
where next_month is null;
</code>```

Body:
In SQL Server 2017, how do I sum the last two records and show the last record in a single query?

CREATE TABLE Billing
(
    Customer CHAR(12),
    Month INT,
    Amount INT
)
GO

INSERT INTO Billing VALUES ('AAAA', 3, 5)
INSERT INTO Billing VALUES ('AAAA', 2, 0)
INSERT INTO Billing VALUES ('AAAA', 1, 2)
INSERT INTO Billing VALUES ('BBBB', 10, 0)
INSERT INTO Billing VALUES ('BBBB', 12, 1)
INSERT INTO Billing VALUES ('BBBB', 11, 0)
INSERT INTO Billing VALUES ('BBBB', 13, 6)

Expected output:

Customer   Total Last 2 Bills   Last Bill
-----------------------------------------
AAAA                         5          5
BBBB                         7          6

I tried using SUM with LAST_VALUE with ORDER BY

Body:
You can use window functions:

select customer, (prev_amount + amount), amount
from (select b.*,
             lag(amount) over (partition by customer order by month) as prev_amount,
             lead(month) over (partition by customer order by month) as next_month
      from billing b
     ) b
where next_month is null;

If you want to ignore values of 0, then filter:

select customer, (coalesce(prev_amount, 0) + amount), amount
from (select b.*,
             lag(amount) over (partition by customer order by month) as prev_amount,
             lead(month) over (partition by customer order by month) as next_month
      from billing b
      where amount <> 0
     ) b
where next_month is null;


问:
Cannot Create Instance Of Class ViewModel
I'm currently working on a countdown app, and whenever I open it, it fails with a message saying Cannot create instance of class com.nailuj29gaming.CountdownViewModel

The stack trace is

```<code>    Process: com.nailuj29gaming.countdown.debug, PID: 17800
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nailuj29gaming.countdown.debug/com.nailuj29gaming.countdown.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2750)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.nailuj29gaming.countdown.CountdownViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
</code>```

I know there is a very similar question, this one, but that is target at Java, and my code is written in Kotlin. My ViewModel class's text is

```<code>package com.nailuj29gaming.countdown

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class CountdownViewModel(application: Application) : AndroidViewModel(application) {
    private val repo: CountdownRepo
    val countdowns: LiveData<List<Countdown>>

    init {
        val countdownDao = AppDatabase.getDatabase(application).countdownDao()
        repo = CountdownRepo(countdownDao)
        countdowns = repo.countdowns

    }

    fun insert(countdown: Countdown) = viewModelScope.launch {
        repo.insert(countdown)
    }

    fun delete(countdown: Countdown) = viewModelScope.launch {
        repo.delete(countdown)
    }
}
</code>```

I create the ViewModel in the first line of my MainActivity.onCreate() method. The code I used to create it is viewModel = ViewModelProvider(this).get(CountdownViewModel::class.java)

My build.gradle file (at least what matters in this question) is

```<code>apply plugin: 'kotlin-kapt'

dependencies {
    def room_version = "2.2.3"
    def lifecycle_version = "2.2.0"
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'androidx.preference:preference:1.1.0'
    implementation 'net.steamcrafted:materialiconlib:1.1.5'
    implementation 'com.google.android.material:material:1.0.0'
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.room:room-ktx:$room_version"
}
</code>```

I tried using a factory, but the ViewModelProviders class is deprecated

When I used a delegate, the IDE did not give me an error, but the compiler said

```<code>Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option
</code>```

My code is compiled into bytecode built with JVM target 1.8, so this error shouldn't show, right?

答:
You should consider this line from the stacktrace

Caused by: java.lang.InstantiationException:
  java.lang.Class has
  no zero argument constructor

This means you should pass an argument in the constructor when you buildng your viewmodel

In the link you quoted there is a specific kotlin answer]1

EDIT:
And also control that you have correctly insta intiated the factory as shown in this response or this other one

Body:
I'm currently working on a countdown app, and whenever I open it, it fails with a message saying Cannot create instance of class com.nailuj29gaming.CountdownViewModel

The stack trace is

    Process: com.nailuj29gaming.countdown.debug, PID: 17800
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nailuj29gaming.countdown.debug/com.nailuj29gaming.countdown.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2750)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.nailuj29gaming.countdown.CountdownViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

I know there is a very similar question, this one, but that is target at Java, and my code is written in Kotlin. My ViewModel class's text is

package com.nailuj29gaming.countdown

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class CountdownViewModel(application: Application) : AndroidViewModel(application) {
    private val repo: CountdownRepo
    val countdowns: LiveData<List<Countdown>>

    init {
        val countdownDao = AppDatabase.getDatabase(application).countdownDao()
        repo = CountdownRepo(countdownDao)
        countdowns = repo.countdowns

    }

    fun insert(countdown: Countdown) = viewModelScope.launch {
        repo.insert(countdown)
    }

    fun delete(countdown: Countdown) = viewModelScope.launch {
        repo.delete(countdown)
    }
}

I create the ViewModel in the first line of my MainActivity.onCreate() method. The code I used to create it is viewModel = ViewModelProvider(this).get(CountdownViewModel::class.java)

My build.gradle file (at least what matters in this question) is

apply plugin: 'kotlin-kapt'

dependencies {
    def room_version = "2.2.3"
    def lifecycle_version = "2.2.0"
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'androidx.preference:preference:1.1.0'
    implementation 'net.steamcrafted:materialiconlib:1.1.5'
    implementation 'com.google.android.material:material:1.0.0'
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.room:room-ktx:$room_version"
}

I tried using a factory, but the ViewModelProviders class is deprecated

When I used a delegate, the IDE did not give me an error, but the compiler said

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option

My code is compiled into bytecode built with JVM target 1.8, so this error shouldn't show, right?


答:
You need this I believe, Find the key in the filters object and compare it to every record you come across in your data object. Once you have the key you can easily check the values

const arrayToFilter = [{
  id: 1,
  name: 'sam'
}, {
  id: 1,
  status: 'open'
}, {
  id: 1,
  name: 'ana'
}];
const data = [{
    formID: 1234,
    name: "sam",
    email: "sam@gmail.com",
    status: "open",
    phone: "333-444-5555"
  },
  {
    formID: 1234,
    name: "mara",
    email: "sam@gmail.com",
    status: "open",
    phone: "333-444-5555"
  },
  {
    formID: 1234,
    name: "eugen",
    email: "eugen@gmail.com",
    status: "close",
    phone: "333-444-5555"
  }, {
    formID: 1234,
    name: "kevin",
    email: "eugen@gmail.com",
    status: "close",
    phone: "333-444-5555"
  },
  {
    formID: 1234,
    name: "ana",
    email: "eugen@gmail.com",
    status: "close",
    phone: "333-444-5555"
  }
]

const result = data.filter(x => {
  return arrayToFilter.some(y => {
    const key = Object.keys(y)[1];
    return y[key] === x[key]
  })
});
console.log(result)```

Title: Javascript filter array by another array of filters

Body:
I have a filtersArray which is a bunch of {id, value} and I want to filter my data (also array of JSON objects) to get back only the elements that match all of the filters? Is there a better way to do this than iterating through the arrayOfFilters with each filter using a for loop and doing a filter on each criteria?

the data is an array of JSON objects - ie

[{formID:1234, name:"sam", email:"sam@gmail.com", status:"open", phone: "333-444-5555"},
 {formID:2155, name:"charlie", email:"charlie@gmail.com", status:"closed", phone: "888-323-1234"},...]

and the filtersArray [{"status":"closed"}, {"name":"charlie"}, {"id":2155}...]

I have tried doing

for(var criteria in arrayOfFilters){
   this.data = this.data.filter( d => d.status === criteria.status)
                    .filter(d => d.name === criteria.name)
                    .filter(d => d.address === criteria.address)...
}

it does not work real well since criteria is a JSON object like {"status":"closed"}, {"name":"charlie"}...