问:
How do I retrieve different types of external files from android device?
I have been looking everywhere to find out how to retrieve a file from the external storage and be able to read it. What I want to be able to do is when I open the android app, there will be a button that when pressed I can go into my phones files and select a CSV file. I don't want to get a preselected file though, I want to be able to choose a different file each time. With this file I just want to be able to read from it or download it to internal storage. I'm not very familiar with android IO so hopefully that makes sense.

Here is my code so far which gets a preselected file (just using a preselected file as an example) and am trying to read the file. So far it fails and prints out the Exception block code.

```<code>public class MainActivity extends AppCompatActivity {

private String filename = "/storage/emulated/0/Download/example.csv";
Scanner sc = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE},
            PackageManager.PERMISSION_GRANTED);
}

public void buttonOpenFile(View view){

    Context context = getApplicationContext();

    File appSpecificExternalDir = new File(context.getExternalFilesDir(null), filename);

   try {
       Scanner sc = new Scanner(appSpecificExternalDir);
       sc.useDelimiter(",");
       while (sc.hasNext()){
           System.out.println(sc.next());
       }
   }catch (Exception e){
       System.out.println("File not valid");
   }

}
}
</code>```

Body:
I have been looking everywhere to find out how to retrieve a file from the external storage and be able to read it. What I want to be able to do is when I open the android app, there will be a button that when pressed I can go into my phones files and select a CSV file. I don't want to get a preselected file though, I want to be able to choose a different file each time. With this file I just want to be able to read from it or download it to internal storage. I'm not very familiar with android IO so hopefully that makes sense.

Here is my code so far which gets a preselected file (just using a preselected file as an example) and am trying to read the file. So far it fails and prints out the Exception block code.

public class MainActivity extends AppCompatActivity {

private String filename = "/storage/emulated/0/Download/example.csv";
Scanner sc = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE},
            PackageManager.PERMISSION_GRANTED);
}

public void buttonOpenFile(View view){

    Context context = getApplicationContext();

    File appSpecificExternalDir = new File(context.getExternalFilesDir(null), filename);

   try {
       Scanner sc = new Scanner(appSpecificExternalDir);
       sc.useDelimiter(",");
       while (sc.hasNext()){
           System.out.println(sc.next());
       }
   }catch (Exception e){
       System.out.println("File not valid");
   }

}
}


来源: stackexchange

问:
How to stream data from an URL to Google Earth Engine
I need to overlay live data from an URL (fuclrumapp.com) to overlay this with remote sensing output google earth engine.
How can this be achieved? Does this need a pipeline through a different platform, as GEE does not seem to be able to import data from URLs?</p>

ContentLicense: CC BY-SA 4.0


问:
how to not collect repetitive data on getStaticProps in NextJs
the next-js server would receive repetitive data in getStaticProps

i have this structure in my project

```<code>-----pages
    -----products
         -----[product_id].jsx
    -----_app.jsx
</code>```

in the [product_id].jsx i have a function that get 'best selling products' from backend

Suppose we have 1000 products on the site, the next-js server will get 'best selling products' 1000 times but once was enough

Body:
the next-js server would receive repetitive data in getStaticProps

i have this structure in my project

-----pages
    -----products
         -----[product_id].jsx
    -----_app.jsx

in the [product_id].jsx i have a function that get 'best selling products' from backend

Suppose we have 1000 products on the site, the next-js server will get 'best selling products' 1000 times but once was enough


问:
How to extract a timezone aware time from a Pandas Datetime & timezone aware column?
I have converted my timezone naive timestamps to be timezone aware in my Pandas dataframe, so that the timestamp column in my data looks like:

df[['timestamp']]
```
```2018-07-29 14:30:00+01:00
```
<p>I want to extract the hour from these timestamps, but with the timezone taken into account. For the example above, I want:</p>
<pre class="lang-py prettyprint-override"><code>df[['timestamp','hour']]
</code>```
```<code>2018-07-29 14:30:00+01:00 , 15
</code>```

However, I can't find a way to do this without dropping the context of the timezone. I've tried
df[['timestamp']].dt.hour but that returns 14, the hour without the timezone.

How can I extract the hour with the timezone taken into account?

Body:
I have converted my timezone naive timestamps to be timezone aware in my Pandas dataframe, so that the timestamp column in my data looks like:

df[['timestamp']]

2018-07-29 14:30:00+01:00

I want to extract the hour from these timestamps, but with the timezone taken into account. For the example above, I want:

df[['timestamp','hour']]

2018-07-29 14:30:00+01:00 , 15

However, I can't find a way to do this without dropping the context of the timezone. I've tried
df[['timestamp']].dt.hour but that returns 14, the hour without the timezone.

How can I extract the hour with the timezone taken into account?


问:
JSTL error when running maven project on eclipse - The absolute uri cant be resolved in either web.xml or the jar files deployed with this application
I am having a probably silly issue with starting up my Maven project in Eclipse. I am creating a job application portal and I am using the following uri code

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

This is my index.jsp page for reference:

```<code><%@page import="com.DB.DBConnect" %>
<%@page import="java.sql.Connection" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AppUp - CUS 1156</title>
<%@include file="all_component/all_css.jsp"%>

<style type="text/css">
.back-img {
    background: url("img/header-image.jpg");
    width: 100%;
    height: 80vh;
    background-repeat: no-repeat;
    background-size: cover;
}
</style>
</head>
<body>

 <%@include file="all_component/navbar.jsp"%>

  <% Connection conn = DBConnect.getConn();
out.println(conn);
%>

    <div class="container-fluid back-img">
        <div class="text-center">
            <h1 class="text-white p-4">
                <i class="fa fa-book mr-2" aria-hidden="true"></i>AppUp
            </h1>
<!--            <p class="text-white p-4">Apply For Entry Level Positions Seamlessly</p> -->
        </div>
    </div>

    <div class="index_info mr-5 ml-5">
        <div class="text-center">
            <h1 class="text-white p-4">
                <h1>Why AppUp?</h1>
                <p>Landing your first gig out of college is a daunting task.
                    Created by two undergraduate students, AppUp is a platform that
                    highlights the achievements of current college students/new grads,
                    and breaks the gap that other job platforms have.</p>
                <p>Simply create an account with your .edu email, and jazz up
                    your profile. What are you studying? Any past experiences you want
                    to share? What about extracurriculars? Personal projects? AppUp is
                    here to highlight unconventional work you have done, and give you a
                    platform specifically for new grad positions an internships!</p>
                <p>AppUp is unique in a special way. We allow recruiters to
                    directly post their jobs on our application, allowing for a seamless
                    process for both recruiters and applicants.</p>
            </h1>
        </div>
        <h1 class="text-white p-4"></h1>
    </div>

    <%@include file="all_component/footer.jsp" %>
</body>
</html>
</code>```

When I run the application, I get this error:

```<code>Type Exception Report

Message The absolute uri: [http://java.sun.com/jsp/jstl/core] cannot be resolved in either web.xml or the jar files deployed with this application

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: The absolute uri: [http://java.sun.com/jsp/jstl/core] cannot be resolved in either web.xml or the jar files deployed with this application
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:54)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:294)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:81)
    org.apache.jasper.compiler.TagLibraryInfoImpl.generateTldResourcePath(TagLibraryInfoImpl.java:251)
    org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:122)
    org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:429)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:487)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1444)
    org.apache.jasper.compiler.Parser.parse(Parser.java:138)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:245)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:106)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:206)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:391)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:367)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:351)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:603)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:380)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:328)
    jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
</code>```

This is my pom.xml:

```<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.apache.maven</groupId>
  <artifactId>maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>maven Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>

  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>2.0.0</version>
</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

  </dependencies>

  <build>
    <finalName>maven</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
</code>```

This is my web.xml:

```<code><!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>
</code>```

And I have also attached an image of the structure of my code.

As you can see, there is no jstl.jar file within the WEB-INF/lib folder. Is this something I need to download online? I already have tomcat up and running (10.0.27) and I put the jstl dependency in my pom.xml. Sorry if this is a silly question, this is my first time working on a project like this.

Any help is extremely appreciated, thank you so much!

Body:
I am having a probably silly issue with starting up my Maven project in Eclipse. I am creating a job application portal and I am using the following uri code

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

This is my index.jsp page for reference:

<%@page import="com.DB.DBConnect" %>
<%@page import="java.sql.Connection" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>

<meta charset="UTF-8">
<title>AppUp - CUS 1156</title>
<%@include file="all_component/all_css.jsp"%>

 <%@include file="all_component/navbar.jsp"%>

  <% Connection conn = DBConnect.getConn();
out.println(conn);
%>

                AppUp

Why AppUp?

Landing your first gig out of college is a daunting task.
                    Created by two undergraduate students, AppUp is a platform that
                    highlights the achievements of current college students/new grads,
                    and breaks the gap that other job platforms have.

Simply create an account with your .edu email, and jazz up
                    your profile. What are you studying? Any past experiences you want
                    to share? What about extracurriculars? Personal projects? AppUp is
                    here to highlight unconventional work you have done, and give you a
                    platform specifically for new grad positions an internships!

AppUp is unique in a special way. We allow recruiters to
                    directly post their jobs on our application, allowing for a seamless
                    process for both recruiters and applicants.

    <%@include file="all_component/footer.jsp" %>

When I run the application, I get this error:

Type Exception Report

Message The absolute uri: [http://java.sun.com/jsp/jstl/core] cannot be resolved in either web.xml or the jar files deployed with this application

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: The absolute uri: [http://java.sun.com/jsp/jstl/core] cannot be resolved in either web.xml or the jar files deployed with this application
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:54)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:294)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:81)
    org.apache.jasper.compiler.TagLibraryInfoImpl.generateTldResourcePath(TagLibraryInfoImpl.java:251)
    org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:122)
    org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:429)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:487)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1444)
    org.apache.jasper.compiler.Parser.parse(Parser.java:138)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:245)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:106)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:206)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:391)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:367)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:351)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:603)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:380)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:328)
    jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.

This is my pom.xml:

<?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.apache.maven</groupId>
  <artifactId>maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>maven Maven Webapp</name>

  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>

  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>2.0.0</version>
</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

  </dependencies>

  <build>
    <finalName>maven</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>

        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

This is my web.xml:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

And I have also attached an image of the structure of my code.

As you can see, there is no jstl.jar file within the WEB-INF/lib folder. Is this something I need to download online? I already have tomcat up and running (10.0.27) and I put the jstl dependency in my pom.xml. Sorry if this is a silly question, this is my first time working on a project like this.

Any help is extremely appreciated, thank you so much!


问:
htaccess does not redirect webpages without https
Im figuring out why when I try to access to https://legacy.dhnn.com/wip/ypf/ruta-nube/ypf-ruta-contado.html, with http instead of https, it wipes the subdomain "legacy"

I dont know much about redirections, but seems like .htaccess needs to be configured, but i dont know how, i did something, but it is not working

Also, i have a lot of websites inside folder "wip", and I dont want to create an htaccess file for each site, is that possible?

is this code right?

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^dhnn.com [NC]
RewriteRule ^(.*)$ http://legacy.dhnn.com/$1 [R=301,L]
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://legacy.dhnn.com/$1 [R,L]
</code>```

Body:
Im figuring out why when I try to access to https://legacy.dhnn.com/wip/ypf/ruta-nube/ypf-ruta-contado.html, with http instead of https, it wipes the subdomain "legacy"

I dont know much about redirections, but seems like .htaccess needs to be configured, but i dont know how, i did something, but it is not working

Also, i have a lot of websites inside folder "wip", and I dont want to create an htaccess file for each site, is that possible?

is this code right?

RewriteEngine on
RewriteCond %{HTTP_HOST} ^dhnn.com [NC]
RewriteRule ^(.*)$ http://legacy.dhnn.com/$1 [R=301,L]
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://legacy.dhnn.com/$1 [R,L]


问:
Updating UI without needing reload/refresh when deleting/adding new rows to DataTables?

I have a table that is rendered using DataTables in a cshtml file. I am adding and removing users. I add users using select2 tag and remove a user from the table.

The table body has a row with a onclick function that deletes that specific row. And select two uses a button to add a new row.

All is working fine, one issue left is that atm I have to reload the page to render the changes.

Is there a simple way to add and delete a row and render it without refreshing the page? Will I need AJAX for this?

```<code>[Authorize(Policy = CMPConstants.AdminUsersOnly)]
    public IActionResult GroupDetails(string groupName)
    { //return data model to render in cshtml,
        var trustMarqueAdmin = SetWrapperModel(groupName);
        return this.View(trustMarqueAdmin);
    }

     // model rendered in cshtml.
<table id="admin-users-table" class="table">
    @{
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.TMUser.DisplayName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.TMUser.GivenName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.TMUser.Surname)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.TMUser.CompanyName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.TMUser.AccessLevel)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.TMUser.AccessScope)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.TMUser.PrismUser)
                </th>
                <th>
                    Remove
                </th>
            </tr>
        </thead>
        <tbody id="table-body-admin-users">
            @foreach (var member in Model.CurrentGroupMembers)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => member.DisplayName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.GivenName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.Surname)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.CompanyName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.AccessLevel)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.AccessScope)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.PrismUser)
                    </td>
                    <td>
                        <button type="button" class="btn btn-secondary delete-user-icon" onclick="RemoveFromGroup('@member.Id','@Model.TMGroup.Id','@member.GivenName','@member.Surname', '@Model.GroupName')">remove</button>
                    </td>
                </tr>
            }
        </tbody>
    }
</table>

 // on clicking add + plus button add members,
function AddToGroup(groupId, groupName) {
  $("#confirm-add-group").modal('show');

  $.post('/Home/AddToGroup',
       {
        userIdList: userIds,
        groupId: groupId,
        groupName:groupName
    });
 }

// on clicking a delete button a row is deleted.
function RemoveFromGroup(userId, groupId, fName, lName, groupName) {
  $(".confirm-delete").click(function () {
   $.post('/Home/RemoveFromGroup', { userId: userId, groupId: groupId });
  });
}

 // running data table here:
$(document).ready(function () {
  $('#admin-users-table').DataTable({
     allowClear: true,
   });
 });

    [Authorize(Policy = CMPConstants.AdminUsersOnly)]
    public async Task RemoveFromGroup(string? userId, string? groupId)
    {
        await this.b2cRepository.DeleteUserFromGroup(userId, groupId).ConfigureAwait(false);
    }

    [Authorize(Policy = CMPConstants.AdminUsersOnly)]
    public async Task AddToGroup(string groupId, string?[] userIdList, string groupName)
    {
        await this.b2cRepository.AddUserToGroup(groupId, userIdList, groupName).ConfigureAwait(false);
    }
</code>```

Body:
I have a table that is rendered using DataTables in a cshtml file. I am adding and removing users. I add users using select2 tag and remove a user from the table.

The table body has a row with a onclick function that deletes that specific row. And select two uses a button to add a new row.

All is working fine, one issue left is that atm I have to reload the page to render the changes.

Is there a simple way to add and delete a row and render it without refreshing the page? Will I need AJAX for this?

[Authorize(Policy = CMPConstants.AdminUsersOnly)]
    public IActionResult GroupDetails(string groupName)
    { //return data model to render in cshtml,
        var trustMarqueAdmin = SetWrapperModel(groupName);
        return this.View(trustMarqueAdmin);
    }

     // model rendered in cshtml.

    @{

                    @Html.DisplayNameFor(model => model.TMUser.DisplayName)

                    @Html.DisplayNameFor(model => model.TMUser.GivenName)

                    @Html.DisplayNameFor(model => model.TMUser.Surname)

                    @Html.DisplayNameFor(model => model.TMUser.CompanyName)

                    @Html.DisplayNameFor(model => model.TMUser.AccessLevel)

                    @Html.DisplayNameFor(model => model.TMUser.AccessScope)

                    @Html.DisplayNameFor(model => model.TMUser.PrismUser)

                    Remove

            @foreach (var member in Model.CurrentGroupMembers)
            {

                        @Html.DisplayFor(modelItem => member.DisplayName)

                        @Html.DisplayFor(modelItem => member.GivenName)

                        @Html.DisplayFor(modelItem => member.Surname)

                        @Html.DisplayFor(modelItem => member.CompanyName)

                        @Html.DisplayFor(modelItem => member.AccessLevel)

                        @Html.DisplayFor(modelItem => member.AccessScope)

                        @Html.DisplayFor(modelItem => member.PrismUser)

                        <button type="button" class="btn btn-secondary delete-user-icon" onclick="RemoveFromGroup('@member.Id','@Model.TMGroup.Id','@member.GivenName','@member.Surname', '@Model.GroupName')">remove</button>

            }

    }

 // on clicking add + plus button add members,
function AddToGroup(groupId, groupName) {
  $("#confirm-add-group").modal('show');

  $.post('/Home/AddToGroup',
       {
        userIdList: userIds,
        groupId: groupId,
        groupName:groupName
    });
 }

// on clicking a delete button a row is deleted.
function RemoveFromGroup(userId, groupId, fName, lName, groupName) {
  $(".confirm-delete").click(function () {
   $.post('/Home/RemoveFromGroup', { userId: userId, groupId: groupId });
  });
}

 // running data table here:
$(document).ready(function () {
  $('#admin-users-table').DataTable({
     allowClear: true,
   });
 });

    [Authorize(Policy = CMPConstants.AdminUsersOnly)]
    public async Task RemoveFromGroup(string? userId, string? groupId)
    {
        await this.b2cRepository.DeleteUserFromGroup(userId, groupId).ConfigureAwait(false);
    }

    [Authorize(Policy = CMPConstants.AdminUsersOnly)]
    public async Task AddToGroup(string groupId, string?[] userIdList, string groupName)
    {
        await this.b2cRepository.AddUserToGroup(groupId, userIdList, groupName).ConfigureAwait(false);
    }


问:
Pearson Correlation Result
I have been carrying out some Pearson correlations. In some of the outcome tables I get the following results inside instead of a correlation value:

"NA", "NaN", "-Inf***"

I found a link that stated NaN indicates there is no correlation between the variables (https://www.mathworks.com/matlabcentral/answers/506464-getting-a-nan-in-correlation-coefficient).

The NaN, in this case, is interpreted as no correlation between the two variables.  The correlation describes how much one variable changes as the other variable changes.  That requires both variables to change.

As shown in the image the issue occurs with variables "sand", "slit", "clay". These variables were a single value measurement in the dataset while the rest of variables in the example ("tc", "soc", "tn") consisted of triplicate measurements within the dataset. I am not sure if this is part of the issue leading to these non-numerical results.

I wanted to ask if each of these results which all appear within the same table mean the same. I hope this makes sense. If a chunk of my data is required to make it easier to understand my query please let me know.

(06/12/2022) - Update
Below there is the code being used. Also this data extract does not have any missing values but the overall data set does have a few missing values. However I noticed the issue seems to only occur with "sand", "silt" and "clay".

```<code># Library
library(tidyverse)
library(Hmisc)

# Data subset
dk1 <-structure(list(tc = c(1.38, 1.76, 1.36, 1.48, 1.25, 1.48),
                     soc = c(0.618, 0.951, 1.08, 1.11, 0.756, 1.38),
                     tn = c(0.104, 0.137, 0.11, 0.112, 0.112, 0.106),
                     sand = c(96, 96, 96, 96, 96, 96),
                     silt = c(2.5,2.5, 2.5, 2.5, 2.5, 2.5),
                     clay = c(1.6, 1.6, 1.6, 1.6, 1.6, 1.6),
                     ph = c(6.77, 7.25, 6.69, 7.14, 6.63, 7.18)),
                row.names = c("1","2", "3", "4", "5", "6"), class = "data.frame")
View(dk1)

# Correlation table
dk1corr <- rcorr(as.matrix(dk1), type = c("pearson"))
dk1corr

# Correlations coefficients and p value extract
ccr.dk1corr<-dk1corr$r
ccp.dk1corr<-dk1corr$P
</code>```

Title: Pearson Correlation Result

Body:
I have been carrying out some Pearson correlations. In some of the outcome tables I get the following results inside instead of a correlation value:

"NA", "NaN", "-Inf***"

I found a link that stated NaN indicates there is no correlation between the variables (https://www.mathworks.com/matlabcentral/answers/506464-getting-a-nan-in-correlation-coefficient).

The NaN, in this case, is interpreted as no correlation between the two variables.  The correlation describes how much one variable changes as the other variable changes.  That requires both variables to change.

As shown in the image the issue occurs with variables "sand", "slit", "clay". These variables were a single value measurement in the dataset while the rest of variables in the example ("tc", "soc", "tn") consisted of triplicate measurements within the dataset. I am not sure if this is part of the issue leading to these non-numerical results.

I wanted to ask if each of these results which all appear within the same table mean the same. I hope this makes sense. If a chunk of my data is required to make it easier to understand my query please let me know.

(06/12/2022) - Update
Below there is the code being used. Also this data extract does not have any missing values but the overall data set does have a few missing values. However I noticed the issue seems to only occur with "sand", "silt" and "clay".

# Library
library(tidyverse)
library(Hmisc)

# Data subset
dk1 <-structure(list(tc = c(1.38, 1.76, 1.36, 1.48, 1.25, 1.48),
                     soc = c(0.618, 0.951, 1.08, 1.11, 0.756, 1.38),
                     tn = c(0.104, 0.137, 0.11, 0.112, 0.112, 0.106),
                     sand = c(96, 96, 96, 96, 96, 96),
                     silt = c(2.5,2.5, 2.5, 2.5, 2.5, 2.5),
                     clay = c(1.6, 1.6, 1.6, 1.6, 1.6, 1.6),
                     ph = c(6.77, 7.25, 6.69, 7.14, 6.63, 7.18)),
                row.names = c("1","2", "3", "4", "5", "6"), class = "data.frame")
View(dk1)

# Correlation table
dk1corr <- rcorr(as.matrix(dk1), type = c("pearson"))
dk1corr

# Correlations coefficients and p value extract
ccr.dk1corr<-dk1corr$r
ccp.dk1corr<-dk1corr$P


问:
Why are the colors transposed in my webm thumbnails?
I have been using ffmpeg to generate webm files from png frames, and the webm files run ok in my video player, but the thumbnail colours appear transposed - blue replacing red, purple replacing orange, brown replacing green. I've also encountered issue uploading the webm to an image hosting site (which normally does support webms), though this might be an issue on their end.
I'm on Ubuntu 22.04.1 LTS

Does anyone know what might be causing this, and how to fix it? Or how to check whether the webm files are ok or corrupted?

*Edit: ok, here's a side-by-side comparison of the thumbnails that appear in my file explorer - mp4 on the left and webm on the right.
Both were generated from the same set of pngs, using the same command except with the filename extension changed.

Specifically,

```<code>ffmpeg -framerate 24 -i Panel2Humanized/frame%04d.png panel2humanskin.webm
</code>```

and

```<code>ffmpeg -framerate 24 -i Panel2Humanized/frame%04d.png panel2humanskin.mp4
</code>```

Both look the same when opened with a video player. It looks like the mp4 thumbnail grabbed the 1st frame while the webm grabbed the last, but the colors should be the same in each. (The text-bubble in the top-left is yellow in the mp4).

*Follow-up: Apparently my WebMs are being generated in GBRP (Green-Blue-Red Planar) pixel format, the site I was trying to upload to requires YUV420P (Luma/Chroma 4:2:0 Planar) format, maybe that's the issue? I'm still not sure exactly what that means or how to fix it.

*Final follow-up: Looks like I needed to change the argument to:

```<code>ffmpeg -framerate 24 -i Panel2Humanized/frame%04d.png -pix_fmt yuv420p paned2humanskin.webm
</code>```

Body:
I have been using ffmpeg to generate webm files from png frames, and the webm files run ok in my video player, but the thumbnail colours appear transposed - blue replacing red, purple replacing orange, brown replacing green. I've also encountered issue uploading the webm to an image hosting site (which normally does support webms), though this might be an issue on their end.
I'm on Ubuntu 22.04.1 LTS

Does anyone know what might be causing this, and how to fix it? Or how to check whether the webm files are ok or corrupted?

*Edit: ok, here's a side-by-side comparison of the thumbnails that appear in my file explorer - mp4 on the left and webm on the right.
Both were generated from the same set of pngs, using the same command except with the filename extension changed.

Specifically,

ffmpeg -framerate 24 -i Panel2Humanized/frame%04d.png panel2humanskin.webm

and

ffmpeg -framerate 24 -i Panel2Humanized/frame%04d.png panel2humanskin.mp4

Both look the same when opened with a video player. It looks like the mp4 thumbnail grabbed the 1st frame while the webm grabbed the last, but the colors should be the same in each. (The text-bubble in the top-left is yellow in the mp4).

*Follow-up: Apparently my WebMs are being generated in GBRP (Green-Blue-Red Planar) pixel format, the site I was trying to upload to requires YUV420P (Luma/Chroma 4:2:0 Planar) format, maybe that's the issue? I'm still not sure exactly what that means or how to fix it.

*Final follow-up: Looks like I needed to change the argument to:

ffmpeg -framerate 24 -i Panel2Humanized/frame%04d.png -pix_fmt yuv420p paned2humanskin.webm


问:
How to upload CSV files over the GCP (automated process)
I have GCP server and I want to upload CSV files in an automated way.

I want to upload all the old CSV file (existing files) over the GCP (BigQuery Table/View)

I want to upload all new arriving files (each day new files arrive) - So, I want to upload only latest files.

For now: I am running Cloud SDK gcloud cp command manually to upload files every day. I login with Remote Desktop > Authenticate myself with GCP SDK > and run gcloud cp command to upload the files in bucket > and from bucket I loaded the data into BigQuery.

The drive is not mapped. The drive physical path is: C:\myDrive

Current solution: Server > C Drive > GCP authentication > gcloud cp command to upload the files in Bucket > Bucket to BigQuery

Looking for automation ETL Process with Dataproc or Dataflow.

Thanks and looking forward to your solutions and tutorial + steps.


问:
Why I see random folders for the delta table that I create through column mappings using databricks in azure storage container
I am working on a pyspark code that reads csv files and save that to the azure storage container using databricks.
Writing the code to read and write the csv files seems to be straight forward using reader and writer api.
As we are dealing with csv files, we have some csv files whose column headers have spaces in them, so we decided to use Column mapping functionality that databricks provide in order to support our use case.
In order to make our code generic and common to read all csv files whether they have special characters or spaces in column header or not, we decided to create all the delta tables that we create using that feature.

I see some odd structure on the azure storage container where the actual parquet files get created.

Image of delta table physical parquet files without using Column Mapping:

Image of delta table physical parquet files using Column Mapping:

I am not doing any partitioning in both the cases.

Just wanted to know why those random folders get created and what is the importance of those folders when someone use column mapping feature of databricks.

I have tried searching for detailed documentation around it but could not find anything fruitful.

Update:

I am using a simple create table script by providing three additional TBLProperties as mentioned in the column mapping document.

```<code>CREATE TABLE delta_table
  USING DELTA
  TBLPROPERTIES ('delta.minReaderVersion' = '2',
  'delta.minWriterVersion' = '5',
  'delta.columnMapping.mode' = 'name')
</code>```

Ref Doc: https://learn.microsoft.com/en-us/azure/databricks/delta/delta-column-mapping

Body:
I am working on a pyspark code that reads csv files and save that to the azure storage container using databricks.
Writing the code to read and write the csv files seems to be straight forward using reader and writer api.
As we are dealing with csv files, we have some csv files whose column headers have spaces in them, so we decided to use Column mapping functionality that databricks provide in order to support our use case.
In order to make our code generic and common to read all csv files whether they have special characters or spaces in column header or not, we decided to create all the delta tables that we create using that feature.

I see some odd structure on the azure storage container where the actual parquet files get created.

Image of delta table physical parquet files without using Column Mapping:

Image of delta table physical parquet files using Column Mapping:

I am not doing any partitioning in both the cases.

Just wanted to know why those random folders get created and what is the importance of those folders when someone use column mapping feature of databricks.

I have tried searching for detailed documentation around it but could not find anything fruitful.

Update:

I am using a simple create table script by providing three additional TBLProperties as mentioned in the column mapping document.

CREATE TABLE delta_table
  USING DELTA
  TBLPROPERTIES ('delta.minReaderVersion' = '2',
  'delta.minWriterVersion' = '5',
  'delta.columnMapping.mode' = 'name')

Ref Doc: https://learn.microsoft.com/en-us/azure/databricks/delta/delta-column-mapping


问:
Resize Column In DataTables
how to resizing width of jabatan ? because it's to long

```<code><div class="card-body">
            <div class="col">
                <div class="row">
                    <a class="mb-3" href="{{ route('karyawan.create') }}">
                      <button class="btn btn-primary">tambah karyawan</button>
                    </a>
                    <a class="ml-3" href="{{ route('import') }}">
                      <button class="btn btn-primary">import karyawan</button>
                    </a>
                    <div class="table-responsive overflow-scroll">
                        <table class="table wi" id="table" >
                          <thead class=" text-primary">
                            <th>
                                No
                            </th>
                            <th>
                              NIP
                            </th>
                            <th>
                              NIK
                            </th>
                            <th>
                                Nama karyawan
                            </th>
                            <th>
                              Kantor
                            </th>
                            <th >
                              Jabatan
                            </th>
                            <th>
                                Aksi
                            </th>
                          </thead>
                          @php
                              $no = 1;
                          @endphp
                          <tbody>
                            @foreach ($data as $item)
                              @php
                                $jabatan = 'Pusat';
                                $kd_ent = null;
                                $data1 = DB::table('mst_divisi')
                                    ->where('kd_divisi', $item->kd_entitas)
                                    ->first();
                                $data2 = DB::table('mst_sub_divisi')
                                    ->where('kd_subdiv', $item->kd_entitas)
                                    ->first();
                                $data3 = DB::table('mst_cabang')
                                    ->where('kd_cabang', $item->kd_entitas)
                                    ->first();

                                if (isset($data1)) {
                                  $jabatan = 'Pusat';
                                } else if (isset($data2)) {
                                  $jabatan = 'Pusat';
                                } else if (isset($data3)) {
                                  $jabatan = $data3->kd_cabang;
                                } else if ($item->kd_bagian) {
                                  $jabatan = 'Pusat';
                                }
                              @endphp
                                <tr>
                                    <td>
                                        {{ $no++ }}
                                    </td>
                                    <td>{{ $item->nip }}</td>
                                    <td>{{ $item->nik }}</td>
                                    <td>
                                      {{ $item->nama_karyawan }}
                                    </td>
                                    <td>
                                      {{ $jabatan }}
                                    </td>
                                    <td>
                                      @php
                                          $ket = null;
                                          if($item->ket_jabatan != null){
                                            $ket = ' ('.$item->ket_jabatan.')';
                                          }
                                          $st_jabatan = DB::table('mst_jabatan')
                                            ->where('kd_jabatan', $item->kd_jabatan)
                                            ->first();

                                          $bagian = '';
                                          if ($item->kd_bagian != null) {
                                            $bagian1 = DB::table('mst_bagian')
                                              ->select('nama_bagian')
                                              ->where('kd_bagian', $item->kd_bagian)
                                              ->first();

                                              if (isset($bagian1)) {
                                                $bagian = $bagian1->nama_bagian;
                                              }
                                          }
                                      @endphp

                                      @if ($item->status_jabatan == "Penjabat")
                                          Pj.{{ $item->nama_jabatan . ' ' . $bagian.$ket }}
                                      @elseif($item->status_jabatan == "Penjabat Sementara")
                                          Pjs.{{ $item->nama_jabatan . ' ' . $bagian.$ket }}
                                      @else
                                      {{ $item->nama_jabatan . ' ' . $bagian.$ket }}
                                      @endif
                                    </td>
                                    <td>
                                      <div class="row">
                                        <a href="{{ route('karyawan.show', $item->nip) }}">
                                          <button class="btn btn-outline-info btn-sm">
                                            Detail
                                          </button>
                                        </a>

                                        {{-- <form action="{{ route('karyawan.destroy', $item->nip) }}" method="POST">
                                          @csrf
                                          @method('DELETE')

                                          <button type="submit" class="btn btn-danger btn-block">Delete</button>
                                        </form> --}}
                                      </div>
                                    </td>
                                </tr>
                            @endforeach
                          </tbody>
                        </table>
                </div>
            </div>
        </div>

 <script>
    $(document).ready( function () {
      $('#table').DataTable();
    });
  </script>
</code>```

how do I adjust the size of the position column, because it's too long and also for the other columns so they don't exceed the limit
also remove the scroll at the bottom of the table, only left on the side of the table
and how also there looks responsive in various devices

Title: Resize Column In DataTables

Body:
how to resizing width of jabatan ? because it's to long

                      <button class="btn btn-primary">tambah karyawan</button>

                      <button class="btn btn-primary">import karyawan</button>

                                No

                              NIP

                              NIK

                                Nama karyawan

                              Kantor

                              Jabatan

                                Aksi

                          @php
                              $no = 1;
                          @endphp

                            @foreach ($data as $item)
                              @php
                                $jabatan = 'Pusat';
                                $kd_ent = null;
                                $data1 = DB::table('mst_divisi')
                                    ->where('kd_divisi', $item->kd_entitas)
                                    ->first();
                                $data2 = DB::table('mst_sub_divisi')
                                    ->where('kd_subdiv', $item->kd_entitas)
                                    ->first();
                                $data3 = DB::table('mst_cabang')
                                    ->where('kd_cabang', $item->kd_entitas)
                                    ->first();

                                if (isset($data1)) {
                                  $jabatan = 'Pusat';
                                } else if (isset($data2)) {
                                  $jabatan = 'Pusat';
                                } else if (isset($data3)) {
                                  $jabatan = $data3->kd_cabang;
                                } else if ($item->kd_bagian) {
                                  $jabatan = 'Pusat';
                                }
                              @endphp

                                        {{ $no++ }}

                                    {{ $item->nip }}
                                    {{ $item->nik }}

                                      {{ $item->nama_karyawan }}

                                      {{ $jabatan }}

                                      @php
                                          $ket = null;
                                          if($item->ket_jabatan != null){
                                            $ket = ' ('.$item->ket_jabatan.')';
                                          }
                                          $st_jabatan = DB::table('mst_jabatan')
                                            ->where('kd_jabatan', $item->kd_jabatan)
                                            ->first();

                                          $bagian = '';
                                          if ($item->kd_bagian != null) {
                                            $bagian1 = DB::table('mst_bagian')
                                              ->select('nama_bagian')
                                              ->where('kd_bagian', $item->kd_bagian)
                                              ->first();

                                              if (isset($bagian1)) {
                                                $bagian = $bagian1->nama_bagian;
                                              }
                                          }
                                      @endphp

                                      @if ($item->status_jabatan == "Penjabat")
                                          Pj.{{ $item->nama_jabatan . ' ' . $bagian.$ket }}
                                      @elseif($item->status_jabatan == "Penjabat Sementara")
                                          Pjs.{{ $item->nama_jabatan . ' ' . $bagian.$ket }}
                                      @else
                                      {{ $item->nama_jabatan . ' ' . $bagian.$ket }}
                                      @endif

                                        nip) }}">
                                          <button class="btn btn-outline-info btn-sm">
                                            Detail
                                          </button>

                                        {{-- <form action="{{ route('karyawan.destroy', $item->nip) }}" method="POST">
                                          @csrf
                                          @method('DELETE')

                                          <button type="submit" class="btn btn-danger btn-block">Delete</button>
                                        </form> --}}

                            @endforeach

how do I adjust the size of the position column, because it's too long and also for the other columns so they don't exceed the limit
also remove the scroll at the bottom of the table, only left on the side of the table
and how also there looks responsive in various devices


问:
VBA ActiveX Listbox gives Error 438 "Property or method not support by this object" when trying to access it in personal
This all started with trying to help someone else with his error in VBA Selecting a a range for a combobox input
I noticed some things wrong with the code but I left out the ListBox so decided to test my code with a ListBox included. That was my first mistake..

I then tried finding a solution to my problem, this is my first time filling a listbox so I didn't expect to get it going first-try but I'm 30 tabs further and still can't access my listbox.

People said you can assign a whole range with .List
How to add data from a Range to an ActiveX ListBox?

```<code>ThisWorkbook.Sheets("Sheet1").ListBox1.Clear 'Error 438
ThisWorkbook.Sheets("Sheet1").ListBox1.ListCount 'Error 438
Sheets("Sheet1").ListBox1.List = arr 'Error 438

</code>```

Here again, usage of ListBox1.List https://stackoverflow.com/a/65898769/19353309 so it really should work but to no avail, can't work with listbox.

Saw the following and thought to simplify things: https://stackoverflow.com/a/31224552/19353309 but that again didn't work.

While I saw a lot of code starting with ThisWorkbook, I figured I can interchange it with normal workbook/worksheet declaration but also tested this again, in a separate module in the workbook I'm testing in. Finally I was able to access the ListBox but why?
Why can't I use the ListBox's properties from within my Personal modules? Not even in "ThisWorkbook" of the workbook I was able to access it.

https://stackoverflow.com/a/62436865/19353309 code seemed simple enough to test things out but didn't work because I didn't know I needed to be in the module of the workbook itself. Shape and Object both gave me what was expected but couldn't use the rest. Is there really no way to control a ListBox or something similar from your Personal or are there certain restrictions for certain Objects?

Ps: I'm glad I got it to work but to avoid further issues like this, I'd like to comprehend the actual problem.

**EDIT: **
Code (for whatever reason) works now in ThisWorkbook of the workbook where the listBox1 is in.
(code from https://stackoverflow.com/a/62436865/19353309 )

Sub ListBoxTest()

    Dim ctrl As OLEObject
    Dim arr As Variant

    For Each ctrl In Sheets("Blad1").OLEObjects
        If TypeName(ctrl.Object) = "ListBox" Then
'            ctrl.Clear
'            ctrl.List = arr
        End If
    Next ctrl

    ' Worksheet
    Dim wkTest As Worksheet: Set wkTest = ThisWorkbook.Worksheets("Blad1")
'    ThisWorkbook.Sheets("Blad1").ListBox1.ListCount 'err 438 when using anywhere but a separate module in active workbook
    ' Shape - no use
    Dim shTest As Shape: Set shTest = wkTest.Shapes("ListBox1")
    Debug.Print "Shape", shTest.Name, shTest.Left
    'shTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...

    ' OLEObject - no use
    Dim ooTest As OLEObject: Set ooTest = wkTest.OLEObjects("ListBox1")
    Debug.Print "OLEObject", ooTest.Name, ooTest.Left
    'ooTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...

    Dim obj As Object

    'Set obj = wkTest.ListBox1 ' Compile error: Method or data member not found.
'    Sheets("Blad1").ListBox1.Name
    ' Object 1 Solution
    Set obj = Worksheets("Blad1").ListBox1
    Debug.Print "Object 1", obj.Name, obj.Left
    obj.AddItem "One"

    ' Object 2 Solution
    Set obj = Blad1.ListBox1
    Debug.Print "Object 2", obj.Name, obj.Left
    obj.AddItem "Two"
    obj.List = Array("AAA", "BBB", "CCC")

    ' Object 3 Solution
    wkTest.Activate
    Set obj = ActiveSheet.ListBox1
    Debug.Print "Object 3", obj.Name, obj.Left
    obj.AddItem "Three"

    ' Favorite
    With Blad1.ListBox1
        Debug.Print "Favorite", .Name, .Left
        .AddItem "Four"
    End With

End Sub
```
<p>I even had to comment out Solution 2 and 4 before because of a compile error when I had this in my Personal.. I swear I've seen code here before where people were active/deactivating checkboxes and the works from their personal before.</p>
<p>To reiterate my question: Why are ActiveX elements unable to be used outside of the workbook it's used in?</p>
<p>Sorry in advance if I did miss a post explaining this already.</p>
<hr />
<p><strong>EDIT:</strong>
Did a bit more testing with what Rory gave me and it's really boiled down to not using the WorkSheet reference, since ActiveSheet and Sheet10 and wb.Sheets("ActiveSheetName") <> Set ws = WorkSheet("ActiveSheetName")</p>
<p>Also tested if ActiveWorkbook.Sheet10.Listbox1 would work but that's a bust.</p>
<p>So the takeaway for other people struggling like I was: not only do you need to use the <code>Codename</code> like VBasic2008 mentioned in the aforementioned link, you also need to avoid using the WorkSheet class when working with ListBox (probably the other ActiveX elements as well) like @Rory said.</p>
<p>In Personal testing:</p>
```Sub ListBoxTest()

    Dim arr As Variant
    Dim wkTest As Worksheet, ws As Worksheet
    Dim wb As Workbook
    Dim LastRow As Long
    Dim Criteria_1 As Range, rng As Range

    Set wb = Workbooks("MOSTEST.xlsx")
    Set ws = wb.Sheets("11.2022")
    Set wkTest = wb.Sheets("AddJournals")
    'LastRow = Sheets("TO DO Prijslijsten").Range("B2").End(xlDown).Row
    LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row

    Set Criteria_1 = ws.Range("C10")
    On Error Resume Next
    ws.ShowAllData
    On Error GoTo 0
    'copies the filtered data to the destination
    With ws.Range("A1")
        .AutoFilter field:=3, Criteria1:=CStr(Criteria_1)
    End With
    Set rng = ws.Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible)
    arr = rng.Value

'    With wkTest.ListBox1 ListBox1 from Sheet
'        Debug.Print "Favorite", .Name, .Left
'        .AddItem = "Four"
'    End With

'    With Blad10.ListBox1 'Error: Object Required which is to be expected, since we're working from personal
'    With wb.Blad10.ListBox1 'Error 438 again so you can only use this in the workbook you're working with, I presume?
'        Debug.Print "FavoriteOther, .Name, .Left"
'        .AddItem = "Five"
'    End With

    Dim obj As Object
'    Set obj = wkTest.ListBox1 'compile error: can't find method or member ~~~~ Now we know it's due to the Class not having ListBox
'    wkTest.Activate
    Set obj = ActiveWorkbook.ActiveSheet.ListBox1 'error 438 when you only use ActiveSheet.ListBox1
    Debug.Print "Set Object", obj.Name, obj.Left

'    With ActiveWorkbook.ActiveSheet.ListBox1 'no error from personal so ActiveSheet doesn't have the same class as Worksheet?
'        .Clear
'    End With

'    With ActiveWorkbook.Blad10.ListBox1 'error 438 so can't refer to Sheet10 as I would be able to in the workbook itself
'        .Clear
'        .List = arr
'    End With

'    Dim obj As Object
    Set obj = wb.Sheets("AddJournals").ListBox1
    With obj
        .Clear
        .List = arr
'        .AddItem = "Test" 'still error 438
    End With
    Set obj = Nothing
End Sub
```
<p>and in the workbook Mostest in a separate module:</p>
```Sub testListBox()

    Dim arr As Variant
    Dim wkTest As Worksheet, ws As Worksheet
    Dim wb As Workbook
    Dim LastRow As Long
    Dim Criteria_1 As Range, rng As Range

    Set wb = Workbooks("MOSTEST.xlsx")
    Set ws = wb.Sheets("11.2022")
    Set wkTest = wb.Sheets("AddJournals")
    'LastRow = Sheets("TO DO Prijslijsten").Range("B2").End(xlDown).Row
    LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row

    Set Criteria_1 = ws.Range("B6")

    'copies the filtered data to the destination
    With ws.Range("A1")
        .AutoFilter field:=2, Criteria1:=Criteria_1
    End With
    Set rng = ws.Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible)
    arr = rng.Value

'    With Blad10.ListBox1
'        Debug.Print "Favorite", .Name, .Left
'        .Clear
'        .List = arr
''        .AddItem = "Four" 'compile error: reference to constant not allowed
'    End With

'    With Sheets("AddJournals").ListBox1 'ok... this works too
'    With wb.Blad10.ListBox1 'Error 438 again
'    With wkTest.ListBox1 'still compile error
    With wb.Sheets("AddJournals").ListBox1 'works
        Debug.Print "FavoriteOther, .Name, .Left"
'        .AddItem = "Five" 'Compile error: not allowed with a constant/error 438 depending on which With I use ^
        .List = arr 'works just fine
    End With
    'no idea why .AddItem is having a fit now, it worked yesterday.. It even shows up when hitting period

End Sub
```

Hope this helps other people out as much as it confused me.

Body:
This all started with trying to help someone else with his error in VBA Selecting a a range for a combobox input
I noticed some things wrong with the code but I left out the ListBox so decided to test my code with a ListBox included. That was my first mistake..

I then tried finding a solution to my problem, this is my first time filling a listbox so I didn't expect to get it going first-try but I'm 30 tabs further and still can't access my listbox.

People said you can assign a whole range with .List
How to add data from a Range to an ActiveX ListBox?

ThisWorkbook.Sheets("Sheet1").ListBox1.Clear 'Error 438
ThisWorkbook.Sheets("Sheet1").ListBox1.ListCount 'Error 438
Sheets("Sheet1").ListBox1.List = arr 'Error 438

Here again, usage of ListBox1.List https://stackoverflow.com/a/65898769/19353309 so it really should work but to no avail, can't work with listbox.

Saw the following and thought to simplify things: https://stackoverflow.com/a/31224552/19353309 but that again didn't work.

While I saw a lot of code starting with ThisWorkbook, I figured I can interchange it with normal workbook/worksheet declaration but also tested this again, in a separate module in the workbook I'm testing in. Finally I was able to access the ListBox but why?
Why can't I use the ListBox's properties from within my Personal modules? Not even in "ThisWorkbook" of the workbook I was able to access it.

https://stackoverflow.com/a/62436865/19353309 code seemed simple enough to test things out but didn't work because I didn't know I needed to be in the module of the workbook itself. Shape and Object both gave me what was expected but couldn't use the rest. Is there really no way to control a ListBox or something similar from your Personal or are there certain restrictions for certain Objects?

Ps: I'm glad I got it to work but to avoid further issues like this, I'd like to comprehend the actual problem.

**EDIT: **
Code (for whatever reason) works now in ThisWorkbook of the workbook where the listBox1 is in.
(code from https://stackoverflow.com/a/62436865/19353309 )

Sub ListBoxTest()

    Dim ctrl As OLEObject
    Dim arr As Variant

    For Each ctrl In Sheets("Blad1").OLEObjects
        If TypeName(ctrl.Object) = "ListBox" Then
'            ctrl.Clear
'            ctrl.List = arr
        End If
    Next ctrl

    ' Worksheet
    Dim wkTest As Worksheet: Set wkTest = ThisWorkbook.Worksheets("Blad1")
'    ThisWorkbook.Sheets("Blad1").ListBox1.ListCount 'err 438 when using anywhere but a separate module in active workbook
    ' Shape - no use
    Dim shTest As Shape: Set shTest = wkTest.Shapes("ListBox1")
    Debug.Print "Shape", shTest.Name, shTest.Left
    'shTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...

    ' OLEObject - no use
    Dim ooTest As OLEObject: Set ooTest = wkTest.OLEObjects("ListBox1")
    Debug.Print "OLEObject", ooTest.Name, ooTest.Left
    'ooTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...

    Dim obj As Object

    'Set obj = wkTest.ListBox1 ' Compile error: Method or data member not found.
'    Sheets("Blad1").ListBox1.Name
    ' Object 1 Solution
    Set obj = Worksheets("Blad1").ListBox1
    Debug.Print "Object 1", obj.Name, obj.Left
    obj.AddItem "One"

    ' Object 2 Solution
    Set obj = Blad1.ListBox1
    Debug.Print "Object 2", obj.Name, obj.Left
    obj.AddItem "Two"
    obj.List = Array("AAA", "BBB", "CCC")

    ' Object 3 Solution
    wkTest.Activate
    Set obj = ActiveSheet.ListBox1
    Debug.Print "Object 3", obj.Name, obj.Left
    obj.AddItem "Three"

    ' Favorite
    With Blad1.ListBox1
        Debug.Print "Favorite", .Name, .Left
        .AddItem "Four"
    End With

End Sub

I even had to comment out Solution 2 and 4 before because of a compile error when I had this in my Personal.. I swear I've seen code here before where people were active/deactivating checkboxes and the works from their personal before.

To reiterate my question: Why are ActiveX elements unable to be used outside of the workbook it's used in?

Sorry in advance if I did miss a post explaining this already.

EDIT:
Did a bit more testing with what Rory gave me and it's really boiled down to not using the WorkSheet reference, since ActiveSheet and Sheet10 and wb.Sheets("ActiveSheetName") <> Set ws = WorkSheet("ActiveSheetName")

Also tested if ActiveWorkbook.Sheet10.Listbox1 would work but that's a bust.

So the takeaway for other people struggling like I was: not only do you need to use the Codename like VBasic2008 mentioned in the aforementioned link, you also need to avoid using the WorkSheet class when working with ListBox (probably the other ActiveX elements as well) like @Rory said.

In Personal testing:

Sub ListBoxTest()

    Dim arr As Variant
    Dim wkTest As Worksheet, ws As Worksheet
    Dim wb As Workbook
    Dim LastRow As Long
    Dim Criteria_1 As Range, rng As Range

    Set wb = Workbooks("MOSTEST.xlsx")
    Set ws = wb.Sheets("11.2022")
    Set wkTest = wb.Sheets("AddJournals")
    'LastRow = Sheets("TO DO Prijslijsten").Range("B2").End(xlDown).Row
    LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row

    Set Criteria_1 = ws.Range("C10")
    On Error Resume Next
    ws.ShowAllData
    On Error GoTo 0
    'copies the filtered data to the destination
    With ws.Range("A1")
        .AutoFilter field:=3, Criteria1:=CStr(Criteria_1)
    End With
    Set rng = ws.Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible)
    arr = rng.Value

'    With wkTest.ListBox1 ListBox1 from Sheet
'        Debug.Print "Favorite", .Name, .Left
'        .AddItem = "Four"
'    End With

'    With Blad10.ListBox1 'Error: Object Required which is to be expected, since we're working from personal
'    With wb.Blad10.ListBox1 'Error 438 again so you can only use this in the workbook you're working with, I presume?
'        Debug.Print "FavoriteOther, .Name, .Left"
'        .AddItem = "Five"
'    End With

    Dim obj As Object
'    Set obj = wkTest.ListBox1 'compile error: can't find method or member ~~~~ Now we know it's due to the Class not having ListBox
'    wkTest.Activate
    Set obj = ActiveWorkbook.ActiveSheet.ListBox1 'error 438 when you only use ActiveSheet.ListBox1
    Debug.Print "Set Object", obj.Name, obj.Left

'    With ActiveWorkbook.ActiveSheet.ListBox1 'no error from personal so ActiveSheet doesn't have the same class as Worksheet?
'        .Clear
'    End With

'    With ActiveWorkbook.Blad10.ListBox1 'error 438 so can't refer to Sheet10 as I would be able to in the workbook itself
'        .Clear
'        .List = arr
'    End With

'    Dim obj As Object
    Set obj = wb.Sheets("AddJournals").ListBox1
    With obj
        .Clear
        .List = arr
'        .AddItem = "Test" 'still error 438
    End With
    Set obj = Nothing
End Sub

and in the workbook Mostest in a separate module:

Sub testListBox()

    Dim arr As Variant
    Dim wkTest As Worksheet, ws As Worksheet
    Dim wb As Workbook
    Dim LastRow As Long
    Dim Criteria_1 As Range, rng As Range

    Set wb = Workbooks("MOSTEST.xlsx")
    Set ws = wb.Sheets("11.2022")
    Set wkTest = wb.Sheets("AddJournals")
    'LastRow = Sheets("TO DO Prijslijsten").Range("B2").End(xlDown).Row
    LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row

    Set Criteria_1 = ws.Range("B6")

    'copies the filtered data to the destination
    With ws.Range("A1")
        .AutoFilter field:=2, Criteria1:=Criteria_1
    End With
    Set rng = ws.Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible)
    arr = rng.Value

'    With Blad10.ListBox1
'        Debug.Print "Favorite", .Name, .Left
'        .Clear
'        .List = arr
''        .AddItem = "Four" 'compile error: reference to constant not allowed
'    End With

'    With Sheets("AddJournals").ListBox1 'ok... this works too
'    With wb.Blad10.ListBox1 'Error 438 again
'    With wkTest.ListBox1 'still compile error
    With wb.Sheets("AddJournals").ListBox1 'works
        Debug.Print "FavoriteOther, .Name, .Left"
'        .AddItem = "Five" 'Compile error: not allowed with a constant/error 438 depending on which With I use ^
        .List = arr 'works just fine
    End With
    'no idea why .AddItem is having a fit now, it worked yesterday.. It even shows up when hitting period

End Sub

Hope this helps other people out as much as it confused me.


问:
Setting a directory in R
I set my working directory by going to the folder and clicking on " Set as Working Directory" and then I add the code line to my document and afterwards i run everything however it tells me that the current working directory is another document. Do you know how can I change it for all chunks ?

enter image description here

enter image description here

I tried to add the code to my markdown so that it is applied when i run everything

Title: Setting a directory in R


问:
i want to make a fonction that make this sequence with a power (down here) without using the ** operator , and this is were i got so far
The sequence requested

```<code>def Pw_e(e):
    for i in range(e+1):
        for x in range(i+1):
            num=1
            if x >0:
                xi=(num*=num*e) #pwr
                ix= x*e #mult
                ixi=+ ix*xi
                return ixi
print(Pw_e(5))
</code>```

i tied to use the *= operator in the fist time to make the power fonction but a error has occurred after i founded an alternative to it and it was to use the *= operand separately it worked but now that trying to affect it to a variable it don’t work should i define a function pwr separately from my code or it can be in the same loop ?!

Body:
The sequence requested

def Pw_e(e):
    for i in range(e+1):
        for x in range(i+1):
            num=1
            if x >0:
                xi=(num*=num*e) #pwr
                ix= x*e #mult
                ixi=+ ix*xi
                return ixi
print(Pw_e(5))

i tied to use the *= operator in the fist time to make the power fonction but a error has occurred after i founded an alternative to it and it was to use the *= operand separately it worked but now that trying to affect it to a variable it don’t work should i define a function pwr separately from my code or it can be in the same loop ?!


问:
ASP.NET Core + React API Call with MSAL Azure AD Auth
I am attempting to make an API call from js to a .net controller using Azure AD authentication via MSAL.

My flow starts with logging into my React application using MSAL. Once logged in, I grab a token.

```<code>    const { instance, accounts, inProgress } = useMsal();
    const [accessToken, setAccessToken] = useState<string | null>(null);

    const name = accounts[0] && accounts[0].name;

    function RequestAccessToken() {
        const request = {
            ...loginRequest,
            account: accounts[0]
        };

        // Silently acquires an access token which is then attached to a request for Microsoft Graph data
        instance.acquireTokenSilent(request).then((response) => {
            setAccessToken(response.accessToken);
        }).catch((e) => {
            instance.acquireTokenPopup(request).then((response) => {
                setAccessToken(response.accessToken);
            });
        });
    }
</code>```

i then attempt to embed this token into my js fetch call

```<code>    const headers = new Headers();
    const bearer = `Bearer ${accessToken}`;

    headers.append("Authorization", bearer);
    //headers.append("Content-Type", "application/json")

    const options: RequestInit = {
        method: "GET",
        headers: headers
    };

    const response = await fetch('/kpiData', options);
</code>```

Program.cs of the asp.net backend has

```<code>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});
</code>```

my network response

why is my token invalid? configuring Program.cs correctly seems quite difficult.

Update:

appsettings.json

```<code>  "AzureAd": {
    "Instance": "https://login.microsoftonline.com",
    "ClientId": "<Client ID from Azure App Registration>",
    "TenantId": "common",
    "Audience": "Client ID from Azure App Registration>"
  }
</code>```

authConfig.ts

```<code>export const msalConfig: Configuration = {
    auth: {
        clientId: "<Client ID from Azure App Registration>",
        authority: "https://login.microsoftonline.com/<Tenant ID>",
        redirectUri: "https://localhost:44493"
    },
    cache: {
        cacheLocation: "sessionStorage", // This configures where your cache will be stored
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    }
};

// Add scopes here for ID token to be used at Microsoft identity platform endpoints.
export const loginRequest: RedirectRequest = {
    scopes: ["api://<Client ID>/User.Read"]
};
</code>```

Body:
I am attempting to make an API call from js to a .net controller using Azure AD authentication via MSAL.

My flow starts with logging into my React application using MSAL. Once logged in, I grab a token.

    const { instance, accounts, inProgress } = useMsal();
    const [accessToken, setAccessToken] = useState<string | null>(null);

    const name = accounts[0] && accounts[0].name;

    function RequestAccessToken() {
        const request = {
            ...loginRequest,
            account: accounts[0]
        };

        // Silently acquires an access token which is then attached to a request for Microsoft Graph data
        instance.acquireTokenSilent(request).then((response) => {
            setAccessToken(response.accessToken);
        }).catch((e) => {
            instance.acquireTokenPopup(request).then((response) => {
                setAccessToken(response.accessToken);
            });
        });
    }

i then attempt to embed this token into my js fetch call

    const headers = new Headers();
    const bearer = `Bearer ${accessToken}`;

    headers.append("Authorization", bearer);
    //headers.append("Content-Type", "application/json")

    const options: RequestInit = {
        method: "GET",
        headers: headers
    };

    const response = await fetch('/kpiData', options);

Program.cs of the asp.net backend has

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

my network response

why is my token invalid? configuring Program.cs correctly seems quite difficult.

Update:

appsettings.json

  "AzureAd": {
    "Instance": "https://login.microsoftonline.com",
    "ClientId": "<Client ID from Azure App Registration>",
    "TenantId": "common",
    "Audience": "Client ID from Azure App Registration>"
  }

authConfig.ts

export const msalConfig: Configuration = {
    auth: {
        clientId: "<Client ID from Azure App Registration>",
        authority: "https://login.microsoftonline.com/<Tenant ID>",
        redirectUri: "https://localhost:44493"
    },
    cache: {
        cacheLocation: "sessionStorage", // This configures where your cache will be stored
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    }
};

// Add scopes here for ID token to be used at Microsoft identity platform endpoints.
export const loginRequest: RedirectRequest = {
    scopes: ["api://<Client ID>/User.Read"]
};


问:
Why has Whatsapp text command stopped working
I have an electron app where I am using the whatsapp shell command to send messages.
It doesn't send message, rather opens up the contact in whatsapp desktop and types the message. But this week, It has stopped typing the text. I am unable to find any announcement around this change from whatsapp.

The command:

```<code>shell.openExternal(`whatsapp://send?phone=+91${moobile}&text=${message}`)
</code>```

Any idea why it stopped working and how to get it running again?

Body:
I have an electron app where I am using the whatsapp shell command to send messages.
It doesn't send message, rather opens up the contact in whatsapp desktop and types the message. But this week, It has stopped typing the text. I am unable to find any announcement around this change from whatsapp.

The command:

shell.openExternal(`whatsapp://send?phone=+91${moobile}&text=${message}`)

Any idea why it stopped working and how to get it running again?


问:
Deployed express server not listening on the specified port
Below is a simple express server. When running it on localhost, I can access the app by navigating to http://localhost:3000. The URL includes the port on which the server is listening.

However when I deploy to a cloud provider like Render, I can't access the app when I include the port on which the server is listening to the URL. For example after deploying the code below, the value of the PORT environment variable is 10000. I would have expected something like https://hostname:10000 to work like with localhost but it doesn't.

However, it works when I use the default port for HTTP like https://hostname:443 or when I don't include the port at all like https://hostname. Why can't I access the server after including the port it is listening on to the URL?

const express = require("express");

const app = express();
const port = process.env.PORT || 3000;

app.get("/", (req, res) => {
  res.json({ port });
});

app.listen( port, () => {
  console.log(`server listening on port ${port}`);
});

```


问:
npm script fails when using **/* in path
Running shasum --algorithm 256 ./{bin,lib}/**/* > SHA256SUM in terminal works as expected but running npm run checkum results in empty SHA256SUM.

{
  "scripts": {
    "checksum": "shasum --algorithm 256 ./{bin,lib}/**/* > SHA256SUM"
  }
}
```


问:
Bulk data insert into databricks
Currently, I am working on databricks that I have access to through a token. I can read data quite fast by pandas.read_sql_query(). However, it was prolonged when inserting data into tables and I used pandas.to_sql(). I wonder if there is a way to use bulk-insert like bcpandas and if anyone can provide a sample code. I have the following info regarding connecting to the databricks and database.

```<code>databricks_server_hostname = 'dsh'
databricks_http_path = 'dhp'
databricks_token = 'dt'
database_or_schema_name = 'my_db_name'
</code>```

I also created an engine by sqlalchemy as follows:

```<code>from sqlalchemy.engine import create_engine
engine = create_engine(
           f"""databricks+connector://token:{dt}@{dsh}:443/{my_db_name}""",
           conect_args = {"http_path": f"{dhp}"},
         )
</code>```

Thanks,

Title: Bulk data insert into databricks

Body:
Currently, I am working on databricks that I have access to through a token. I can read data quite fast by pandas.read_sql_query(). However, it was prolonged when inserting data into tables and I used pandas.to_sql(). I wonder if there is a way to use bulk-insert like bcpandas and if anyone can provide a sample code. I have the following info regarding connecting to the databricks and database.

databricks_server_hostname = 'dsh'
databricks_http_path = 'dhp'
databricks_token = 'dt'
database_or_schema_name = 'my_db_name'

I also created an engine by sqlalchemy as follows:

from sqlalchemy.engine import create_engine
engine = create_engine(
           f"""databricks+connector://token:{dt}@{dsh}:443/{my_db_name}""",
           conect_args = {"http_path": f"{dhp}"},
         )

Thanks,


问:
Linear Regression with scipy.linregress, sns and statsmodels output different results
I'm trying to find the 95% ci for the linear regression model of a set of data.
Data are provided in the code below.
I'm trying to do so using scipy.linregress, then I moved on as scipy doesn't provide a useful method to calculate the 95% CI so I came across this question where I read that seaborn uses statsmodels under the hood. I tried both method and I was surprised to see different results.
I let here the code per reproducibility.

```<code>import matplotlib.pyplot as plt
import pandas as pd
from statsmodels import api as sm
import seaborn as sns
from scipy import stats

df = pd.DataFrame(
    [
        [371.0, 577.0],
        [621.0, 493.0],
        [697.0, 356.0],
        [762.0, 386.0],
        [820.0, 283.0],
        [832.0, 354.0],
        [849.0, 540.0],
        [864.0, 370.0],
        [916.0, 284.0],
        [949.0, 95.0],
        [970.0, 145.0],
        [1051.0, 95.0],
        [1101.0, 45.0],
        [1190.0, 45.0],
    ],
    index=[
        2014,
        2015,
        2016,
        2017,
        2011,
        2018,
        2013,
        2012,
        2019,
        2009,
        2010,
        2008,
        2007,
        2006,
    ],
    columns=['x', 'y'],
)

print(df)

lr = stats.linregress(df['x'], df['y'])
# lr.slope, lr.intercept, lr.rvalue, lr.pvalue, lr.stderr, lr.intercept_stderr
tinv = lambda p, df: abs(stats.t.ppf(p / 2, df))
ts = tinv(0.05, len(df.index) - 2)

print(f'pvalue: {lr.pvalue:6f}.')
print(f'R-squared: {lr.rvalue**2:.6f}.')
print(
    f'slope: {lr.slope:.3f}, 95%CI[{lr.slope - ts * lr.stderr:.3f} - {lr.slope + ts * lr.stderr:.3f}].'
)
print(
    f'intercept: {lr.intercept:.3f}, 95%CI[{lr.intercept - ts * lr.intercept_stderr:.3f} - {lr.intercept + ts * lr.intercept_stderr:.3f}].'
)

plt.scatter(df['x'], df['y'], label='data')
plt.plot(df['x'], df['x'] * lr.slope + lr.intercept, c='blue', label='lr model')
plt.legend()
plt.title('with scipy')
plt.show()

sns.lmplot(x='x', y='y', data=df, fit_reg=True, ci=95, n_boot=1000)
plt.title('with sns')
plt.show()

X = sm.add_constant(df['x'])
ols_model = sm.OLS(df['y'], X)
est = ols_model.fit()
print(est.summary())
predictions = est.get_prediction(X).summary_frame()

plt.scatter(df['x'], df['y'], label='data')
plt.plot(df['x'][predictions.index], predictions['mean'], c='blue', label='lr model')
plt.fill_between(
    df['x'][predictions.index],
    predictions['mean_ci_lower'],
    predictions['mean_ci_upper'],
    color='blue',
    alpha=0.3,
    label='lr model CI 95%',
)
plt.fill_between(
    df['x'][predictions.index],
    predictions['obs_ci_lower'],
    predictions['obs_ci_upper'],
    color='green',
    alpha=0.3,
    label='prediction_interval CI 95%',
)

plt.legend()
plt.title('with statsmodels')
plt.show()

sns.lmplot(x='x', y='y', data=df, fit_reg=True, ci=95, n_boot=1000)
plt.plot(df['x'][predictions.index], predictions['mean'], c='blue', label='lr model')
plt.fill_between(
    df['x'][predictions.index],
    predictions['mean_ci_lower'],
    predictions['mean_ci_upper'],
    color='blue',
    alpha=0.1,
    label='lr model CI 95%',
)

plt.title('sns + statsmodels')
plt.legend()
plt.show()
</code>```

This code generates 4 plots: first one with linregress, second one with sns, third one with statsmodels and the lastone is the sns + statsmodel, which I post also here.

sns output is the greenone, while the blueone is the model obtained with statsmodels.

Why are the plots obtained with sns and statsmodels different?

Body:
I'm trying to find the 95% ci for the linear regression model of a set of data.
Data are provided in the code below.
I'm trying to do so using scipy.linregress, then I moved on as scipy doesn't provide a useful method to calculate the 95% CI so I came across this question where I read that seaborn uses statsmodels under the hood. I tried both method and I was surprised to see different results.
I let here the code per reproducibility.

import matplotlib.pyplot as plt
import pandas as pd
from statsmodels import api as sm
import seaborn as sns
from scipy import stats

df = pd.DataFrame(
    [
        [371.0, 577.0],
        [621.0, 493.0],
        [697.0, 356.0],
        [762.0, 386.0],
        [820.0, 283.0],
        [832.0, 354.0],
        [849.0, 540.0],
        [864.0, 370.0],
        [916.0, 284.0],
        [949.0, 95.0],
        [970.0, 145.0],
        [1051.0, 95.0],
        [1101.0, 45.0],
        [1190.0, 45.0],
    ],
    index=[
        2014,
        2015,
        2016,
        2017,
        2011,
        2018,
        2013,
        2012,
        2019,
        2009,
        2010,
        2008,
        2007,
        2006,
    ],
    columns=['x', 'y'],
)

print(df)

lr = stats.linregress(df['x'], df['y'])
# lr.slope, lr.intercept, lr.rvalue, lr.pvalue, lr.stderr, lr.intercept_stderr
tinv = lambda p, df: abs(stats.t.ppf(p / 2, df))
ts = tinv(0.05, len(df.index) - 2)

print(f'pvalue: {lr.pvalue:6f}.')
print(f'R-squared: {lr.rvalue**2:.6f}.')
print(
    f'slope: {lr.slope:.3f}, 95%CI[{lr.slope - ts * lr.stderr:.3f} - {lr.slope + ts * lr.stderr:.3f}].'
)
print(
    f'intercept: {lr.intercept:.3f}, 95%CI[{lr.intercept - ts * lr.intercept_stderr:.3f} - {lr.intercept + ts * lr.intercept_stderr:.3f}].'
)

plt.scatter(df['x'], df['y'], label='data')
plt.plot(df['x'], df['x'] * lr.slope + lr.intercept, c='blue', label='lr model')
plt.legend()
plt.title('with scipy')
plt.show()

sns.lmplot(x='x', y='y', data=df, fit_reg=True, ci=95, n_boot=1000)
plt.title('with sns')
plt.show()

X = sm.add_constant(df['x'])
ols_model = sm.OLS(df['y'], X)
est = ols_model.fit()
print(est.summary())
predictions = est.get_prediction(X).summary_frame()

plt.scatter(df['x'], df['y'], label='data')
plt.plot(df['x'][predictions.index], predictions['mean'], c='blue', label='lr model')
plt.fill_between(
    df['x'][predictions.index],
    predictions['mean_ci_lower'],
    predictions['mean_ci_upper'],
    color='blue',
    alpha=0.3,
    label='lr model CI 95%',
)
plt.fill_between(
    df['x'][predictions.index],
    predictions['obs_ci_lower'],
    predictions['obs_ci_upper'],
    color='green',
    alpha=0.3,
    label='prediction_interval CI 95%',
)

plt.legend()
plt.title('with statsmodels')
plt.show()

sns.lmplot(x='x', y='y', data=df, fit_reg=True, ci=95, n_boot=1000)
plt.plot(df['x'][predictions.index], predictions['mean'], c='blue', label='lr model')
plt.fill_between(
    df['x'][predictions.index],
    predictions['mean_ci_lower'],
    predictions['mean_ci_upper'],
    color='blue',
    alpha=0.1,
    label='lr model CI 95%',
)

plt.title('sns + statsmodels')
plt.legend()
plt.show()

This code generates 4 plots: first one with linregress, second one with sns, third one with statsmodels and the lastone is the sns + statsmodel, which I post also here.

sns output is the greenone, while the blueone is the model obtained with statsmodels.

Why are the plots obtained with sns and statsmodels different?


问:
How to load a relative image URL with webpack 5?
I am using webpack 5 and trying to get it to work with esbuild-loader and ES6 modules.

In the code, I have to load an image's url to pass to some other third-party library. So it needs to be relative to wherever webpack bundles it...

Previously I had an image loading like this...

```<code>import * as DEFAULT_POSTER_URL = require("../assets/default-poster.png");
</code>```

Seemingly working fine, but now when I converted everything from requirejs to ES6 modules, I am trying to load the same URL like this...

```<code>import * as DEFAULT_POSTER_URL from "../assets/default-poster.png";
</code>```

But now I'm getting undefined.

The rules section of my webpack.config.js looks like this...

```<code>  rules: [
    {
      test: /\.(ts|tsx)$/,
      loader: "esbuild-loader",
      options: {
        loader: "tsx",
        target: "es2015"
      },
      exclude: /node_modules/
    },
    {
      test: /\.(s([ac])ss)$/,
      include: [path.resolve(__dirname, "./src/app/assets/sass")],
      use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
    },
    {
      test: /\.(png|svg|jpg|jpeg|gif)$/i,
      type: "asset/resource"
    },
    {
      test: /\.(woff|woff2|eot|ttf|otf)$/i,
      type: "asset/resource"
    }
  ]
},
</code>```

Reading the documentation some, I see there is also a asset/inline to load an asset as a URL, but that didn't seem to work when I tried changing my images to load like that.

Body:
I am using webpack 5 and trying to get it to work with esbuild-loader and ES6 modules.

In the code, I have to load an image's url to pass to some other third-party library. So it needs to be relative to wherever webpack bundles it...

Previously I had an image loading like this...

import * as DEFAULT_POSTER_URL = require("../assets/default-poster.png");

Seemingly working fine, but now when I converted everything from requirejs to ES6 modules, I am trying to load the same URL like this...

import * as DEFAULT_POSTER_URL from "../assets/default-poster.png";

But now I'm getting undefined.

The rules section of my webpack.config.js looks like this...

  rules: [
    {
      test: /\.(ts|tsx)$/,
      loader: "esbuild-loader",
      options: {
        loader: "tsx",
        target: "es2015"
      },
      exclude: /node_modules/
    },
    {
      test: /\.(s([ac])ss)$/,
      include: [path.resolve(__dirname, "./src/app/assets/sass")],
      use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
    },
    {
      test: /\.(png|svg|jpg|jpeg|gif)$/i,
      type: "asset/resource"
    },
    {
      test: /\.(woff|woff2|eot|ttf|otf)$/i,
      type: "asset/resource"
    }
  ]
},

Reading the documentation some, I see there is also a asset/inline to load an asset as a URL, but that didn't seem to work when I tried changing my images to load like that.