问:
Android Studio - Get the recorded Sound Level
I am trying to build an app which amongst other things, has a sound recording functionality. I have followed the guide from the Android Developer Documentation found here, and created the AudioRecordTest Class containing the following code:

```<code>package com.example.ssresilience;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.os.Bundle;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.io.IOException;

public class AudioRecordTest extends AppCompatActivity {

    private static final String LOG_TAG = "AudioRecordTest";
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private static String fileName = null;

    private RecordButton recordButton = null;
    private MediaRecorder recorder = null;

    private PlayButton playButton = null;
    private MediaPlayer player = null;

    // Requesting permission to RECORD_AUDIO
    private boolean permissionToRecordAccepted = false;
    private String [] permissions = {Manifest.permission.RECORD_AUDIO};

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_RECORD_AUDIO_PERMISSION:
                permissionToRecordAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                break;
        }
        if (!permissionToRecordAccepted ) finish();

    }

    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        player = new MediaPlayer();
        try {
            player.setDataSource(fileName);
            player.prepare();
            player.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        player.release();
        player = null;
    }

    void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setOutputFile(fileName);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            recorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        recorder.start();
    }

    private void stopRecording() {
        recorder.stop();
        recorder.release();
        recorder = null;
    }

    class RecordButton extends androidx.appcompat.widget.AppCompatButton {
        boolean mStartRecording = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };

        public RecordButton(Context ctx) {
            super(ctx);
            setText("Start recording");
            setOnClickListener(clicker);
        }
    }

    class PlayButton extends androidx.appcompat.widget.AppCompatButton {
        boolean mStartPlaying = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onPlay(mStartPlaying);
                if (mStartPlaying) {
                    setText("Stop playing");
                } else {
                    setText("Start playing");
                }
                mStartPlaying = !mStartPlaying;
            }
        };

        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // Record to the external cache directory for visibility
        fileName = getExternalCacheDir().getAbsolutePath();
        fileName += "/audiorecordtest.3gp";

        ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);

        LinearLayout ll = new LinearLayout(this);
        recordButton = new RecordButton(this);
        ll.addView(recordButton,
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        0));
        playButton = new PlayButton(this);
        ll.addView(playButton,
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        0));
        getAmplitude();
        setContentView(ll);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (recorder != null) {
            recorder.release();
            recorder = null;
        }

        if (player != null) {
            player.release();
            player = null;
        }
    }
}
</code>```

The recording start / stop process, as well as the audio playback using the Media Player appear to be working just fine, but in my case this is not exactly what I want to achieve.

I wish to somehow implement a function in this example, which returns the recorder sound level (maybe in decibels?) as soon as I tap "Stop Recording", and then print it. I have looked at many other examples, but none of them seem to work since the app crashes as soon as the method to start recording is called. With that in mind, this is why I would like to stick to this example.

Any ideas?

答:
Figured it out!

I had to call the method getMaxAmplitude() on both the start and stop methods, like so:

```<code>    void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setOutputFile(fileName);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            recorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
        recorder.start();
        audiolevel = recorder.getMaxAmplitude();
        System.out.println(audiolevel);
    }

    private void stopRecording() {
        audiolevelprocessed = recorder.getMaxAmplitude();
        System.out.println(audiolevelprocessed);
        recorder.stop();
        recorder.release();
        recorder = null;
    }
</code>```

This stores and prints the Max Amplitude twice, with the first one always being 0. If it doesn't exist on both methods I always get 0 as a print value. Not entirely sure why this happens, but as you can see I have stored both occasions on different variables and can now use the second one.

Body:
I am trying to build an app which amongst other things, has a sound recording functionality. I have followed the guide from the Android Developer Documentation found here, and created the AudioRecordTest Class containing the following code:

package com.example.ssresilience;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.os.Bundle;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.io.IOException;

public class AudioRecordTest extends AppCompatActivity {

    private static final String LOG_TAG = "AudioRecordTest";
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private static String fileName = null;

    private RecordButton recordButton = null;
    private MediaRecorder recorder = null;

    private PlayButton playButton = null;
    private MediaPlayer player = null;

    // Requesting permission to RECORD_AUDIO
    private boolean permissionToRecordAccepted = false;
    private String [] permissions = {Manifest.permission.RECORD_AUDIO};

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_RECORD_AUDIO_PERMISSION:
                permissionToRecordAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                break;
        }
        if (!permissionToRecordAccepted ) finish();

    }

    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        player = new MediaPlayer();
        try {
            player.setDataSource(fileName);
            player.prepare();
            player.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        player.release();
        player = null;
    }

    void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setOutputFile(fileName);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            recorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        recorder.start();
    }

    private void stopRecording() {
        recorder.stop();
        recorder.release();
        recorder = null;
    }

    class RecordButton extends androidx.appcompat.widget.AppCompatButton {
        boolean mStartRecording = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };

        public RecordButton(Context ctx) {
            super(ctx);
            setText("Start recording");
            setOnClickListener(clicker);
        }
    }

    class PlayButton extends androidx.appcompat.widget.AppCompatButton {
        boolean mStartPlaying = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onPlay(mStartPlaying);
                if (mStartPlaying) {
                    setText("Stop playing");
                } else {
                    setText("Start playing");
                }
                mStartPlaying = !mStartPlaying;
            }
        };

        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // Record to the external cache directory for visibility
        fileName = getExternalCacheDir().getAbsolutePath();
        fileName += "/audiorecordtest.3gp";

        ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);

        LinearLayout ll = new LinearLayout(this);
        recordButton = new RecordButton(this);
        ll.addView(recordButton,
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        0));
        playButton = new PlayButton(this);
        ll.addView(playButton,
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        0));
        getAmplitude();
        setContentView(ll);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (recorder != null) {
            recorder.release();
            recorder = null;
        }

        if (player != null) {
            player.release();
            player = null;
        }
    }
}

The recording start / stop process, as well as the audio playback using the Media Player appear to be working just fine, but in my case this is not exactly what I want to achieve.

I wish to somehow implement a function in this example, which returns the recorder sound level (maybe in decibels?) as soon as I tap "Stop Recording", and then print it. I have looked at many other examples, but none of them seem to work since the app crashes as soon as the method to start recording is called. With that in mind, this is why I would like to stick to this example.

Any ideas?

Body:
Figured it out!

I had to call the method getMaxAmplitude() on both the start and stop methods, like so:

    void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setOutputFile(fileName);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            recorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
        recorder.start();
        audiolevel = recorder.getMaxAmplitude();
        System.out.println(audiolevel);
    }

    private void stopRecording() {
        audiolevelprocessed = recorder.getMaxAmplitude();
        System.out.println(audiolevelprocessed);
        recorder.stop();
        recorder.release();
        recorder = null;
    }

This stores and prints the Max Amplitude twice, with the first one always being 0. If it doesn't exist on both methods I always get 0 as a print value. Not entirely sure why this happens, but as you can see I have stored both occasions on different variables and can now use the second one.


来源: stackexchange

问:
Unable to expose SCTP server running in a kubernetes pod using NodePort
I have a single node kubernetes cluster running in a VM in azure. I have a service running SCTP server in port 38412. I need to expose that port externally. I have tried by changing the port type to NodePort. But no success. I am using flannel as a overlay network. using Kubernetes version 1.23.3.

This is my service.yaml file

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    meta.helm.sh/release-name: fivegcore
    meta.helm.sh/release-namespace: open5gs
  creationTimestamp: "2022-02-11T09:24:09Z"
  labels:
    app.kubernetes.io/managed-by: Helm
    epc-mode: amf
  name: fivegcore-amf
  namespace: open5gs
  resourceVersion: "33072"
  uid: 4392dd8d-2561-49ab-9d57-47426b5d951b
spec:
  clusterIP: 10.111.94.85
  clusterIPs:
  - 10.111.94.85
  externalTrafficPolicy: Cluster
  internalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - name: tcp
    nodePort: 30314
    port: 80
    protocol: TCP
    targetPort: 80
  - name: ngap
    nodePort: 30090
    port: 38412
    protocol: SCTP
    targetPort: 38412
  selector:
    epc-mode: amf
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}
</code>```

As you can see I changed the port type to NodePort.

```<code>open5gs fivegcore-amf NodePort 10.111.94.85  <none>  80:30314/TCP,38412:30090/SCTP
</code>```

This is my Configmap.yaml. In this configmap that ngap dev is the server I want to connect which is using default eth0 interface in the container.

```<code>apiVersion: v1
data:
  amf.yaml: |
    logger:
        file: /var/log/open5gs/amf.log
        #level: debug
        #domain: sbi

    amf:
        sbi:
        - addr: 0.0.0.0
          advertise: fivegcore-amf
        ngap:
          dev: eth0
        guami:
          - plmn_id:
              mcc: 208
              mnc: 93
            amf_id:
              region: 2
              set: 1
        tai:
          - plmn_id:
              mcc: 208
              mnc: 93
            tac: 7
        plmn_support:
        - plmn_id:
            mcc: 208
            mnc: 93
          s_nssai:
          - sst: 1
            sd: 1
        security:
            integrity_order : [ NIA2, NIA1, NIA0 ]
            ciphering_order : [ NEA0, NEA1, NEA2 ]
        network_name:
            full: Open5GS
        amf_name: open5gs-amf0
    nrf:
     sbi:
       name: fivegcore-nrf
kind: ConfigMap
metadata:
  annotations:
    meta.helm.sh/release-name: fivegcore
    meta.helm.sh/release-namespace: open5gs
  creationTimestamp: "2022-02-11T09:24:09Z"
  labels:
    app.kubernetes.io/managed-by: Helm
    epc-mode: amf

</code>```

I exec in to the container and check whether the server is running or not.
This is the netstat of the container.

```<code>Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 10.244.0.31:37742       10.105.167.186:80       ESTABLISHED 1/open5gs-amfd
sctp                10.244.0.31:38412                               LISTEN      1/open5gs-amfd
</code>```

sctp module is also loaded in the host.

```<code>$lsmod | grep sctp
sctp                  356352  8
xt_sctp                20480  0
libcrc32c              16384  5 nf_conntrack,nf_nat,nf_tables,ip_vs,sctp
x_tables               49152  18 ip6table_filter,xt_conntrack,xt_statistic,iptable_filter,iptable_security,xt_tcpudp,xt_addrtype,xt_nat,xt_comment,xt_owner,ip6_tables,xt_sctp,ipt_REJECT,ip_tables,ip6table_mangle,xt_MASQUERADE,iptable_mangle,xt_mark

</code>```

Is it possible to expose this server externally?

答: Neither AKS nor Flannel supports SCTP at this point of writing. Here's some details about it.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a single node kubernetes cluster running in a VM in azure. I have a service running SCTP server in port 38412. I need to expose that port externally. I have tried by changing the port type to NodePort. But no success. I am using flannel as a overlay network. using Kubernetes version 1.23.3.

This is my service.yaml file

apiVersion: v1
kind: Service
metadata:
  annotations:
    meta.helm.sh/release-name: fivegcore
    meta.helm.sh/release-namespace: open5gs
  creationTimestamp: "2022-02-11T09:24:09Z"
  labels:
    app.kubernetes.io/managed-by: Helm
    epc-mode: amf
  name: fivegcore-amf
  namespace: open5gs
  resourceVersion: "33072"
  uid: 4392dd8d-2561-49ab-9d57-47426b5d951b
spec:
  clusterIP: 10.111.94.85
  clusterIPs:
  - 10.111.94.85
  externalTrafficPolicy: Cluster
  internalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - name: tcp
    nodePort: 30314
    port: 80
    protocol: TCP
    targetPort: 80
  - name: ngap
    nodePort: 30090
    port: 38412
    protocol: SCTP
    targetPort: 38412
  selector:
    epc-mode: amf
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}

As you can see I changed the port type to NodePort.

open5gs fivegcore-amf NodePort 10.111.94.85  <none>  80:30314/TCP,38412:30090/SCTP

This is my Configmap.yaml. In this configmap that ngap dev is the server I want to connect which is using default eth0 interface in the container.

apiVersion: v1
data:
  amf.yaml: |
    logger:
        file: /var/log/open5gs/amf.log
        #level: debug
        #domain: sbi

    amf:
        sbi:
        - addr: 0.0.0.0
          advertise: fivegcore-amf
        ngap:
          dev: eth0
        guami:
          - plmn_id:
              mcc: 208
              mnc: 93
            amf_id:
              region: 2
              set: 1
        tai:
          - plmn_id:
              mcc: 208
              mnc: 93
            tac: 7
        plmn_support:
        - plmn_id:
            mcc: 208
            mnc: 93
          s_nssai:
          - sst: 1
            sd: 1
        security:
            integrity_order : [ NIA2, NIA1, NIA0 ]
            ciphering_order : [ NEA0, NEA1, NEA2 ]
        network_name:
            full: Open5GS
        amf_name: open5gs-amf0
    nrf:
     sbi:
       name: fivegcore-nrf
kind: ConfigMap
metadata:
  annotations:
    meta.helm.sh/release-name: fivegcore
    meta.helm.sh/release-namespace: open5gs
  creationTimestamp: "2022-02-11T09:24:09Z"
  labels:
    app.kubernetes.io/managed-by: Helm
    epc-mode: amf

I exec in to the container and check whether the server is running or not.
This is the netstat of the container.

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 10.244.0.31:37742       10.105.167.186:80       ESTABLISHED 1/open5gs-amfd
sctp                10.244.0.31:38412                               LISTEN      1/open5gs-amfd

sctp module is also loaded in the host.

$lsmod | grep sctp
sctp                  356352  8
xt_sctp                20480  0
libcrc32c              16384  5 nf_conntrack,nf_nat,nf_tables,ip_vs,sctp
x_tables               49152  18 ip6table_filter,xt_conntrack,xt_statistic,iptable_filter,iptable_security,xt_tcpudp,xt_addrtype,xt_nat,xt_comment,xt_owner,ip6_tables,xt_sctp,ipt_REJECT,ip_tables,ip6table_mangle,xt_MASQUERADE,iptable_mangle,xt_mark

Is it possible to expose this server externally?


问:
What the heck is this: background-image: url("/images/sprites.png?v=3");

Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

```<code>/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }
</code>```

I've seen this used on link tags also on http://html5boilerplate.com/:

```<code>   <link rel="stylesheet" href="css/style.css?v=2">
</code>```

答:
It's likely that the URL routes to a static resource on the server, and that the query string is simply a cache-busting modification of the URL. After rolling out a new version of the website's UI, they wanted to make sure none of the old versions of any images were cached on client's machines.

Another common approach is to append a timestamp, which would cause the resource to never be cached.

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }

I've seen this used on link tags also on http://html5boilerplate.com/:

   <link rel="stylesheet" href="css/style.css?v=2">


问:
Accelerating transitions in gganimate
I have a plot with several hundred lines. I would like these lines to appear over time; first slowly, to have the time to explain what's going on to the audience; then faster and faster.

The minimal example below gives an example of how the animation currently looks. What I want is that the first frame has a few seconds, the second is roughly half as long, the third another half of that, etc. Essentially, the duration should get exponentially smaller.

However, I cannot figure out how to change the duration. I thought that the option ease_aes() should do it as it allows functions such as exponential_in. Using this option though seems to change nothing for me.

I also found an SO post that slows one particular frame down, so I thought I should be able to apply this code to my use case. Again though, the transition duration looks identical across frames. (Note that the last example has the issue that the prior line disappears, which is also not want I want; it's just to illustrate though that the durations don't change).

What am I missing?

```<code>library(data.table)
library(gganimate)
DT <- data.table(x  = rep(1:10,  times=100),
                 y  = rep(1:10,  times=100) + rnorm(1000),
                 id = rep(1:100, each=10))
anim <- ggplot(DT) +
  geom_line(aes(x=x, y=y, group=id)) +
  transition_reveal(id)

animate(anim, nframes = 100)

####Playing around with eas_aes does not work for me
anim <- ggplot(DT) +
  geom_line(aes(x=x, y=y, group=id)) +
  transition_reveal(id) +
  ease_aes("exponential-in")

animate(anim, nframes = 100)

####Transition states also doesn't work:
# https://stackoverflow.com/questions/66923904/how-to-make-the-transition-time-between-2-frames-longer-in-gganimate
anim <- ggplot(DT) +
  geom_line(aes(x=x, y=y, group=id)) +
  transition_states(id,
                    state_length = 0,
                    transition_length = 100:1)

animate(anim, nframes = 100)
</code>```

答:
Just create a time column with an exponentially falling gap between successive times, and reveal according to that.

DT <- data.table(x  = rep(1:10,  times=100),
                 y  = rep(1:10,  times=100) + rnorm(1000),
                 id = rep(1:100, each=10),
                 time = rep(cumsum(100 / 1:100), each = 10))
anim <- ggplot(DT) +
  geom_line(aes(x=x, y=y, group=id)) +
  transition_reveal(time)

animate(anim, nframes = 200)
```

Title: Accelerating transitions in gganimate

Body:
I have a plot with several hundred lines. I would like these lines to appear over time; first slowly, to have the time to explain what's going on to the audience; then faster and faster.

The minimal example below gives an example of how the animation currently looks. What I want is that the first frame has a few seconds, the second is roughly half as long, the third another half of that, etc. Essentially, the duration should get exponentially smaller.

However, I cannot figure out how to change the duration. I thought that the option ease_aes() should do it as it allows functions such as exponential_in. Using this option though seems to change nothing for me.

I also found an SO post that slows one particular frame down, so I thought I should be able to apply this code to my use case. Again though, the transition duration looks identical across frames. (Note that the last example has the issue that the prior line disappears, which is also not want I want; it's just to illustrate though that the durations don't change).

What am I missing?

library(data.table)
library(gganimate)
DT <- data.table(x  = rep(1:10,  times=100),
                 y  = rep(1:10,  times=100) + rnorm(1000),
                 id = rep(1:100, each=10))
anim <- ggplot(DT) +
  geom_line(aes(x=x, y=y, group=id)) +
  transition_reveal(id)

animate(anim, nframes = 100)

####Playing around with eas_aes does not work for me
anim <- ggplot(DT) +
  geom_line(aes(x=x, y=y, group=id)) +
  transition_reveal(id) +
  ease_aes("exponential-in")

animate(anim, nframes = 100)

####Transition states also doesn't work:
# https://stackoverflow.com/questions/66923904/how-to-make-the-transition-time-between-2-frames-longer-in-gganimate
anim <- ggplot(DT) +
  geom_line(aes(x=x, y=y, group=id)) +
  transition_states(id,
                    state_length = 0,
                    transition_length = 100:1)

animate(anim, nframes = 100)


问:
Kotlin rxjava switchIfEmpty
I'm trying to understand the logic of switchIfEmpty operator. I will be very thankful for every explanation.
I have a local database (Room) and remote server. My goal is to implement logic with switchIfEmpty to check if there is data in local DB to take it and if local DB is empty to call from remote. The process starts in activity where I subscribe to Observable:

```<code>    private fun subscribeOnDataChanges() = with(viewModel) {
        requestNextPage()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                filmsAdapter.addItems(it)
            }, {
                errorEvent.value = ERROR_MSG
                it.printStackTrace()
            }).addTo(autoDisposable)
    }
</code>```

Then the methods in the View Model:

```<code>    fun requestNextPage(): Observable<List<Film>> {
        return requestPageOfFilms()
    }

    private fun requestPageOfFilms(): Observable<List<Film>> =
        interactor.requestPageOfFilmsFromDataSource()
</code>```

And, finally the method with switchIfEmpty in the Interactor:

```<code>
    fun requestPageOfFilmsFromDataSource(): Observable<List<Film>> {
        return repo.getPageOfFilmsInCategory(category).filter { it.isNotEmpty() }.switchIfEmpty(
            getFromRemote(category)
        )
    }

    private fun getFromRemote(category: String): Observable<List<Film>> {
        return convertSingleApiToObservableDtoList(
            retrofitService.getFilms(
                category, API.KEY, "ru-RU", NEXT_PAGE
            )
        )
    }
</code>```

I cannot understand the next things:

Why, when local db (repo) is NOT empty, getFromRemote() is called?

If local db is empty, why network call in the method getFromRemote() is not performed? No matters, that I subscribed in the activity? Because if I add the subscription inside the switchIfEmpty(), the network call is performed.

答:
To answer your questions :

Why, when local db (repo) is NOT empty, getFromRemote() is called?

Because this function convertSingleApiToObservableDtoList() is being evaluated at Assembly Time and not Subscription Time (https://github.com/ReactiveX/RxJava#assembly-time). The result is that the Observable object is eagerly evaluated.

If local db is empty, why network call in the method getFromRemote() is not performed? No matters, that I subscribed in the activity? Because if I add the subscription inside the switchIfEmpty(), the network call is performed.

Because the upstream has not emitted a value yet or completed.  You are conflating an empty List with an empty Observable (https://reactivex.io/documentation/operators/defaultifempty.html)

A better solution to your problem would be using the flatMap or even switchMap operator if you expect a chatty upstream and only care about latest result, something like :

```<code>fun requestPageOfFilmsFromDataSource(): Observable<List<Film>> {
    return repo.getPageOfFilmsInCategory(category)
        .flatMap { films ->
            if (films.isNotEmpty()) {
                Observable.just(films)
            } else getFromRemote(category)
        }
}
</code>```

Title: Kotlin rxjava switchIfEmpty

Body:
I'm trying to understand the logic of switchIfEmpty operator. I will be very thankful for every explanation.
I have a local database (Room) and remote server. My goal is to implement logic with switchIfEmpty to check if there is data in local DB to take it and if local DB is empty to call from remote. The process starts in activity where I subscribe to Observable:

    private fun subscribeOnDataChanges() = with(viewModel) {
        requestNextPage()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                filmsAdapter.addItems(it)
            }, {
                errorEvent.value = ERROR_MSG
                it.printStackTrace()
            }).addTo(autoDisposable)
    }

Then the methods in the View Model:

    fun requestNextPage(): Observable<List<Film>> {
        return requestPageOfFilms()
    }

    private fun requestPageOfFilms(): Observable<List<Film>> =
        interactor.requestPageOfFilmsFromDataSource()

And, finally the method with switchIfEmpty in the Interactor:

    fun requestPageOfFilmsFromDataSource(): Observable<List<Film>> {
        return repo.getPageOfFilmsInCategory(category).filter { it.isNotEmpty() }.switchIfEmpty(
            getFromRemote(category)
        )
    }

    private fun getFromRemote(category: String): Observable<List<Film>> {
        return convertSingleApiToObservableDtoList(
            retrofitService.getFilms(
                category, API.KEY, "ru-RU", NEXT_PAGE
            )
        )
    }

I cannot understand the next things:

Why, when local db (repo) is NOT empty, getFromRemote() is called?

If local db is empty, why network call in the method getFromRemote() is not performed? No matters, that I subscribed in the activity? Because if I add the subscription inside the switchIfEmpty(), the network call is performed.

Body:
To answer your questions :

Why, when local db (repo) is NOT empty, getFromRemote() is called?

Because this function convertSingleApiToObservableDtoList() is being evaluated at Assembly Time and not Subscription Time (https://github.com/ReactiveX/RxJava#assembly-time). The result is that the Observable object is eagerly evaluated.

If local db is empty, why network call in the method getFromRemote() is not performed? No matters, that I subscribed in the activity? Because if I add the subscription inside the switchIfEmpty(), the network call is performed.

Because the upstream has not emitted a value yet or completed.  You are conflating an empty List with an empty Observable (https://reactivex.io/documentation/operators/defaultifempty.html)

A better solution to your problem would be using the flatMap or even switchMap operator if you expect a chatty upstream and only care about latest result, something like :

fun requestPageOfFilmsFromDataSource(): Observable<List<Film>> {
    return repo.getPageOfFilmsInCategory(category)
        .flatMap { films ->
            if (films.isNotEmpty()) {
                Observable.just(films)
            } else getFromRemote(category)
        }
}


问:
How to find sum of 2 date/time string in swift 5
I have multiple date/time string inside a loop

```<code>for item in self.sleepingActivityData ?? [] {
                    let value = Util.getFormattedDateString(inputDateString: self.findDateDiff(time1Str: item.startsAt ?? "", time2Str: item.endsAt ?? ""), inputDateFormat: "h m", outputDateFormat: "HH:mm")
                    print(value as Any) // "00:45"

                }
</code>```

value of 'value' is "00:45", "00:30", "00:45". I want to add this 3 timeString, So the sum should be "02:00"
how can I achieve this in swift?

This is my getFormattedDateString() func:

```<code>static func getFormattedDateString(inputDateString: String, inputDateFormat: String, outputDateFormat: String) -> String?{
        let dateFormatterInput = DateFormatter()
        dateFormatterInput.dateFormat = inputDateFormat//"yyyy-MM-dd HH:mm:ss"

        let dateFormatterOutput = DateFormatter()
        dateFormatterOutput.dateFormat = outputDateFormat//"EEEE, MMM dd hh:mm a"

        if let date = dateFormatterInput.date(from: inputDateString) {
            return (dateFormatterOutput.string(from: date))
        } else {
            return nil
        }
    }
</code>```

& thats how I found the difference between 2 time in findDateFiid() func:

```<code>   func findDateDiff(time1Str: String, time2Str: String) -> String {
        let timeformatter = DateFormatter()
        timeformatter.dateFormat = "HH:mm:ss"

        guard let time1 = timeformatter.date(from: time1Str),
            let time2 = timeformatter.date(from: time2Str) else { return "" }
        //You can directly use from here if you have two dates
        let interval = time2.timeIntervalSince(time1)
        let hour = interval / 3600;
        let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
        return "\(Int(hour)) \(Int(minute))"
    }
</code>```

答:
I coded this in playground, you cam replace date dateArray with your own array: self.sleepingActivityData

import UIKit

```<code>var dateArray = ["00:45", "00:30", "00:45"]
var sumH: Int = Int()
var sumM: Int = Int()

for (index, item) in dateArray.enumerated() {
    print(item as Any) // "00:45"
    if index < dateArray.count {
        addTime(timeStr: dateArray[index])
    }
}

func addTime(timeStr: String) {
    let values = timeStr.components(separatedBy: ":")
    //sum hours
    guard let h = Int(values[0]) else {return}
    //sum minutes
    guard let m = Int(values[1]) else {return}

    sumM = sumM + m
    sumH = sumH + h

    if sumM >= 60 {
        sumM = sumM - 60
        sumH = sumH+1
    }

    print("hours:",sumH)
    print("minutes:",sumM)
}
</code>```

Body:
I have multiple date/time string inside a loop

for item in self.sleepingActivityData ?? [] {
                    let value = Util.getFormattedDateString(inputDateString: self.findDateDiff(time1Str: item.startsAt ?? "", time2Str: item.endsAt ?? ""), inputDateFormat: "h m", outputDateFormat: "HH:mm")
                    print(value as Any) // "00:45"

                }

value of 'value' is "00:45", "00:30", "00:45". I want to add this 3 timeString, So the sum should be "02:00"
how can I achieve this in swift?

This is my getFormattedDateString() func:

static func getFormattedDateString(inputDateString: String, inputDateFormat: String, outputDateFormat: String) -> String?{
        let dateFormatterInput = DateFormatter()
        dateFormatterInput.dateFormat = inputDateFormat//"yyyy-MM-dd HH:mm:ss"

        let dateFormatterOutput = DateFormatter()
        dateFormatterOutput.dateFormat = outputDateFormat//"EEEE, MMM dd hh:mm a"

        if let date = dateFormatterInput.date(from: inputDateString) {
            return (dateFormatterOutput.string(from: date))
        } else {
            return nil
        }
    }

& thats how I found the difference between 2 time in findDateFiid() func:

   func findDateDiff(time1Str: String, time2Str: String) -> String {
        let timeformatter = DateFormatter()
        timeformatter.dateFormat = "HH:mm:ss"

        guard let time1 = timeformatter.date(from: time1Str),
            let time2 = timeformatter.date(from: time2Str) else { return "" }
        //You can directly use from here if you have two dates
        let interval = time2.timeIntervalSince(time1)
        let hour = interval / 3600;
        let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
        return "\(Int(hour)) \(Int(minute))"
    }

Body:
I coded this in playground, you cam replace date dateArray with your own array: self.sleepingActivityData

import UIKit

var dateArray = ["00:45", "00:30", "00:45"]
var sumH: Int = Int()
var sumM: Int = Int()

for (index, item) in dateArray.enumerated() {
    print(item as Any) // "00:45"
    if index < dateArray.count {
        addTime(timeStr: dateArray[index])
    }
}

func addTime(timeStr: String) {
    let values = timeStr.components(separatedBy: ":")
    //sum hours
    guard let h = Int(values[0]) else {return}
    //sum minutes
    guard let m = Int(values[1]) else {return}

    sumM = sumM + m
    sumH = sumH + h

    if sumM >= 60 {
        sumM = sumM - 60
        sumH = sumH+1
    }

    print("hours:",sumH)
    print("minutes:",sumM)
}


问:
Mock suspend that never returns
I'd like to mock a suspend function to never return any result. Analogous to this would be usage of Single.never().

Is it possible?

答:
My team achieved that with a suspendCancellableCoroutine that never calls resume(). Something like this:

```<code>suspend fun never(): Nothing = suspendCancellableCoroutine { }
</code>```

Title: Mock suspend that never returns

Body:
My team achieved that with a suspendCancellableCoroutine that never calls resume(). Something like this:

suspend fun never(): Nothing = suspendCancellableCoroutine { }


问:
Why is Tomcat doubling my log lines in the catalina.out logfile?
Every time I look at Tomcat's catalina.out log file, I see double lines for every log entry.  Why is this happening?  Has this happen before to any Java (Tomcat) users?

答:
This happens to me when i have 2 copies of log4j.properties on the classpath.
Check for multiple logging configurations</p>

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

OwnerDisplayName: Matt


问:
How do I use a relative import in a csproj template?
I've create a project template which contains a csproj which contains an Import pointing to a project file where I list all the third party project locations. I'm always using this project template to create projects in the same relative directory.

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="../../../3rdParty/ThirdParty.targets" />
  ...
  <ItemGroup>
    <Reference Include="Library, Version=$(LibraryVersion), Culture=neutral, PublicKeyToken=$(LibraryPublicKeyToken), processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>$(LibraryDir)LibraryDll.dll</HintPath>
    </Reference>
  </ItemGroup>
  ...
</Project>
</code>```

The csproj file works properly in Visual Studio and when running msbuild from the command prompt. When I try to create a project using the project template I get the following error:

C:\Users...\AppData\Local\Temp\534cylld.o0p\Temp\MyModule.csproj(3,3): The imported project "C:\Users...\AppData\Local\3rdParty\ThirdParty.targets" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk.

It seems that Visual Studio is trying to open the project in a temporary location first.
I've tried adding $(MSBuildProjectDirectory) to the import location hoping that it might force it to use the location I intended, but that also didn't work.

Any suggestions?

答:
I think I might use an environment variable instead... Would that work in your situation? And if you had to share the project templates between developers, you could do something fancy in a powershell script where it would set the environment variable either automatically or by asking the developer where his template directory is.

```<code>[Environment]::SetEnvironmentVariable("3rdPartyTargets", "%ProgramFiles%/3rdParty/ThirdParty.targets", "User")
</code>```

And then in csproj macro:

```<code><Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(3rdPartyTargets)" />
  ...
</code>```

Oh wait. That works for C++, but you might have to use msbuild for a c#/vb.net proj.

Body:
I've create a project template which contains a csproj which contains an Import pointing to a project file where I list all the third party project locations. I'm always using this project template to create projects in the same relative directory.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="../../../3rdParty/ThirdParty.targets" />
  ...
  <ItemGroup>
    <Reference Include="Library, Version=$(LibraryVersion), Culture=neutral, PublicKeyToken=$(LibraryPublicKeyToken), processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>$(LibraryDir)LibraryDll.dll</HintPath>
    </Reference>
  </ItemGroup>
  ...
</Project>

The csproj file works properly in Visual Studio and when running msbuild from the command prompt. When I try to create a project using the project template I get the following error:

C:\Users...\AppData\Local\Temp\534cylld.o0p\Temp\MyModule.csproj(3,3): The imported project "C:\Users...\AppData\Local\3rdParty\ThirdParty.targets" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk.

It seems that Visual Studio is trying to open the project in a temporary location first.
I've tried adding $(MSBuildProjectDirectory) to the import location hoping that it might force it to use the location I intended, but that also didn't work.

Any suggestions?

Body:
I think I might use an environment variable instead... Would that work in your situation? And if you had to share the project templates between developers, you could do something fancy in a powershell script where it would set the environment variable either automatically or by asking the developer where his template directory is.

[Environment]::SetEnvironmentVariable("3rdPartyTargets", "%ProgramFiles%/3rdParty/ThirdParty.targets", "User")

And then in csproj macro:

<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(3rdPartyTargets)" />
  ...

Oh wait. That works for C++, but you might have to use msbuild for a c#/vb.net proj.


问:
Tkinter.PhotoImage doesn't not support png image
I am using Tkinter to write a GUI and want to display a png file in a Tkiner.Label.
So I have some code like this:

```<code>self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
self.vcode.config(image=self.vcode.img)
</code>```

This code runs correctly on my Linux machine. But when I run it on my windows machine, it fails. I also tested on several other machines (include windows and linux), it failed all the time.

The Traceback is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
   self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: image format "png" is not supported
```

<p>If I delete <code>format='png'</code> in the source code, the traceback will become:</p>

<pre class="lang-none prettyprint-override"><code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read())
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't recognize image data
</code>```

So, what should I do to make it support png files?

答:
I used PhotoImage to add my Gui an icon with png format.
Like in below, It can work or give you an idea.</p>
```<code>iconn = PhotoImage(file = "arcen.png" )
root.iconphoto(0, iconn)
</code>```

Body:
I am using Tkinter to write a GUI and want to display a png file in a Tkiner.Label.
So I have some code like this:

self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
self.vcode.config(image=self.vcode.img)

This code runs correctly on my Linux machine. But when I run it on my windows machine, it fails. I also tested on several other machines (include windows and linux), it failed all the time.

The Traceback is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
   self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: image format "png" is not supported

If I delete format='png' in the source code, the traceback will become:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read())
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't recognize image data

So, what should I do to make it support png files?

Body:
I used PhotoImage to add my Gui an icon with png format.
Like in below, It can work or give you an idea.

iconn = PhotoImage(file = "arcen.png" )
root.iconphoto(0, iconn)


问:
Using User defined types in DB2
I am migrating my database from ORACLE to DB2, While doing the migrations I have come across a
situation related to User defined types. As I have been working with DB2 recently, I have been through the SQL standards and have been successful in migrating most of the stuffs.

I am kind of stuck with this UDT and tried with few of the suggestion by some DB experts here, but the thing I am trying to achieve isnt working well.

I have created the below UDT and created another UDT as table and been trying to use in a function.

```<code>CREATE OR REPLACE TYPE "XYZ" AS OBJECT (
   aa           VARCHAR2(30),
   bb   NUMBER (18),
   cc     NUMBER (30, 12),
   count      NUMBER (18),
   value_1             NUMBER (18),
   value_2             NUMBER (18),
   value_3             NUMBER (18),
   display_1           VARCHAR2 (256),
   display_2           VARCHAR2 (256),
   display_3           VARCHAR2 (256),
   status              NUMBER (1)
)
CREATE OR REPLACE TYPE "XYZ_TBL" AS TABLE OF XYZ;

</code>```

As I have read that If we create a UDT in DB2, DB2 automatically creates a function of the above XYZ without parameters I believe. And to use the UDT, we have to create a function calling the constructor. I created a function with a same name XYZ referencing the UDT.

```<code>CREATE OR REPLACE FUNCTION XYZ(
   aa                  VARCHAR2,
   bb                  NUMBER,
   cc                  NUMBER,
   count               NUMBER,
   value_1             NUMBER,
   value_2             NUMBER,
   value_3             NUMBER,
   display_1           VARCHAR2,
   display_2           VARCHAR2,
   display_3           VARCHAR2,
   status              NUMBER
)
return XYZ
IS
rec      xyz := xyz(cast(null as varchar), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as varchar), cast(null as varchar), cast(NULL as varchar),cast(null as decimal));
BEGIN
    RETURN rec;
END;
</code>```

Every thing got compiled perfectly . And I am calling this function in a package as

```<code> FUNCTION get_combinations(aa        VARCHAR2, bb     VARCHAR2,
                              cc  VARCHAR,  dd NUMBER,
                              prefix_1          VARCHAR2, prefix_2       VARCHAR2,
                              prefix_3          VARCHAR2, filter_1       NUMBER,
                              filter_2          NUMBER,   filter_3       NUMBER)
             RETURN xyz_tbl PIPELINED
    IS
        rec      xyz := xyz(cast(null as varchar), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as varchar), cast(null as varchar), cast(NULL as varchar),cast(null as decimal));
        cur      sys_refcursor;
        ccyCol   VARCHAR(64);
        txQuery  VARCHAR(4000);

\\and doing further stuffs
</code>```

Now, When I am using the function in one of the stored procedure, It gives me the below error

SQL0724N The activation of "XYZ" of type "FUNCTION " would exceed the maximum level of indirect SQL cascading.

and when I try to use the UDT XYZ directly into the package without creating any caller for it, the package is not able to locate XYZ and doesn't compile.

In a package I am using the function XYZ to pass the values from different set of tables and building a dynamic select query for further processing.

May be I am doing something wrong against the SQL standards?

答:
The constructor function for a structured type is created automatically by Db2. It returns a new object of the type with all fields set to NULL. You would then need to create setter methods to set the fields appropriately.

The "constructor" that you have defined calls itself recursively until it exceeds the maximum recursion level of 64.

Title: Using User defined types in DB2

Body:
I am migrating my database from ORACLE to DB2, While doing the migrations I have come across a
situation related to User defined types. As I have been working with DB2 recently, I have been through the SQL standards and have been successful in migrating most of the stuffs.

I am kind of stuck with this UDT and tried with few of the suggestion by some DB experts here, but the thing I am trying to achieve isnt working well.

I have created the below UDT and created another UDT as table and been trying to use in a function.

CREATE OR REPLACE TYPE "XYZ" AS OBJECT (
   aa           VARCHAR2(30),
   bb   NUMBER (18),
   cc     NUMBER (30, 12),
   count      NUMBER (18),
   value_1             NUMBER (18),
   value_2             NUMBER (18),
   value_3             NUMBER (18),
   display_1           VARCHAR2 (256),
   display_2           VARCHAR2 (256),
   display_3           VARCHAR2 (256),
   status              NUMBER (1)
)
CREATE OR REPLACE TYPE "XYZ_TBL" AS TABLE OF XYZ;

As I have read that If we create a UDT in DB2, DB2 automatically creates a function of the above XYZ without parameters I believe. And to use the UDT, we have to create a function calling the constructor. I created a function with a same name XYZ referencing the UDT.

CREATE OR REPLACE FUNCTION XYZ(
   aa                  VARCHAR2,
   bb                  NUMBER,
   cc                  NUMBER,
   count               NUMBER,
   value_1             NUMBER,
   value_2             NUMBER,
   value_3             NUMBER,
   display_1           VARCHAR2,
   display_2           VARCHAR2,
   display_3           VARCHAR2,
   status              NUMBER
)
return XYZ
IS
rec      xyz := xyz(cast(null as varchar), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as varchar), cast(null as varchar), cast(NULL as varchar),cast(null as decimal));
BEGIN
    RETURN rec;
END;

Every thing got compiled perfectly . And I am calling this function in a package as

 FUNCTION get_combinations(aa        VARCHAR2, bb     VARCHAR2,
                              cc  VARCHAR,  dd NUMBER,
                              prefix_1          VARCHAR2, prefix_2       VARCHAR2,
                              prefix_3          VARCHAR2, filter_1       NUMBER,
                              filter_2          NUMBER,   filter_3       NUMBER)
             RETURN xyz_tbl PIPELINED
    IS
        rec      xyz := xyz(cast(null as varchar), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as decimal), cast(null as varchar), cast(null as varchar), cast(NULL as varchar),cast(null as decimal));
        cur      sys_refcursor;
        ccyCol   VARCHAR(64);
        txQuery  VARCHAR(4000);

\\and doing further stuffs

Now, When I am using the function in one of the stored procedure, It gives me the below error

SQL0724N The activation of "XYZ" of type "FUNCTION " would exceed the maximum level of indirect SQL cascading.

and when I try to use the UDT XYZ directly into the package without creating any caller for it, the package is not able to locate XYZ and doesn't compile.

In a package I am using the function XYZ to pass the values from different set of tables and building a dynamic select query for further processing.

May be I am doing something wrong against the SQL standards?


问:
WebView doesn't load fully and doesn't react in Android
I have a WebView in Android and am trying to load this website: https://www.zomato.com/mount-kembla-nsw/rubys-mount-kembla-mount-kembla/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop

The problem is that the loading bar gets stuck towards the end and the "Continue in app" and "Continue in browser" show, but nothing happens when clicked. I can scroll the WebView, but it's greyed out and not loaded fully. This is my code:

```<code>val webView = binding.webView

webView.post {
                webView.settings.allowContentAccess = true
                webView.settings.loadWithOverviewMode = true
                webView.settings.useWideViewPort = true
                webView.settings.builtInZoomControls = true
                webView.settings.allowFileAccess = true
                webView.settings.domStorageEnabled = true
                webView.settings.cacheMode = WebSettings.LOAD_DEFAULT
                webView.settings.loadsImagesAutomatically = true

                webView.webViewClient = WebViewClient()
                webView.loadUrl(restaurantInfo.menu_url!!)
            }
</code>```

Any help will be appreciated.

答:
try to enable javaScript in your web view with this code:</p>
```<code>webView.settings.javaScriptEnabled=true
webView.settings.javaScriptCanOpenWindowsAutomatically=true
</code>```

Body:
I have a WebView in Android and am trying to load this website: https://www.zomato.com/mount-kembla-nsw/rubys-mount-kembla-mount-kembla/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop

The problem is that the loading bar gets stuck towards the end and the "Continue in app" and "Continue in browser" show, but nothing happens when clicked. I can scroll the WebView, but it's greyed out and not loaded fully. This is my code:

val webView = binding.webView

webView.post {
                webView.settings.allowContentAccess = true
                webView.settings.loadWithOverviewMode = true
                webView.settings.useWideViewPort = true
                webView.settings.builtInZoomControls = true
                webView.settings.allowFileAccess = true
                webView.settings.domStorageEnabled = true
                webView.settings.cacheMode = WebSettings.LOAD_DEFAULT
                webView.settings.loadsImagesAutomatically = true

                webView.webViewClient = WebViewClient()
                webView.loadUrl(restaurantInfo.menu_url!!)
            }

Any help will be appreciated.

Body:
try to enable javaScript in your web view with this code:

webView.settings.javaScriptEnabled=true
webView.settings.javaScriptCanOpenWindowsAutomatically=true


问:
My localhost/H2-console doesn't create my tables
Yoo Codeers,
have issue with h2-console if i create table in java and open h2-console on port what i using, so i don't see my tables,i following one video,but for me doesn't work.

POM

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>sk.wynny</groupId>
    <artifactId>springLearn</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springLearn</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

MOVIE CLASS

```<code>package sk.wynny.model;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Movie {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;

    @ManyToMany
    @JoinTable(name = "movie_director",joinColumns =
    @JoinColumn(name = "movie_id"),inverseJoinColumns = @JoinColumn(name ="director_id" ))
    Set<Director> movieSet = new HashSet<>();

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Movie() {
    }
}
</code>```

**Basic Class **

```<code>package sk.wynny.springlearn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringLearnApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringLearnApplication.class, args);
    }

}
</code>```

app properties - from following video what i see, he doesnt use log info,he just use spring.h2.console.enabled=true and for him was worked,i try many options simply like that (but,can't connect to my h2-console,cause error),or like this bellow.. i connect to my h2 DB,but didnt see my tables.

```<code>   server.port=8080
    spring.h2.console.enabled=true
    spring.datasource.platform=h2
    spring.datasource.url=jdbc:h2:mem:wynny

    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    spring.datasource.driver-class-name=org.h2.Driver
    spring.datasource.username=wynny
</code>```

Have some tips how repair it ? :D
Director class is not included in this post,is same like MOVIES.

答:
AFTER RUN

```<code>2022-02-13 15:03:22.146  INFO 13392 --- [           main] s.w.springlearn.SpringLearnApplication   : Starting SpringLearnApplication using Java 17.0.1 on DESKTOP-K3O8I67 with PID 13392 (C:\Users\Patrik Severín\IdeaProjects\springLearn\target\classes started by Wynny in C:\Users\Patrik Severín\IdeaProjects\springLearn)
2022-02-13 15:03:22.148  INFO 13392 --- [           main] s.w.springlearn.SpringLearnApplication   : No active profile set, falling back to default profiles: default
2022-02-13 15:03:22.923  INFO 13392 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-02-13 15:03:22.940  INFO 13392 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 6 ms. Found 0 JPA repository interfaces.
2022-02-13 15:03:23.589  INFO 13392 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-02-13 15:03:23.599  INFO 13392 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-13 15:03:23.600  INFO 13392 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-13 15:03:23.704  INFO 13392 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-13 15:03:23.704  INFO 13392 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1509 ms
2022-02-13 15:03:23.739  INFO 13392 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-02-13 15:03:23.931  INFO 13392 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-02-13 15:03:23.943  INFO 13392 --- [           main] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:file:C:\Users\Patrik Severín\IdeaProjects\springLearn/data/sample'
2022-02-13 15:03:24.095  INFO 13392 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-02-13 15:03:24.143  INFO 13392 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.4.Final
2022-02-13 15:03:24.298  INFO 13392 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-02-13 15:03:24.433  INFO 13392 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2022-02-13 15:03:24.624  INFO 13392 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-02-13 15:03:24.634  INFO 13392 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-02-13 15:03:24.674  WARN 13392 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-02-13 15:03:24.930  WARN 13392 --- [           main] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2022-02-13 15:03:25.045  INFO 13392 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-02-13 15:03:25.057  INFO 13392 --- [           main] s.w.springlearn.SpringLearnApplication   : Started SpringLearnApplication in 3.292 seconds (JVM running for 3.695)
</code>```

h2 console write this

```<code>Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200] 90149/90149 (Help)
org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:622)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
    at org.h2.message.DbException.get(DbException.java:205)
    at org.h2.message.DbException.get(DbException.java:181)
    at org.h2.engine.Engine.openSession(Engine.java:71)
    at org.h2.engine.Engine.openSession(Engine.java:192)
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:171)
    at org.h2.engine.Engine.createSession(Engine.java:166)
    at org.h2.engine.Engine.createSession(Engine.java:29)
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152)
    at org.h2.Driver.connect(Driver.java:69)
    at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:309)
    at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:289)
    at org.h2.server.web.WebServer.getConnection(WebServer.java:785)
    at org.h2.server.web.WebApp.login(WebApp.java:1008)
    at org.h2.server.web.WebApp.process(WebApp.java:223)
    at org.h2.server.web.WebApp.processRequest(WebApp.java:173)
    at org.h2.server.web.WebServlet.doGet(WebServlet.java:129)
    at org.h2.server.web.WebServlet.doPost(WebServlet.java:166)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

Body:
Yoo Codeers,
have issue with h2-console if i create table in java and open h2-console on port what i using, so i don't see my tables,i following one video,but for me doesn't work.

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/>
    </parent>
    <groupId>sk.wynny</groupId>
    <artifactId>springLearn</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springLearn</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

MOVIE CLASS

package sk.wynny.model;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Movie {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;

    @ManyToMany
    @JoinTable(name = "movie_director",joinColumns =
    @JoinColumn(name = "movie_id"),inverseJoinColumns = @JoinColumn(name ="director_id" ))
    Set<Director> movieSet = new HashSet<>();

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Movie() {
    }
}

**Basic Class **

package sk.wynny.springlearn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringLearnApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringLearnApplication.class, args);
    }

}

app properties - from following video what i see, he doesnt use log info,he just use spring.h2.console.enabled=true and for him was worked,i try many options simply like that (but,can't connect to my h2-console,cause error),or like this bellow.. i connect to my h2 DB,but didnt see my tables.

   server.port=8080
    spring.h2.console.enabled=true
    spring.datasource.platform=h2
    spring.datasource.url=jdbc:h2:mem:wynny

    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    spring.datasource.driver-class-name=org.h2.Driver
    spring.datasource.username=wynny

Have some tips how repair it ? :D
Director class is not included in this post,is same like MOVIES.

Body:
AFTER RUN

2022-02-13 15:03:22.146  INFO 13392 --- [           main] s.w.springlearn.SpringLearnApplication   : Starting SpringLearnApplication using Java 17.0.1 on DESKTOP-K3O8I67 with PID 13392 (C:\Users\Patrik Severín\IdeaProjects\springLearn\target\classes started by Wynny in C:\Users\Patrik Severín\IdeaProjects\springLearn)
2022-02-13 15:03:22.148  INFO 13392 --- [           main] s.w.springlearn.SpringLearnApplication   : No active profile set, falling back to default profiles: default
2022-02-13 15:03:22.923  INFO 13392 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-02-13 15:03:22.940  INFO 13392 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 6 ms. Found 0 JPA repository interfaces.
2022-02-13 15:03:23.589  INFO 13392 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-02-13 15:03:23.599  INFO 13392 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-13 15:03:23.600  INFO 13392 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-13 15:03:23.704  INFO 13392 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-13 15:03:23.704  INFO 13392 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1509 ms
2022-02-13 15:03:23.739  INFO 13392 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-02-13 15:03:23.931  INFO 13392 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-02-13 15:03:23.943  INFO 13392 --- [           main] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:file:C:\Users\Patrik Severín\IdeaProjects\springLearn/data/sample'
2022-02-13 15:03:24.095  INFO 13392 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-02-13 15:03:24.143  INFO 13392 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.4.Final
2022-02-13 15:03:24.298  INFO 13392 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-02-13 15:03:24.433  INFO 13392 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2022-02-13 15:03:24.624  INFO 13392 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-02-13 15:03:24.634  INFO 13392 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-02-13 15:03:24.674  WARN 13392 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-02-13 15:03:24.930  WARN 13392 --- [           main] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2022-02-13 15:03:25.045  INFO 13392 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-02-13 15:03:25.057  INFO 13392 --- [           main] s.w.springlearn.SpringLearnApplication   : Started SpringLearnApplication in 3.292 seconds (JVM running for 3.695)

h2 console write this

Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200] 90149/90149 (Help)
org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:622)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
    at org.h2.message.DbException.get(DbException.java:205)
    at org.h2.message.DbException.get(DbException.java:181)
    at org.h2.engine.Engine.openSession(Engine.java:71)
    at org.h2.engine.Engine.openSession(Engine.java:192)
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:171)
    at org.h2.engine.Engine.createSession(Engine.java:166)
    at org.h2.engine.Engine.createSession(Engine.java:29)
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152)
    at org.h2.Driver.connect(Driver.java:69)
    at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:309)
    at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:289)
    at org.h2.server.web.WebServer.getConnection(WebServer.java:785)
    at org.h2.server.web.WebApp.login(WebApp.java:1008)
    at org.h2.server.web.WebApp.process(WebApp.java:223)
    at org.h2.server.web.WebApp.processRequest(WebApp.java:173)
    at org.h2.server.web.WebServlet.doGet(WebServlet.java:129)
    at org.h2.server.web.WebServlet.doPost(WebServlet.java:166)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)


问:
Java get duplicated elements more than 2 list
I have 9 list and I want to compare all of them and get duplicated elements.

I tried  retainAll() method but it deletes elements that is not duplicated.

For example when I only compare SUPPORT and PROJECT_AND_SUPPORT_NAMES I get duplicated value.

But when I compare like below it returns empty.

```<code>        MANAGEMENT_NAMES.retainAll(SUPPORT_NAMES);
        MANAGEMENT_NAMES.retainAll(PROJECT_AND_SUPPORT_NAMES);
        MANAGEMENT_NAMES.retainAll(SALES_NAMES);
        MANAGEMENT_NAMES.retainAll(MARKETING_NAMES);
        MANAGEMENT_NAMES.retainAll(ACADEMY_NAMES);
        MANAGEMENT_NAMES.retainAll(DEVELOPMENT_NAMES);
        MANAGEMENT_NAMES.retainAll(HR_AND_ADMINISTRATION_NAMES);
        MANAGEMENT_NAMES.retainAll(WAREHOUSE_NAMES);

        SUPPORT_NAMES.retainAll(PROJECT_AND_SUPPORT_NAMES);
        SUPPORT_NAMES.retainAll(SALES_NAMES);
        SUPPORT_NAMES.retainAll(MARKETING_NAMES);
        SUPPORT_NAMES.retainAll(ACADEMY_NAMES);
        SUPPORT_NAMES.retainAll(DEVELOPMENT_NAMES);
        SUPPORT_NAMES.retainAll(HR_AND_ADMINISTRATION_NAMES);
        SUPPORT_NAMES.retainAll(WAREHOUSE_NAMES);

        PROJECT_AND_SUPPORT_NAMES.retainAll(SALES_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(MARKETING_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(ACADEMY_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(DEVELOPMENT_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(HR_AND_ADMINISTRATION_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(WAREHOUSE_NAMES);
.
.
.

        HR_AND_ADMINISTRATION_NAMES.retainAll(WAREHOUSE_NAMES);
</code>```

I want to get result like :

Department A - Jerry

Department B - Chris

Department C - Jerry

Department D - Chris

Department E - Chris

Department F - Jerry

答:
You said that this was the meaning of duplicate that you wanted:

"elements that appear more than once in any one of the lists"

Here is a simple solution.

```<code>Set<String> duplicates = new HashSet<>();

for (List<String> list: lists) {
    Set<String> all = new HashSet<>();
    for (String s: list) {
        if (!all.add(s)) {
            duplicates.add(s);
        }
    }
}
</code>```

The logic is that a string will only be added to duplicates if it was already in all.  (The add method will return true if the element wasn't in the set already.  Check the javadocs.)

Since you want elements that are duplicate within a given list, we need to reset all for each list.

This could be coded in other ways (e.g. using Java 8+ streams), but in a situation like this, the most important thing is that you can understand the code.

Body:
I have 9 list and I want to compare all of them and get duplicated elements.

I tried  retainAll() method but it deletes elements that is not duplicated.

For example when I only compare SUPPORT and PROJECT_AND_SUPPORT_NAMES I get duplicated value.

But when I compare like below it returns empty.

        MANAGEMENT_NAMES.retainAll(SUPPORT_NAMES);
        MANAGEMENT_NAMES.retainAll(PROJECT_AND_SUPPORT_NAMES);
        MANAGEMENT_NAMES.retainAll(SALES_NAMES);
        MANAGEMENT_NAMES.retainAll(MARKETING_NAMES);
        MANAGEMENT_NAMES.retainAll(ACADEMY_NAMES);
        MANAGEMENT_NAMES.retainAll(DEVELOPMENT_NAMES);
        MANAGEMENT_NAMES.retainAll(HR_AND_ADMINISTRATION_NAMES);
        MANAGEMENT_NAMES.retainAll(WAREHOUSE_NAMES);

        SUPPORT_NAMES.retainAll(PROJECT_AND_SUPPORT_NAMES);
        SUPPORT_NAMES.retainAll(SALES_NAMES);
        SUPPORT_NAMES.retainAll(MARKETING_NAMES);
        SUPPORT_NAMES.retainAll(ACADEMY_NAMES);
        SUPPORT_NAMES.retainAll(DEVELOPMENT_NAMES);
        SUPPORT_NAMES.retainAll(HR_AND_ADMINISTRATION_NAMES);
        SUPPORT_NAMES.retainAll(WAREHOUSE_NAMES);

        PROJECT_AND_SUPPORT_NAMES.retainAll(SALES_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(MARKETING_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(ACADEMY_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(DEVELOPMENT_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(HR_AND_ADMINISTRATION_NAMES);
        PROJECT_AND_SUPPORT_NAMES.retainAll(WAREHOUSE_NAMES);
.
.
.

        HR_AND_ADMINISTRATION_NAMES.retainAll(WAREHOUSE_NAMES);

I want to get result like :

Department A - Jerry

Department B - Chris

Department C - Jerry

Department D - Chris

Department E - Chris

Department F - Jerry

Body:
You said that this was the meaning of duplicate that you wanted:

"elements that appear more than once in any one of the lists"

Here is a simple solution.

Set<String> duplicates = new HashSet<>();

for (List<String> list: lists) {
    Set<String> all = new HashSet<>();
    for (String s: list) {
        if (!all.add(s)) {
            duplicates.add(s);
        }
    }
}

The logic is that a string will only be added to duplicates if it was already in all.  (The add method will return true if the element wasn't in the set already.  Check the javadocs.)

Since you want elements that are duplicate within a given list, we need to reset all for each list.

This could be coded in other ways (e.g. using Java 8+ streams), but in a situation like this, the most important thing is that you can understand the code.


问:
Recreation of grid with flex box text alignment
I am pretty new to flexbox and I am trying to get proficient with it. I am trying to recreate this grid with flexbox - it's pretty close but I am having trouble with the text alignment, How can I align the flexbox text the way the grid text is aligned?'

Edit: I don't know what's unclear about this. I am trying to make the flex box aligned left-center the same way the bottom grid is. The flex box is centered but not left justified.

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet"/>

This is Flex:

Box 1.1

Box 1.1 Flexbox

Box 1.2

Box 1.2 Flexbox

Box 1.3

Box 1.3 Flexbox

    This is Grid:

Box 2.1

Box 2.1 Flexbox

Box 2.2

Box 2.2 Flexbox

Box 2.3

Box 2.3 Flexbox

```

答:
How can I align the flexbox text the way the grid text is aligned?'

Can't be done (with plain CSS).

Grid establishes column tracks. You can align content within those tracks (hence, the left-alignment).

Flex has no such column tracks, just flex lines. This means that the content has nothing to left-align against (beyond the container borders). It can only align along the flex line based on the free space.


问:
REACT onclick change color of div
I am trying to change each div's color onClick. The problem in my code is that all divs change color when one is clicked. Looking for a way to change each one's color individually

Here is my code :

```<code>class Main extends React.PureComponent {
state = {
    color: 'blue',
};
onChange = () => {
    this.setState({color: 'red'});
};
render() {
    return (
        <Box sx={SX.root}>
            <Box sx={SX.page}>
                <Box sx={SX.shapeContainer}>
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                </Box>
                <MathGrid sx={SX.math1} />
            </Box>

            <Box sx={SX.header} />
            <Box sx={SX.footer} />
        </Box>
    );
}
</code>```

output

答:
You have to create separate component for each div with changeable colour. This way each component will have its own independently managed state. In your example, you share same color state as the rest.

BoxComponent

```<code>class BoxComponent extends React.Component {
    state = {
        color: "blue",
    };

    onChange = () => {
        this.setState({ color: "red" });
    };

    render() {
        return (
            <div
                style={{ backgroundColor: this.state.color, width: 20, height: 20, opacity: "50%" }}
                onClick={this.onChange}
            />
        );
    }
}

</code>```

MainComponent

```<code>class Main extends React.PureComponent {
    render() {
        return (
            <Box sx={SX.root}>
                <Box sx={SX.page}>
                    <Box sx={SX.shapeContainer}>
                        <BoxComponent />
                        <BoxComponent />
                    </Box>
                    <MathGrid sx={SX.math1} />
                </Box>

                <Box sx={SX.header} />
                <Box sx={SX.footer} />
            </Box>
        );
    }
}
</code>```

Title: REACT onclick change color of div

Body:
I am trying to change each div's color onClick. The problem in my code is that all divs change color when one is clicked. Looking for a way to change each one's color individually

Here is my code :

class Main extends React.PureComponent {
state = {
    color: 'blue',
};
onChange = () => {
    this.setState({color: 'red'});
};
render() {
    return (
        <Box sx={SX.root}>
            <Box sx={SX.page}>
                <Box sx={SX.shapeContainer}>

                </Box>
                <MathGrid sx={SX.math1} />
            </Box>

            <Box sx={SX.header} />
            <Box sx={SX.footer} />
        </Box>
    );
}

output

Body:
You have to create separate component for each div with changeable colour. This way each component will have its own independently managed state. In your example, you share same color state as the rest.

BoxComponent

class BoxComponent extends React.Component {
    state = {
        color: "blue",
    };

    onChange = () => {
        this.setState({ color: "red" });
    };

    render() {
        return (
            <div
                style={{ backgroundColor: this.state.color, width: 20, height: 20, opacity: "50%" }}
                onClick={this.onChange}
            />
        );
    }
}

MainComponent

class Main extends React.PureComponent {
    render() {
        return (
            <Box sx={SX.root}>
                <Box sx={SX.page}>
                    <Box sx={SX.shapeContainer}>
                        <BoxComponent />
                        <BoxComponent />
                    </Box>
                    <MathGrid sx={SX.math1} />
                </Box>

                <Box sx={SX.header} />
                <Box sx={SX.footer} />
            </Box>
        );
    }
}


问:
Finding and Dropping the Negative values
Database

In this database i have, there are negative values in "Benefits", "OvertimePay" and "OtherPay"
How can i drop the rows that have negative values in any of those 3 columns ?

Thank You.

答:
you are close with df[df['Benefits'] < 0]. You need any of those 3 columns to have this so you can "or" them with |. But you want to drop so we put ~ beginnig to invert the condition and select others.

```<code>new = df[~((df['Benefits'] < 0) | (df['OvertimePay'] < 0) | (df['OtherPay'] < 0))].copy()
</code>```

(i copy so you get not a view but a copy)

but there is a better way with any

```<code>new = df[~df[['Benefits', 'OvertimePay', 'OtherPay']].lt(0).any(axis=1)].copy()
</code>```

lt is a method way of < (less than). any(axis=1) checks if any of the columns has less than 0.

maybe better to write two lines

```<code>drop_these = df[['Benefits', 'OvertimePay', 'OtherPay']].lt(0).any(axis=1)
new = df[~drop_these].copy()
</code>```

Body:
you are close with df[df['Benefits'] < 0]. You need any of those 3 columns to have this so you can "or" them with |. But you want to drop so we put ~ beginnig to invert the condition and select others.

new = df[~((df['Benefits'] < 0) | (df['OvertimePay'] < 0) | (df['OtherPay'] < 0))].copy()

(i copy so you get not a view but a copy)

but there is a better way with any

new = df[~df[['Benefits', 'OvertimePay', 'OtherPay']].lt(0).any(axis=1)].copy()

lt is a method way of < (less than). any(axis=1) checks if any of the columns has less than 0.

maybe better to write two lines

drop_these = df[['Benefits', 'OvertimePay', 'OtherPay']].lt(0).any(axis=1)
new = df[~drop_these].copy()