问:
Where does this (student) append come from

class Student:
    def __init__(self,name,age,grade): #giving the attributes
        self.name=name
        self.age=age
        self.grade=grade

    def get_grade(self):
        return self.grade

class Course:
    def __init__(self,lesson,max_student):#giving attributes
        self.lesson=lesson
        self.max_student=max_student
        self.students=[]

    def add_student(self,student):
        if len(self.students)<self.max_student:
            self.students.append(student) #append(student) from where
            #I don't get where the append(student) get the name from.
            #As above code did't use student.
            return True
        return False

s1=Student('Tim',19,95) #Naming the student
s2=Student('bill',19,75)
s3=Student('jill',19,65)

course1=Course('Math',2)
course1.add_student(s1) #Adding the Student to a list by appending
course1.add_student(s2)

print(course1.students[0].name)
#Will give Tim but how do i print them all at once
#instead of multiple print maybe like a [0:1] but got error
```

答:
The append method is part of Python. It's part of the list class, so all lists have this method (among others). Check the docs. You set self.students to an empty list in the line self.students = [].

The student variable comes from the argument to add_student, as you specified here: def add_student(self,student). So, when you call course1.add_student(s1), the s1 will be student inside the method (because for class methods, the first argument self is always the class instance itself and doesn't have to be specified in the call).


来源: stackexchange

问:
In python, why does math.floor(4.9999999999999999) == 5?
I know this is some floating point error, but I had read that python has infinite precision, so this kind of thing shouldn't happen.

Self contained runnable code:

```<code>import math
math.floor(4.9999999999999999)
</code>```

答:
It's rounded up to 5.0 before math.floor is called.

```<code>>>> 4.9999999999999999 == 5.0
True
>>> import math
>>> math.floor(5.0)
5.0
</code>```

One way to get correct behavior is using Decimal (and not using float or math at all):

```<code>>>> import decimal
>>> int(decimal.Decimal('4.99999999999999999999999999999999999999999999999999999999999999999999999'
).to_integral(rounding=decimal.ROUND_DOWN))
4
</code>```

FYI The Python float type is an IEEE 754 64-bit float, thus it can have (at most) 2**64 different values. The decimal constant 4.9999999999999999 cannot be represented exactly, so it's rounded to some other value (which happens to be the exact representation of 5.0) when Python parses the source code. Without the quotes, the float is rounded before it gets converted to Decimal:

```<code>>>> import decimal
>>> decimal.Decimal(4.9999999999999999)
Decimal('5')
>>> decimal.Decimal('4.9999999999999999')
Decimal('4.9999999999999999')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know this is some floating point error, but I had read that python has infinite precision, so this kind of thing shouldn't happen.

Self contained runnable code:

import math
math.floor(4.9999999999999999)

Body:
It's rounded up to 5.0 before math.floor is called.

>>> 4.9999999999999999 == 5.0
True
>>> import math
>>> math.floor(5.0)
5.0

One way to get correct behavior is using Decimal (and not using float or math at all):

>>> import decimal
>>> int(decimal.Decimal('4.99999999999999999999999999999999999999999999999999999999999999999999999'
).to_integral(rounding=decimal.ROUND_DOWN))
4

FYI The Python float type is an IEEE 754 64-bit float, thus it can have (at most) 2**64 different values. The decimal constant 4.9999999999999999 cannot be represented exactly, so it's rounded to some other value (which happens to be the exact representation of 5.0) when Python parses the source code. Without the quotes, the float is rounded before it gets converted to Decimal:

>>> import decimal
>>> decimal.Decimal(4.9999999999999999)
Decimal('5')
>>> decimal.Decimal('4.9999999999999999')
Decimal('4.9999999999999999')


问:
Kubernetes Ingress + Apache airflow
Can you please help me?

I'm trying to start Apache airflow in Kubernetes (AWS), in vpc.
I'm using helm stable/airflow 7.1.1

Everything starts ok. But to get access to web interface I need to expose it via ingress ELB.
I have this setup.
The rule for airflow looks like this:

```<code>apiVersion: v1
items:
- apiVersion: extensions/v1beta1
  kind: Ingress
  metadata:
    annotations:
      kubernetes.io/ingress.class: nginx
      nginx.ingress.kubernetes.io/connection-proxy-header: upgrade
      nginx.ingress.kubernetes.io/rewrite-target: /$2
    creationTimestamp: "2020-05-29T14:52:54Z"
    generation: 31
    labels:
      app.kubernetes.io/instance: airflow-dev-web
      app.kubernetes.io/managed-by: Tiller
      app.kubernetes.io/name: airflow-dev-web
      app.kubernetes.io/version: "1.0"
      helm.sh/chart: web-service-0.1.0
    name: airflow
    namespace: dev
    resourceVersion: "45272238"
    selfLink: /apis/extensions/v1beta1/namespaces/dev/ingresses/airflow
    uid: 64f276ad-b51f-4551-8078-51a7184b04b4
  spec:
    rules:
    - host: public.host.com
      http:
        paths:
        - backend:
            serviceName: airflow-dev-web
            servicePort: 8080
          path: /airflow(/|$)(.*)
  status:
    loadBalancer:
      ingress:
      - ip: <public_ip>
</code>```

I can open the /health with is OK:

https://public.host.com/airflow/health

But when I open admin web endpoint:

https://public.host.com/airflow/admin

I have many not rewritten urls - they are pointing to public.host.com but not to public.host.com/airflow/ .... Like this:

```<code>URL: https://public.host.com/admin/admin/bootstrap/bootstrap3/css/bootstrap-theme.min.css?v=3.3.5
Status: 404 Not Found
</code>```

I found that I need special setup for reverse proxy.. Like here:

https://airflow.readthedocs.io/en/stable/howto/run-behind-proxy.html

But I cannot find how to do this using Ingress.... :((

Please help me!

答:
Is not actual anymore.
Have won it using:

```<code>nginx.ingress.kubernetes.io/server-snippet: |
          proxy_set_header Host $host;
          proxy_redirect off;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
</code>```

Also it will be needed to setup in airflow:

```<code>ENABLE_PROXY_FIX: "True"
</code>```

and

```<code>baseUrl: "http://local.airflow/airflow"
</code>```

Title: Kubernetes Ingress + Apache airflow

Body:
Can you please help me?

I'm trying to start Apache airflow in Kubernetes (AWS), in vpc.
I'm using helm stable/airflow 7.1.1

Everything starts ok. But to get access to web interface I need to expose it via ingress ELB.
I have this setup.
The rule for airflow looks like this:

apiVersion: v1
items:
- apiVersion: extensions/v1beta1
  kind: Ingress
  metadata:
    annotations:
      kubernetes.io/ingress.class: nginx
      nginx.ingress.kubernetes.io/connection-proxy-header: upgrade
      nginx.ingress.kubernetes.io/rewrite-target: /$2
    creationTimestamp: "2020-05-29T14:52:54Z"
    generation: 31
    labels:
      app.kubernetes.io/instance: airflow-dev-web
      app.kubernetes.io/managed-by: Tiller
      app.kubernetes.io/name: airflow-dev-web
      app.kubernetes.io/version: "1.0"
      helm.sh/chart: web-service-0.1.0
    name: airflow
    namespace: dev
    resourceVersion: "45272238"
    selfLink: /apis/extensions/v1beta1/namespaces/dev/ingresses/airflow
    uid: 64f276ad-b51f-4551-8078-51a7184b04b4
  spec:
    rules:
    - host: public.host.com
      http:
        paths:
        - backend:
            serviceName: airflow-dev-web
            servicePort: 8080
          path: /airflow(/|$)(.*)
  status:
    loadBalancer:
      ingress:
      - ip: <public_ip>

I can open the /health with is OK:

https://public.host.com/airflow/health

But when I open admin web endpoint:

https://public.host.com/airflow/admin

I have many not rewritten urls - they are pointing to public.host.com but not to public.host.com/airflow/ .... Like this:

URL: https://public.host.com/admin/admin/bootstrap/bootstrap3/css/bootstrap-theme.min.css?v=3.3.5
Status: 404 Not Found

I found that I need special setup for reverse proxy.. Like here:

https://airflow.readthedocs.io/en/stable/howto/run-behind-proxy.html

But I cannot find how to do this using Ingress.... :((

Please help me!

Body:
Is not actual anymore.
Have won it using:

nginx.ingress.kubernetes.io/server-snippet: |
          proxy_set_header Host $host;
          proxy_redirect off;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";

Also it will be needed to setup in airflow:

ENABLE_PROXY_FIX: "True"

and

baseUrl: "http://local.airflow/airflow"


问:
Binary serialization protocol
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

```<code>class Person
{
   int age;
   string name;
};
</code>```

Java class

```<code>class Person
{
   int age;
   String name;
}
</code>```

C++ encoding

```<code>Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);
</code>```

Java decoding

```<code>byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);
</code>```

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

答: Check out Google's protocol buffers.</p>

ContentLicense: CC BY-SA 3.0

Title: Binary serialization protocol

Body:
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

class Person
{
   int age;
   string name;
};

Java class

class Person
{
   int age;
   String name;
}

C++ encoding

Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);

Java decoding

byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

Body: Check out Google's protocol buffers.


问:
JavaFx Exception in Application start method and Exception in Application start method
I have created this javaFx class to shuffle and show play cards in different angles. But Suddenly I got an error. I tried to fix it but I still couldn't able to make it work. Code explanation is given with the code below.
The program supposes to pick random png card images and display on the first row. The second row shows three joker cards in different angles. The third row shows another three different cards in 3 different angles

The code:

```<code>import java.util.ArrayList;
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

//Creating class JavaFXCardGUI which is extending Application class
//Now JavaFXCardGUI class will act as an JavaFX Application
public class JavaFXCards extends Application{

   //Overriding start method of Application class which is always a starting point of any JavaFX Application
   @Override
   public void start(Stage stage) throws Exception {

       //Creating a VBox object
       VBox vBox=new VBox();
       //Setting its spacing and padding
       vBox.setSpacing(50);
       vBox.setPadding(new Insets(20, 40, 40, 60));

       //Creating a HBox object which will store the first row cards and setting its spacing property
       HBox firstRowHBox=new HBox();
       firstRowHBox.setSpacing(50);

       //Creating a HBox object which will store the second row cards and setting its spacing property
       HBox secondRowHBox=new HBox();
       secondRowHBox.setSpacing(50);

       //Creating a HBox object which will store the third row cards and setting its spacing property
       HBox thirdRowHBox=new HBox();
       thirdRowHBox.setSpacing(50);

       //Creating a arraylist of unique 52 cards which will store the each card number
       //If that card number will be already present in the arraylist then that card will not be added
       ArrayList<Integer> lstUnique52Cards=new ArrayList<Integer>();

       //Creating a random class object
       Random random=new Random();

      //This loop will add the three cards in first row
       while(lstUnique52Cards.size()<3) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Then add the image to the firstRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               firstRowHBox.getChildren().add(imgViewCard);
           }
       }

      //This loop will add the three joker cards in second row
       //Here the uniqueness doesn't matter for the card
       for(int i=1;i<=3;i++) {
           //Below statement random.nextInt(2) will generate two random numbers 0 and 1 only as we are having
           //only two joker cards. Since two joker cards images number are 53.png and 54.png.
           //Hence adding 53 to get that correpsonding joker card number
           int randomNumber=random.nextInt(2)+53;

           //Creating ImageView object with the given card number image
           ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));

           //If the value of i is 1 i.e. it is first card then set the rotation angle as 45
           if(i==1)
               imgViewCard.setRotate(45);

           //If the value of i is 2 i.e. it is second card then set the rotation angle as 90
           if(i==2)
               imgViewCard.setRotate(90);

           //If the value of i is 3 i.e. it is third card then set the rotation angle as 135
           if(i==3)
               imgViewCard.setRotate(135);

           //Add the imgViewCard in secondRowHBox
           secondRowHBox.getChildren().add(imgViewCard);
       }

       //This loop will add the three more unique cards
       //Initializing cardNumber with 1
       int cardNumber=1;
       while(lstUnique52Cards.size()<6) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Also set the correpsonding angle to the cardNumber of this thirdRowHBox
           //Then add the image view card to the thirdRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               if(cardNumber==1)
                   imgViewCard.setRotate(135);
               if(cardNumber==2)
                   imgViewCard.setRotate(90);
               if(cardNumber==3)
                   imgViewCard.setRotate(45);
               thirdRowHBox.getChildren().add(imgViewCard);
               cardNumber++; //Increment cardNumber by 1
           }
       }

       //Add all the three HBox objects in the vBox
       vBox.getChildren().add(firstRowHBox);
       vBox.getChildren().add(secondRowHBox);
       vBox.getChildren().add(thirdRowHBox);

       //Create a scene object with the child as vBox
       Scene scene = new Scene(vBox ,450, 450);

       //Setting the stage title as Cards
       stage.setTitle("Cards");

       //Setting the scene to the stage
       stage.setScene(scene);

       //Showing the stage
       stage.show();
   }

   //Main method it will invoke start method of Application class
   public static void main(String[] args) {
       launch(args);
   }
}
</code>```

The error:

```<code>ant -f c:\Users\Desktop\Tempory\card jfxsa-run
init:
Deleting: c:\Users\Desktop\Tempory\card\build\built-jar.properties
deps-jar:
Updating property file: c:\Users\Desktop\Tempory\card\build\built-jar.properties
compile:
Detected JavaFX Ant API version 1.3
jfx-deployment:
jar:
Copying 12 files to c:\Users\Desktop\Tempory\card\dist\run395293642
jfx-project-run:
Executing c:\Users\Desktop\Tempory\card\dist\run395293642\JavaFXCards.jar using platform C:\Program Files\Java\jdk1.8.0_221\jre/bin/java
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
    at javafx.scene.image.Image.validateUrl(Image.java:1121)
    at javafx.scene.image.Image.<init>(Image.java:620)
    at JavaFXCardGUI.start(JavaFXCardGUI.java:58)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$3(WinApplication.java:177)
    ... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:607)
    at java.net.URL.<init>(URL.java:497)
    at java.net.URL.<init>(URL.java:446)
    at javafx.scene.image.Image.validateUrl(Image.java:1115)
    ... 11 more
Exception running application JavaFXCardGUI
Java Result: 1
Deleting directory c:\Users\Desktop\Tempory\card\dist\run395293642
jfxsa-run:
BUILD SUCCESSFUL (total time: 2 seconds)
</code>```

答:
The file protocol in front of the image file paths is missing:</p>

```<code>ImageView imgViewCard=new ImageView(new Image("file:\\\c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
</code>```

Body:
I have created this javaFx class to shuffle and show play cards in different angles. But Suddenly I got an error. I tried to fix it but I still couldn't able to make it work. Code explanation is given with the code below.
The program supposes to pick random png card images and display on the first row. The second row shows three joker cards in different angles. The third row shows another three different cards in 3 different angles

The code:

import java.util.ArrayList;
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

//Creating class JavaFXCardGUI which is extending Application class
//Now JavaFXCardGUI class will act as an JavaFX Application
public class JavaFXCards extends Application{

   //Overriding start method of Application class which is always a starting point of any JavaFX Application
   @Override
   public void start(Stage stage) throws Exception {

       //Creating a VBox object
       VBox vBox=new VBox();
       //Setting its spacing and padding
       vBox.setSpacing(50);
       vBox.setPadding(new Insets(20, 40, 40, 60));

       //Creating a HBox object which will store the first row cards and setting its spacing property
       HBox firstRowHBox=new HBox();
       firstRowHBox.setSpacing(50);

       //Creating a HBox object which will store the second row cards and setting its spacing property
       HBox secondRowHBox=new HBox();
       secondRowHBox.setSpacing(50);

       //Creating a HBox object which will store the third row cards and setting its spacing property
       HBox thirdRowHBox=new HBox();
       thirdRowHBox.setSpacing(50);

       //Creating a arraylist of unique 52 cards which will store the each card number
       //If that card number will be already present in the arraylist then that card will not be added
       ArrayList<Integer> lstUnique52Cards=new ArrayList<Integer>();

       //Creating a random class object
       Random random=new Random();

      //This loop will add the three cards in first row
       while(lstUnique52Cards.size()<3) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Then add the image to the firstRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               firstRowHBox.getChildren().add(imgViewCard);
           }
       }

      //This loop will add the three joker cards in second row
       //Here the uniqueness doesn't matter for the card
       for(int i=1;i<=3;i++) {
           //Below statement random.nextInt(2) will generate two random numbers 0 and 1 only as we are having
           //only two joker cards. Since two joker cards images number are 53.png and 54.png.
           //Hence adding 53 to get that correpsonding joker card number
           int randomNumber=random.nextInt(2)+53;

           //Creating ImageView object with the given card number image
           ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));

           //If the value of i is 1 i.e. it is first card then set the rotation angle as 45
           if(i==1)
               imgViewCard.setRotate(45);

           //If the value of i is 2 i.e. it is second card then set the rotation angle as 90
           if(i==2)
               imgViewCard.setRotate(90);

           //If the value of i is 3 i.e. it is third card then set the rotation angle as 135
           if(i==3)
               imgViewCard.setRotate(135);

           //Add the imgViewCard in secondRowHBox
           secondRowHBox.getChildren().add(imgViewCard);
       }

       //This loop will add the three more unique cards
       //Initializing cardNumber with 1
       int cardNumber=1;
       while(lstUnique52Cards.size()<6) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Also set the correpsonding angle to the cardNumber of this thirdRowHBox
           //Then add the image view card to the thirdRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               if(cardNumber==1)
                   imgViewCard.setRotate(135);
               if(cardNumber==2)
                   imgViewCard.setRotate(90);
               if(cardNumber==3)
                   imgViewCard.setRotate(45);
               thirdRowHBox.getChildren().add(imgViewCard);
               cardNumber++; //Increment cardNumber by 1
           }
       }

       //Add all the three HBox objects in the vBox
       vBox.getChildren().add(firstRowHBox);
       vBox.getChildren().add(secondRowHBox);
       vBox.getChildren().add(thirdRowHBox);

       //Create a scene object with the child as vBox
       Scene scene = new Scene(vBox ,450, 450);

       //Setting the stage title as Cards
       stage.setTitle("Cards");

       //Setting the scene to the stage
       stage.setScene(scene);

       //Showing the stage
       stage.show();
   }

   //Main method it will invoke start method of Application class
   public static void main(String[] args) {
       launch(args);
   }
}

The error:

ant -f c:\Users\Desktop\Tempory\card jfxsa-run
init:
Deleting: c:\Users\Desktop\Tempory\card\build\built-jar.properties
deps-jar:
Updating property file: c:\Users\Desktop\Tempory\card\build\built-jar.properties
compile:
Detected JavaFX Ant API version 1.3
jfx-deployment:
jar:
Copying 12 files to c:\Users\Desktop\Tempory\card\dist\run395293642
jfx-project-run:
Executing c:\Users\Desktop\Tempory\card\dist\run395293642\JavaFXCards.jar using platform C:\Program Files\Java\jdk1.8.0_221\jre/bin/java
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
    at javafx.scene.image.Image.validateUrl(Image.java:1121)
    at javafx.scene.image.Image.<init>(Image.java:620)
    at JavaFXCardGUI.start(JavaFXCardGUI.java:58)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$3(WinApplication.java:177)
    ... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:607)
    at java.net.URL.<init>(URL.java:497)
    at java.net.URL.<init>(URL.java:446)
    at javafx.scene.image.Image.validateUrl(Image.java:1115)
    ... 11 more
Exception running application JavaFXCardGUI
Java Result: 1
Deleting directory c:\Users\Desktop\Tempory\card\dist\run395293642
jfxsa-run:
BUILD SUCCESSFUL (total time: 2 seconds)

Body:
The file protocol in front of the image file paths is missing:

ImageView imgViewCard=new ImageView(new Image("file:\\\c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));


问:
Populate DefaultTableModel from test file
I have this text file:

```<code>A
B
3.00

A
B
3.00
</code>```

and my view is:

I want to match each row with each column(first_row-first_column,second_row-second_column, etc..) Where have I made a mistake?
My code is as follows:

```<code>    BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
</code>```

答: Your counter is incrementing at the begining of loop, so you never have 0 but 1 on if statement. Then empty line is parsed as 1 and goes to A column. You can solve it in multpile ways like skip empty lines or increment counter if line is not empty.</p>

Body:
I have this text file:

A
B
3.00

A
B
3.00

and my view is:

I want to match each row with each column(first_row-first_column,second_row-second_column, etc..) Where have I made a mistake?
My code is as follows:

    BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}


问:
Netbeans - storing GUI components made with GUI Builder in an array
Say I have n numbered components, e.g. n jPanels called panel1, panel2, ..., paneln, that were created using Netbeans' GUI Builder. As far as I'm aware the GUI Builder doesn't allow me to store components in an array when creating them, which means if I wanted to modify them during execution I'd have to do something like

```<code>jPanel[] panels = new jPanel[n];
panels[1] = panel1;
panels[2] = panel2;
.
.
.
panels[n] = paneln;

for(int i = 0; i < n; i++) {
    //Do stuff with panels[i]
}
</code>```

Is there some other way to do this without having to drop the Builder and create the interface from scratch?

答:
Add this in your code:

```<code>List<JPanel> myPanels = new ArrayList<>();
private JPanel getNewPanel()
{
    JPanel panel=new JPanel();
    myPanels.add(panel);
    return panel;
}
</code>```

Then in the Netbeans GUI builder:

Using ctrl-click select all the panels you want to access via
myPanels

In the Code tab of the Properties window, set the Custom Creation Code to: getNewPanel();

Body:
Say I have n numbered components, e.g. n jPanels called panel1, panel2, ..., paneln, that were created using Netbeans' GUI Builder. As far as I'm aware the GUI Builder doesn't allow me to store components in an array when creating them, which means if I wanted to modify them during execution I'd have to do something like

jPanel[] panels = new jPanel[n];
panels[1] = panel1;
panels[2] = panel2;
.
.
.
panels[n] = paneln;

for(int i = 0; i < n; i++) {
    //Do stuff with panels[i]
}

Is there some other way to do this without having to drop the Builder and create the interface from scratch?

Body:
Add this in your code:

List<JPanel> myPanels = new ArrayList<>();
private JPanel getNewPanel()
{
    JPanel panel=new JPanel();
    myPanels.add(panel);
    return panel;
}

Then in the Netbeans GUI builder:

Using ctrl-click select all the panels you want to access via
myPanels

In the Code tab of the Properties window, set the Custom Creation Code to: getNewPanel();


问:
Write JSON string into a JSON file in a proper format without using inbuilt methods or third party libraries
I have a text file which contains Data and another text file that contains data fields. I am able to read in the the data and data fields into separate array

I have managed to convert it into JsonFormat. But when I am writing it in the json file it is not coming properly formatted ike a json data would. How would it come into a proper format? Also I don't want to use serialization or third party libs.

My input data file contains 102 lines where 1st and last can be ignored. Each line corresponds to one record. So it has around 100 records. Each record has 150 fields seperated by |.

Sample record:

928338219||3HY83||A|Z5|20030917|20160629|20150630|20150630|FEDERAL HIGHWAY ADMINISTRATION||OFFICE OF ACQUISITIION AND GRANTS MANAGEMENT||1200 NEW JERSEY AVE SE||WASHINGTON|DC|20590|0001|USA|98|19720101|0930||2A|||0003|2R~NG~VW|926120|0001|926120N|0000||||1200 NEW JERSEY AVENUE, SE|ROOM E65-101|WASHINGTON|20590|0001|USA|DC|FRANK WALTOS||WALTOS||1200 NEW JERSEY AVENUE, SE|ROOM E65-312|WASHINGTON|20590|0001|USA|DC|2023664205|||2023663705|Frank.Waltos@dot.gov|FRANK||WALTOS||1200 NEW JERSEY AVENUE SE|ROOM E65-312|WASHINGTON|20590|0001|USA|DC|2023664205|||2023663705|Frank.Waltos@dot.gov|||||||||||||||||||||||||||||||||FRANK||WALTOS||1200 NEW JERSEY AVENUE SE|ROOM E65-312|WASHINGTON|20590|0001|USA|DC|2023664205|||2023663705|Frank.Waltos@dot.gov|JASON||JOHNSON||1200 NEW JERSEY AVENUE SE||WASHINGTON|20590|0001|USA|DC|2023665880|||2023663705|jason.johnson@dot.gov|0000||N||0000|||0000||!end

The DataFields file contains the 150 fields

sample:

DUNS

DUNS+4

CAGE CODE

DODAAC

SAM EXTRACT CODE

PURPOSE OF REGISTRATION

REGISTRATION DATE
EXPIRATION DATE

I am expecting the records to be written something like this

```<code> {
  "DUNS": "070815200",
  "DUNS+4": "",
  "CAGE CODE": "7HEG5",
  "DODAAC": "",
  "SAM EXTRACT CODE": "A",
  "PURPOSE OF REGISTRATION": "Z2",
  "REGISTRATION DATE": "20151113",
  "EXPIRATION DATE": "20161112",
  "LAST UPDATE DATE": "20151123"
 }
</code>```

right now they are getting written without any formatting like this

{"DataFile1" :[{"DUNS":"928338219","DUNS+4":""}.

I have checked my JSON string in Jsonlint and it is a valid JSON

```<code>public void convertToJSONsyntax( string [] data, string [] dataFields)
    {
  string[] splitData = new string[150];
        var JSONSyntaxString = "{\"DataFile1\" :[";
        //var json = JsonConvert.DeserializeObject(JSONSyntaxString);
        for (int i=0;i<data.Length; i++)
        {
            JSONSyntaxString += "{";
            splitData = data[i].Split('|');
            for(int j = 0; j < dataFields.Length; j++)
            {
                if (j == dataFields.Length - 1)
                {
                    JSONSyntaxString += "\"" + dataFields[j] + "\":\"" + splitData[j] + "\"";
                }
                else
                {
                    JSONSyntaxString += "\"" + dataFields[j] + "\":\"" + splitData[j] + "\",";
                }
            }
            if (i == data.Length - 1)
            {
                JSONSyntaxString += "}";
            }
            else
            {
                JSONSyntaxString += "},";
            }
        }
        JSONSyntaxString = JSONSyntaxString + "]}";
        File.WriteAllText("C:\\OutputData.json", JSONSyntaxString);
</code>```

答:
:) Okay, so when you write text to a file. And you wish it to display with text formatting you have to keep track of the formatting itself.

Let us say you have a tab indent, you would like to apply? Or a newline?

You have to write that into the text formatting.

Something like this:

```<code> string[] splitData = new string[150];
            var JSONSyntaxString = "{\"\tDataFile1\" :[\r\n";

            for (int i = 0; i < data.Length; i++)
            {
                JSONSyntaxString += "\t\t{\r\n";
                splitData = data[i].Split('|');
                for (int j = 0; j < dataFields.Length; j++)
                {
                    if (j == dataFields.Length - 1)
                    {
                        JSONSyntaxString += "\t\t\t\"" + dataFields[j] + "\":\"" + splitData[j] + "\"";
                    }
                    else
                    {
                        JSONSyntaxString += "\t\t\t\"" + dataFields[j] + "\":\"" + splitData[j] + "\",\r\n";
                    }
                }
                if (i == data.Length - 1)
                {
                    JSONSyntaxString += "\r\n\t\t}\r\n";
                }
                else
                {
                    JSONSyntaxString += "\r\n\t\t},\r\n";
                }
            }
            JSONSyntaxString = JSONSyntaxString + "]}";
            File.WriteAllText("E:\\Test\\OutputData.json", JSONSyntaxString);
</code>```

\t = tab

\r\n = Newline.

With my improptu test data that gave me this result:

```<code>{"  DataFile1" :[
        {
            "Key":"SomeValueForKey",
            "Key2":"SomeValueForKey2"
        },
        {
            "Key":"SomeValueForKeyForAnotherItem",
            "Key2":"SomeOtherValueForAnotherItem2"
        }
]}
</code>```

I hope that this is enough help to get you over the finishline yourself :)

Body:
I have a text file which contains Data and another text file that contains data fields. I am able to read in the the data and data fields into separate array

I have managed to convert it into JsonFormat. But when I am writing it in the json file it is not coming properly formatted ike a json data would. How would it come into a proper format? Also I don't want to use serialization or third party libs.

My input data file contains 102 lines where 1st and last can be ignored. Each line corresponds to one record. So it has around 100 records. Each record has 150 fields seperated by |.

Sample record:

928338219||3HY83||A|Z5|20030917|20160629|20150630|20150630|FEDERAL HIGHWAY ADMINISTRATION||OFFICE OF ACQUISITIION AND GRANTS MANAGEMENT||1200 NEW JERSEY AVE SE||WASHINGTON|DC|20590|0001|USA|98|19720101|0930||2A|||0003|2R~NG~VW|926120|0001|926120N|0000||||1200 NEW JERSEY AVENUE, SE|ROOM E65-101|WASHINGTON|20590|0001|USA|DC|FRANK WALTOS||WALTOS||1200 NEW JERSEY AVENUE, SE|ROOM E65-312|WASHINGTON|20590|0001|USA|DC|2023664205|||2023663705|Frank.Waltos@dot.gov|FRANK||WALTOS||1200 NEW JERSEY AVENUE SE|ROOM E65-312|WASHINGTON|20590|0001|USA|DC|2023664205|||2023663705|Frank.Waltos@dot.gov|||||||||||||||||||||||||||||||||FRANK||WALTOS||1200 NEW JERSEY AVENUE SE|ROOM E65-312|WASHINGTON|20590|0001|USA|DC|2023664205|||2023663705|Frank.Waltos@dot.gov|JASON||JOHNSON||1200 NEW JERSEY AVENUE SE||WASHINGTON|20590|0001|USA|DC|2023665880|||2023663705|jason.johnson@dot.gov|0000||N||0000|||0000||!end

The DataFields file contains the 150 fields

sample:

DUNS

DUNS+4

CAGE CODE

DODAAC

SAM EXTRACT CODE

PURPOSE OF REGISTRATION

REGISTRATION DATE
EXPIRATION DATE

I am expecting the records to be written something like this

 {
  "DUNS": "070815200",
  "DUNS+4": "",
  "CAGE CODE": "7HEG5",
  "DODAAC": "",
  "SAM EXTRACT CODE": "A",
  "PURPOSE OF REGISTRATION": "Z2",
  "REGISTRATION DATE": "20151113",
  "EXPIRATION DATE": "20161112",
  "LAST UPDATE DATE": "20151123"
 }

right now they are getting written without any formatting like this

{"DataFile1" :[{"DUNS":"928338219","DUNS+4":""}.

I have checked my JSON string in Jsonlint and it is a valid JSON

public void convertToJSONsyntax( string [] data, string [] dataFields)
    {
  string[] splitData = new string[150];
        var JSONSyntaxString = "{\"DataFile1\" :[";
        //var json = JsonConvert.DeserializeObject(JSONSyntaxString);
        for (int i=0;i<data.Length; i++)
        {
            JSONSyntaxString += "{";
            splitData = data[i].Split('|');
            for(int j = 0; j < dataFields.Length; j++)
            {
                if (j == dataFields.Length - 1)
                {
                    JSONSyntaxString += "\"" + dataFields[j] + "\":\"" + splitData[j] + "\"";
                }
                else
                {
                    JSONSyntaxString += "\"" + dataFields[j] + "\":\"" + splitData[j] + "\",";
                }
            }
            if (i == data.Length - 1)
            {
                JSONSyntaxString += "}";
            }
            else
            {
                JSONSyntaxString += "},";
            }
        }
        JSONSyntaxString = JSONSyntaxString + "]}";
        File.WriteAllText("C:\\OutputData.json", JSONSyntaxString);

Body:
:) Okay, so when you write text to a file. And you wish it to display with text formatting you have to keep track of the formatting itself.

Let us say you have a tab indent, you would like to apply? Or a newline?

You have to write that into the text formatting.

Something like this:

 string[] splitData = new string[150];
            var JSONSyntaxString = "{\"\tDataFile1\" :[\r\n";

            for (int i = 0; i < data.Length; i++)
            {
                JSONSyntaxString += "\t\t{\r\n";
                splitData = data[i].Split('|');
                for (int j = 0; j < dataFields.Length; j++)
                {
                    if (j == dataFields.Length - 1)
                    {
                        JSONSyntaxString += "\t\t\t\"" + dataFields[j] + "\":\"" + splitData[j] + "\"";
                    }
                    else
                    {
                        JSONSyntaxString += "\t\t\t\"" + dataFields[j] + "\":\"" + splitData[j] + "\",\r\n";
                    }
                }
                if (i == data.Length - 1)
                {
                    JSONSyntaxString += "\r\n\t\t}\r\n";
                }
                else
                {
                    JSONSyntaxString += "\r\n\t\t},\r\n";
                }
            }
            JSONSyntaxString = JSONSyntaxString + "]}";
            File.WriteAllText("E:\\Test\\OutputData.json", JSONSyntaxString);

\t = tab

\r\n = Newline.

With my improptu test data that gave me this result:

{"  DataFile1" :[
        {
            "Key":"SomeValueForKey",
            "Key2":"SomeValueForKey2"
        },
        {
            "Key":"SomeValueForKeyForAnotherItem",
            "Key2":"SomeOtherValueForAnotherItem2"
        }
]}

I hope that this is enough help to get you over the finishline yourself :)


问:
Recursion error when using the @property and @setter decorators
```<code>class Phone:
    def __init__(self,brand,model_name,price):
        self.brand = brand
        self.model_name = model_name
        self.price = price
    @property
    def price(self):
        return self.price
    @price.setter
    def price(self,new_value):
        self.price = max(new_value,0)

p1 = Phone('Asus','Asus10',102000)
print(p1.price)
</code>```

Error :

RecursionError: maximum recursion depth exceeded

答:
The property name and the field names are the same. Adding an underscore before the field name can fix it.</p>

```<code>class Phone:
    def __init__(self,brand,model_name,price):
        self.brand = brand
        self.model_name = model_name
        self._price = price
    @property
    def price(self):
        return self._price
    @price.setter
    def price(self,new_value):
        self._price = max(new_value,0)

p1 = Phone('Asus','Asus10',102000)
print(p1.price)
</code>```

Body:
class Phone:
    def __init__(self,brand,model_name,price):
        self.brand = brand
        self.model_name = model_name
        self.price = price
    @property
    def price(self):
        return self.price
    @price.setter
    def price(self,new_value):
        self.price = max(new_value,0)

p1 = Phone('Asus','Asus10',102000)
print(p1.price)

Error :

RecursionError: maximum recursion depth exceeded

Body:
The property name and the field names are the same. Adding an underscore before the field name can fix it.

class Phone:
    def __init__(self,brand,model_name,price):
        self.brand = brand
        self.model_name = model_name
        self._price = price
    @property
    def price(self):
        return self._price
    @price.setter
    def price(self,new_value):
        self._price = max(new_value,0)

p1 = Phone('Asus','Asus10',102000)
print(p1.price)


问:
Threadpooling hangs the web page
I am generating 1000's of PDFs from crystal report. Generating PDF one by one(sequentially) takes time which degrades performance. To improve performance i am using ThreadPooling which is generating PDFs much faster way but when the PDF generation completes. My webpage controls dont fire events i.e i have a radio button(autopostback=true) so i should fire an event when onchange event occurs but i dont understand whats going wrong it doesnt raise the event? Am i using threadpool in asp.net wrong way or is there any other class available which works same as threadpool?</p>

```<code>dynamic obj = new { strvalue = strvalue, SimulActual = SimulActual, IsCrewRPT = IsCrewRPT, rowcount = rowcount, FileName = FileName, RankP = RankP, RankCDP = RankCDP, intRowNo = intRowNo, rpt = rpt, ToYear = ToYear, Cdc_no = Cdc_no, TotalPDF = TotalPDF, TotalRowcount1 = TotalRowcount1 };
                    ThreadPool.QueueUserWorkItem(new WaitCallback(PDFActualOffThreadWithPanCard), obj);
                    ThreadPool.SetMaxThreads(10, 5);

                    obj = null;
</code>```

答:
You should not rely on the thread pool in ASP.NET.  There are a number of reasons for this.  The main one is that ASP.NET can, and will, recycle the application pool servicing your page at any time, including between page requests, while your PDFs are generating.  If that happens, your PDF generation will stop midway through.

The proper way to solve this problem is to offload the PDF generation request to something that is more controllable, usually a windows service (which can run on the same machine).  A common technique is to use MSMQ or another persistent, transactional queue mechanism to control communication between the web server and a pool of PDF generator instances, potentially on multiple machines.

As for the problem of the postback, I think you need to provide a little more information about what is going on there for us to help you.

Title: Threadpooling hangs the web page

Body:
I am generating 1000's of PDFs from crystal report. Generating PDF one by one(sequentially) takes time which degrades performance. To improve performance i am using ThreadPooling which is generating PDFs much faster way but when the PDF generation completes. My webpage controls dont fire events i.e i have a radio button(autopostback=true) so i should fire an event when onchange event occurs but i dont understand whats going wrong it doesnt raise the event? Am i using threadpool in asp.net wrong way or is there any other class available which works same as threadpool?

dynamic obj = new { strvalue = strvalue, SimulActual = SimulActual, IsCrewRPT = IsCrewRPT, rowcount = rowcount, FileName = FileName, RankP = RankP, RankCDP = RankCDP, intRowNo = intRowNo, rpt = rpt, ToYear = ToYear, Cdc_no = Cdc_no, TotalPDF = TotalPDF, TotalRowcount1 = TotalRowcount1 };
                    ThreadPool.QueueUserWorkItem(new WaitCallback(PDFActualOffThreadWithPanCard), obj);
                    ThreadPool.SetMaxThreads(10, 5);

                    obj = null;


问:
How to design dialog to have Checkboxes and one EditText box?
I'm trying to design the dialog xml file. It's a bit hard to follow the Material Design guidelines. Basically I want the dialog window to allow users to multi-check the checkboxes and on the bottom to have an option to add custom option (one EditText). For example:

```<code>Choose the options

[x] Option1
[] Option2
[x] Option3
[] Option4

Add custom options:
__________

       [Cancel] [Ok]
</code>```

The code I have:

```<code>public void onClick(View view) {
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(AddData.this);
    View mView = getLayoutInflater().inflate(R.layout.dialog_adding_data,null);
    // More code here
    mBuilder.show();
}
</code>```

As I understand I'm using a custom dialog layout. But in the material design guidelines I didn't see an option to do something like that. Also I'm not sure how to to design the dialog_adding_data file. How can I design the dialog_adding_data so it will follow the material design guidelines and have the same functionality?

答:
To achieve your UI requirements, you need to set a custom view to your dialog. The key point here is to use the following:

```<code>mBuilder.setView(mView);
</code>```

If you are not using view/data binding, when referencing the views, make sure to use mView.findViewById and not findViewById like the following:

```<code>EditText editText = mView.findViewById(R.id.edit_text);
// Add your code logic, etc.
</code>```

Concerning dialog_adding_data.xml that you have created, it will simply be like any other layout. Its hierarchy, depending on your exact needs, may look something like this:

```<code><ScrollView>

    <LinearLayout>

        <CheckBox />

        <CheckBox />

        <!-- This one controls the EditText below. -->
        <CheckBox android:text="Add custom options" />

        <EditText />

    </LinearLayout>

</ScrollView>
</code>```

If the check boxes count are dynamic, then you might need to use a RecyclerView with 2 view types (one for a normal option, and the other for the custom options) instead.

Body:
I'm trying to design the dialog xml file. It's a bit hard to follow the Material Design guidelines. Basically I want the dialog window to allow users to multi-check the checkboxes and on the bottom to have an option to add custom option (one EditText). For example:

Choose the options

[x] Option1
[] Option2
[x] Option3
[] Option4

Add custom options:
__________

       [Cancel] [Ok]

The code I have:

public void onClick(View view) {
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(AddData.this);
    View mView = getLayoutInflater().inflate(R.layout.dialog_adding_data,null);
    // More code here
    mBuilder.show();
}

As I understand I'm using a custom dialog layout. But in the material design guidelines I didn't see an option to do something like that. Also I'm not sure how to to design the dialog_adding_data file. How can I design the dialog_adding_data so it will follow the material design guidelines and have the same functionality?

Body:
To achieve your UI requirements, you need to set a custom view to your dialog. The key point here is to use the following:

mBuilder.setView(mView);

If you are not using view/data binding, when referencing the views, make sure to use mView.findViewById and not findViewById like the following:

EditText editText = mView.findViewById(R.id.edit_text);
// Add your code logic, etc.

Concerning dialog_adding_data.xml that you have created, it will simply be like any other layout. Its hierarchy, depending on your exact needs, may look something like this:

<ScrollView>

    <LinearLayout>

        <CheckBox />

        <CheckBox />

        <!-- This one controls the EditText below. -->
        <CheckBox android:text="Add custom options" />

        <EditText />

    </LinearLayout>

</ScrollView>

If the check boxes count are dynamic, then you might need to use a RecyclerView with 2 view types (one for a normal option, and the other for the custom options) instead.


问:
Why does fseek from SEEK_CUR use random character for space?
Having this:

```<code>int main (void) {

    FILE *fp = fopen("txt2", "r+");

    rewind(fp);
    fprintf(fp, "ab");
    fseek(fp,1L,SEEK_CUR); //trying to change offset to 1,2,3,...
    fprintf(fp, "cd");
    rewind(fp);

    for(int c;(c=getc(fp))!=EOF;)
        putchar(c);

    fclose(fp);

    return 0;
}
</code>```

I want to know, If fseek from current position offsets forward with spaces or some garbage. I will gives output with ^ in places, where should be space.

```<code>fseek(fp,0L,SEEK_CUR)
->  abcd //yes, that is what I expect

fseek(fp,1L,SEEK_CUR)
-> abccd //not space -> 'c' char instead
     ^

fseek(fp,2L,SEEK_CUR)
-> abcdcd //'cd' are in addition (random chars?)
     ^^

fseek(fp,3L,SEEK_CUR)
-> abcdccd //'cdc' no it is probably not "random", they repeat
     ^^^

fseek(fp,100000000000L,SEEK_CUR)
-> abcdcdcdcdcdcdcdcdcd

fseek(fp,1000000000000000000000000L,SEEK_CUR0
->warning: integer constant is too large for its type
fseek(fp,1000000000000000000000000L,SEEK_CUR);
</code>```

What is going on with fseek moving? They are pattern on which the "moved char" will be made? In this case according to the next printf chars? (cd). I do not really understand this behaviour and how to move by spaces with fseek? I only know to use rewind before and after every writing in order to perform correct read (in for loop), but that does not explain the behaviour. Can someone give a hint?

答:
here is what is actually happening:</p>

```<code>FILE *fp = fopen("txt2", "r+");
// need to check (!=NULL) to assure `fopen()` was successful

rewind(fp);
// `fopen()` places current position in file at beginning, so this call not needed

fprintf(fp, "ab");
// current position now ==2 (starts at 0)

fseek(fp,1L,SEEK_CUR); //trying to change offset to 1,2,3,...
// current position now at 3 I.E. "ab?"

fprintf(fp, "cd");
// current position now == 5 I.E. "ab?cd"

the value, at the '?' is what ever happened to be on the disk at (current position =2) position in the file
</code>```

Body:
Having this:

int main (void) {

    FILE *fp = fopen("txt2", "r+");

    rewind(fp);
    fprintf(fp, "ab");
    fseek(fp,1L,SEEK_CUR); //trying to change offset to 1,2,3,...
    fprintf(fp, "cd");
    rewind(fp);

    for(int c;(c=getc(fp))!=EOF;)
        putchar(c);

    fclose(fp);

    return 0;
}

I want to know, If fseek from current position offsets forward with spaces or some garbage. I will gives output with ^ in places, where should be space.

fseek(fp,0L,SEEK_CUR)
->  abcd //yes, that is what I expect

fseek(fp,1L,SEEK_CUR)
-> abccd //not space -> 'c' char instead
     ^

fseek(fp,2L,SEEK_CUR)
-> abcdcd //'cd' are in addition (random chars?)
     ^^

fseek(fp,3L,SEEK_CUR)
-> abcdccd //'cdc' no it is probably not "random", they repeat
     ^^^

fseek(fp,100000000000L,SEEK_CUR)
-> abcdcdcdcdcdcdcdcdcd

fseek(fp,1000000000000000000000000L,SEEK_CUR0
->warning: integer constant is too large for its type
fseek(fp,1000000000000000000000000L,SEEK_CUR);

What is going on with fseek moving? They are pattern on which the "moved char" will be made? In this case according to the next printf chars? (cd). I do not really understand this behaviour and how to move by spaces with fseek? I only know to use rewind before and after every writing in order to perform correct read (in for loop), but that does not explain the behaviour. Can someone give a hint?

Body:
here is what is actually happening:

FILE *fp = fopen("txt2", "r+");
// need to check (!=NULL) to assure `fopen()` was successful

rewind(fp);
// `fopen()` places current position in file at beginning, so this call not needed

fprintf(fp, "ab");
// current position now ==2 (starts at 0)

fseek(fp,1L,SEEK_CUR); //trying to change offset to 1,2,3,...
// current position now at 3 I.E. "ab?"

fprintf(fp, "cd");
// current position now == 5 I.E. "ab?cd"

the value, at the '?' is what ever happened to be on the disk at (current position =2) position in the file


问:
Delete all the Hangfire jobs
At startup, I try to delete all the existing hangfire jobs, but none of the methods I use seem to work.
Notice that I use a MongoDB database, but not sure it is related to the issue.

Here is how I add my job:

```<code>RecurringJob.AddOrUpdate<IPostIndexerJob>(j => j.Execute(), configuration.GetValue<string>("Job:Interval"));
</code>```

Here is my code, if anyone has an idea that help?

```<code>static private void ScheduleJobs(IConfiguration configuration)
        {
            PurgeJobs1();
            PurgeJobs2();
            PurgeJobs3();
        }

        static private void PurgeJobs1()
        {
            var mon = JobStorage.Current.GetMonitoringApi();
            mon.EnqueuedJobs("socloze-elasticsearch-post-indexer", 0, 99999999).ForEach(x =>
            {
                BackgroundJob.Delete(x.Key);
            });
        }

        static private void PurgeJobs2()
        {
            var monitor = JobStorage.Current.GetMonitoringApi();
            foreach (var queue in monitor.Queues())
            {
                PurgeQueue(queue.Name);
            }
        }

        static private void PurgeJobs3()
        {
            // Clean
            foreach (var item in Hangfire.JobStorage.Current.GetConnection().GetRecurringJobs())
                RecurringJob.RemoveIfExists(item.Id);
        }

        static private void PurgeQueue(string queueName)
        {
            var toDelete = new List<string>();
            var monitor = JobStorage.Current.GetMonitoringApi();

            var queue = monitor.Queues().First(x => x.Name == queueName);
            for (var i = 0; i < System.Math.Ceiling(queue.Length / 1000d); i++)
            {
                monitor.EnqueuedJobs(queue.Name, 1000 * i, 1000)
                    .ForEach(x => toDelete.Add(x.Key));
            }
            foreach (var jobId in toDelete)
            {
                BackgroundJob.Delete(jobId);
            }
        }
</code>```

答:
To delete recurring job (what i think you meant) you should firstly ask your storage to provide you all recurring jobs you have set:

```<code>jobStorage.GetConnection().GetRecurringJobs(); // where jobStorage is your storage instance, you can access it via JobStorage.Current in static context.
</code>```

then delete a desired entry:

```<code>recurringJobManager.RemoveIfExists("someId"); // where recurringJobManager is instance of IRecurringJobManager
</code>```

then PurgeJobs3() should work as expected (as it uses IRecurringJobManager under the hood). Perhaps the job identifier does not match your target?

Title: Delete all the Hangfire jobs

Body:
At startup, I try to delete all the existing hangfire jobs, but none of the methods I use seem to work.
Notice that I use a MongoDB database, but not sure it is related to the issue.

Here is how I add my job:

RecurringJob.AddOrUpdate<IPostIndexerJob>(j => j.Execute(), configuration.GetValue<string>("Job:Interval"));

Here is my code, if anyone has an idea that help?

static private void ScheduleJobs(IConfiguration configuration)
        {
            PurgeJobs1();
            PurgeJobs2();
            PurgeJobs3();
        }

        static private void PurgeJobs1()
        {
            var mon = JobStorage.Current.GetMonitoringApi();
            mon.EnqueuedJobs("socloze-elasticsearch-post-indexer", 0, 99999999).ForEach(x =>
            {
                BackgroundJob.Delete(x.Key);
            });
        }

        static private void PurgeJobs2()
        {
            var monitor = JobStorage.Current.GetMonitoringApi();
            foreach (var queue in monitor.Queues())
            {
                PurgeQueue(queue.Name);
            }
        }

        static private void PurgeJobs3()
        {
            // Clean
            foreach (var item in Hangfire.JobStorage.Current.GetConnection().GetRecurringJobs())
                RecurringJob.RemoveIfExists(item.Id);
        }

        static private void PurgeQueue(string queueName)
        {
            var toDelete = new List<string>();
            var monitor = JobStorage.Current.GetMonitoringApi();

            var queue = monitor.Queues().First(x => x.Name == queueName);
            for (var i = 0; i < System.Math.Ceiling(queue.Length / 1000d); i++)
            {
                monitor.EnqueuedJobs(queue.Name, 1000 * i, 1000)
                    .ForEach(x => toDelete.Add(x.Key));
            }
            foreach (var jobId in toDelete)
            {
                BackgroundJob.Delete(jobId);
            }
        }

Body:
To delete recurring job (what i think you meant) you should firstly ask your storage to provide you all recurring jobs you have set:

jobStorage.GetConnection().GetRecurringJobs(); // where jobStorage is your storage instance, you can access it via JobStorage.Current in static context.

then delete a desired entry:

recurringJobManager.RemoveIfExists("someId"); // where recurringJobManager is instance of IRecurringJobManager

then PurgeJobs3() should work as expected (as it uses IRecurringJobManager under the hood). Perhaps the job identifier does not match your target?


问:
Codeigniter 3 SameSite attribute for csrf protection
I have applications that make CORS calls to each other. Google in April 2020 will need SameSite cookies = none. https://www.chromestatus.com/feature/5633521622188032

Since chrome version 80+ all user that use chrome browser impact this csrf error. how to fix this problem on Codeigniter framework that using PHP 7.3

答:
I had this same problem but my PHP 7.2 and my CI 3.X.
The problem was solved by making the following change to the applications / config / config.php file</p>

```<code>$config['cookie_prefix']    = '';
$config['cookie_domain']    = '';
$config['cookie_path']      = '/; SameSite=None';
$config['cookie_secure']    = TRUE;
$config['cookie_httponly']  = FALSE;
</code>```

Body:
I had this same problem but my PHP 7.2 and my CI 3.X.
The problem was solved by making the following change to the applications / config / config.php file

$config['cookie_prefix']    = '';
$config['cookie_domain']    = '';
$config['cookie_path']      = '/; SameSite=None';
$config['cookie_secure']    = TRUE;
$config['cookie_httponly']  = FALSE;


问:
Spring Cloud Stream custom binder with extension binding properties
I'm writing a custom binder for Spring Cloud Streams. The basic binder is hooked into Spring Cloud Streams and is works.

I'm now trying to create extended binding properties. I'm trying to follow the pattern used by the Kalka Binder, but is is a bit of a black hole. Is there documentation or a sample somewhere that shows how to create a binder that supports extension binding properties.

I feel very close. My ConsumerProperty extension is being created and initialized from my application.yml. But them another ConsumerProperty extension is created and never initialized. That is the one that is ultimately passed into my MessageProducer.

Here's my sample-binder: https://github.com/mburbidg/sample-binder

答:
Does your binder implement the ExtendedPropertiesBinder marker interface?

The code that clones the producer properties for such binders is here.

If it does implement it, I would set a breakpoint there to figure out what's going on.

EDIT

Two problems:

You are creating a new extended binding properties here (the Kafka binder injects the actual properties here).

Also see KafkaExtendedBindingProperties.getBindings().


问:
Accessing EJS variable in Javascript logic
I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.

Right now, it's being done like this with Express v2.5.8:

```<code>server.get("/room/:name/:roomId, function (req, res) {
  game = ~databaseLookup~
  res.render("board", { gameState : game.gameState });
}
</code>```

Over in board.ejs I can access the gameState manner with code like this:

```<code><% if (gameState) { %>
  <h2>I have a game state!</h2>
<% } %>
</code>```

Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~ and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.

Thanks!

答:
In the EJS template:

ex:- testing.ejs

```<code><html>
<!-- content -->
<script>
    // stringify the data passed from router to ejs (within the EJS template only)
    var parsed_data = <%- JSON.stringify(data) %>
</script>
</html>
</code>```

In the Server side script:

ex: Router.js

```<code>res.render('/testing', {
    data: data // any data to be passed to ejs template
});
</code>```

In the linked js (or jquery) script file:

ex:- script.js
In JavaScript:

```<code>console.log(parsed_data)
</code>```

In JQuery:

```<code>$(document).ready(function(){
    console.log(parsed_data)
 });
</code>```

Note:
1. user - instead of = in <% %> tag

2. you can't declare or use data passed from router to view directly into the linked javascript or jquery script file directly.

3. declare the <% %> in the EJS template only and use it any linked script file.

I'm not sure but I've found it to be the best practice to use passed data from router to view in a script file or script tag.

Body:
I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.

Right now, it's being done like this with Express v2.5.8:

server.get("/room/:name/:roomId, function (req, res) {
  game = ~databaseLookup~
  res.render("board", { gameState : game.gameState });
}

Over in board.ejs I can access the gameState manner with code like this:

<% if (gameState) { %>

I have a game state!

<% } %>

Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~ and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.

Thanks!

Body:
In the EJS template:

ex:- testing.ejs

<html>
<!-- content -->
<script>
    // stringify the data passed from router to ejs (within the EJS template only)
    var parsed_data = <%- JSON.stringify(data) %>
</script>
</html>

In the Server side script:

ex: Router.js

res.render('/testing', {
    data: data // any data to be passed to ejs template
});

In the linked js (or jquery) script file:

ex:- script.js
In JavaScript:

console.log(parsed_data)

In JQuery:

$(document).ready(function(){
    console.log(parsed_data)
 });

Note:
1. user - instead of = in <% %> tag

2. you can't declare or use data passed from router to view directly into the linked javascript or jquery script file directly.

3. declare the <% %> in the EJS template only and use it any linked script file.

I'm not sure but I've found it to be the best practice to use passed data from router to view in a script file or script tag.


问:
Frida python redirect outpout to file
I'm using frida-python to hook android function and I'm trying to redirect the output to a file.

I've tried to redirect stdout to a file :

```<code>sys.stdout = open(os.path.join(self.dump_path,'apk_hook.txt'), 'w')
</code>```

before calling

```<code>script = self.session.create_script(open("java_hook.js").read())
script.load()
</code>```

But this redirect everything and not just the result of frida-python.

I've also tried to write the result in a file directly in the javascript file (java_hook.js)
but i don't know how to pass my variable self.dump_path from my python file to my javascript file.

```<code>Java.use('java.net.URL').$init.overload('java.lang.String').implementation = function(str1) {
     var file = new File(How_can_i_pass_this_dynamic_variable,"w");
     file.write("helloworld");
     return this.$init(str1);
};
</code>```

Do you know how can i do it ??

Thanks.

答:
Use send

Java.use('java.net.URL').$init.overload('java.lang.String').implementation = function(str1) {
     send(dynamic_variable);
     return this.$init(str1);
};
```

<p>In the python side </p>

<pre class="lang-py prettyprint-override"><code>f = open('/tmp/log', 'w')
# ...
def on_message(msg, _data):
    f.write(msg['payload'] + '\n')
# ...
script.on('message', on_message)
</code>```

Unless you want to write to a file on the phone

    var f = new File("/sdcard/log.txt", "w");
    f.write("line\n");
    f.flush();
    f.close();

```

Title: Frida python redirect outpout to file

Body:
I'm using frida-python to hook android function and I'm trying to redirect the output to a file.

I've tried to redirect stdout to a file :

sys.stdout = open(os.path.join(self.dump_path,'apk_hook.txt'), 'w')

before calling

script = self.session.create_script(open("java_hook.js").read())
script.load()

But this redirect everything and not just the result of frida-python.

I've also tried to write the result in a file directly in the javascript file (java_hook.js)
but i don't know how to pass my variable self.dump_path from my python file to my javascript file.

Java.use('java.net.URL').$init.overload('java.lang.String').implementation = function(str1) {
     var file = new File(How_can_i_pass_this_dynamic_variable,"w");
     file.write("helloworld");
     return this.$init(str1);
};

Do you know how can i do it ??

Thanks.

Body:
Use send

Java.use('java.net.URL').$init.overload('java.lang.String').implementation = function(str1) {
     send(dynamic_variable);
     return this.$init(str1);
};

In the python side

f = open('/tmp/log', 'w')
# ...
def on_message(msg, _data):
    f.write(msg['payload'] + '\n')
# ...
script.on('message', on_message)

Unless you want to write to a file on the phone

    var f = new File("/sdcard/log.txt", "w");
    f.write("line\n");
    f.flush();
    f.close();


问:
Throwing own exceptions
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }
```

<p>Now I also have this exception that I wrote </p>

<pre class="lang-java prettyprint-override"><code>    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }
</code>```

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

```<code>class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}
</code>```

答:
It depends on the interface you create. You currently have an interface in your code where you return false if the account is not found or something other fails. That kind of error handling has benefits and drawbacks. One way that is potentially fragile is that the caller of the method(s) might forget to check the return code, which could be potentially very bad for this case (the caller first attempts to withdraw some money, which fails, and then deposits money into another account, creating money out of nowhere).

There are arguments for and against. An alternative way of doing error handling would be to throw exceptions instead of returning a boolean for error handling - that would have its own benefits and drawbacks. In Java, if you ensure it is a checked exception, the caller would be forced to catch or throw the exception as part of the type system. In any case, I don't know how I feel about mixing the two ways of handling errors, since that might be very error prone and confusing.

If you go along with the exception way of handling errors, one common refactoring might be to have a private method called checkOrThrowAccountMustExist, that takes an account ID as input and throws if it does not exist.

There is also the issue of whether to place the checks in the Banking class and/or in the Account class. My own feeling would be that it may make sense to include at least some checks in both, and that it would be a good idea to include checks in those classes that are exposed externally or to other parts of your program (and document if a class is not meant to be used outside a small part of your program). But this may or may not be outside the scope of your assignment.

Title: Throwing own exceptions

Body:
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }

Now I also have this exception that I wrote

    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}


问:
How can I "think OOP" when using R?
I am a statistics graduate student who works a lot with R.  I am familiar with OOP in other programming contexts.  I even see its use in various statistical packages that define new classes for storing data.

At this stage in my graduate career, I am usually coding some algorithm for some class assignment--something that takes in raw data and gives some kind of output.  I would like to make it easier to reuse code, and establish good coding habits, especially before I move on to more involved research.  Please offer some advice on how to "think OOP" when doing statistical programming in R.

答:
I have a limited knowledge of how to use R effectively, but there here is an article that allowed even me to walk through using R in an OO manner:

http://www.ibm.com/developerworks/linux/library/l-r3/index.html

Title: How can I "think OOP" when using R?


问:
Hello World dotnet core example not working
I am running Visual Studio and tried Hello World console example for dotnet core.

```<code>PS d:\test> dotnet nuget list source
Registered Sources:
  1.  Microsoft Visual Studio Offline Packages [Enabled]
      C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\
  3.  Package source 1 [Enabled]
      C:\Program Files\dotnet\packs
  4.  Package source 2 [Enabled]
      C:\Program Files\dotnet\sdk\NuGetFallbackFolder

PS d:\test> dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.300
 Commit:    b2475c1295

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.18362
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\3.1.300\

Host (useful for support):
  Version: 3.1.4
  Commit:  0c2e69caa6

.NET Core SDKs installed:
  2.1.514 [C:\Program Files\dotnet\sdk]
  3.1.300 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.18 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.18 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.1.4 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.18 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.4 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.WindowsDesktop.App 3.1.4 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download
</code>```

The example gives package not found error:

```<code>PS d:\test> dotnet new console --force
The template "Console Application" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on d:\test\test.csproj...
  Determining projects to restore...
d:\test\test.csproj : error NU1101: Unable to find package Microsoft.AspNetCore.App.Ref. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages, Package source, Package source 1, Package source 2
  Failed to restore d:\test\test.csproj (in 402 ms).
</code>```

The package is available at: C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.1.3
Also, if I try changing the target framework to 2.1 everything works fine.

Default .csproj file created by dotnet command line.

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

Is there something I missed?

EDIT: Output after running clean

PS d:\test> dotnet clean
Microsoft (R) Build Engine version 16.6.0

```<code>+5ff7b0c9e for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 5/30/2020 6:01:58 PM.

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.71
PS d:\test> dotnet run
d:\test\test.csproj : error NU1101: Unable to find package Microsoft.AspNetCore.App.Ref. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages, Package source, Package source 1, Package source 2

The build failed. Fix the build errors and run again.
</code>```

If I just change 'netcore3.1' => 'netcore2.1' and everything works.

答:
Thanks for all the suggestion.

I figured the issue.
My nuget source list didn't have following, so tool never tried online for packages.

```<code>https://api.nuget.org/v3/index.json
</code>```

Body:
I am running Visual Studio and tried Hello World console example for dotnet core.

PS d:\test> dotnet nuget list source
Registered Sources:
  1.  Microsoft Visual Studio Offline Packages [Enabled]
      C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\
  3.  Package source 1 [Enabled]
      C:\Program Files\dotnet\packs
  4.  Package source 2 [Enabled]
      C:\Program Files\dotnet\sdk\NuGetFallbackFolder

PS d:\test> dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.300
 Commit:    b2475c1295

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.18362
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\3.1.300\

Host (useful for support):
  Version: 3.1.4
  Commit:  0c2e69caa6

.NET Core SDKs installed:
  2.1.514 [C:\Program Files\dotnet\sdk]
  3.1.300 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.18 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.18 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.1.4 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.18 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.4 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.WindowsDesktop.App 3.1.4 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

The example gives package not found error:

PS d:\test> dotnet new console --force
The template "Console Application" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on d:\test\test.csproj...
  Determining projects to restore...
d:\test\test.csproj : error NU1101: Unable to find package Microsoft.AspNetCore.App.Ref. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages, Package source, Package source 1, Package source 2
  Failed to restore d:\test\test.csproj (in 402 ms).

The package is available at: C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.1.3
Also, if I try changing the target framework to 2.1 everything works fine.

Default .csproj file created by dotnet command line.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>

Is there something I missed?

EDIT: Output after running clean

PS d:\test> dotnet clean
Microsoft (R) Build Engine version 16.6.0

+5ff7b0c9e for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 5/30/2020 6:01:58 PM.

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.71
PS d:\test> dotnet run
d:\test\test.csproj : error NU1101: Unable to find package Microsoft.AspNetCore.App.Ref. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages, Package source, Package source 1, Package source 2

The build failed. Fix the build errors and run again.

If I just change 'netcore3.1' => 'netcore2.1' and everything works.

Body:
Thanks for all the suggestion.

I figured the issue.
My nuget source list didn't have following, so tool never tried online for packages.

https://api.nuget.org/v3/index.json