问:
How to stop Java GUI without killing the JVM
I have a java console application that opens a GUI application that is on a separate class after the user gives a certain input. I want to return back to the console once I close the GUI which is achieved by pressing an "Exit" button that the user has the option to do another task or repeat it. I noticed that killing the system with System.exit(0) kills the whole process. I tried working things with threads but I'm relatively new to this and it doesn't seem to work either. Can someone point me in the right direction? Thanks.

I tried using frame.dispose() as well. It does load up the console and prints out the things as expected on calling the main method on System, but won't allow me to enter another input.

```<code>btnExit.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
     frame.dispose();
     System.main(null);
 }
});
</code>```

Error message: Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException: No line found.

答:
Don’t call your main method from a listener method. This may look like having the desired effect, but will have the main method running on the event handling thread while the methods invoked for the current event processing are still on the stack. This will not only keep their resources in memory, it will backfire if you ever try to open a GUI again.

Further take care not to close any console related resource (System.in or System.out) when opening the GUI, as you can’t re-open them when you want to use the console again.

If I understand you correctly, you have a program flow in your main method that doesn’t follow the event driven flow of a GUI application and you want to return to that program flow. One approach for a simple GUI, is to use a modal dialog instead of a window or frame.

```<code>public static void main(String[] args) {
    // a simple console application
    for(boolean exit = false; !exit; ) {
        System.out.println("Enter choice:");
        System.out.println("\t1 - Say hello");
        System.out.println("\t2 - Open GUI");
        System.out.println("\t3 - Exit");
        switch(System.console().readLine()) {
            case "1": sayHello(); break;
            case "2": openGUI(); break;
            case "3": exit = true; break;
            default: System.out.println("Not a valid input");
        }
    }
}

private static void sayHello() {
    String name = System.console().readLine("Enter your name: ");
    System.out.println("Hello "+name);
}

private static void openGUI() { // a temporary GUI application
    JDialog d = new JDialog((Window)null, Dialog.ModalityType.TOOLKIT_MODAL);
    JButton b = new JButton("Exit GUI");
    b.addActionListener(ev -> d.dispose());
    d.getContentPane().add(b, BorderLayout.PAGE_END);
    d.pack();
    d.setVisible(true);
}
</code>```

For a modal dialog, the method invocation that will open it does not return until it has been closed. The example uses dispose() to ensure that the resources are released timely and the event handling thread will terminate, so the main method can terminate the program by simply returning, like an ordinary console application.

If a dialog is not an option or a more complex GUI is involved, the logic of letting a GUI run until a certain event will happen, has been generalized with the SecondaryLoop class:

```<code>public static void main(String[] args) {
    for(boolean exit = false; !exit; ) {
        System.out.println("Enter choice:");
        System.out.println("\t1 - Say hello");
        System.out.println("\t2 - Open GUI");
        System.out.println("\t3 - Exit");
        switch(System.console().readLine()) {
            case "1": sayHello(); break;
            case "2": openGUI(); break;
            case "3": exit = true; break;
            default: System.out.println("Not a valid input");
        }
    }
}

private static void sayHello() {
    String name = System.console().readLine("Enter your name: ");
    System.out.println("Hello "+name);
}

private static void openGUI() {
    JFrame d = new JFrame();
    SecondaryLoop eventLoop = d.getToolkit().getSystemEventQueue().createSecondaryLoop();
    JButton b = new JButton("Exit GUI");
    b.addActionListener(ev -> {
        d.dispose();
        eventLoop.exit();
    });
    d.getContentPane().add(b, BorderLayout.PAGE_END);
    d.pack();
    d.setVisible(true);
    System.out.println("UI created");
    eventLoop.enter();
    System.out.println("UI disposed");
}
</code>```

Since opening the JFrame does not let the main thread wait, as indicated by the subsequent print statement, this code uses the SecondaryLoop’s enter() method, to enter an event processing loop that will only end when the button’s action listener will call the exit() method. Then, the main thread returns and continues processing the console loop.

Body:
I have a java console application that opens a GUI application that is on a separate class after the user gives a certain input. I want to return back to the console once I close the GUI which is achieved by pressing an "Exit" button that the user has the option to do another task or repeat it. I noticed that killing the system with System.exit(0) kills the whole process. I tried working things with threads but I'm relatively new to this and it doesn't seem to work either. Can someone point me in the right direction? Thanks.

I tried using frame.dispose() as well. It does load up the console and prints out the things as expected on calling the main method on System, but won't allow me to enter another input.

btnExit.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
     frame.dispose();
     System.main(null);
 }
});

Error message: Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException: No line found.

Body:
Don’t call your main method from a listener method. This may look like having the desired effect, but will have the main method running on the event handling thread while the methods invoked for the current event processing are still on the stack. This will not only keep their resources in memory, it will backfire if you ever try to open a GUI again.

Further take care not to close any console related resource (System.in or System.out) when opening the GUI, as you can’t re-open them when you want to use the console again.

If I understand you correctly, you have a program flow in your main method that doesn’t follow the event driven flow of a GUI application and you want to return to that program flow. One approach for a simple GUI, is to use a modal dialog instead of a window or frame.

public static void main(String[] args) {
    // a simple console application
    for(boolean exit = false; !exit; ) {
        System.out.println("Enter choice:");
        System.out.println("\t1 - Say hello");
        System.out.println("\t2 - Open GUI");
        System.out.println("\t3 - Exit");
        switch(System.console().readLine()) {
            case "1": sayHello(); break;
            case "2": openGUI(); break;
            case "3": exit = true; break;
            default: System.out.println("Not a valid input");
        }
    }
}

private static void sayHello() {
    String name = System.console().readLine("Enter your name: ");
    System.out.println("Hello "+name);
}

private static void openGUI() { // a temporary GUI application
    JDialog d = new JDialog((Window)null, Dialog.ModalityType.TOOLKIT_MODAL);
    JButton b = new JButton("Exit GUI");
    b.addActionListener(ev -> d.dispose());
    d.getContentPane().add(b, BorderLayout.PAGE_END);
    d.pack();
    d.setVisible(true);
}

For a modal dialog, the method invocation that will open it does not return until it has been closed. The example uses dispose() to ensure that the resources are released timely and the event handling thread will terminate, so the main method can terminate the program by simply returning, like an ordinary console application.

If a dialog is not an option or a more complex GUI is involved, the logic of letting a GUI run until a certain event will happen, has been generalized with the SecondaryLoop class:

public static void main(String[] args) {
    for(boolean exit = false; !exit; ) {
        System.out.println("Enter choice:");
        System.out.println("\t1 - Say hello");
        System.out.println("\t2 - Open GUI");
        System.out.println("\t3 - Exit");
        switch(System.console().readLine()) {
            case "1": sayHello(); break;
            case "2": openGUI(); break;
            case "3": exit = true; break;
            default: System.out.println("Not a valid input");
        }
    }
}

private static void sayHello() {
    String name = System.console().readLine("Enter your name: ");
    System.out.println("Hello "+name);
}

private static void openGUI() {
    JFrame d = new JFrame();
    SecondaryLoop eventLoop = d.getToolkit().getSystemEventQueue().createSecondaryLoop();
    JButton b = new JButton("Exit GUI");
    b.addActionListener(ev -> {
        d.dispose();
        eventLoop.exit();
    });
    d.getContentPane().add(b, BorderLayout.PAGE_END);
    d.pack();
    d.setVisible(true);
    System.out.println("UI created");
    eventLoop.enter();
    System.out.println("UI disposed");
}

Since opening the JFrame does not let the main thread wait, as indicated by the subsequent print statement, this code uses the SecondaryLoop’s enter() method, to enter an event processing loop that will only end when the button’s action listener will call the exit() method. Then, the main thread returns and continues processing the console loop.


来源: stackexchange

问:
Creating an array element-wise from product of two arrays
I have a project wherein, after multiplying arrays, I have to arrange them into a separate array (element-wise) and get their sums.

```<code>As an example:
a = [1, 0, 1]
b = [[3,5,2], [5,4,3], [5,2,2]]
c = a*b
c = [ [3, 5, 2]
      [0, 0, 0]
      [5, 2, 2] ]
</code>```

Now, I want to put the answers in an individual array element wise such as:

```<code>r1 = [3, 0, 5]
r2 = [5, 0, 2]
r3 = [2, 0, 2]
</code>```

Then, get its sum.

```<code>sum_r1 = [8]
sum_r2 = [7]
sum_r3 = [4]
</code>```

So far, my I am only able to code the multiplication. I am still trying the appropriate code for the succeeding steps. My code looks like this:

```<code> [EDIT]
 def fitness_score(a, b):
   c = numpy.multiply(a, b)
   trns = numpy.transpose(c)
   s = numpy.sum(trns, axis=1)
   return s
</code>```

Output gives the answer but it has an error something like this: ValueError: operands could not be broadcast together with shapes (500,3) (3,3). Note that the values in a are obtained randomly.

Any help would be appreciated! Thank you in advance!

答:
You can use NumPy, just use transpose on the second matrix to get the desired result.

```<code>import numpy as np
a = [1, 0, 1]
b = [[3,5,2], [5,4,3], [5,2,2]]
a = np.array(a)
b = np.array(b)
mul = a*b.T
#array([[3, 0, 5],
#       [5, 0, 2],
#       [2, 0, 2]])

s = np.sum(a*b.T, axis=1)
#array([8, 7, 4])
</code>```

If you have a 500 by 3 shaped array for a. You can try this:

```<code>import numpy as np
a = [[1, 0, 1] for _ in range(500)]
b = [[3,5,2], [5,4,3], [5,2,2]]
a = np.array(a)
b = np.array(b)

mul = [a_c*b.T for a_c in a]
#array([[3, 0, 5],
#       [5, 0, 2],
#       [2, 0, 2]])

s = np.sum(mul, axis=-1)

print(s)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a project wherein, after multiplying arrays, I have to arrange them into a separate array (element-wise) and get their sums.

As an example:
a = [1, 0, 1]
b = [[3,5,2], [5,4,3], [5,2,2]]
c = a*b
c = [ [3, 5, 2]
      [0, 0, 0]
      [5, 2, 2] ]

Now, I want to put the answers in an individual array element wise such as:

r1 = [3, 0, 5]
r2 = [5, 0, 2]
r3 = [2, 0, 2]

Then, get its sum.

sum_r1 = [8]
sum_r2 = [7]
sum_r3 = [4]

So far, my I am only able to code the multiplication. I am still trying the appropriate code for the succeeding steps. My code looks like this:

 [EDIT]
 def fitness_score(a, b):
   c = numpy.multiply(a, b)
   trns = numpy.transpose(c)
   s = numpy.sum(trns, axis=1)
   return s

Output gives the answer but it has an error something like this: ValueError: operands could not be broadcast together with shapes (500,3) (3,3). Note that the values in a are obtained randomly.

Any help would be appreciated! Thank you in advance!

Body:
You can use NumPy, just use transpose on the second matrix to get the desired result.

import numpy as np
a = [1, 0, 1]
b = [[3,5,2], [5,4,3], [5,2,2]]
a = np.array(a)
b = np.array(b)
mul = a*b.T
#array([[3, 0, 5],
#       [5, 0, 2],
#       [2, 0, 2]])

s = np.sum(a*b.T, axis=1)
#array([8, 7, 4])

If you have a 500 by 3 shaped array for a. You can try this:

import numpy as np
a = [[1, 0, 1] for _ in range(500)]
b = [[3,5,2], [5,4,3], [5,2,2]]
a = np.array(a)
b = np.array(b)

mul = [a_c*b.T for a_c in a]
#array([[3, 0, 5],
#       [5, 0, 2],
#       [2, 0, 2]])

s = np.sum(mul, axis=-1)

print(s)


问:
Asynchronous UI testing in Swift
I have a button in a UI test that logs in to an app. The user flow to automate is this:

User taps button

Button text changes from "Log In" to "Processing..."

Button disappears when log in is successful

My UI test code is very simple for the functional test:

```<code>let loginButton = app.buttons["LOG IN"]
let welcomeText = app.staticTexts["Welcome!"]
loginButton.tap()
XCTAssertTrue(welcomeText.waitForExistence(10))
</code>```

However, it does not validate that the button changes state to "Processing...".

If I attempt to put a check in the code like this, it doesn't work because by the time the UI Test has walked the screen looking for the text, it might have disappeared.

```<code>let loginButton = app.buttons["LOG IN"]
let loginButtonProcessingText = app.buttons.staticTexts["Processing..."]
let welcomeText = app.staticTexts["Welcome!"]
loginButton.tap()
XCTAssertTrue(loginButtonProcessingText.exists)
XCTAssertTrue(welcomeText.waitForExistence(10))
</code>```

So my thought is that I need to somehow start the check for the processing test simultaneously with the button tap, or maybe a second before it.

Is there a way to spin up a check like that asynchronously in XCUI testing?

答:
You can use expectation to test asynchronous task.
But first it can be more clear if you separate your steps like below;</p>

```<code>let loginButton = app.buttons["LOG IN"]
loginButton.tap()

let loginButtonProcessingText = app.buttons.staticTexts["Processing..."]
XCTAssertTrue(loginButtonProcessingText.exists)

let welcomeText = app.staticTexts["Welcome!"]
XCTAssertTrue(welcomeText.waitForExistence(10))
</code>```

Title: Asynchronous UI testing in Swift

Body:
I have a button in a UI test that logs in to an app. The user flow to automate is this:

User taps button

Button text changes from "Log In" to "Processing..."

Button disappears when log in is successful

My UI test code is very simple for the functional test:

let loginButton = app.buttons["LOG IN"]
let welcomeText = app.staticTexts["Welcome!"]
loginButton.tap()
XCTAssertTrue(welcomeText.waitForExistence(10))

However, it does not validate that the button changes state to "Processing...".

If I attempt to put a check in the code like this, it doesn't work because by the time the UI Test has walked the screen looking for the text, it might have disappeared.

let loginButton = app.buttons["LOG IN"]
let loginButtonProcessingText = app.buttons.staticTexts["Processing..."]
let welcomeText = app.staticTexts["Welcome!"]
loginButton.tap()
XCTAssertTrue(loginButtonProcessingText.exists)
XCTAssertTrue(welcomeText.waitForExistence(10))

So my thought is that I need to somehow start the check for the processing test simultaneously with the button tap, or maybe a second before it.

Is there a way to spin up a check like that asynchronously in XCUI testing?

Body:
You can use expectation to test asynchronous task.
But first it can be more clear if you separate your steps like below;

let loginButton = app.buttons["LOG IN"]
loginButton.tap()

let loginButtonProcessingText = app.buttons.staticTexts["Processing..."]
XCTAssertTrue(loginButtonProcessingText.exists)

let welcomeText = app.staticTexts["Welcome!"]
XCTAssertTrue(welcomeText.waitForExistence(10))


问:
How to get n stars on 5 stars here
This is the function I'm getting the stars for rating. I need 5 white stars and get the n golden on it.

```<code>let n = []
for(var i = 0; i < product.avg_rating; i++) {
  n.push(<i class="fa fa-star" key={i}></i>)
}
</code>```

I'm calling this variable here

```<code><div className="rating">
  {n}
</div>
</code>```

答:
As per my understanding of your question
You can do something like this:</p>

```<code>let golden = [];
for(var i = 0; i < product.avg_rating; i++) {
  golden.push(<i class="fa fa-star" key={i}></i>)
}
let white = [];
for(var i = 0; i < (5-product.avg_rating); i++) {
  white.push(<i class="fa fa-star" key={i}></i>) // provide appropriate class for white stars
}

return(
<div className="rating">
{golden}
{white.map((i)=><span> {i} </span>)}
</div>
)
</code>```

Title: How to get n stars on 5 stars here

Body:
This is the function I'm getting the stars for rating. I need 5 white stars and get the n golden on it.

let n = []
for(var i = 0; i < product.avg_rating; i++) {
  n.push()
}

I'm calling this variable here

  {n}

Body:
As per my understanding of your question
You can do something like this:

let golden = [];
for(var i = 0; i < product.avg_rating; i++) {
  golden.push(<i class="fa fa-star" key={i}></i>)
}
let white = [];
for(var i = 0; i < (5-product.avg_rating); i++) {
  white.push(<i class="fa fa-star" key={i}></i>) // provide appropriate class for white stars
}

return(
<div className="rating">
{golden}
{white.map((i)=><span> {i} </span>)}
</div>
)


问:
How to detect the end of the list element on scroll event?
How to detect the end of the list element on scroll event? Lets say i have array [1,2,3,4,5,6,7,8,9,10], i need to detect if the scroll was reached the end of the list and return then value(in this case the value is 10)? Here is my snippet code: https://codesandbox.io/s/react-window-detect-last-element-on-scrolling-down-oo99p

答:
You can use onScroll event for parent div:

```<code>const onScroll = (event) => {
  var element = event.target;
  if (element.scrollHeight - element.scrollTop === element.clientHeight)
  {
      console.log(dataArray[dataArray.length - 1]);
  }
}
</code>```

See in playground: https://codesandbox.io/s/react-window-detect-last-element-on-scrolling-down-c4sv0?file=/src/index.js

Body:
You can use onScroll event for parent div:

const onScroll = (event) => {
  var element = event.target;
  if (element.scrollHeight - element.scrollTop === element.clientHeight)
  {
      console.log(dataArray[dataArray.length - 1]);
  }
}

See in playground: https://codesandbox.io/s/react-window-detect-last-element-on-scrolling-down-c4sv0?file=/src/index.js


问:
Google Earth Engine using Python
How should a beginner start learning Google Earth Engine coding with python using colab? I know python, but how do I come to know about the objects of images and image classification.  </p>

答: i use geemap package for convert shape file to earth engine variable without uploading file on assets </p>

Title: Google Earth Engine using Python


问:
declearing a variable in dart and changing its value
Why i have an error in this case :

```<code>class Person {
  Person({name,age});
  var name,age = 5;
  name = "wael";
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}
</code>```

error

```
1.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
Try adding the name of the type of the variable or the keyword 'var'.
  name = "wael";
  ^^^^
1.dart:6:3: Error: 'name' is already declared in this scope.
  name = "wael";
  ^^^^
1.dart:5:7: Context: Previous declaration of 'name'.
  var name,age = 5;
      ^^^^
1.dart:7:26: Error: Can't use 'name' because it is declared more than once.
  void Xprint()=>print('$name is $age years old');
                         ^
```

答:
You can not have any instruction in open place of a class. Any instruction must be inside a method. Yo can do this:

```<code>class Person {
  Person({name,age});
  var name= "wael",age = 5; // assign default value while declartion
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}
</code>```

or set the default value on constructor

```<code>class Person {
  Person({this.name= "wael",age});
  var name,age = 5;
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}
</code>```

Body:
Why i have an error in this case :

class Person {
  Person({name,age});
  var name,age = 5;
  name = "wael";
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}

error

1.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
Try adding the name of the type of the variable or the keyword 'var'.
  name = "wael";
  ^^^^
1.dart:6:3: Error: 'name' is already declared in this scope.
  name = "wael";
  ^^^^
1.dart:5:7: Context: Previous declaration of 'name'.
  var name,age = 5;
      ^^^^
1.dart:7:26: Error: Can't use 'name' because it is declared more than once.
  void Xprint()=>print('$name is $age years old');
                         ^

Body:
You can not have any instruction in open place of a class. Any instruction must be inside a method. Yo can do this:

class Person {
  Person({name,age});
  var name= "wael",age = 5; // assign default value while declartion
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}

or set the default value on constructor

class Person {
  Person({this.name= "wael",age});
  var name,age = 5;
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}


问:
django create abstractbaseuser model, error
I'm making my personal project.
I'm trying to coding signup function. but not work.
createuser is doing right. but when i runserver, and go signup.html page, input value, always same error. what is wrong with my code?

model.py

```<code>from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin)
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    use_in_migrations = True
    def create_user(self, username, userid, company, companycode, password=None):

        if not username:
            raise ValueError(_('Users must have an name!'))

        user = self.User(
            username=username,
            userid = userid,
            company= company,
            companycode = companycode,
        )

        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, username, userid, company, companycode, password):
        user = self.create_user(
            username=username,
            userid = userid,
            company = company,
            companycode = companycode,
            password=password,
        )
        user.is_active = True
        user.is_superuser = True
        user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=10, unique=True, verbose_name="이름")
    userid = models.CharField(max_length=100, unique=True, verbose_name="아이디")
    company = models.CharField(max_length=10, verbose_name="회사")
    companycode = models.CharField(max_length=100, verbose_name="회사코드")
    created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜")
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = 'user'

    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['userid', 'company', 'companycode']
    def __str__(self):
        return self.username

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All superusers are staff
        return self.is_superuser

    get_full_name.short_description = _('Full name')
</code>```

views.py

```<code>from django.shortcuts import render
from django.http.response import HttpResponseRedirect
from django.urls.base import reverse
from django.contrib.auth.models import User, UserManager
from django.http import HttpResponse

from django.shortcuts import render
from .models import UserManager

def signup(request):
    if request.method == 'GET':
        return render(request, 'useraccount/signup.html')

def signup_sign(request):
    if request.method == 'POST':
        username = request.POST['name']
        userid = request.POST['id']
        company = request.POST['company']
        code = request.POST['code']
        account = UserManager.create_user(
            username=username,
            userid = userid,
            company = company,
            companycode = code,
        )
        account.save()
        return render(request, 'useraccount/success.html')
</code>```

signup.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form name="test" action="/signup_sign/" method="post"> {% csrf_token %}
        NAME : <input type="text" name="name" > </br>
        ID : <input type="text" name="id" > </br>
        COMPANY: <input type="text" name="company"> </br>
        CODE: <input type="password" name="code"> </br>
        <input type="submit" value="send">
    </form>
</body>

</html>
</code>```

basically baseuser required email, name, last name, first name etc..
but i just want input name, id, company name, company code.
so i crated new model using AbstractBaseUser.

but always this error apper.
error.

```<code>Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/signup_sign/

Django Version: 3.0.6
Python Version: 3.7.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'useraccount']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/junbeomkwak/Desktop/fido_project/useraccount/views.py", line 25, in signup_sign
    companycode = code,

Exception Type: TypeError at /signup_sign/
Exception Value: create_user() missing 1 required positional argument: 'self'
</code>```

答:
In your views.py, this line is incorrect:

```<code>  account = UserManager.create_user(
      username=username,
      userid = userid,
      company = company,
      companycode = code,
  )
</code>```

You should use User.objects.create_user:

```<code>  account = User.objects.create_user(
      username=username,
      userid = userid,
      company = company,
      companycode = code,
  )
</code>```

Make sure to include from .models import User at the top of your file.

The reason why your code did not work is because create_user is not a static method, so it can only be called from an instance of UserManager, not its class. User has an instance of UserManager, created by this snippet: objects = UserManager()

Body:
I'm making my personal project.
I'm trying to coding signup function. but not work.
createuser is doing right. but when i runserver, and go signup.html page, input value, always same error. what is wrong with my code?

model.py

from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin)
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    use_in_migrations = True
    def create_user(self, username, userid, company, companycode, password=None):

        if not username:
            raise ValueError(_('Users must have an name!'))

        user = self.User(
            username=username,
            userid = userid,
            company= company,
            companycode = companycode,
        )

        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, username, userid, company, companycode, password):
        user = self.create_user(
            username=username,
            userid = userid,
            company = company,
            companycode = companycode,
            password=password,
        )
        user.is_active = True
        user.is_superuser = True
        user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=10, unique=True, verbose_name="이름")
    userid = models.CharField(max_length=100, unique=True, verbose_name="아이디")
    company = models.CharField(max_length=10, verbose_name="회사")
    companycode = models.CharField(max_length=100, verbose_name="회사코드")
    created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜")
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = 'user'

    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['userid', 'company', 'companycode']
    def __str__(self):
        return self.username

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All superusers are staff
        return self.is_superuser

    get_full_name.short_description = _('Full name')

views.py

from django.shortcuts import render
from django.http.response import HttpResponseRedirect
from django.urls.base import reverse
from django.contrib.auth.models import User, UserManager
from django.http import HttpResponse

from django.shortcuts import render
from .models import UserManager

def signup(request):
    if request.method == 'GET':
        return render(request, 'useraccount/signup.html')

def signup_sign(request):
    if request.method == 'POST':
        username = request.POST['name']
        userid = request.POST['id']
        company = request.POST['company']
        code = request.POST['code']
        account = UserManager.create_user(
            username=username,
            userid = userid,
            company = company,
            companycode = code,
        )
        account.save()
        return render(request, 'useraccount/success.html')

signup.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <form name="test" action="/signup_sign/" method="post"> {% csrf_token %}
        NAME : <input type="text" name="name" >

        ID : <input type="text" name="id" >

        COMPANY: <input type="text" name="company">

        CODE: <input type="password" name="code">

        <input type="submit" value="send">
    </form>

basically baseuser required email, name, last name, first name etc..
but i just want input name, id, company name, company code.
so i crated new model using AbstractBaseUser.

but always this error apper.
error.

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/signup_sign/

Django Version: 3.0.6
Python Version: 3.7.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'useraccount']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/junbeomkwak/Desktop/fido_project/useraccount/views.py", line 25, in signup_sign
    companycode = code,

Exception Type: TypeError at /signup_sign/
Exception Value: create_user() missing 1 required positional argument: 'self'

Body:
In your views.py, this line is incorrect:

  account = UserManager.create_user(
      username=username,
      userid = userid,
      company = company,
      companycode = code,
  )

You should use User.objects.create_user:

  account = User.objects.create_user(
      username=username,
      userid = userid,
      company = company,
      companycode = code,
  )

Make sure to include from .models import User at the top of your file.

The reason why your code did not work is because create_user is not a static method, so it can only be called from an instance of UserManager, not its class. User has an instance of UserManager, created by this snippet: objects = UserManager()


问:
Custom Installer in .Net showing Form behind installer
```<code>[RunInstaller(true)]
public partial class Installer1 : Installer
{
    public Installer1()
    {
        InitializeComponent();
    }

    public override void Install(System.Collections.IDictionary stateSaver)
    {
        base.Install(stateSaver);
    }
    private void Installer1_AfterInstall(object sender, InstallEventArgs e)
    {
        Form1 topmostForm = new Form1();
        topmostForm.BringToFront();
        topmostForm.TopMost = true;
        topmostForm.ShowDialog();
  } }
</code>```

I need to display the topmostForm in front of the default Windows Installer UI. The above is sample code inside my CustomAction that I am using to create a Form. Setting the TopMost property or using ShowDialog is not helping. Is there any other solution to make my form the top most and focussed?

答:
If you want to have complete control over installer user interface for branding or custom dialogs and don't want to use installer builder software like InstallShield then you can create a C++ application to serve as shell for Windows Installer - there is no need to implement installer actions such as copying files by yourself.

Windows Installer has API for such purpose. With function MsiSetExternalUIRecord you can provide a callback to capture installer notifications such as messages and progress updates.

ContentLicense: CC BY-SA 3.0

Body:
[RunInstaller(true)]
public partial class Installer1 : Installer
{
    public Installer1()
    {
        InitializeComponent();
    }

    public override void Install(System.Collections.IDictionary stateSaver)
    {
        base.Install(stateSaver);
    }
    private void Installer1_AfterInstall(object sender, InstallEventArgs e)
    {
        Form1 topmostForm = new Form1();
        topmostForm.BringToFront();
        topmostForm.TopMost = true;
        topmostForm.ShowDialog();
  } }

I need to display the topmostForm in front of the default Windows Installer UI. The above is sample code inside my CustomAction that I am using to create a Form. Setting the TopMost property or using ShowDialog is not helping. Is there any other solution to make my form the top most and focussed?


问:
Consuming Paginated API in React Component
I'm just getting started with React. As a simple exercise, I wanted to create some components for viewing data retrieved from the JsonMonk API. The API contains 83 user records and serves them in pages of 10.

I am trying to develop a component for viewing a list of users one page at a time which I called UserList. The code for it is below:

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

    this.state = {
      pageNumber: 1,
      users: [],
    };

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

  componentDidMount() {
    this.fetchUsers(this.state.pageNumber)
      .then((users) => this.setState({users: users}));
  }

  async fetchUsers(pageNumber) {
    const response = await fetch(`https://jsonmonk.com/api/v1/users?page=${pageNumber}`);

    const jsonResponse = await response.json();

    return jsonResponse.data.records;
  }

  onPageNext() {
    // ...
  }

  render() {
    const postElements = this.state.users.map(
      (props) => <User key={props._id} {...props} />);

    return (

        {postElements}

          <button onClick={this.onPageNext}>Next</button>

    );
  }
}
```

<p>The problem I am having pertains to the <code>onPageNext</code> method of my component. When the user clicks the "Next" button, I want to make a fetch for the next page of data and update the list.</p>

<p>My first attempt used an asynchronous arrow function passed to setState like so:</p>

<pre class="lang-js prettyprint-override"><code>  onPageNext() {
    this.setState(async (state, props) => {
      const nextPageNumber = state.pageNumber + 1;

      const users = await this.fetchUsers(nextPageNumber);

      return {pageNumber: nextPageNumber, users: users}
    })
  }
</code>```

However, it does not seem React supports this behavior because the state is never updated.

Next, I tried to use promise .then syntax like so:

  onPageNext() {
    const nextPageNumber = this.state.pageNumber + 1;

    this.fetchUsers(nextPageNumber)
      .then((users) => this.setState({pageNumber: nextPageNumber, users: users}));
  }
```

This works but the problem here is that I am accessing the class's state directly and not through setState's argument so I may receive an incorrect value. Say the user clicks the "Next" button three times quickly, they may not advance three pages.

I have essentially run into a chicken-or-the-egg type problem. I need to pass a callback to setState but I need to know the next page ID to fetch the data which requires calling setState. After studying the docs, I feel like the solution is moving the fetch logic out of the UsersList component, but I'm not entirely sure how to attack it.

As always, any help is appreciated.

答:
You need to change onPageNext as below:

```<code>onPageNext() {
        this.setState( prevState => {
            return {pageNumber: prevState.pageNumber + 1}
        }, () =>{
            this.fetchUsers(this.state.pageNumber).then(users => this.setState({users: users}) )
        });
    }
</code>```

Here is the Complete Code:

```<code>import React from "react";

export default class UserList extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            pageNumber: 1,
            users: [],
        };

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

    componentDidMount() {
        this.fetchUsers(this.state.pageNumber)
            .then((users) => {
                    console.log(users, 'users');
                    this.setState({users: users})
                }
            );
    }

    async fetchUsers(pageNumber) {
        const response = await fetch(`https://jsonmonk.com/api/v1/users?page=${pageNumber}`);

        const jsonResponse = await response.json();

        return jsonResponse.data.records;
    }

    onPageNext() {
        this.setState( prevState => {
            return {pageNumber: prevState.pageNumber + 1}
        }, () =>{
            this.fetchUsers(this.state.pageNumber).then(users => this.setState({users: users}) )
        });
    }

    render() {
        const postElements = this.state.users.map(
            (user) => <User key={user._id} {...user} />);

        return (
            <div>
                {postElements}
                <div>
                    <button onClick={this.onPageNext}>Next</button>
                </div>
            </div>
        );
    }
}

function User(props) {
    return (
        <div>
            <div style={{padding: 5}}>Name: {props.first_name} {props.last_name}</div>
            <div style={{padding: 5}}>Email: {props.email}</div>
            <div style={{padding: 5}}>Phone: {props.mobile_no}</div>
            <hr/>
        </div>
    );
}
</code>```

Here is the Code Sandbox

Body:
I'm just getting started with React. As a simple exercise, I wanted to create some components for viewing data retrieved from the JsonMonk API. The API contains 83 user records and serves them in pages of 10.

I am trying to develop a component for viewing a list of users one page at a time which I called UserList. The code for it is below:

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

    this.state = {
      pageNumber: 1,
      users: [],
    };

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

  componentDidMount() {
    this.fetchUsers(this.state.pageNumber)
      .then((users) => this.setState({users: users}));
  }

  async fetchUsers(pageNumber) {
    const response = await fetch(`https://jsonmonk.com/api/v1/users?page=${pageNumber}`);

    const jsonResponse = await response.json();

    return jsonResponse.data.records;
  }

  onPageNext() {
    // ...
  }

  render() {
    const postElements = this.state.users.map(
      (props) => <User key={props._id} {...props} />);

    return (

        {postElements}

          <button onClick={this.onPageNext}>Next</button>

    );
  }
}

The problem I am having pertains to the onPageNext method of my component. When the user clicks the "Next" button, I want to make a fetch for the next page of data and update the list.

My first attempt used an asynchronous arrow function passed to setState like so:

  onPageNext() {
    this.setState(async (state, props) => {
      const nextPageNumber = state.pageNumber + 1;

      const users = await this.fetchUsers(nextPageNumber);

      return {pageNumber: nextPageNumber, users: users}
    })
  }

However, it does not seem React supports this behavior because the state is never updated.

Next, I tried to use promise .then syntax like so:

  onPageNext() {
    const nextPageNumber = this.state.pageNumber + 1;

    this.fetchUsers(nextPageNumber)
      .then((users) => this.setState({pageNumber: nextPageNumber, users: users}));
  }

This works but the problem here is that I am accessing the class's state directly and not through setState's argument so I may receive an incorrect value. Say the user clicks the "Next" button three times quickly, they may not advance three pages.

I have essentially run into a chicken-or-the-egg type problem. I need to pass a callback to setState but I need to know the next page ID to fetch the data which requires calling setState. After studying the docs, I feel like the solution is moving the fetch logic out of the UsersList component, but I'm not entirely sure how to attack it.

As always, any help is appreciated.

Body:
You need to change onPageNext as below:

onPageNext() {
        this.setState( prevState => {
            return {pageNumber: prevState.pageNumber + 1}
        }, () =>{
            this.fetchUsers(this.state.pageNumber).then(users => this.setState({users: users}) )
        });
    }

Here is the Complete Code:

import React from "react";

export default class UserList extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            pageNumber: 1,
            users: [],
        };

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

    componentDidMount() {
        this.fetchUsers(this.state.pageNumber)
            .then((users) => {
                    console.log(users, 'users');
                    this.setState({users: users})
                }
            );
    }

    async fetchUsers(pageNumber) {
        const response = await fetch(`https://jsonmonk.com/api/v1/users?page=${pageNumber}`);

        const jsonResponse = await response.json();

        return jsonResponse.data.records;
    }

    onPageNext() {
        this.setState( prevState => {
            return {pageNumber: prevState.pageNumber + 1}
        }, () =>{
            this.fetchUsers(this.state.pageNumber).then(users => this.setState({users: users}) )
        });
    }

    render() {
        const postElements = this.state.users.map(
            (user) => <User key={user._id} {...user} />);

        return (
            <div>
                {postElements}
                <div>
                    <button onClick={this.onPageNext}>Next</button>
                </div>
            </div>
        );
    }
}

function User(props) {
    return (
        <div>
            <div style={{padding: 5}}>Name: {props.first_name} {props.last_name}</div>
            <div style={{padding: 5}}>Email: {props.email}</div>
            <div style={{padding: 5}}>Phone: {props.mobile_no}</div>
            <hr/>
        </div>
    );
}

Here is the Code Sandbox


问:
Console error in google "Uncaught TypeError: Cannot read property 'style' of null"
I have put the option to add the PWA app from various buttons on my website, but the google console gives me the error "Uncaught TypeError: Cannot read property 'style' of null".

My intention is that the PWA app can be installed from the menu, the header and at the end in the footer. The buttons work, but the error in the console persists ...

I pass the code I have in footer.php:

```<code>    <script type="text/javascript">
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register('/sw.js')
                    .then(function(registration) {
                        console.log('service worker ready');
                        registration.update();
                    })
                    .catch(function(error) {
                        console.log('Registration failed with ' + error);
                    });
            });
        }

        let deferredPrompt;
        const addBtnHeader = document.querySelector('.add-button-header');
        const addBtnMenu = document.querySelector('.add-button-menu');
        const addBtnFooter = document.querySelector('.add-button-footer');

        addBtnHeader.style.display = 'none';
        addBtnMenu.style.display = 'none';
        addBtnFooter.style.display = 'none';

        window.addEventListener('beforeinstallprompt', (e) => {
            // Prevent the mini-infobar from appearing on mobile. Evita que Chrome 67 y versiones anteriores muestren automáticamente el aviso
            e.preventDefault();
            // Guarda el evento para que pueda activarse más tarde
            deferredPrompt = e;
            // Actualizar la interfaz de usuario para notificar al usuario que puede agregar a la pantalla de inicio
            addBtnHeader.style.display = 'block';
            addBtnMenu.style.display = 'block';
            addBtnFooter.style.display = 'block';

            addBtnHeader.addEventListener('click', (e) => {
                // Oculta nuestra interfaz de usuario que muestra nuestro botón A2HS
                addBtnHeader.style.display = 'none';
                // Mostrar el aviso
                deferredPrompt.prompt();
                // Espere a que el usuario responda a la pregunta
                deferredPrompt.userChoice.then((choiceResult) => {
                    if (choiceResult.outcome === 'accepted') {
                        console.log('User accepted the A2HS prompt');
                    } else {
                        console.log('User dismissed the A2HS prompt');
                    }
                    deferredPrompt = null;
                });
            });

            addBtnMenu.addEventListener('click', (e) => {
                // Oculta nuestra interfaz de usuario que muestra nuestro botón A2HS
                addBtnMenu.style.display = 'none';
                // Mostrar el aviso
                deferredPrompt.prompt();
                // Espere a que el usuario responda a la pregunta
                deferredPrompt.userChoice.then((choiceResult) => {
                    if (choiceResult.outcome === 'accepted') {
                        console.log('User accepted the A2HS prompt');
                    } else {
                        console.log('User dismissed the A2HS prompt');
                    }
                    deferredPrompt = null;
                });
            });

            addBtnFooter.addEventListener('click', (e) => {
                // Oculta nuestra interfaz de usuario que muestra nuestro botón A2HS
                addBtnFooter.style.display = 'none';
                // Mostrar el aviso
                deferredPrompt.prompt();
                // Espere a que el usuario responda a la pregunta
                deferredPrompt.userChoice.then((choiceResult) => {
                    if (choiceResult.outcome === 'accepted') {
                        console.log('User accepted the A2HS prompt');
                    } else {
                        console.log('User dismissed the A2HS prompt');
                    }
                    deferredPrompt = null;
                });
            });

        });
    </script>
</code>```

The code of a button, the rest are similar, changing the content of class:

```<code><a style="position: fixed;bottom:117px;left: 10px;z-index:9999;" class="add-button-footer mobile-menu añadirapp" title="pulsar para añadir a tus aplicaciones" href="#" onclick="javascript:return alert('<?php echo osc_esc_js(__('LEALES.ORG EN TUS APLICACIONES<br><br>• Pulsando Añadir en el siguiente mensaje se añadirá a tus aplicaciones, para que accedas cómodamente.<br><br>• Si no se muestra el mensaje, actualiza e inténtalo nuevamente.', 'beta')); ?>')">
            <i class="fas fa-mobile-alt" href="#" style="margin-top:8px;margin-right:13px;font-size:34px;color:#F56200;"></i>
        </a>
</code>```

Thanks in advance!

This tells me to add more details, but there is not much more to add ... This tells me to add more details, but there is not much more to add ... This tells me to add more details, but there is not much more to add add ... This tells me to add more details, but not much more to add ...

答: It has been solved, the error is that the button with class = "add-button-footer" was only shown when it detected a mobile phone and when looking for it in the computer version it did not appear.</p>

Body:
I have put the option to add the PWA app from various buttons on my website, but the google console gives me the error "Uncaught TypeError: Cannot read property 'style' of null".

My intention is that the PWA app can be installed from the menu, the header and at the end in the footer. The buttons work, but the error in the console persists ...

I pass the code I have in footer.php:

The code of a button, the rest are similar, changing the content of class:

<a style="position: fixed;bottom:117px;left: 10px;z-index:9999;" class="add-button-footer mobile-menu añadirapp" title="pulsar para añadir a tus aplicaciones" href="#" onclick="javascript:return alert('<?php echo osc_esc_js(__('LEALES.ORG EN TUS APLICACIONES

• Pulsando Añadir en el siguiente mensaje se añadirá a tus aplicaciones, para que accedas cómodamente.

• Si no se muestra el mensaje, actualiza e inténtalo nuevamente.', 'beta')); ?>')">

Thanks in advance!

This tells me to add more details, but there is not much more to add ... This tells me to add more details, but there is not much more to add ... This tells me to add more details, but there is not much more to add add ... This tells me to add more details, but not much more to add ...


问:
How to use Google Apps Script setAuthentication?
So, I created an script on google sheets that, basically, selects a set of addresses on a sheet and uses Maps.newGeocoder.geocode() to get geocodes and calculate distances. It works wonderfully, no problems there. However, when I try to authenticate using Maps.setAuthentication(clientId, signingKey);, I just get an error.

I got my credentials from loging into https://console.cloud.google.com/, creating a random project and by going in "Create credentials". When I go into the credentials tab, I can select OAuth2.0 and see clientId and client secret key. I am using these to authenticate. Is it correct? What am I doing wrong? How the hell can I get the credentials? Thanks a lot!

答:
The setAuthentication(clientId, signingKey) method enables the use of an externally established Google Maps APIs Premium Plan account, to leverage additional quota allowances. Your client ID and signing key can be obtained from the Google Enterprise Support Portal.

They are not the same as client ID and client secret key as explained here.

Note that this type of account is not longer available for new customers.

Here some helpful links:

Premium Plan Support

Premium Plan FAQ


问:
C++ classes vs. C different files
Currently in a project there is a clear set of functions that pertain to a clear responsibility. Because the responsibility is a periodic process that requires buffers and counters for each iteration, I have to reset the variables used by those functions after each cycle. The variables are mostly static because per cycle the functions are called thousands of times. (It is a set of digital FIR filters that process the 5 second data that is coming in every 2 minutes or so). The variables have to be declared in the file scope, because the functions share them. E.g. the reset / initialize function and the actual filter functions.

As of now, the whole project is in C (but C++ is easily supported, as the possibly breaking parts already contain 'extern C {}'). To make the code cleaner, I thought to group the functions and variables in a separate implementation file. But of course, I could also use C++ classes, which I would like to work with more.

What are the essential differences between these options?

Simplified example of what I mean:
In this example, I just kept the structure of the program. The Filter() function is called for example 1000 times in 5 seconds for the first iteration. Then for the next iterations, the Reset() function is called prior to the actual Filter() function calls, to reset all the buffers that are used.

```<code>// File-scope variables
static float   buffer[BUFFER_SIZE];
static uint8_t bufferOffset = 0;

// Filter
static float Filter (const float sample)
{
  buffer[bufferOffset] = sample;

  // Removed actual filter code here

  return result;
}

// Reset functions
static void Reset (void)
{
  memset(buffer, 0, sizeof(buffer));
  bufferOffset = 0;
}
</code>```

答:
To declare static file scope variables is the simplest form of private encapsulation. Such design is particularly common in embedded systems and hardware-related code. It's perfectly OK practice in a single-threaded program where there is just one single instance of the module/ADT that uses the variables ("singleton pattern").

Given your simple example, this should be just fine for your specific case. The art of program design is to know when to add extra layers of abstraction and when to avoid them. It isn't easy to teach, this mostly comes with experience.

A rule of thumb for the inexperienced programmer: if you are uncertain how to make the code more abstract, then don't add that extra abstraction. It is very likely to cause more far harm than it does good.

In case the code turns more complex, the next level of abstraction is simply to split it into several related files. Or rather into several .h + .c file pairs.

The point where this turns burdensome is where you need multiple instances of the module doing the same thing. Suppose you need multiple filters using the same code, but getting called by unrelated caller code. Having one set of static variables won't work then.

The sloppy but old school way of taking such abstraction further in C is to make a struct definition visible to the caller, then provide an interface such as void fir_init (fir_t* obj); where obj is allocated on the caller-side. This solves the multiple instances problem, but breaks private encapsulation.

The professional design would rather be to use the concept of opaque types (which is explained in multiple posts elsewhere on this site), where you only expose an incomplete struct type to the caller and let your module handle the allocation. This gives true OO design - you can declare multiple instances of the object while maintaining private encapsulation.

The C++ equivalent of opaque type is class and abstract base classes behave in exactly the same manner as opaque types in C - the caller can declare a pointer/reference to one, but not declare an object. C++ also provides constructors/destructors, which is more convenient than calling some "init" function manually. But this also leads to execution overhead when static storage duration objects have their default constructors called at start-up.

Also, C++ member functions come with their this pointer, so you don't need to pass a pointer to the object along manually. You can also have static members in a class and they behave just like C file scope static, with a single instance shared between all instances.

Title: C++ classes vs. C different files

Body:
Currently in a project there is a clear set of functions that pertain to a clear responsibility. Because the responsibility is a periodic process that requires buffers and counters for each iteration, I have to reset the variables used by those functions after each cycle. The variables are mostly static because per cycle the functions are called thousands of times. (It is a set of digital FIR filters that process the 5 second data that is coming in every 2 minutes or so). The variables have to be declared in the file scope, because the functions share them. E.g. the reset / initialize function and the actual filter functions.

As of now, the whole project is in C (but C++ is easily supported, as the possibly breaking parts already contain 'extern C {}'). To make the code cleaner, I thought to group the functions and variables in a separate implementation file. But of course, I could also use C++ classes, which I would like to work with more.

What are the essential differences between these options?

Simplified example of what I mean:
In this example, I just kept the structure of the program. The Filter() function is called for example 1000 times in 5 seconds for the first iteration. Then for the next iterations, the Reset() function is called prior to the actual Filter() function calls, to reset all the buffers that are used.

// File-scope variables
static float   buffer[BUFFER_SIZE];
static uint8_t bufferOffset = 0;

// Filter
static float Filter (const float sample)
{
  buffer[bufferOffset] = sample;

  // Removed actual filter code here

  return result;
}

// Reset functions
static void Reset (void)
{
  memset(buffer, 0, sizeof(buffer));
  bufferOffset = 0;
}


问:
Rails help model design problem
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

```<code>before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end
</code>```

答:
if you always do

self.rating = 0 if ratings == 0 else (rating_score/ratings)

Title: Rails help model design problem

Body:
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end


问:
SSDT Installation fails for VS 2015
I have Microsoft Visual Studio Professional 2015 installed on my machine, i also have SQL Server 2017 installed.

I am trying to install SQL Server Development Tools for BI projects on my machine,i tried installing    'SSDT for VS2015 17.4' , 'SSDT for VS2015 17.3' and also 'SSDT for VS2015 16.5' and everything failed.

```<code>[5290:0FCC][2020-05-30T11:21:16]: Burn v3.6.3542.0, Windows v6.3 (Build 9600: Service Pack 0), path: C:\Users\honey\Downloads\SSDTSetup (3).exe, cmdline: ''
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'InstallLanguage' to value '1033'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'EnglishLanguage' to value '1033'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLINTEGRATEDSHELL' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLAS' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLRS' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLIS' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLALL' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'SKIPENVIRONMENTSETUP' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLSHORTCUT' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'TELEMETRYOPTIN' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'WixBundleLog' to value 'C:\Users\honey\AppData\Local\Temp\sql_SSDT_1400_20200530112116.log'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'WixBundleOriginalSource' to value 'C:\Users\honey\Downloads\SSDTSetup (3).exe'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'WixBundleName' to value 'Microsoft SQL Server Data Tools - Visual Studio 2015'
[5290:0FCC][2020-05-30T11:21:16]: Detect 43 packages
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'devenv_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Registry key not found. Key = 'SOFTWARE\Microsoft\DevDiv\VS\Servicing\14.0\premium'
[5290:0FCC][2020-05-30T11:21:16]: Setting numeric variable 'DEVENV_PROPLUS' to value 0
[5290:0FCC][2020-05-30T11:21:16]: Condition 'NOT DEVENV_PROPLUS' evaluates to true.
[5290:0FCC][2020-05-30T11:21:16]: Setting numeric variable 'DEVENV_PROPLUS' to value 1
[5290:0FCC][2020-05-30T11:21:16]: Condition 'NOT DEVENV_PROPLUS' evaluates to false.
[5290:0FCC][2020-05-30T11:21:16]: Condition 'NOT DEVENV_PROPLUS' evaluates to false.
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'devenvLang_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Registry key not found. Key = 'SOFTWARE\Microsoft\DevDiv\VS\Servicing\14.0\intshelladditionalres\1033'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'isoShellInstall_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'isoShellLPInstall_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'netfxfullredist_64_DetectKey' to value '4.8.03752'
</code>```

I see it says registry key not found, any clue on how to resolve this ?

答:
Please try these steps:

First, please make sure that your Internet connection is ok and your VS2015 has already installed the Sql Server workload.(you can try to check whether you can create a project called Sql Server Database Project)

Then,

1) Please check all the Windows update and install the latest patches.

2) use .Net Framework Repair Tool to repair the Net Framework's problems.

3) download this repair tool and then run it.

4) clean any caches under %temp%(C:\Users\xxx\AppData\Local\Temp) and then reboot your PC.

5) when you restart PC,  turn off any third party software, firewall, Antivirus software and then run SSDT for VS2015 as Administrator.

Besides, you can also try to create an offline installation package for VS2015.

1) Open CMD using 'Run As Administrator' option.

2) Navigate to installer location using the opened CMD/

3) Type the installer filename followed by /layout option. Like SSDT-Setup-ENU.exe /layout 'C:\layout'(the created folder)

4) then run the exe in that folder to install it.

In addition, Since your log is not full enough and if your issue still persists, you could use collect log tool to gather the installation logs. find vslogs.zip from %temp% folder. Please upload the file to Onedrive and share the link here.

Title: SSDT Installation fails for VS 2015

Body:
I have Microsoft Visual Studio Professional 2015 installed on my machine, i also have SQL Server 2017 installed.

I am trying to install SQL Server Development Tools for BI projects on my machine,i tried installing    'SSDT for VS2015 17.4' , 'SSDT for VS2015 17.3' and also 'SSDT for VS2015 16.5' and everything failed.

[5290:0FCC][2020-05-30T11:21:16]: Burn v3.6.3542.0, Windows v6.3 (Build 9600: Service Pack 0), path: C:\Users\honey\Downloads\SSDTSetup (3).exe, cmdline: ''
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'InstallLanguage' to value '1033'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'EnglishLanguage' to value '1033'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLINTEGRATEDSHELL' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLAS' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLRS' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLIS' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLALL' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'SKIPENVIRONMENTSETUP' to value '0'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'INSTALLSHORTCUT' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Initializing numeric variable 'TELEMETRYOPTIN' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'WixBundleLog' to value 'C:\Users\honey\AppData\Local\Temp\sql_SSDT_1400_20200530112116.log'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'WixBundleOriginalSource' to value 'C:\Users\honey\Downloads\SSDTSetup (3).exe'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'WixBundleName' to value 'Microsoft SQL Server Data Tools - Visual Studio 2015'
[5290:0FCC][2020-05-30T11:21:16]: Detect 43 packages
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'devenv_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Registry key not found. Key = 'SOFTWARE\Microsoft\DevDiv\VS\Servicing\14.0\premium'
[5290:0FCC][2020-05-30T11:21:16]: Setting numeric variable 'DEVENV_PROPLUS' to value 0
[5290:0FCC][2020-05-30T11:21:16]: Condition 'NOT DEVENV_PROPLUS' evaluates to true.
[5290:0FCC][2020-05-30T11:21:16]: Setting numeric variable 'DEVENV_PROPLUS' to value 1
[5290:0FCC][2020-05-30T11:21:16]: Condition 'NOT DEVENV_PROPLUS' evaluates to false.
[5290:0FCC][2020-05-30T11:21:16]: Condition 'NOT DEVENV_PROPLUS' evaluates to false.
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'devenvLang_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Registry key not found. Key = 'SOFTWARE\Microsoft\DevDiv\VS\Servicing\14.0\intshelladditionalres\1033'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'isoShellInstall_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'isoShellLPInstall_DetectKey' to value '1'
[5290:0FCC][2020-05-30T11:21:16]: Setting string variable 'netfxfullredist_64_DetectKey' to value '4.8.03752'

I see it says registry key not found, any clue on how to resolve this ?


问:
Pandas: modify multiple dataframes (in a loop)
I have multiple data frames that I want to do the same function for them. therefore I need to iterate over my frameworks.

```<code># read text files
df1 = pd.read_csv("df1.txt", sep="\t", error_bad_lines=False, index_col =None)
df2 = pd.read_csv("df2.txt", sep="\t", error_bad_lines=False, index_col =None)
df3 = pd.read_csv("df3.txt", sep="\t", error_bad_lines=False, index_col =None)
</code>```

I have used the following code, however, it is not working (it means that all dataframes are still the same, and the changes do not affect them):

```<code>for df in [df1 , df2 , df3]:
    df = df[df["Time"]>= 600.0].reset_index(drop=True)
    df.head()
</code>```

How I can iterate over them? and how can I overwrite dataframes?

答:
This might work:</p>

```<code>df_list=[df1,df2,df3]

for df in range(len(df_list)):
    df=df_list[i]
    df_list[i]=df[df["Time"]>=600.0].reset_iundex(drop=True)
</code>```

Body:
I have multiple data frames that I want to do the same function for them. therefore I need to iterate over my frameworks.

# read text files
df1 = pd.read_csv("df1.txt", sep="\t", error_bad_lines=False, index_col =None)
df2 = pd.read_csv("df2.txt", sep="\t", error_bad_lines=False, index_col =None)
df3 = pd.read_csv("df3.txt", sep="\t", error_bad_lines=False, index_col =None)

I have used the following code, however, it is not working (it means that all dataframes are still the same, and the changes do not affect them):

for df in [df1 , df2 , df3]:
    df = df[df["Time"]>= 600.0].reset_index(drop=True)
    df.head()

How I can iterate over them? and how can I overwrite dataframes?

Body:
This might work:

df_list=[df1,df2,df3]

for df in range(len(df_list)):
    df=df_list[i]
    df_list[i]=df[df["Time"]>=600.0].reset_iundex(drop=True)


问:
Different use cases and the technical difference and between MyBatis and jOOQ
From what I can tell, MyBatis and jOOQ are used for similar cases. So I was wondering when one should use jOOQ over MyBatis in a Spring application and what the technical pros and cons each library and framework brings when developing.

If someone is already proficient in writing SQL queries using a framework like MyBatis, what technical benefits (query runtime, compilation-time error) would switching over to jOOQ bring to them?

答:
Product visions

MyBatis's product vision, as I understand it, is to provide a way to implement templating on top of the SQL language, using their XML syntax. The goal is to keep SQL outside of your Java logic in external files (which can be replaced at runtime, e.g. to add hints to your queries), and to use native SQL. (jOOQ can do that as well, but it's not the most advertised feature). The advantage of using plain SQL is obviously the ability to run your SQL directly in a database client, just like with views or stored procedures as well.

jOOQ's product vision is to offer type safe, embedded, dynamic SQL by implementing SQL as a Java API, and with code generation, offering type safe access to your database schema. The point here is to make your SQL logic part of your Java logic, as this will lead to better type safety, and thus quality. Side effects of this are vendor agnosticity (your SQL will run on many dialects), and very easy dynamic SQL. If you have any of these requirements, the choice is easy.

Other features of products

The above are the main visions of the respective products, which influence the perception people have of them, but this doesn't keep either products from having additional features which may help you with your every day tasks. I don't know MyBatis well enough - it does seem to have improved a bit on their internal DSL for dynamic SQL recently, just like jOOQ can be used for occasional templating. A set of sub-products in MyBatis can be seen here.

Some lesser known jOOQ features that may or may not be of immediate use to your every day work include:

A rich set of SPIs and settings that help control the details of how your generated SQL is produced, including things like identifier qualification (useful for multi tenancy), quoting, and much more

DDL statement support

Procedural language support, to allow for running imperative logic on the server, dynamically

Support for a lot of functions

XML and JSON support, which can be very useful when exporting hierarchical data from the database

Data export and import APIs

A SQL parser (see also the translator)

A schema comparison utility (see also here)

A SQL interpreter that can be used to reverse engineer SQL scripts and introspect their meta information programmatically

(Disclaimer: I work for the company behind jOOQ)


问:
how to get parent folder name in spark?
file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/run_1/batch_id=73/part-00000-7489f493-c825-469a-9877-0b0e2c75cd4b.c000.snappy.parquet like i have many files

from this
i only want batch_id column with 73

答:
One way is to split the string by "/", after that delete the last part (".....parquet") and then kepp only the last element

```<code>def getParent(path: String) : String = {
    //split the string into an array
    val tmpList = path
      .split("/")
    //remove the last element and after that keep only the last one.
    val parent = tmpList.dropRight(1).last

    parent
}
</code>```

To apply that function on a column you can use

```<code>val getParentPath = udf((path: String) => {
     //split the string into an array
        val tmpList = path
          .split("/")
        //remove the last element and after that keep only the last one.
        val parent = tmpList.dropRight(1).last

        parent
})
val dfWithPath = oldDf.withColumn("parent_path", getParentPath($"path")
</code>```

Title: how to get parent folder name in spark?

Body:
One way is to split the string by "/", after that delete the last part (".....parquet") and then kepp only the last element

def getParent(path: String) : String = {
    //split the string into an array
    val tmpList = path
      .split("/")
    //remove the last element and after that keep only the last one.
    val parent = tmpList.dropRight(1).last

    parent
}

To apply that function on a column you can use

val getParentPath = udf((path: String) => {
     //split the string into an array
        val tmpList = path
          .split("/")
        //remove the last element and after that keep only the last one.
        val parent = tmpList.dropRight(1).last

        parent
})
val dfWithPath = oldDf.withColumn("parent_path", getParentPath($"path")


问:
Flutter Xlider - setState - value remains 0 and snaps back
This might be just a simple problem but I can't figure it out somehow right now. I am using the Flutter xslider https://pub.dev/packages/flutter_xlider vertically with values from 0 to 90. When I am dragging the slider it repaints a line depending on the value of the slider and simultaneously it changes the numeric value in a TextField. This once worked but after adding the TextField and updating all the components (Flutter. Dart. Packages. AndroidStudio) I have the following problem:

because of the line setState(() { }); in onDragging the value of the slider always remains 0 and snaps back after the dragging is finished. if I leave out the setState method the slider works however my line gets of course not painted. what am I doing wrong? does it has something to do with the surrounding components while building? or is there another reason?

UPDATE: i found the solution. I now update the values property by myself such as values: [sliderValue] whereas sliderValue is a double initialized once and then updated within the onDragging. its strange that this is never suggested inside the documentation

```<code> body: Column(
            children: [
              new Padding(
                padding: new EdgeInsets.all(15.0),
              ),
              angleTextQuestion,
              new Padding(
                child: Column(children:[ TextField(  controller: txtAngleC,
                  keyboardType: TextInputType.number,
                  onChanged: (text) {
                    double angle = double.parse(text);
                    if(angle >= 0 && angle <= 90) {
                      _angleAirplane = double.parse(text);
                      setState(() {});
                    }
                  },),
                  Text("(type in a value between 0 - 90)")
                ]),
                padding: new EdgeInsets.all(15.0),
              ),

              Expanded( child: new Row( children: [
                new Padding(
                  padding: new EdgeInsets.all(20.0),
                ),
                Expanded( child: new SizedBox(
                    height: 250,
                    width: 50,
                    child: FlutterSlider(
                values: [0],
                rangeSlider: false,
                max: 90,
                min: 0,
                rtl: true,
                step: FlutterSliderStep(step: 1.0),
                axis: Axis.vertical,
                      tooltip: FlutterSliderTooltip(
                        textStyle: TextStyle(fontSize: 14, color: Colors.lightBlue),
                      ),
                onDragging: (handlerIndex, lowerValue, upperValue) {
                  _angleAirplane = lowerValue;
                  txtAngleC.text = _angleAirplane.toString();
                  setState(() { });
                },
              ))),
                Text(_angleAirplane.toString()),
                new Padding(
                  padding: new EdgeInsets.all(10.0),
                ),
                Expanded( child: new CustomPaint(
                  foregroundPainter: new AnglePainter(
                  angle: _angleAirplane
                )))
              ]
              )),
 ]
        ),
```
```

答:
change values:[0] to this

```<code>values: [_angleAirplane]
</code>```

this happens because there is a setState inside your onDragging method and redraw the slider with 0 value.

Body:
This might be just a simple problem but I can't figure it out somehow right now. I am using the Flutter xslider https://pub.dev/packages/flutter_xlider vertically with values from 0 to 90. When I am dragging the slider it repaints a line depending on the value of the slider and simultaneously it changes the numeric value in a TextField. This once worked but after adding the TextField and updating all the components (Flutter. Dart. Packages. AndroidStudio) I have the following problem:

because of the line setState(() { }); in onDragging the value of the slider always remains 0 and snaps back after the dragging is finished. if I leave out the setState method the slider works however my line gets of course not painted. what am I doing wrong? does it has something to do with the surrounding components while building? or is there another reason?

UPDATE: i found the solution. I now update the values property by myself such as values: [sliderValue] whereas sliderValue is a double initialized once and then updated within the onDragging. its strange that this is never suggested inside the documentation

 body: Column(
            children: [
              new Padding(
                padding: new EdgeInsets.all(15.0),
              ),
              angleTextQuestion,
              new Padding(
                child: Column(children:[ TextField(  controller: txtAngleC,
                  keyboardType: TextInputType.number,
                  onChanged: (text) {
                    double angle = double.parse(text);
                    if(angle >= 0 && angle <= 90) {
                      _angleAirplane = double.parse(text);
                      setState(() {});
                    }
                  },),
                  Text("(type in a value between 0 - 90)")
                ]),
                padding: new EdgeInsets.all(15.0),
              ),

              Expanded( child: new Row( children: [
                new Padding(
                  padding: new EdgeInsets.all(20.0),
                ),
                Expanded( child: new SizedBox(
                    height: 250,
                    width: 50,
                    child: FlutterSlider(
                values: [0],
                rangeSlider: false,
                max: 90,
                min: 0,
                rtl: true,
                step: FlutterSliderStep(step: 1.0),
                axis: Axis.vertical,
                      tooltip: FlutterSliderTooltip(
                        textStyle: TextStyle(fontSize: 14, color: Colors.lightBlue),
                      ),
                onDragging: (handlerIndex, lowerValue, upperValue) {
                  _angleAirplane = lowerValue;
                  txtAngleC.text = _angleAirplane.toString();
                  setState(() { });
                },
              ))),
                Text(_angleAirplane.toString()),
                new Padding(
                  padding: new EdgeInsets.all(10.0),
                ),
                Expanded( child: new CustomPaint(
                  foregroundPainter: new AnglePainter(
                  angle: _angleAirplane
                )))
              ]
              )),
 ]
        ),
```

Body:
change values:[0] to this

values: [_angleAirplane]

this happens because there is a setState inside your onDragging method and redraw the slider with 0 value.


问:
Error com.huawei.trustspace, 11 is illLegal. I want to access TrustSpace on the security screen
I want to access TrustSpace on the security screen.

I'm using Unity and implemented login using wechat and QQ.

However, in Huawei Android 10, wechat and QQ are protected by the TrustSpace security feature.

Because of this, you cannot log in.

So, I was able to move to the security screen through android code, but not to the TrustSpace screen below.

In conclusion

Go to TrustSpace below the Security screen.

Unprotecting wechat and QQ within TrustSpace.

I want to control both of them with code, but I want to know how to do that if possible.

答:
Step one, please open Huawei mobile phone, finding the "Settings" icon,  clicking to enter the main interface.

Step two, after entering the “settings” interface, choosing the “security and privacy” button on the screen.

Step three, selecting the “Payment protection Center” option in the new interface.

Step four, choosing the option of “Payment protection Center” and switching on. That’s it.

Here is a detailed picture and text introduction:https://www.kafan.cn/edu/20052152.html


问:
Opengl proper lighting problem
I have written the following program to display a teapot on a table in a room with 2side walls and a floor.

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

void wall1(float thickness)
{
    glPushMatrix();
    glTranslatef(100,100,0);
    glRotatef(90,1,0,0);
    glScalef(thickness,1,1);
    glutSolidCube(100);
    glPopMatrix();
}
void wall2(float thickness)
{
    glPushMatrix();
    glTranslatef(150,100,-50);
    glScalef(1,1,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void floor(float thickness)
{
    glPushMatrix();
    glTranslatef(150,50,0);
    glScalef(1,thickness,1);
    glutSolidCube(100);
    glPopMatrix();
}
void leg(float thickness)
{
    glPushMatrix();
    glScalef(thickness,.5,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void tableTop(float thickess)
{
    glPushMatrix();
    glTranslatef(150,100,0);
    glScalef(.5,thickess,.5);
    glutSolidCube(100);
    glPopMatrix();
}
void table()
{
    tableTop(.05);

    glPushMatrix();
    glTranslatef(125,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(125,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(150,110,0);
    glScalef(.1,.1,.1);
    glutSolidTeapot(100);
    glPopMatrix();
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float pos[] = {200,200,0};
    float dif[] = {.3,.3,.3,3};
    float spe[] = {1,1,1,1};
    float amb[] = {1,1,1,0};
    glLightfv(GL_LIGHT0,GL_POSITION,pos);
    glLightfv(GL_LIGHT0,GL_DIFFUSE,dif);
    glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
    glLightfv(GL_LIGHT0,GL_SPECULAR,spe);

    glTranslatef(50,50,0);
    glRotatef(30,1,0,0);
    glRotatef(-30,0,1,0);
    wall1(.05);
    wall2(.05);
    floor(0.05);
    table();

    glFlush();
}
void reshape(int w,int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,400,0,400,-400,400);
    glMatrixMode(GL_MODELVIEW);
}

void main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(400,400);
    glutCreateWindow("woot");
    glClearColor(1,1,1,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glShadeModel(GL_SMOOTH);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMainLoop();
}
</code>```

The problem with this is my lighting part is not working as expected. Its not illuminating evenly all my objects... What am i missing? This making even the teapot hard to sea.
My lighting part is in display function.

答:
OpenGL fixed function pipeline lighting is evaluated at the vertices only. glutSolidCube just creates vertices at the corners and nowhere else. So your lighting is calculated only very coarse. You could either switch to per fragment lighting by using a shader, or tesselate your objects. The latter requires you don't use glutSolidCube and instead load objects modelled in a 3D modeller or write your own primitive generators that offer a higher tesselation. I strongly recommend the first option.

glutSolidCube is just a very crude stand in function BTW.

Title: Opengl proper lighting problem

Body:
I have written the following program to display a teapot on a table in a room with 2side walls and a floor.

#include <stdio.h>
#include <glut.h>

void wall1(float thickness)
{
    glPushMatrix();
    glTranslatef(100,100,0);
    glRotatef(90,1,0,0);
    glScalef(thickness,1,1);
    glutSolidCube(100);
    glPopMatrix();
}
void wall2(float thickness)
{
    glPushMatrix();
    glTranslatef(150,100,-50);
    glScalef(1,1,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void floor(float thickness)
{
    glPushMatrix();
    glTranslatef(150,50,0);
    glScalef(1,thickness,1);
    glutSolidCube(100);
    glPopMatrix();
}
void leg(float thickness)
{
    glPushMatrix();
    glScalef(thickness,.5,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void tableTop(float thickess)
{
    glPushMatrix();
    glTranslatef(150,100,0);
    glScalef(.5,thickess,.5);
    glutSolidCube(100);
    glPopMatrix();
}
void table()
{
    tableTop(.05);

    glPushMatrix();
    glTranslatef(125,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(125,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(150,110,0);
    glScalef(.1,.1,.1);
    glutSolidTeapot(100);
    glPopMatrix();
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float pos[] = {200,200,0};
    float dif[] = {.3,.3,.3,3};
    float spe[] = {1,1,1,1};
    float amb[] = {1,1,1,0};
    glLightfv(GL_LIGHT0,GL_POSITION,pos);
    glLightfv(GL_LIGHT0,GL_DIFFUSE,dif);
    glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
    glLightfv(GL_LIGHT0,GL_SPECULAR,spe);

    glTranslatef(50,50,0);
    glRotatef(30,1,0,0);
    glRotatef(-30,0,1,0);
    wall1(.05);
    wall2(.05);
    floor(0.05);
    table();

    glFlush();
}
void reshape(int w,int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,400,0,400,-400,400);
    glMatrixMode(GL_MODELVIEW);
}

void main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(400,400);
    glutCreateWindow("woot");
    glClearColor(1,1,1,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glShadeModel(GL_SMOOTH);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMainLoop();
}

The problem with this is my lighting part is not working as expected. Its not illuminating evenly all my objects... What am i missing? This making even the teapot hard to sea.
My lighting part is in display function.


问:
Serverless Nodejs Application gives Error "Unsupported Framework" when invoking
I am trying to deploy an existing node js application using serverless on AWS infrastructure.

my yaml is like :

```<code>service: todo-app-api
provider:
  name: aws
  runtime: nodejs10.x

functions:
     app:
        handler: server.run
        events:
          - http:
              path: /
              method: ANY
              cors: false
          - http:
              path: /{proxy+}
              method: ANY
              cors: false
plugins:
  - serverless-offline
</code>```

SLS deploy works fine and it creates lambda and other resources well. But when invoking that getting internal server error, when I see aws logs it gives error details as

```<code>    "errorType": "Error",
    "errorMessage": "Unsupported framework",
    "stack": [
        "Error: Unsupported framework",
        "    at getFramework (/var/task/node_modules/serverless-http/lib/framework/get-framework.js:69:9)",
        "    at module.exports (/var/task/node_modules/serverless-http/serverless-http.js:14:21)",
        "    at Object.<anonymous> (/var/task/server.js:31:22)",
        "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
        "    at Module.load (internal/modules/cjs/loader.js:653:32)",
        "    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
        "    at Module.require (internal/modules/cjs/loader.js:692:17)",
        "    at require (internal/modules/cjs/helpers.js:25:18)",
        "    at _tryRequire (/var/runtime/UserFunction.js:75:12)",
        "    at _loadUserApp (/var/runtime/UserFunction.js:95:12)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:45:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)"
    ]
}
</code>```

can somebody tell me if anything wrong I have done?

Thanks In Advance.

答:
It was actually problem at my end.
code in my server.js file was like

module.exports.run = sls(app_1);
instead of

module.exports.run = sls(app_1.default);

Also in my app.js file
exports.default = new App().app;

My code is working fine now.

Thanks

Body:
I am trying to deploy an existing node js application using serverless on AWS infrastructure.

my yaml is like :

service: todo-app-api
provider:
  name: aws
  runtime: nodejs10.x

functions:
     app:
        handler: server.run
        events:
          - http:
              path: /
              method: ANY
              cors: false
          - http:
              path: /{proxy+}
              method: ANY
              cors: false
plugins:
  - serverless-offline

SLS deploy works fine and it creates lambda and other resources well. But when invoking that getting internal server error, when I see aws logs it gives error details as

    "errorType": "Error",
    "errorMessage": "Unsupported framework",
    "stack": [
        "Error: Unsupported framework",
        "    at getFramework (/var/task/node_modules/serverless-http/lib/framework/get-framework.js:69:9)",
        "    at module.exports (/var/task/node_modules/serverless-http/serverless-http.js:14:21)",
        "    at Object.<anonymous> (/var/task/server.js:31:22)",
        "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
        "    at Module.load (internal/modules/cjs/loader.js:653:32)",
        "    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
        "    at Module.require (internal/modules/cjs/loader.js:692:17)",
        "    at require (internal/modules/cjs/helpers.js:25:18)",
        "    at _tryRequire (/var/runtime/UserFunction.js:75:12)",
        "    at _loadUserApp (/var/runtime/UserFunction.js:95:12)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:45:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)"
    ]
}

can somebody tell me if anything wrong I have done?

Thanks In Advance.


问:
Unable to use BackHandler for Perticular Screen Using react-native
I want to create Backhandler functionality for only one screen. I have more than one screen and I want to show the backhandler popup message after the user successfully login. This code works properly, but the problem is that this code is used for all screens. Just want to show popup message only on home screen. Please make any suggestions as to how I can resolve this issue.

```<code> componentDidMount() {
  BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
 }

 componentWillUnmount() {
 BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
 }
  handleBackPress = () => {
  Alert.alert(
  'Exit',
  'Do you want to Exit App?',
  [
   { text: 'Cancel', onPress: () => { return null } },
  {
    text: 'Confirm', onPress: async () => {
      BackHandler.exitApp();
    }
  },
 ],
  {
   cancelable: false
  }
  )
  return true;
};
</code>```

I am navigating the screens with the help of this code.Plese Check my code.

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();
 function App() {
 return (

 <NavigationContainer>
  <Stack.Navigator initialRouteName="AuthLoading">
    <Stack.Screen name="AuthLoading" component={AuthLoadingScreen}  options=
    {{headerShown:false}} />
    <Stack.Screen name="LOGIN" component={Login} options={{headerShown:false}} />
   <Stack.Screen name= "Register" component={Registration} options={{headerShown:false}} />
    <Stack.Screen name="Home" component={Home} options={{headerShown:false}}  />
     </Stack.Navigator>
   </NavigationContainer>
   );
  }
 export default App;
</code>```

答:
A screen is not unmounted when a new screen is pushed, so hooking on to componentWillUnmount will not work for your situation.

User React Navigation's Navigation events to listen for blur and focus events instead. - documentation

```<code>const focusUnsubscribe = navigation.addListener('focus', () => {
      BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
});

const blurUnsubscribe = navigation.addListener('blur', () => {
      BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
});
</code>```

(call focus/blur unsubscribe in componentWillUnmount)

Body:
I want to create Backhandler functionality for only one screen. I have more than one screen and I want to show the backhandler popup message after the user successfully login. This code works properly, but the problem is that this code is used for all screens. Just want to show popup message only on home screen. Please make any suggestions as to how I can resolve this issue.

 componentDidMount() {
  BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
 }

 componentWillUnmount() {
 BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
 }
  handleBackPress = () => {
  Alert.alert(
  'Exit',
  'Do you want to Exit App?',
  [
   { text: 'Cancel', onPress: () => { return null } },
  {
    text: 'Confirm', onPress: async () => {
      BackHandler.exitApp();
    }
  },
 ],
  {
   cancelable: false
  }
  )
  return true;
};

I am navigating the screens with the help of this code.Plese Check my code.

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();
 function App() {
 return (

 <NavigationContainer>
  <Stack.Navigator initialRouteName="AuthLoading">
    <Stack.Screen name="AuthLoading" component={AuthLoadingScreen}  options=
    {{headerShown:false}} />
    <Stack.Screen name="LOGIN" component={Login} options={{headerShown:false}} />
   <Stack.Screen name= "Register" component={Registration} options={{headerShown:false}} />
    <Stack.Screen name="Home" component={Home} options={{headerShown:false}}  />
     </Stack.Navigator>
   </NavigationContainer>
   );
  }
 export default App;

Body:
A screen is not unmounted when a new screen is pushed, so hooking on to componentWillUnmount will not work for your situation.

User React Navigation's Navigation events to listen for blur and focus events instead. - documentation

const focusUnsubscribe = navigation.addListener('focus', () => {
      BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
});

const blurUnsubscribe = navigation.addListener('blur', () => {
      BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
});

(call focus/blur unsubscribe in componentWillUnmount)