问:
How to do nested partials to construct "incomplete" object trees in TypeScript?
I have this basically (a small snippet of the types I have so far, which is far from complete yet):

```<code>export type ASTFormType = {
  base: Array<ASTFormType>;
  hook: Record<string, ASTHookType>;
  like: "form";
  link: Record<string, ASTTakeType>;
  name: string;
  task: Record<string, ASTTaskType>;
  wear: Record<string, ASTWearType>;
};

export type ASTHookType = {
  flow: Array<ASTTaskFlowType>;
  like: "hook";
  name: string;
  take: Record<string, ASTTakeType>;
};

export type ASTTaskCallType = {
  bind: Record<string, ASTBindType>;
  like: "call";
};

export type ASTHoldType = {
  like: "hold";
};

export type ASTTakeType = {
  like: "take";
  name: string;
  takeLike: ASTLikeType;
};

export type ASTLikeType = {
  bind?: Record<string, ASTLikeType>;
  like: "like";
  name: string;
};

export type ASTTaskFlowType = ASTTaskCallType | ASTHoldType;

export type ASTBindType = {
  bond: ASTBondType;
  like: "bind";
  name: string;
};

export type ASTBondType = ASTCordType | ASTMarkType;

export type ASTCordType = {
  cord: string;
  like: "cord";
};

export type ASTMarkType = {
  like: "mark";
  mark: number;
};

export type ASTWearType = {
  like: "wear";
  link: Record<string, ASTTakeType>;
  name: string;
  task: Record<string, ASTTaskType>;
};

export type ASTTaskType = {
  like: "task";
  move: Array<ASTTaskFlowType>;
  take: Record<string, ASTTakeType>;
  task: Record<string, ASTTaskType>;
};
</code>```

The type ASTFormType has a bunch of nested objects, which can have nested objects / arrays of nested objects, etc.. So you could have:

```<code>  const formA = {
    like: 'form',
    name: 'user',
    link: {
      email: {
        name: 'email',
        takeLike: {
          name: 'string'
        }
      },
      username: {
        name: 'username',
        takeLike: {
          name: 'string'
        }
      }
    },
    task: {
      login: { ... }
    }
  }
</code>```

But, in this compiler, when this object is first constructed, it is hardly filled out. Instead of being filled out, it looks essentially like this (this is what I currently have):

```<code>export type NestedPartial<T extends object> = {
  [K in keyof T]?: T[K] extends object ? NestedPartial<T[K]> : T[K];
};

const form: NestedPartial<ASTFormType> = {
  base: [],
  hook: {},
  like: "form",
  link: {},
  // name: "", // leave off for demo purposes
  task: {},
  // wear: {}, // leave this off for demo purposes
};
</code>```

With that NestedPartial, I am trying to say "this form record itself is partial", meaning it doesn't have all it's properties necessarily. And also want to say, all the nested maps and arrays have objects which are also partial! So something like this (which doesn't work):

```<code>const form: Partial<ASTFormType> = {
  base: <Partial<ASTLikeType>>[],
  hook: <Record<string, Partial<ASTHookType>>>{},
  like: "form",
  link: <Record<string, Partial<ASTTakeType>>>{},
  task: <Record<string, Partial<ASTTaskType>>>{},
};
</code>```

But (a), that is a lot of annotations, and (b) it doesn't actually work (syntax error).

How can I do something like this though? Partially typing the tree of objects. I don't want to say (recursively) that everything is Partial (like my NestedPartial tries to do (but fails at for some reason)). I want to just say that specific pieces of the tree of objects are Partial. How can I accomplish something like that?

That way, I can progressively build up the objects and some attributes can be undefined while I am in the middle of processing. Only later will I strip out the Partial from the definition, to get back to the inner object fully filled out!

Body:
I have this basically (a small snippet of the types I have so far, which is far from complete yet):

export type ASTFormType = {
  base: Array<ASTFormType>;
  hook: Record<string, ASTHookType>;
  like: "form";
  link: Record<string, ASTTakeType>;
  name: string;
  task: Record<string, ASTTaskType>;
  wear: Record<string, ASTWearType>;
};

export type ASTHookType = {
  flow: Array<ASTTaskFlowType>;
  like: "hook";
  name: string;
  take: Record<string, ASTTakeType>;
};

export type ASTTaskCallType = {
  bind: Record<string, ASTBindType>;
  like: "call";
};

export type ASTHoldType = {
  like: "hold";
};

export type ASTTakeType = {
  like: "take";
  name: string;
  takeLike: ASTLikeType;
};

export type ASTLikeType = {
  bind?: Record<string, ASTLikeType>;
  like: "like";
  name: string;
};

export type ASTTaskFlowType = ASTTaskCallType | ASTHoldType;

export type ASTBindType = {
  bond: ASTBondType;
  like: "bind";
  name: string;
};

export type ASTBondType = ASTCordType | ASTMarkType;

export type ASTCordType = {
  cord: string;
  like: "cord";
};

export type ASTMarkType = {
  like: "mark";
  mark: number;
};

export type ASTWearType = {
  like: "wear";
  link: Record<string, ASTTakeType>;
  name: string;
  task: Record<string, ASTTaskType>;
};

export type ASTTaskType = {
  like: "task";
  move: Array<ASTTaskFlowType>;
  take: Record<string, ASTTakeType>;
  task: Record<string, ASTTaskType>;
};

The type ASTFormType has a bunch of nested objects, which can have nested objects / arrays of nested objects, etc.. So you could have:

  const formA = {
    like: 'form',
    name: 'user',
    link: {
      email: {
        name: 'email',
        takeLike: {
          name: 'string'
        }
      },
      username: {
        name: 'username',
        takeLike: {
          name: 'string'
        }
      }
    },
    task: {
      login: { ... }
    }
  }

But, in this compiler, when this object is first constructed, it is hardly filled out. Instead of being filled out, it looks essentially like this (this is what I currently have):

export type NestedPartial<T extends object> = {
  [K in keyof T]?: T[K] extends object ? NestedPartial<T[K]> : T[K];
};

const form: NestedPartial<ASTFormType> = {
  base: [],
  hook: {},
  like: "form",
  link: {},
  // name: "", // leave off for demo purposes
  task: {},
  // wear: {}, // leave this off for demo purposes
};

With that NestedPartial, I am trying to say "this form record itself is partial", meaning it doesn't have all it's properties necessarily. And also want to say, all the nested maps and arrays have objects which are also partial! So something like this (which doesn't work):

const form: Partial<ASTFormType> = {
  base: <Partial<ASTLikeType>>[],
  hook: <Record<string, Partial<ASTHookType>>>{},
  like: "form",
  link: <Record<string, Partial<ASTTakeType>>>{},
  task: <Record<string, Partial<ASTTaskType>>>{},
};

But (a), that is a lot of annotations, and (b) it doesn't actually work (syntax error).

How can I do something like this though? Partially typing the tree of objects. I don't want to say (recursively) that everything is Partial (like my NestedPartial tries to do (but fails at for some reason)). I want to just say that specific pieces of the tree of objects are Partial. How can I accomplish something like that?

That way, I can progressively build up the objects and some attributes can be undefined while I am in the middle of processing. Only later will I strip out the Partial from the definition, to get back to the inner object fully filled out!


来源: stackexchange

问:
Call Rest endpoint and display data into Spring MVC table
I have this Endpoint:

```<code>@RestController
public class FileImportsController {

    private EntityImportRequestsService entityImportRequestsService;

    @Autowired
    public FileImportsController(EntityImportRequestsService entityImportRequestsService) {
        this.entityImportRequestsService = entityImportRequestsService;
    }

    @GetMapping("/imported_files")
    public String viewHomePage(Model model) {
        List<EntityImportRequestsTable> listProducts = entityImportRequestsService.findAll();
        System.out.println("Size is " + listProducts.size());

        model.addAttribute("listProducts", listProducts);
        return "index";
    }
}
</code>```

Entity:

```<code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Entity
@Table(name = "EntityImportRequests")
public class EntityImportRequestsTable implements Serializable {

    @Id
    @Column(name = "requestId")
    private String requestId;
}
</code>```

Web page index.html

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8"/>
  <title>Product Manager</title>
</head>
<body>
<div align="center">
  <h1>Product List</h1>
  <table border="1" cellpadding="10">
    <tr>
      <th>requestId</th>
    </tr>
    <tr th:each="product: ${listProducts}">
      <td th:text="${product.requestId}" />
      <td th:text="${product.name}" />
      <td th:text="${product.price}" />
    </tr>
  </table>
</div>
</body>
</html>
</code>```

When I open the page data is not displayed. What is the proper way to call endpoint imported_files and display all the data?

ContentLicense: CC BY-SA 4.0

Body:
I have this Endpoint:

@RestController
public class FileImportsController {

    private EntityImportRequestsService entityImportRequestsService;

    @Autowired
    public FileImportsController(EntityImportRequestsService entityImportRequestsService) {
        this.entityImportRequestsService = entityImportRequestsService;
    }

    @GetMapping("/imported_files")
    public String viewHomePage(Model model) {
        List<EntityImportRequestsTable> listProducts = entityImportRequestsService.findAll();
        System.out.println("Size is " + listProducts.size());

        model.addAttribute("listProducts", listProducts);
        return "index";
    }
}

Entity:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Entity
@Table(name = "EntityImportRequests")
public class EntityImportRequestsTable implements Serializable {

    @Id
    @Column(name = "requestId")
    private String requestId;
}

Web page index.html

<!DOCTYPE html>

  <meta charset="utf-8"/>
  <title>Product Manager</title>

Product List

      requestId

When I open the page data is not displayed. What is the proper way to call endpoint imported_files and display all the data?


问:
How do I reliably detect if a Browser session is in incognito mode / inPrivate browsing?
I want to be able to detect if a user is using incognito mode or such other styles of temporary sessions.

I've been using detectIncognito, but it relies on measuring heap quota and I don't believe it will remain accessible for long due to security concerns.
I also considered using Google Analytics to check if a cookie is newly requested from a previous users IP, but that might be overcomplicating things and relies on allowing the cookie.


问:
Add hyperlink to cell of flextable that open in a new tab
How do I add a hyperlink to the text in a cell of a flextable? The hyperlink should be underlined and open in a new tab.

In the R script below, This is a link to google. should be the hyperlink.

I included the hyperlink_text example from the documentation which results in an error for me.

```<code>library(tidyverse)
library(flextable)

df <- tibble(
  desc = c("R1", "R2", "R3"),
  A = c("This is a long sentence that should go over into B's column. This is a link to google.", "just one cell in colA", "just one cell in colA"),
  B = c("", "just one cell in colB", "just one cell in colB"),
  C = c("just one cell in colC", "just one cell in colC", "just one cell in colC")
)

flextable(df) |>
  merge_at(i = 1, j = 2:3)

# hyperlink_text p.103
# From documentation: https://cran.r-project.org/web/packages/flextable/flextable.pdf
dat <- data.frame(
  col = "Google it",
  href = "https://www.google.fr/search?source=hp&q=flextable+R+package",
  stringsAsFactors = FALSE)
ftab <- flextable(dat)
ftab <- compose( x = ftab, j = "col",
                 value = as_paragraph(
                   "This is a link: ",
                   hyperlink_text(x = col, url = href ) ) )

# Error in data.frame(x = x, url = url, stringsAsFactors = FALSE) :
#   object 'href' not found
</code>```

Body:
How do I add a hyperlink to the text in a cell of a flextable? The hyperlink should be underlined and open in a new tab.

In the R script below, This is a link to google. should be the hyperlink.

I included the hyperlink_text example from the documentation which results in an error for me.

library(tidyverse)
library(flextable)

df <- tibble(
  desc = c("R1", "R2", "R3"),
  A = c("This is a long sentence that should go over into B's column. This is a link to google.", "just one cell in colA", "just one cell in colA"),
  B = c("", "just one cell in colB", "just one cell in colB"),
  C = c("just one cell in colC", "just one cell in colC", "just one cell in colC")
)

flextable(df) |>
  merge_at(i = 1, j = 2:3)

# hyperlink_text p.103
# From documentation: https://cran.r-project.org/web/packages/flextable/flextable.pdf
dat <- data.frame(
  col = "Google it",
  href = "https://www.google.fr/search?source=hp&q=flextable+R+package",
  stringsAsFactors = FALSE)
ftab <- flextable(dat)
ftab <- compose( x = ftab, j = "col",
                 value = as_paragraph(
                   "This is a link: ",
                   hyperlink_text(x = col, url = href ) ) )

# Error in data.frame(x = x, url = url, stringsAsFactors = FALSE) :
#   object 'href' not found


问:
Error "Member get_attribute is unknown" in selenium
I'm using selenium in python and simply trying to get an attribute from a HTML element, but the "get_attribute" is not being recognized.

I already imported webdriver from selenium, and that's what I'm doing:

```<code>element = driver.find_element(by=By.XPATH, value='//*[@id="example"]').click()

html_content = element.get_attribute('outerHTML')
</code>```

The error that is occuring is the following:

```<code>Cannot access member "get_attribute" for type "None"
Member "get_attribute" is unknown
</code>```

Body:
I'm using selenium in python and simply trying to get an attribute from a HTML element, but the "get_attribute" is not being recognized.

I already imported webdriver from selenium, and that's what I'm doing:

element = driver.find_element(by=By.XPATH, value='//*[@id="example"]').click()

html_content = element.get_attribute('outerHTML')

The error that is occuring is the following:

Cannot access member "get_attribute" for type "None"
Member "get_attribute" is unknown


问:
Adding dates from a dataframe
I am trying to create a dataframe which has an addition of dates (which is and index) from an orginial dataframe which looks like this:

```<code>df_galletas.head(10)

|              | Sales    || Monday   | ....     || Saturday | Januray  || ...      | Promo    |
| --------     | -------- || -------- | -------- || -------- | -------- || -------- | -------- |
| 2021-05-02   | 5        || 0        | ...      || 0        | 0        || ...      | 1        |
| 2021-05-03   | 6        || 1        | ...      || 0        | 0        || ...      | 0        |

</code>```

The dataframe should look like this, with a range of 15 days from the last day of this dataframe.

Can anyone help me?

Title: Adding dates from a dataframe

Body:
I am trying to create a dataframe which has an addition of dates (which is and index) from an orginial dataframe which looks like this:

df_galletas.head(10)

|              | Sales    || Monday   | ....     || Saturday | Januray  || ...      | Promo    |
| --------     | -------- || -------- | -------- || -------- | -------- || -------- | -------- |
| 2021-05-02   | 5        || 0        | ...      || 0        | 0        || ...      | 1        |
| 2021-05-03   | 6        || 1        | ...      || 0        | 0        || ...      | 0        |

The dataframe should look like this, with a range of 15 days from the last day of this dataframe.

Can anyone help me?


问:
Android app down from Play Store, Segment SDK
My app has been down from Playstore, I have received an email saying:

```<code>We’ve identified that your app is using the Segment SDK. We do not allow 3rd party SDKs to collect persistent device identifiers that may be linked to other personal and sensitive user data or resettable device identifiers.
</code>```

Googling, I've read in other stackoverflow questions that some people had the problem with Expo and Analytics 3rd party plugins, but in my case I don't have any related to Analytics or something that collects unique id or sensitive data.

My app is a simple Webview made with Kotlin 3 months ago, that has some read and write permissions for camera, files, and that's all.

This are the imports of my only WebActivity that I have:

```<code>    package cx.somedomain.myapp

    import android.Manifest
    import android.content.pm.PackageManager
    import android.graphics.Bitmap
    import android.os.Bundle
    import android.os.Handler
    import android.os.Looper
    import android.view.View
    import android.webkit.*
    import androidx.activity.result.ActivityResultLauncher
    import androidx.activity.result.contract.ActivityResultContracts
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.content.ContextCompat
    import cx.somedomain.myapp.databinding.ActivityWebBinding
</code>```

The first part of my build.gradle is:

```<code>android {
    compileSdk 32
    android.buildFeatures.viewBinding = true

    defaultConfig {
        applicationId "cx.somedomain.myapp"
        minSdk 23
        targetSdk 32
        versionCode 4195
        versionName "4.1.95"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
// etc...
dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code>```

I can't find more info about the problem, so I wonder if anyone else knows something.

Body:
My app has been down from Playstore, I have received an email saying:

We’ve identified that your app is using the Segment SDK. We do not allow 3rd party SDKs to collect persistent device identifiers that may be linked to other personal and sensitive user data or resettable device identifiers.

Googling, I've read in other stackoverflow questions that some people had the problem with Expo and Analytics 3rd party plugins, but in my case I don't have any related to Analytics or something that collects unique id or sensitive data.

My app is a simple Webview made with Kotlin 3 months ago, that has some read and write permissions for camera, files, and that's all.

This are the imports of my only WebActivity that I have:

    package cx.somedomain.myapp

    import android.Manifest
    import android.content.pm.PackageManager
    import android.graphics.Bitmap
    import android.os.Bundle
    import android.os.Handler
    import android.os.Looper
    import android.view.View
    import android.webkit.*
    import androidx.activity.result.ActivityResultLauncher
    import androidx.activity.result.contract.ActivityResultContracts
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.content.ContextCompat
    import cx.somedomain.myapp.databinding.ActivityWebBinding

The first part of my build.gradle is:

android {
    compileSdk 32
    android.buildFeatures.viewBinding = true

    defaultConfig {
        applicationId "cx.somedomain.myapp"
        minSdk 23
        targetSdk 32
        versionCode 4195
        versionName "4.1.95"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
// etc...
dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

I can't find more info about the problem, so I wonder if anyone else knows something.


问:
Passing Uri value from Dialog Fragment Class to an Adapter specifically on "onBindViewHolder"
I want to pass the value of String image = uri.toString to the Adapter specifically on "onBindViewHolder" to make it appear on the recylerview, but don't know how, this the code of my uploadImageToFirebase(Uri imageUri) method in my Dialog Fragment:

```<code>private void uploadImageToFirebase(Uri imageUri) {
    AddUserStudent addUserStudentCourse = (AddUserStudent) getActivity();
    String importClass = addUserStudentCourse.exportCourse();

    AddUserStudent addUserStudentSection = (AddUserStudent) getActivity();
    String importSection = addUserStudentSection.exportSection();

    user = FirebaseAuth.getInstance().getCurrentUser();
    userId = user.getUid();
    StorageReference fileRef = storageReference.child("Students/" + FirebaseDatabase.getInstance().getReference("Users").child(userId).child("Courses").child(importClass).child("Section").child(importSection).child("Students").child(sFullname.getText().toString()) +"/profile.jpg");
    fileRef.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Picasso.get().load(uri).transform(new CropCircleTransformation()).into(studentImage);
                    String image = uri.toString();
                    Toast.makeText(getContext(), image, Toast.LENGTH_SHORT).show();

                }
            });
            Toast.makeText(getContext(), "Image Uploaded", Toast.LENGTH_SHORT).show();

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(getContext(), "Uploading Image Failed", Toast.LENGTH_SHORT).show();
        }
    });
}

</code>```

and this is where I am trying to pass the value of that string image, on the adapter, specifically on "onBindViewHolder" (Note: Both the dialog fragment and adapter are part of one activity class):

```<code>public class AddStudentAdapter extends FirebaseRecyclerAdapter<AddStudent, AddStudentAdapter.myViewHodler> {

    /**
     * Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
     * {@link FirebaseRecyclerOptions} for configuration options.
     *
     * @param options
     */
    AlertDialog.Builder builder;
    public AddStudentAdapter(@NonNull FirebaseRecyclerOptions<AddStudent> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull myViewHodler holder, int position, @NonNull AddStudent model) {
            holder.sName.setText(model.studentFullname);
            holder.sEmail.setText(model.studentEmail);
            holder.sAge.setText(model.studentAge);
//        Picasso.get()          This where I want to pass the uri on the dialog fragment
//                .load()
//                        .into(holder.imgStudent);

}
}
</code>```

I've tried using bundle and intent by creating bundle in that dialog fragment below that uri and pass it in the main activity, after that I've created a method in the main activity wherein it stores the args of that bundle, and in the adapter, I'd call that method from main actvity.  But it seems that stuff doesn't work, and only provides a null pointer exception

P.S:
Already got the answer, I just make a:

```<code>public String getUri(String uri){
        this.setUri = uri;
        return uri;
    }
</code>```

then on the onActvity result, I just call that getUri method pass the uri value to that method.

Body:
I want to pass the value of String image = uri.toString to the Adapter specifically on "onBindViewHolder" to make it appear on the recylerview, but don't know how, this the code of my uploadImageToFirebase(Uri imageUri) method in my Dialog Fragment:

private void uploadImageToFirebase(Uri imageUri) {
    AddUserStudent addUserStudentCourse = (AddUserStudent) getActivity();
    String importClass = addUserStudentCourse.exportCourse();

    AddUserStudent addUserStudentSection = (AddUserStudent) getActivity();
    String importSection = addUserStudentSection.exportSection();

    user = FirebaseAuth.getInstance().getCurrentUser();
    userId = user.getUid();
    StorageReference fileRef = storageReference.child("Students/" + FirebaseDatabase.getInstance().getReference("Users").child(userId).child("Courses").child(importClass).child("Section").child(importSection).child("Students").child(sFullname.getText().toString()) +"/profile.jpg");
    fileRef.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Picasso.get().load(uri).transform(new CropCircleTransformation()).into(studentImage);
                    String image = uri.toString();
                    Toast.makeText(getContext(), image, Toast.LENGTH_SHORT).show();

                }
            });
            Toast.makeText(getContext(), "Image Uploaded", Toast.LENGTH_SHORT).show();

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(getContext(), "Uploading Image Failed", Toast.LENGTH_SHORT).show();
        }
    });
}

and this is where I am trying to pass the value of that string image, on the adapter, specifically on "onBindViewHolder" (Note: Both the dialog fragment and adapter are part of one activity class):

public class AddStudentAdapter extends FirebaseRecyclerAdapter<AddStudent, AddStudentAdapter.myViewHodler> {

    /**
     * Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
     * {@link FirebaseRecyclerOptions} for configuration options.
     *
     * @param options
     */
    AlertDialog.Builder builder;
    public AddStudentAdapter(@NonNull FirebaseRecyclerOptions<AddStudent> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull myViewHodler holder, int position, @NonNull AddStudent model) {
            holder.sName.setText(model.studentFullname);
            holder.sEmail.setText(model.studentEmail);
            holder.sAge.setText(model.studentAge);
//        Picasso.get()          This where I want to pass the uri on the dialog fragment
//                .load()
//                        .into(holder.imgStudent);

}
}

I've tried using bundle and intent by creating bundle in that dialog fragment below that uri and pass it in the main activity, after that I've created a method in the main activity wherein it stores the args of that bundle, and in the adapter, I'd call that method from main actvity.  But it seems that stuff doesn't work, and only provides a null pointer exception

P.S:
Already got the answer, I just make a:

public String getUri(String uri){
        this.setUri = uri;
        return uri;
    }

then on the onActvity result, I just call that getUri method pass the uri value to that method.


问:
Hide empty column from datatable in html
I created a datatable with search feature enabled. In below code, if I search for "office" it returns two rows and the age column doesn't have any value in it, so I want to hide it. It should hide only when there is no data in all the rows in a column.

I've researched this question and have no idea of how to hide cells with no data in a column.

```<code><script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css" />

<script>
    $(document).ready(function() {
        $("#example").DataTable({
            buttons: ["columnsToggle"],
            hideEmptyCols: true,
        });
    });
</script>

<table id="example" class="display" style="width: 100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Location</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Zenaida Frank</td>
            <td>Software Engineer</td>
            <td>New York</td>
            <td>63</td>
        </tr>
        <tr>
            <td>Zorita Serrano</td>
            <td>Software Engineer</td>
            <td>San Francisco</td>
            <td>56</td>
        </tr>
        <tr>
            <td>Jennifer Acosta</td>
            <td>Junior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>43</td>
        </tr>
        <tr>
            <td>Fiona Green</td>
            <td>Chief Operating Officer (COO)</td>
            <td>San Francisco</td>
            <td>-</td>
        </tr>
        <tr>
            <td>Brielle Williamson</td>
            <td>Integration Specialist</td>
            <td>New York</td>
            <td>61</td>
        </tr>
        <tr>
            <td>Herrod Chandler</td>
            <td>Sales Assistant</td>
            <td>San Francisco</td>
            <td>59</td>
        </tr>
        <tr>
            <td>Rhona Davidson</td>
            <td>Integration Specialist</td>
            <td>Tokyo</td>
            <td>55</td>
        </tr>
        <tr>
            <td>Jena Gaines</td>
            <td>Office Manager</td>
            <td>London</td>
            <td>-</td>
        </tr>
    </tbody>
</table>
</code>```

Added

```<code>hideEmptyCols: true
</code>```

but it has no effect on this. I was expecting any column after searching/filter has no value that column should be hidden.

I will have multiple columns in this table but after putting a filter, it should hide all the columns that do not have any value in a particular column. How can we achieve this?

Body:
I created a datatable with search feature enabled. In below code, if I search for "office" it returns two rows and the age column doesn't have any value in it, so I want to hide it. It should hide only when there is no data in all the rows in a column.

I've researched this question and have no idea of how to hide cells with no data in a column.

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css" />

            Name
            Position
            Location
            Age

            Zenaida Frank
            Software Engineer
            New York
            63

            Zorita Serrano
            Software Engineer
            San Francisco
            56

            Jennifer Acosta
            Junior Javascript Developer
            Edinburgh
            43

            Fiona Green
            Chief Operating Officer (COO)
            San Francisco
            -

            Brielle Williamson
            Integration Specialist
            New York
            61

            Herrod Chandler
            Sales Assistant
            San Francisco
            59

            Rhona Davidson
            Integration Specialist
            Tokyo
            55

            Jena Gaines
            Office Manager
            London
            -

Added

hideEmptyCols: true

but it has no effect on this. I was expecting any column after searching/filter has no value that column should be hidden.

I will have multiple columns in this table but after putting a filter, it should hide all the columns that do not have any value in a particular column. How can we achieve this?


问:
TypeError: this.props.fetchUser is not a function. (In 'this.props.fetchUser()', 'this.props.fetchUser' is undefined)
I'm using react native , redux and expo : My Main function is as follows:

```<code>import React, { Component } from 'react'
import { View, Text} from 'react-native'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {connect} from 'react-redux'
import { bindActionCreators } from 'redux'
import { fetchUser } from '../redux/actions/index'

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

//const Tab = createBottomTabNavigator();

const Stack = createStackNavigator()

export class MainScreen extends Component {
    componentDidMount(){
        this.props.fetchUser()
    }
  render() {
    const {currentUser} = this.props;
    console.log(currentUser)

    if (currentUser == undefined){
        return(
          <View></View>
        )
    }

    return (

      <View style={{flex:1, justifyContent:'center'}}>
        <Text>{currentUser.firstname} User is Logged in</Text>

      </View>

    )
  }
}

const mapStateToProps = (store) => ({
  currentUser: store.userState.currentUser
})
const mapDispatchProps = (dispatch)=> bindActionCreators({fetchUser}, dispatch);

export default connect(mapStateToProps, mapDispatchProps)(MainScreen);
</code>```

and my action/index.js is as follows:

```<code>import firebase from "@firebase/app-compat";
import { USER_STATE_CHANGE } from "../constants/index";

export function fetchUser(){
    return((dispatch) => {
        firebase.firestore()
        .collection("users")
        .doc(firebase.auth().currentUser.uid)
        .get()
        .then((snapshot)=> {
            if (snapshot.exists){
                dispatch({type: USER_STATE_CHANGE, currentUser:snapshot.data()})
            }
            else{
                console.log('does not exist')
            }
        })

    })
}

</code>```

Here, When i "expo start -c " this then I'm getting

TypeError: this.props.fetchUser is not a function. (In 'this.props.fetchUser()', 'this.props.fetchUser' is undefined) . But it looks like the fetchuser is defined

I tried running this and it returned this error:

```<code>TypeError: this.props.fetchUser is not a function. (In 'this.props.fetchUser()', 'this.props.fetchUser' is undefined)

This error is located at:
    in MainScreen (at SceneView.tsx:132)
    in StaticContainer
    in EnsureSingleNavigator (at SceneView.tsx:124)
    in SceneView (at useDescriptors.tsx:217)
    in RCTView (at View.js:32)
    in View (at CardContainer.tsx:281)
    in RCTView (at View.js:32)
    in View (at CardContainer.tsx:279)
    in RCTView (at View.js:32)
.
.
..
.
..
.
.
..
.
.
</code>```

Body:
I'm using react native , redux and expo : My Main function is as follows:

import React, { Component } from 'react'
import { View, Text} from 'react-native'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {connect} from 'react-redux'
import { bindActionCreators } from 'redux'
import { fetchUser } from '../redux/actions/index'

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

//const Tab = createBottomTabNavigator();

const Stack = createStackNavigator()

export class MainScreen extends Component {
    componentDidMount(){
        this.props.fetchUser()
    }
  render() {
    const {currentUser} = this.props;
    console.log(currentUser)

    if (currentUser == undefined){
        return(
          <View></View>
        )
    }

    return (

      <View style={{flex:1, justifyContent:'center'}}>
        <Text>{currentUser.firstname} User is Logged in</Text>

      </View>

    )
  }
}

const mapStateToProps = (store) => ({
  currentUser: store.userState.currentUser
})
const mapDispatchProps = (dispatch)=> bindActionCreators({fetchUser}, dispatch);

export default connect(mapStateToProps, mapDispatchProps)(MainScreen);

and my action/index.js is as follows:

import firebase from "@firebase/app-compat";
import { USER_STATE_CHANGE } from "../constants/index";

export function fetchUser(){
    return((dispatch) => {
        firebase.firestore()
        .collection("users")
        .doc(firebase.auth().currentUser.uid)
        .get()
        .then((snapshot)=> {
            if (snapshot.exists){
                dispatch({type: USER_STATE_CHANGE, currentUser:snapshot.data()})
            }
            else{
                console.log('does not exist')
            }
        })

    })
}

Here, When i "expo start -c " this then I'm getting

TypeError: this.props.fetchUser is not a function. (In 'this.props.fetchUser()', 'this.props.fetchUser' is undefined) . But it looks like the fetchuser is defined

I tried running this and it returned this error:

TypeError: this.props.fetchUser is not a function. (In 'this.props.fetchUser()', 'this.props.fetchUser' is undefined)

This error is located at:
    in MainScreen (at SceneView.tsx:132)
    in StaticContainer
    in EnsureSingleNavigator (at SceneView.tsx:124)
    in SceneView (at useDescriptors.tsx:217)
    in RCTView (at View.js:32)
    in View (at CardContainer.tsx:281)
    in RCTView (at View.js:32)
    in View (at CardContainer.tsx:279)
    in RCTView (at View.js:32)
.
.
..
.
..
.
.
..
.
.


问:
My buttons only appear when I click them or my cursor is over them
First of all, sorry for my English!

I am creating a videogame as a beginner, and I have four buttons, but I dont know why I can only see them when i put my mouse over them.

Maybe is because I have a thread?

I will try to upload the code and classes!!

Thank you very very much!!!

```<code>

package Launcher;
import Character.CharacterSet;
import Character.CharacterFabric;
import Character.CharSelection;

import javax.swing.*;

public class Main
{
    public static void main(String[] args){

        WindowPanel winP = new WindowPanel();
        winP.myWindowPanel();

        CharSelection charSelection = new CharSelection();
        charSelection.myCharSelection();

    }

}
</code>```
```<code>

package Launcher;

import java.awt.*;
import java.awt.event.KeyListener;
import java.sql.SQLOutput;
import javax.swing.*;

import  Character.Player;

public class GamePanel extends JPanel implements  Runnable{

    //Window settings variables
    KeyHandler KH = new KeyHandler();
    final int originalTileSize = 16; //16x16px
    final int scale = 3;
    final int tileSize = originalTileSize * scale; //48x48px
    final int maxScreenCol = 16; //Tiles in a column
    final int maxScreenRow = 12; //Tiles in a row
    final int maxScreenWidth = tileSize * maxScreenCol;
    final int maxScreenHeight = tileSize * maxScreenRow;

    Thread gameThread;

    Player player = new Player(this, KH);
    int framesPS = 60;

    //Player pos
    int playerX = 100;
    int playerY = 100;
    int playerSpeed = 4;
    public GamePanel(){

        this.setVisible(false);

        //Window Settings with variable implementation
        this.setPreferredSize(new Dimension(maxScreenWidth, maxScreenHeight));
        this.setBackground(Color.white);
        this.setDoubleBuffered(true);
        this.addKeyListener(KH);
        this.setFocusable(true);

        //////////7
        JButton exit = new JButton();
        JButton moreSize = new JButton();
        JButton lessSize = new JButton();

        exit.setSize(30, 30);
        moreSize.setSize(30, 30);
        lessSize.setSize(30, 30);

        //exit.setVisible(true);
        exit.setBackground(Color.BLUE);
        this.add(exit);
        ///////
        //optionSel = "Archer";

        JButton butW = new JButton("^");
        butW.setSize(500, 500);
        butW.setBackground(Color.BLUE);
        this.add(butW);
        butW.setVisible(true);
        butW.revalidate();
        butW.repaint();

        this.setVisible(true);
        this.repaint();
        this.revalidate();

        }

    public void startGameThread(){
        gameThread = new Thread(this);
        gameThread.start();

    }

    public void update(){
        //System.out.println(playerY);

        //System.out.println(upP);
        if(KH.upPressed){
            playerY -= playerSpeed;
        }
        else if(KH.downPressed == true){
            playerY += playerSpeed;
        }
        else if(KH.leftPressed == true){
            playerX -= playerSpeed;
        }
        else if(KH.rightPressed){
            playerX += playerSpeed;
        }

    }

    /*public void run(){

        double drawInterval = 1000000000/framesPS; //0.0166 seconds
        double nextDrawTime = System.nanoTime() + drawInterval;

        while(gameThread != null){

            //long currentTime = System.nanoTime();
            //1.Update
            update();
            //2Draw screen info
            repaint();

            try {
                double remainingTime = nextDrawTime -System.nanoTime();
                remainingTime = remainingTime/1000000;

                if(remainingTime < 0){
                    remainingTime = 0;
                }

                Thread.sleep((long)remainingTime);

                nextDrawTime += drawInterval;

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }*/

    public void run(){

        double drawInterval = 1000000000/framesPS;
        double delta = 0;
        long lastTime = System.nanoTime();
        long currentTime;
        long timer = 0;
        int drawCount = 0;

        while(gameThread != null){

            currentTime = System.nanoTime();
            delta += (currentTime - lastTime)/drawInterval;
            timer += (currentTime-lastTime);
            lastTime = currentTime;
            if (delta >= 1){
                update();
                repaint();
                delta--;
                drawCount++;
            }
            if(timer >= 1000000000){
                System.out.println("System FPS= "+drawCount);
                drawCount = 0;
                timer = 0;
            }

        }
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D)g;
        //System.out.println("painting");

        g2.setColor(Color.GREEN);
        g2.fillRect(playerX, playerY, tileSize, tileSize);

        g2.dispose();

    }

}

</code>```
```<code>package Launcher;

import javax.swing.*;
import java.awt.*;

public class WindowPanel {

    //public static String optionSel;
    public boolean startThread;
    public void myWindowPanel(){

        JFrame window = new JFrame();
        //Window Creation

        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.setTitle("My Game");
        window.setLocation(0, 0);//No le indica un lugar especifico donde salir, por lo que sale en el medio

        GamePanel gamePanel = new GamePanel();
        window.add(gamePanel);

        ///
        JButton butW = new JButton("^");
        butW.setSize(100, 100);
        butW.setBackground(Color.BLUE);
        gamePanel.add(butW);
        butW.setVisible(true);

        butW.revalidate();
        butW.repaint();

        ///

        window.pack();

        window.setLocationRelativeTo(null);
        window.setVisible(true);
        gamePanel.startGameThread();

    }

}

</code>```

I´m trying to see the buttons :C

Body:
First of all, sorry for my English!

I am creating a videogame as a beginner, and I have four buttons, but I dont know why I can only see them when i put my mouse over them.

Maybe is because I have a thread?

I will try to upload the code and classes!!

Thank you very very much!!!

package Launcher;
import Character.CharacterSet;
import Character.CharacterFabric;
import Character.CharSelection;

import javax.swing.*;

public class Main
{
    public static void main(String[] args){

        WindowPanel winP = new WindowPanel();
        winP.myWindowPanel();

        CharSelection charSelection = new CharSelection();
        charSelection.myCharSelection();

    }

}

package Launcher;

import java.awt.*;
import java.awt.event.KeyListener;
import java.sql.SQLOutput;
import javax.swing.*;

import  Character.Player;

public class GamePanel extends JPanel implements  Runnable{

    //Window settings variables
    KeyHandler KH = new KeyHandler();
    final int originalTileSize = 16; //16x16px
    final int scale = 3;
    final int tileSize = originalTileSize * scale; //48x48px
    final int maxScreenCol = 16; //Tiles in a column
    final int maxScreenRow = 12; //Tiles in a row
    final int maxScreenWidth = tileSize * maxScreenCol;
    final int maxScreenHeight = tileSize * maxScreenRow;

    Thread gameThread;

    Player player = new Player(this, KH);
    int framesPS = 60;

    //Player pos
    int playerX = 100;
    int playerY = 100;
    int playerSpeed = 4;
    public GamePanel(){

        this.setVisible(false);

        //Window Settings with variable implementation
        this.setPreferredSize(new Dimension(maxScreenWidth, maxScreenHeight));
        this.setBackground(Color.white);
        this.setDoubleBuffered(true);
        this.addKeyListener(KH);
        this.setFocusable(true);

        //////////7
        JButton exit = new JButton();
        JButton moreSize = new JButton();
        JButton lessSize = new JButton();

        exit.setSize(30, 30);
        moreSize.setSize(30, 30);
        lessSize.setSize(30, 30);

        //exit.setVisible(true);
        exit.setBackground(Color.BLUE);
        this.add(exit);
        ///////
        //optionSel = "Archer";

        JButton butW = new JButton("^");
        butW.setSize(500, 500);
        butW.setBackground(Color.BLUE);
        this.add(butW);
        butW.setVisible(true);
        butW.revalidate();
        butW.repaint();

        this.setVisible(true);
        this.repaint();
        this.revalidate();

        }

    public void startGameThread(){
        gameThread = new Thread(this);
        gameThread.start();

    }

    public void update(){
        //System.out.println(playerY);

        //System.out.println(upP);
        if(KH.upPressed){
            playerY -= playerSpeed;
        }
        else if(KH.downPressed == true){
            playerY += playerSpeed;
        }
        else if(KH.leftPressed == true){
            playerX -= playerSpeed;
        }
        else if(KH.rightPressed){
            playerX += playerSpeed;
        }

    }

    /*public void run(){

        double drawInterval = 1000000000/framesPS; //0.0166 seconds
        double nextDrawTime = System.nanoTime() + drawInterval;

        while(gameThread != null){

            //long currentTime = System.nanoTime();
            //1.Update
            update();
            //2Draw screen info
            repaint();

            try {
                double remainingTime = nextDrawTime -System.nanoTime();
                remainingTime = remainingTime/1000000;

                if(remainingTime < 0){
                    remainingTime = 0;
                }

                Thread.sleep((long)remainingTime);

                nextDrawTime += drawInterval;

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }*/

    public void run(){

        double drawInterval = 1000000000/framesPS;
        double delta = 0;
        long lastTime = System.nanoTime();
        long currentTime;
        long timer = 0;
        int drawCount = 0;

        while(gameThread != null){

            currentTime = System.nanoTime();
            delta += (currentTime - lastTime)/drawInterval;
            timer += (currentTime-lastTime);
            lastTime = currentTime;
            if (delta >= 1){
                update();
                repaint();
                delta--;
                drawCount++;
            }
            if(timer >= 1000000000){
                System.out.println("System FPS= "+drawCount);
                drawCount = 0;
                timer = 0;
            }

        }
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D)g;
        //System.out.println("painting");

        g2.setColor(Color.GREEN);
        g2.fillRect(playerX, playerY, tileSize, tileSize);

        g2.dispose();

    }

}

package Launcher;

import javax.swing.*;
import java.awt.*;

public class WindowPanel {

    //public static String optionSel;
    public boolean startThread;
    public void myWindowPanel(){

        JFrame window = new JFrame();
        //Window Creation

        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.setTitle("My Game");
        window.setLocation(0, 0);//No le indica un lugar especifico donde salir, por lo que sale en el medio

        GamePanel gamePanel = new GamePanel();
        window.add(gamePanel);

        ///
        JButton butW = new JButton("^");
        butW.setSize(100, 100);
        butW.setBackground(Color.BLUE);
        gamePanel.add(butW);
        butW.setVisible(true);

        butW.revalidate();
        butW.repaint();

        ///

        window.pack();

        window.setLocationRelativeTo(null);
        window.setVisible(true);
        gamePanel.startGameThread();

    }

}

I´m trying to see the buttons :C


问:
I tried connecting to a test server on localhost from socket.io's swift client but it can't find the hostname
I have a socket.io server running on Node.js listening on localhost:3000. I then try to connect to that server with a swift mac app. Here's how I'm doing the connection in swift

```<code>let manager = SocketManager(socketURL: URL(string: "https://localhost:3000/")!, config: [.secure(true), .log(true), .compress])
    let socket: SocketIOClient

    init() {
        socket = manager.defaultSocket

        print(storage)

        addHandlers()
        socket.connect()
    }
</code>```

The above code is inside a struct which is created as a property value in a ContentView so I don't think my manager is being destroyed.

Here are the relevant logs

```<code>2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketIOClient{/}: Joining namespace /
2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketManager: Tried connecting socket when engine isn't open. Connecting
2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketManager: Adding engine
2022-12-20 17:05:48.743 MultiSnake[46501:971274] LOG SocketEngine: Starting engine. Server: https://localhost:3000/
2022-12-20 17:05:48.743 MultiSnake[46501:971274] LOG SocketEngine: Handshaking
2022-12-20 17:05:48.745 MultiSnake[46501:971274] LOG SocketEnginePolling: Doing polling GET https://localhost:3000/socket.io/?transport=polling&b64=1&EIO=4
2022-12-20 17:05:48.857 MultiSnake[46501:971288] ERROR SocketEnginePolling: A server with the specified hostname could not be found.
2022-12-20 17:05:48.857 MultiSnake[46501:971288] ERROR SocketEngine: A server with the specified hostname could not be found.
2022-12-20 17:05:48.871 MultiSnake[46501:971261] ERROR SocketManager: A server with the specified hostname could not be found.
2022-12-20 17:05:48.871 MultiSnake[46501:971261] LOG SocketIOClient{/}: Handling event: error with data: ["A server with the specified hostname could not be found."]
2022-12-20 17:05:48.872 MultiSnake[46501:971261] LOG SocketManager: Starting reconnect
</code>```

I can connect to localhost:3000 from the browser and I have done the required Certficate Authority related things for HTTPS to work. I have not made an ATS exception in my mac app and I would prefer not to.

I have tried to change the "https://localhost:3000/" string to "localhost:3000/" and add .secure(true) to the manager's config but then socket.io would poll https:/socket.io instead of the right url.
I don't know where I can specify the hostname and I think I have followed the examples here.

Body:
I have a socket.io server running on Node.js listening on localhost:3000. I then try to connect to that server with a swift mac app. Here's how I'm doing the connection in swift

let manager = SocketManager(socketURL: URL(string: "https://localhost:3000/")!, config: [.secure(true), .log(true), .compress])
    let socket: SocketIOClient

    init() {
        socket = manager.defaultSocket

        print(storage)

        addHandlers()
        socket.connect()
    }

The above code is inside a struct which is created as a property value in a ContentView so I don't think my manager is being destroyed.

Here are the relevant logs

2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketIOClient{/}: Joining namespace /
2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketManager: Tried connecting socket when engine isn't open. Connecting
2022-12-20 17:05:48.742 MultiSnake[46501:971261] LOG SocketManager: Adding engine
2022-12-20 17:05:48.743 MultiSnake[46501:971274] LOG SocketEngine: Starting engine. Server: https://localhost:3000/
2022-12-20 17:05:48.743 MultiSnake[46501:971274] LOG SocketEngine: Handshaking
2022-12-20 17:05:48.745 MultiSnake[46501:971274] LOG SocketEnginePolling: Doing polling GET https://localhost:3000/socket.io/?transport=polling&b64=1&EIO=4
2022-12-20 17:05:48.857 MultiSnake[46501:971288] ERROR SocketEnginePolling: A server with the specified hostname could not be found.
2022-12-20 17:05:48.857 MultiSnake[46501:971288] ERROR SocketEngine: A server with the specified hostname could not be found.
2022-12-20 17:05:48.871 MultiSnake[46501:971261] ERROR SocketManager: A server with the specified hostname could not be found.
2022-12-20 17:05:48.871 MultiSnake[46501:971261] LOG SocketIOClient{/}: Handling event: error with data: ["A server with the specified hostname could not be found."]
2022-12-20 17:05:48.872 MultiSnake[46501:971261] LOG SocketManager: Starting reconnect

I can connect to localhost:3000 from the browser and I have done the required Certficate Authority related things for HTTPS to work. I have not made an ATS exception in my mac app and I would prefer not to.

I have tried to change the "https://localhost:3000/" string to "localhost:3000/" and add .secure(true) to the manager's config but then socket.io would poll https:/socket.io instead of the right url.
I don't know where I can specify the hostname and I think I have followed the examples here.


问:
Spring hibernate exception creating EntityManagerFactory - NegativeArraySizeException: -947658752
I have a spring boot application that serves map tiles from an SQLite database stored within the resources directory. This application runs perfectly fine within an IDE, and have never had an issue until I was attempting to run the compiled jar with the java -jar command. The database is being built into the JAR, but I don't understand how that could be an issue at all. When I run the compiled jar I get the following exception:

```<code>Exception encountered during context initialization - cancelling refresh attempt:
     org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mapEntityManagerFactory' defined in class path resource
     [com/app/application/configuration/MapDataSourceConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NegativeArraySizeException: -947658752

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mapEntityManagerFactory' defined in class path resource [com/app/application/configuration/MapDataSourceConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NegativeArraySizeException: -947658752
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
    at com.app.map.MapApplicationKt.main(MapApplication.kt:12)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:108)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65)

Caused by: java.lang.NegativeArraySizeException: -947658752
    at org.hibernate.boot.archive.internal.ArchiveHelper.getBytesFromInputStream(ArchiveHelper.java:181)
    at org.hibernate.boot.archive.internal.ArchiveHelper.getBytesFromInputStreamSafely(ArchiveHelper.java:139)
    at org.hibernate.boot.archive.spi.AbstractArchiveDescriptor.buildByteBasedInputStreamAccess(AbstractArchiveDescriptor.java:75)
    at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:117)
    at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:48)
    at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:107)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:269)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:182)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:52)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
</code>```

Application.yml:

```<code>spring:
  jpa:
    database-platform: org.hibernate.dialect.SQLiteDialect
  datasource:
    map:
      url: jdbc:sqlite:backend/src/main/resources/db/mbtile/map.mbtiles
      driver-class-name: org.sqlite.JDBC
      configuration:
        maximum-pool-size: 1
</code>```

MapDataSourceConfiguration:

```<code>@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackageClasses = [Tile::class],
    basePackages = ["com.app.domain.repository.map"],
    entityManagerFactoryRef = "mapEntityManagerFactory"
)
class MapDataSourceConfiguration {

    @Bean
    @ConfigurationProperties("spring.datasource.map")
    fun mapDataSourceProperties(): DataSourceProperties = DataSourceProperties()

    @Bean
    @ConfigurationProperties("spring.datasource.map.configuration")
    fun mapDataSource(properties: DataSourceProperties): HikariDataSource =
        properties.initializeDataSourceBuilder().type(HikariDataSource::class.java).build()

    @Bean
    fun mapEntityManagerFactory(): LocalContainerEntityManagerFactoryBean = (LocalContainerEntityManagerFactoryBean()).apply {
        dataSource = mapDataSource(mapDataSourceProperties())
        setPackagesToScan("com.app.domain.model.map")
        jpaVendorAdapter = HibernateJpaVendorAdapter()
    }
}
</code>```

Tile.kt:

```<code>@Entity
@IdClass(TileCompositeKey::class)
@Table(name = "tiles")
data class Tile(
    @Id @Column(name = "zoom_level") val zoomLevel: Int = 0,
    @Id @Column(name = "tile_column") val tileColumn: Int? = 0,
    @Id @Column(name = "tile_row") val tileRow: Int? = 0,
    @Column(name = "tile_data") val tileData: ByteArray? = null,
)

private class TileCompositeKey(
    private val zoomLevel: Int? = 0,
    private val tileColumn: Int? = 0,
    private val tileRow: Int? = 0,
) : Serializable
</code>```

Build.gradle.kts:

```<code>dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.xerial:sqlite-jdbc:3.32.3.2")
    implementation("com.github.gwenn:sqlite-dialect:0.1.0")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.flywaydb:flyway-core")
    implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.14.1")
    implementation("com.fasterxml.jackson.core:jackson-databind:2.14.1")
}
</code>```

Has anyone seen this issue before?

Body:
I have a spring boot application that serves map tiles from an SQLite database stored within the resources directory. This application runs perfectly fine within an IDE, and have never had an issue until I was attempting to run the compiled jar with the java -jar command. The database is being built into the JAR, but I don't understand how that could be an issue at all. When I run the compiled jar I get the following exception:

Exception encountered during context initialization - cancelling refresh attempt:
     org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mapEntityManagerFactory' defined in class path resource
     [com/app/application/configuration/MapDataSourceConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NegativeArraySizeException: -947658752

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mapEntityManagerFactory' defined in class path resource [com/app/application/configuration/MapDataSourceConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NegativeArraySizeException: -947658752
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
    at com.app.map.MapApplicationKt.main(MapApplication.kt:12)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:108)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65)

Caused by: java.lang.NegativeArraySizeException: -947658752
    at org.hibernate.boot.archive.internal.ArchiveHelper.getBytesFromInputStream(ArchiveHelper.java:181)
    at org.hibernate.boot.archive.internal.ArchiveHelper.getBytesFromInputStreamSafely(ArchiveHelper.java:139)
    at org.hibernate.boot.archive.spi.AbstractArchiveDescriptor.buildByteBasedInputStreamAccess(AbstractArchiveDescriptor.java:75)
    at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:117)
    at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:48)
    at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:107)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:269)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:182)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:52)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)

Application.yml:

spring:
  jpa:
    database-platform: org.hibernate.dialect.SQLiteDialect
  datasource:
    map:
      url: jdbc:sqlite:backend/src/main/resources/db/mbtile/map.mbtiles
      driver-class-name: org.sqlite.JDBC
      configuration:
        maximum-pool-size: 1

MapDataSourceConfiguration:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackageClasses = [Tile::class],
    basePackages = ["com.app.domain.repository.map"],
    entityManagerFactoryRef = "mapEntityManagerFactory"
)
class MapDataSourceConfiguration {

    @Bean
    @ConfigurationProperties("spring.datasource.map")
    fun mapDataSourceProperties(): DataSourceProperties = DataSourceProperties()

    @Bean
    @ConfigurationProperties("spring.datasource.map.configuration")
    fun mapDataSource(properties: DataSourceProperties): HikariDataSource =
        properties.initializeDataSourceBuilder().type(HikariDataSource::class.java).build()

    @Bean
    fun mapEntityManagerFactory(): LocalContainerEntityManagerFactoryBean = (LocalContainerEntityManagerFactoryBean()).apply {
        dataSource = mapDataSource(mapDataSourceProperties())
        setPackagesToScan("com.app.domain.model.map")
        jpaVendorAdapter = HibernateJpaVendorAdapter()
    }
}

Tile.kt:

@Entity
@IdClass(TileCompositeKey::class)
@Table(name = "tiles")
data class Tile(
    @Id @Column(name = "zoom_level") val zoomLevel: Int = 0,
    @Id @Column(name = "tile_column") val tileColumn: Int? = 0,
    @Id @Column(name = "tile_row") val tileRow: Int? = 0,
    @Column(name = "tile_data") val tileData: ByteArray? = null,
)

private class TileCompositeKey(
    private val zoomLevel: Int? = 0,
    private val tileColumn: Int? = 0,
    private val tileRow: Int? = 0,
) : Serializable

Build.gradle.kts:

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.xerial:sqlite-jdbc:3.32.3.2")
    implementation("com.github.gwenn:sqlite-dialect:0.1.0")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.flywaydb:flyway-core")
    implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.14.1")
    implementation("com.fasterxml.jackson.core:jackson-databind:2.14.1")
}

Has anyone seen this issue before?


问:
Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime
I'm quite new to use the build and artifacts features. I have a program that reads a JSON file, evaluates it and return a different JSON file. After creating an artifact and built it, I go in the terminal in the same folder as the one where jar that I built (that I would call programExample.jar for example) is, and type in the terminal to launch the program.

java -jar programExample.jar jsonToRead.json jsonOutput.json

The issue is that after typing this command, this error shows up:

Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime (class file version 63.0), this version of the Java Runtime only recognizes class file versions up to 52.0

I don't understand how I have to solve that and have been looking for a few hours now.

The project use openjdk-19 and when typing java -version in the terminal, I have java version "1.8.0_351" and typing javac -version, I have

javac : The term 'javac' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Would love to have an insight.

If needed, here is also my Maven file:

```<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Declarations</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.9.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>19</source>
                    <target>19</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Body:
I'm quite new to use the build and artifacts features. I have a program that reads a JSON file, evaluates it and return a different JSON file. After creating an artifact and built it, I go in the terminal in the same folder as the one where jar that I built (that I would call programExample.jar for example) is, and type in the terminal to launch the program.

java -jar programExample.jar jsonToRead.json jsonOutput.json

The issue is that after typing this command, this error shows up:

Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime (class file version 63.0), this version of the Java Runtime only recognizes class file versions up to 52.0

I don't understand how I have to solve that and have been looking for a few hours now.

The project use openjdk-19 and when typing java -version in the terminal, I have java version "1.8.0_351" and typing javac -version, I have

javac : The term 'javac' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Would love to have an insight.

If needed, here is also my Maven file:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Declarations</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.9.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>19</source>
                    <target>19</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


问:
Dockerfile: problem installing yarn / npm / npx / nvm in one RUN statement and using it in following one
I started learning how to create docker images from Dockerfiles recently and I already got quite far. But I am facing problems using installed software from one RUN statement in following RUN or CMD statement. See my simplyfied Dockerfile below:

```<code># Working just fine
FROM ubuntu:22.04
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
RUN apt update \
    && apt install -y curl
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash \
    && source ~/.nvm/nvm.sh \
    && nvm install 16.19.0 \
    && nvm alias default 16.19.0 \
    && nvm use default \
    && npm install --global yarn@1.22.19

# Problem using yarn / npm / npx / nvm in following RUN or CMD statemtens e.g.
RUN npm --version
</code>```

The console shows me the error npm: command not found

The image gets built just fine without the last npm --version statement. And when I run the image and attach a bash to it I can execute the command by hand.

Also following other commands get not found:

```<code>RUN nvm --version
RUN npx --version
RUN yarn --version
</code>```

How can I persist the yarn / npm / npx / nvm installation across various RUN statements?

Do I need to somehow add them to PATH explicitly? The $PATH contains following in an image without the last problematic statement: /root/.nvm/versions/node/v16.19.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

I tried following commands, which did not help me out yet

```<code>ENV NODE_PATH ~/.nvm/versions/node/v$NODE_VERSION/lib/node_modules
ENV PATH      ~/.nvm/versions/node/v$NODE_VERSION/bin:$PATH
</code>```

Body:
I started learning how to create docker images from Dockerfiles recently and I already got quite far. But I am facing problems using installed software from one RUN statement in following RUN or CMD statement. See my simplyfied Dockerfile below:

# Working just fine
FROM ubuntu:22.04
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
RUN apt update \
    && apt install -y curl
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash \
    && source ~/.nvm/nvm.sh \
    && nvm install 16.19.0 \
    && nvm alias default 16.19.0 \
    && nvm use default \
    && npm install --global yarn@1.22.19

# Problem using yarn / npm / npx / nvm in following RUN or CMD statemtens e.g.
RUN npm --version

The console shows me the error npm: command not found

The image gets built just fine without the last npm --version statement. And when I run the image and attach a bash to it I can execute the command by hand.

Also following other commands get not found:

RUN nvm --version
RUN npx --version
RUN yarn --version

How can I persist the yarn / npm / npx / nvm installation across various RUN statements?

Do I need to somehow add them to PATH explicitly? The $PATH contains following in an image without the last problematic statement: /root/.nvm/versions/node/v16.19.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

I tried following commands, which did not help me out yet

ENV NODE_PATH ~/.nvm/versions/node/v$NODE_VERSION/lib/node_modules
ENV PATH      ~/.nvm/versions/node/v$NODE_VERSION/bin:$PATH


问:
How to connect AWS S3 from Spotfire
We have our data in  AWS S3 bucket and respective schema defined in Glue Catelog.
Right now Athena queries are possible to the S3 bucket(well defined schema).
We need to visualize these data from spotfire.

What are the possible way of achieving this.

I am newbie to Spotfire.

Title: How to connect AWS S3 from Spotfire


问:
Discord bot in python not properly detecting messages
I'm building a discord bot using python and previously had the bot running and after one too many changes the bot no longer goes online to join a voice call to play youtube videos.

```<code>import asyncio
import youtube_dl
import requests

# Replace YOUR_TOKEN_HERE with your Discord bot token
intents = discord.Intents.all()
client = discord.Client(intents=intents, token="Censored")

# Set the YouTube Data API key
YOUTUBE_API_KEY = "Censored"

# A queue of songs to play
song_queue = []

# The current song that is playing
current_song = None

# The voice client that will be used to play the songs
voice_client = None

# This function is called when the bot is ready
@client.event
async def on_ready():
    print("Bot is ready!")

# This function is called when the bot receives a message
@client.event
async def on_message(message):
    # If the message is from the bot itself, do nothing
    if message.author == client.user:
        return

    # If the message starts with "!play", try to play the specified YouTube video
    if message.content.startswith("!play"):
        # Split the message into a list of words
        words = message.content.split(" ")
        # If a YouTube URL was provided, add it to the queue
        if len(words) > 1:
            song_queue.append(words[1])
            # If the queue was empty before, start playing the first song in the queue
            if current_song is None:
                await play_next_song(message.author.voice.channel)
        else:
            await message.channel.send("Please provide a YouTube URL to play")

    # If the message is "!skip", skip the current song if there is one
    elif message.content == "!skip":
        if current_song is not None:
            current_song.stop()
        else:
            await message.channel.send("There is no song currently playing")

    # If the message is "!queue", display the current song queue
    elif message.content == "!queue":
        if len(song_queue) > 0:
            queue_string = "Songs in queue:\n"
            for i, song in enumerate(song_queue):
                queue_string += f"{i + 1}. {song}\n"
            await message.channel.send(queue_string)
        else:
            await message.channel.send("The queue is empty")

# This function plays the next song in the queue
async def play_next_song(channel):
    global current_song
    # If there are no more songs in the queue, do nothing
    if len(song_queue) == 0:
        current_song = None
        return
    # Get the next song in the queue
    next_song = song_queue.pop(0)
    # Create the voice client and start playing the song
    voice_client = await channel.connect()
    current_song = voice_client.play(audio_source, after=lambda e: print("Song done!"))
        # Create a YouTube Data API request to get the video's title
    api_request = f"https://www.googleapis.com/youtube/v3/videos?key={YOUTUBE_API_KEY}&part=snippet&id={video_id}"
    # Make the request and get the response
    api_response = requests.get(api_request)
    # Get the video's title from the response
    video_title = api_response.json()["items"][0]["snippet"]["title"]
    # Send a message to the channel with the video's title
    await message.channel.send(f"Playing {video_title}")
    # Create a YouTubeDL object
    ydl_opts = {
        "format": "bestaudio/best",
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "192",
        }],
    }
    ydl = youtube_dl.YoutubeDL(ydl_opts)
    # Download the audio from the YouTube video
    info = ydl.extract_info(url, download=False)
    audio_url = info["formats"][0]["url"]
    # Create an FFmpegPCMAudio object from the audio URL
    audio_source = discord.FFmpegPCMAudio(audio_url)
    # Play the audio
    current_song = voice_client.play(audio_source)
    # Wait for the song to end
    await current_song.wait_for_completion()
    # Disconnect from the voice call
    await voice_client.disconnect()
    # Play the next song in the queue
    await play_next_song(channel)
</code>```

Please note that I am a very beginner programmer and used AI assistance in writing this code so I don't fully understand everything going on here.

Body:
I'm building a discord bot using python and previously had the bot running and after one too many changes the bot no longer goes online to join a voice call to play youtube videos.

import asyncio
import youtube_dl
import requests

# Replace YOUR_TOKEN_HERE with your Discord bot token
intents = discord.Intents.all()
client = discord.Client(intents=intents, token="Censored")

# Set the YouTube Data API key
YOUTUBE_API_KEY = "Censored"

# A queue of songs to play
song_queue = []

# The current song that is playing
current_song = None

# The voice client that will be used to play the songs
voice_client = None

# This function is called when the bot is ready
@client.event
async def on_ready():
    print("Bot is ready!")

# This function is called when the bot receives a message
@client.event
async def on_message(message):
    # If the message is from the bot itself, do nothing
    if message.author == client.user:
        return

    # If the message starts with "!play", try to play the specified YouTube video
    if message.content.startswith("!play"):
        # Split the message into a list of words
        words = message.content.split(" ")
        # If a YouTube URL was provided, add it to the queue
        if len(words) > 1:
            song_queue.append(words[1])
            # If the queue was empty before, start playing the first song in the queue
            if current_song is None:
                await play_next_song(message.author.voice.channel)
        else:
            await message.channel.send("Please provide a YouTube URL to play")

    # If the message is "!skip", skip the current song if there is one
    elif message.content == "!skip":
        if current_song is not None:
            current_song.stop()
        else:
            await message.channel.send("There is no song currently playing")

    # If the message is "!queue", display the current song queue
    elif message.content == "!queue":
        if len(song_queue) > 0:
            queue_string = "Songs in queue:\n"
            for i, song in enumerate(song_queue):
                queue_string += f"{i + 1}. {song}\n"
            await message.channel.send(queue_string)
        else:
            await message.channel.send("The queue is empty")

# This function plays the next song in the queue
async def play_next_song(channel):
    global current_song
    # If there are no more songs in the queue, do nothing
    if len(song_queue) == 0:
        current_song = None
        return
    # Get the next song in the queue
    next_song = song_queue.pop(0)
    # Create the voice client and start playing the song
    voice_client = await channel.connect()
    current_song = voice_client.play(audio_source, after=lambda e: print("Song done!"))
        # Create a YouTube Data API request to get the video's title
    api_request = f"https://www.googleapis.com/youtube/v3/videos?key={YOUTUBE_API_KEY}&part=snippet&id={video_id}"
    # Make the request and get the response
    api_response = requests.get(api_request)
    # Get the video's title from the response
    video_title = api_response.json()["items"][0]["snippet"]["title"]
    # Send a message to the channel with the video's title
    await message.channel.send(f"Playing {video_title}")
    # Create a YouTubeDL object
    ydl_opts = {
        "format": "bestaudio/best",
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "192",
        }],
    }
    ydl = youtube_dl.YoutubeDL(ydl_opts)
    # Download the audio from the YouTube video
    info = ydl.extract_info(url, download=False)
    audio_url = info["formats"][0]["url"]
    # Create an FFmpegPCMAudio object from the audio URL
    audio_source = discord.FFmpegPCMAudio(audio_url)
    # Play the audio
    current_song = voice_client.play(audio_source)
    # Wait for the song to end
    await current_song.wait_for_completion()
    # Disconnect from the voice call
    await voice_client.disconnect()
    # Play the next song in the queue
    await play_next_song(channel)

Please note that I am a very beginner programmer and used AI assistance in writing this code so I don't fully understand everything going on here.