问:
How to render multiple component which parent are wrapped into another multiple element in react router v6
I am creating a Project where I have multiple component in /. So I wrapped them into a Route with Fragment. Now from those child component one is parent of another some component.

How can I set them to Route?

Infomation

Browser Router are in it's parent component.

I can see all 4 Dashboard, Hero, List, Footer in Homepage.

I am getting nothing after List

The router will be like /li/:liId/:olId means /li/1/1. I can view only /

Code

```<code><Routes>
     <Route path='/' element={
        <>
          <Dashboard />
          <Hero />
          <List>
             <Route path="/li" element={<Hi />}>
                <Route path="/:liId" element={<Hi />} >
                    <Route path="/:olId" element={<Hi />} />
                    <Route path="/i" element={<Info />} />
                    <Route path='/d' element={<Details />} />
                 </Route>
              </Route>
              <Route path='*' element={<Error />} />
           </List>
           <Footer />
        </>
       }>
      </Route>
 </Routes>
</code>```

Solved with

<Routes>
  <Route
    path='/*'
    element={(
      <>
        <Dashboard />
        <Hero />
        <List>
          <Outlet />
        </List>

      </>
    )}
  >
    <Route path="/li/:liId" element={<Hi />}>
      <Route path="/li/:liId/:olId" element={<Hi />}/>
        <Route path="/li/:liId/i" element={<Info />} />
        <Route path="*" element={<Error />} />
    </Route>
  </Route>
</Routes>
```

答:
The Route components that are rendering nested routes should specify the trailing "/*" wildcard character to allow sub-route path matching.

Route components should also only have either the Routes or another Route component as parent.

You can either wrap the nested routes in a Routes component:

```<code><Routes>
  <Route
    path='/*'
    element={(
      <>
        <Dashboard />
        <Hero />
        <List>
          <Routes>
            <Route path="li" element={<Hi />}>
              <Route path=":liId" element={<Hi />}>
                <Route path=":olId" element={<Hi />} />
                <Route path="i" element={<Info />} />
                <Route path="d" element={<Details />} />
              </Route>
            </Route>
            <Route path='*' element={<Error />} />
          </Routes>
        </List>
        <Footer />
      </>
    )}
  />
</Routes>
</code>```

Or render an Outlet for the nested Route components to be rendered into.

```<code><Routes>
  <Route
    path='/'
    element={(
      <>
        <Dashboard />
        <Hero />
        <List>
          <Outlet /> // <-- nested `Route`s render out here
        </List>
        <Footer />
      </>
    )}
  >
    <Route path="li" element={<Hi />}>
      <Route path=":liId" element={<Hi />}>
        <Route path=":olId" element={<Hi />} />
        <Route path="i" element={<Info />} />
        <Route path="d" element={<Details />} />
      </Route>
    </Route>
    <Route path='*' element={<Error />} />
  </Route>
</Routes>
</code>```

Body:
I am creating a Project where I have multiple component in /. So I wrapped them into a Route with Fragment. Now from those child component one is parent of another some component.

How can I set them to Route?

Infomation

Browser Router are in it's parent component.

I can see all 4 Dashboard, Hero, List, Footer in Homepage.

I am getting nothing after List

The router will be like /li/:liId/:olId means /li/1/1. I can view only /

Code

<Routes>
     <Route path='/' element={
        <>
          <Dashboard />
          <Hero />
          <List>
             <Route path="/li" element={<Hi />}>
                <Route path="/:liId" element={<Hi />} >
                    <Route path="/:olId" element={<Hi />} />
                    <Route path="/i" element={<Info />} />
                    <Route path='/d' element={} />
                 </Route>
              </Route>
              <Route path='*' element={<Error />} />
           </List>

        </>
       }>
      </Route>
 </Routes>

Solved with

<Routes>
  <Route
    path='/*'
    element={(
      <>
        <Dashboard />
        <Hero />
        <List>
          <Outlet />
        </List>

      </>
    )}
  >
    <Route path="/li/:liId" element={<Hi />}>
      <Route path="/li/:liId/:olId" element={<Hi />}/>
        <Route path="/li/:liId/i" element={<Info />} />
        <Route path="*" element={<Error />} />
    </Route>
  </Route>
</Routes>

Body:
The Route components that are rendering nested routes should specify the trailing "/*" wildcard character to allow sub-route path matching.

Route components should also only have either the Routes or another Route component as parent.

You can either wrap the nested routes in a Routes component:

<Routes>
  <Route
    path='/*'
    element={(
      <>
        <Dashboard />
        <Hero />
        <List>
          <Routes>
            <Route path="li" element={<Hi />}>
              <Route path=":liId" element={<Hi />}>
                <Route path=":olId" element={<Hi />} />
                <Route path="i" element={<Info />} />
                <Route path="d" element={<Details />} />
              </Route>
            </Route>
            <Route path='*' element={<Error />} />
          </Routes>
        </List>
        <Footer />
      </>
    )}
  />
</Routes>

Or render an Outlet for the nested Route components to be rendered into.

<Routes>
  <Route
    path='/'
    element={(
      <>
        <Dashboard />
        <Hero />
        <List>
          <Outlet /> // <-- nested `Route`s render out here
        </List>
        <Footer />
      </>
    )}
  >
    <Route path="li" element={<Hi />}>
      <Route path=":liId" element={<Hi />}>
        <Route path=":olId" element={<Hi />} />
        <Route path="i" element={<Info />} />
        <Route path="d" element={<Details />} />
      </Route>
    </Route>
    <Route path='*' element={<Error />} />
  </Route>
</Routes>


来源: stackexchange

问:
Help in creating Zip files from .Net and reading them from Java
I'm trying to create a Zip file from .Net that can be read from Java code.

I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java.

Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see http://community.sharpdevelop.net/forums/t/8272.aspx for info) but with no result.

Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class?

Regards
Massimo

答:
I have used DotNetZip library and it seems to work properly. Typical code:</p>

```<code>using (ZipFile zipFile = new ZipFile())
{
  zipFile.AddDirectory(sourceFolderPath);
  zipFile.Save(archiveFolderName);
}
</code>```

OwnerDisplayName: massimogentilini

ContentLicense: CC BY-SA 2.5

Body:
I have used DotNetZip library and it seems to work properly. Typical code:

using (ZipFile zipFile = new ZipFile())
{
  zipFile.AddDirectory(sourceFolderPath);
  zipFile.Save(archiveFolderName);
}

OwnerDisplayName: Panos


问:
What features are people looking forward to in .Net 4.0 - 4.1
I am very interested in learning what features people are interested in in the forthcoming .net framework(s)?

Whether these be new classes or new controls I am curious to know people views.

答: Ummm... Isn't the StringOr class an April Fools joke?

OwnerDisplayName: Joe


问:
Delete visible filtered Rows, Run-time error 1004:Cannot use that command on overlapping selections
I need to delete visible filtered Rows.

I got this  Run-time error 1004: Cannot use that command on overlapping selections.

My data has header on first row.

In advance , greatfull for your help.

```<code>Sub Macro2()

    Dim rng As Range: Set rng = ActiveSheet.Range("A1:Q6880")
    rng.AutoFilter Field:=8, Criteria1:="0"
    rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete

End Sub
</code>```

答:
In some circumstances, filtering creates a discontinuous range with overlapping areas. Please, try the next way, which eliminates these overlappings:

```<code>Sub MacroDeleteFilteredRows()
    Dim rng As Range: Set rng = ActiveSheet.Range("A1:Q6880")
    rng.AutoFilter field:=8, Criteria1:="0"
    Intersect(ActiveSheet.cells, rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow).Delete
End Sub
</code>```

A error handling for the case of no any visible cells in the filtered range is good to be implemented, even if this situation is not very probable...

ContentLicense: CC BY-SA 4.0

Body:
I need to delete visible filtered Rows.

I got this  Run-time error 1004: Cannot use that command on overlapping selections.

My data has header on first row.

In advance , greatfull for your help.

Sub Macro2()

    Dim rng As Range: Set rng = ActiveSheet.Range("A1:Q6880")
    rng.AutoFilter Field:=8, Criteria1:="0"
    rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete

End Sub

Body:
In some circumstances, filtering creates a discontinuous range with overlapping areas. Please, try the next way, which eliminates these overlappings:

Sub MacroDeleteFilteredRows()
    Dim rng As Range: Set rng = ActiveSheet.Range("A1:Q6880")
    rng.AutoFilter field:=8, Criteria1:="0"
    Intersect(ActiveSheet.cells, rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow).Delete
End Sub

A error handling for the case of no any visible cells in the filtered range is good to be implemented, even if this situation is not very probable...


问:
Return multiple resultset from a function in postgres using cursor
I want to write a function in postgres which will return multiple resultset from different tables. I found that we can achieve that using ref cursors. So i created one function supposed to return 2 results from different tables. When I call the cursors under a transaction , no results are returned. It just says query executed successfully. Postgres version --> 14.X. I am running this query in pgadmin 4.</p>
```<code>CREATE OR REPLACE FUNCTION multipleresultset()
RETURNS SETOF refcursor AS
$BODY$
DECLARE
ref1 refcursor := 'cursor1';
ref2 refcursor := 'cursor2';
BEGIN
open ref1 FOR
SELECT * FROM table1;
RETURN NEXT ref1;

open ref2 FOR
SELECT * FROM table2;
RETURN NEXT ref2;
--RETURN;
END;$BODY$
LANGUAGE 'plpgsql';

begin;
select * from multipleresultset();
FETCH ALL in "cursor1";
FETCH ALL in "cursor2";
commit;
</code>```

答:
This SQL code is fine by itself, but your SQL client is probably sending the whole block in one go as a multi-query string. Then if shows only the result of the last instruction of that sequence, which is the result of commit.

If you tried this in in psql (the primary command-line interface for postgresql), it would show results, since psql parses the SQL buffer to identify queries between ; and sends them as separate statements (use \; to group them).

Body:
I want to write a function in postgres which will return multiple resultset from different tables. I found that we can achieve that using ref cursors. So i created one function supposed to return 2 results from different tables. When I call the cursors under a transaction , no results are returned. It just says query executed successfully. Postgres version --> 14.X. I am running this query in pgadmin 4.

CREATE OR REPLACE FUNCTION multipleresultset()
RETURNS SETOF refcursor AS
$BODY$
DECLARE
ref1 refcursor := 'cursor1';
ref2 refcursor := 'cursor2';
BEGIN
open ref1 FOR
SELECT * FROM table1;
RETURN NEXT ref1;

open ref2 FOR
SELECT * FROM table2;
RETURN NEXT ref2;
--RETURN;
END;$BODY$
LANGUAGE 'plpgsql';

begin;
select * from multipleresultset();
FETCH ALL in "cursor1";
FETCH ALL in "cursor2";
commit;


问:
Github workflow without .ENV
I'm trying to setup a Github Workflow pipeline for my Flutter App but building and flutter analyze commands fail since I do not commit my .ENV file

Is there a way to add the .ENV to my Workflow without committing it to source control ?

Since .env shouldn’t be commited

```<code>name: CI
on:
  pull_request:
    branches:
      - master
      - dev

jobs:
  flutter_test:
    name: Run flutter test and analyze
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          channel: "stable"
      - run: flutter pub get
      - run: flutter analyze
      - run: flutter test

  build_ios:
    name: Build Flutter (iOS)
    needs: [flutter_test]
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          channel: "stable"
      - run: flutter pub get
      - run: flutter clean
      - run: flutter build ios --release --no-codesign

  build_appbundle:
    name: Build Flutter (Android)
    needs: [flutter_test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          channel: "stable"
      - run: flutter pub get
      - run: flutter clean
      - run: flutter build appbundle
</code>```

答:
Did you previously commit .env then add it to .gitignore after?

You can remove .env from git cache:

```<code>git rm --cached -r <path to your .env>
</code>```

Title: Github workflow without .ENV

Body:
I'm trying to setup a Github Workflow pipeline for my Flutter App but building and flutter analyze commands fail since I do not commit my .ENV file

Is there a way to add the .ENV to my Workflow without committing it to source control ?

Since .env shouldn’t be commited

name: CI
on:
  pull_request:
    branches:
      - master
      - dev

jobs:
  flutter_test:
    name: Run flutter test and analyze
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          channel: "stable"
      - run: flutter pub get
      - run: flutter analyze
      - run: flutter test

  build_ios:
    name: Build Flutter (iOS)
    needs: [flutter_test]
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          channel: "stable"
      - run: flutter pub get
      - run: flutter clean
      - run: flutter build ios --release --no-codesign

  build_appbundle:
    name: Build Flutter (Android)
    needs: [flutter_test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          channel: "stable"
      - run: flutter pub get
      - run: flutter clean
      - run: flutter build appbundle

Body:
Did you previously commit .env then add it to .gitignore after?

You can remove .env from git cache:

git rm --cached -r <path to your .env>


问:
Uploaded images organisation (DIR Structure) in django or any without affecting the web app speed or load time?
I'm confused about organising files and media. Let say, I have a Django website, it has over 25 models, all of them contains at least one image field. Every submitted entry in the database, create 5-6 different versions of that image by size and format. Currently, I just have a DIR for each model inside the media root which store all uploaded image related to that specific model. What is the best way to organise them in terms of loading speed. If any model or models, let say have 10,000s of entries means 50,000 to 60,000 of images as well. And when someone visits the website does it affect the speed because it is looking through so many images and putting that specifics on the user requested page? Or it doesn't matter at all?

Best way, I can keep them without putting any affecting the loading speed?:

Storing all images in one dir of that model (MEDIA > MODEL DIR > All Images), because it doesn't matter.

MEDIA > MODEL DIR > SIZES/FORMAT DIR (e.g. 200x200 or png) > All entries' images that are 200x200 in size, can have thousands of images.

Storing every single entry's images in a separate folder (MEDIA > MODEL DIR > ID/ENTRY NAME DIR > All images including different sizes and format, this would make 15-20 images per DIR).

(MEDIA > MODEL DIR > ID/ENTRY NAME DIR > SIZE/FORMAT DIR > All images of that size or format related to that entry, this would make 1 or 2 images per DIR).

or date/month/year wise directories? But I'm not really a fan of this one.

Also, in general what's the best way if the website is not on django?

Thanks!

答:
I have this problem and I use object storage with CDN.
It can be so helpful if you use this solution.</p>


问:
why powermail form don't send emails?
I'm using Typo3 powermail mail forms, after send the form is stored in backend but never send a copy to the recepient or user adress. how can i troubleshoot this issue ?
btw, Test emails from installtool works good.</p>

答:
Did you configure your form that it uses the email address of the visitor who fills in the form as sender address? That's not good practice anymore. Most mail servers check the SPF record and reject mails that don't pass that test.

You can configure the default sender name and address via TypoScript. And check if the SPF Record fits for that sender address.

Title: why powermail form don't send emails?


问:
HTTPS connection with basic auth result into Unauthorized
I am trying to access Basecamp API from my Android/Java source code following way ....

```<code>import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class BCActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DefaultHttpClient httpClient = new DefaultHttpClient();

        //final String url = "https://encrypted.google.com/webhp?hl=en"; //This url works
        final String url = "https://username:password@projectsource.basecamphq.com/people.xml"; //This don't
        HttpGet http = new HttpGet(url);
        http.addHeader("Accept", "application/xml");
        http.addHeader("Content-Type", "application/xml");

        try {

            //  HttpResponse response = httpClient.execute(httpPost);
            HttpResponse response = httpClient.execute(http);

            StatusLine statusLine = response.getStatusLine();
            System.out.println("statusLine : "+ statusLine.toString());

            ResponseHandler <String> res = new BasicResponseHandler();

            String strResponse = httpClient.execute(http, res);
            System.out.println("________**_________________________\n"+strResponse);
            System.out.println("\n________**_________________________\n");

        } catch (Exception e) {
            e.printStackTrace();
        }

        WebView myWebView = (WebView) this.findViewById(R.id.webView);
        myWebView.loadUrl(url);//Here it works and displays XML response

    }
}
</code>```

This URL displays the response in WebView, but shows Unauthorized exception when I try to access through HttpClient as shown above.

Is this is right way to access Basecamp API through Android/Java?
or
Please provide me a right way to do so.

答:
The HttpClient can't take the login creditals from the URI.

You have to give them with specified methods.

If you use HttpClient 4.x have a look on this:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

But notice if you don't want to use the new version on the HttpClient (Android uses version 3.x), you should look here:

http://hc.apache.org/httpclient-3.x/authentication.html

That was the theory, now we use them:

Basically we use HTTP, but if you want to use HTTPS, you have to edit the following assignment new HttpHost("www.google.com", 80, "http") into new HttpHost("www.google.com", 443, "https").

Furthermore you have to edit the host (www.google.com) for your concerns.

Notice: Only the full qualified domain name (FQDN) is needed not the full URI.

HttpClient 3.x:

```<code>package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class Test2aActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

HttpClient 4.x:

Attention: You will need the new HttpClient from Apache and additionally you must rearrange the order, that the jar-file is before the Android library.

```<code>package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                // Generate BASIC scheme object and add it to the local
                // auth cache
                BasicScheme basicAuth = new BasicScheme();
                authCache.put(targetHost, basicAuth);

                // Add AuthCache to the execution context
                BasicHttpContext localcontext = new BasicHttpContext();
                localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to access Basecamp API from my Android/Java source code following way ....

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class BCActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DefaultHttpClient httpClient = new DefaultHttpClient();

        //final String url = "https://encrypted.google.com/webhp?hl=en"; //This url works
        final String url = "https://username:password@projectsource.basecamphq.com/people.xml"; //This don't
        HttpGet http = new HttpGet(url);
        http.addHeader("Accept", "application/xml");
        http.addHeader("Content-Type", "application/xml");

        try {

            //  HttpResponse response = httpClient.execute(httpPost);
            HttpResponse response = httpClient.execute(http);

            StatusLine statusLine = response.getStatusLine();
            System.out.println("statusLine : "+ statusLine.toString());

            ResponseHandler <String> res = new BasicResponseHandler();

            String strResponse = httpClient.execute(http, res);
            System.out.println("________**_________________________\n"+strResponse);
            System.out.println("\n________**_________________________\n");

        } catch (Exception e) {
            e.printStackTrace();
        }

        WebView myWebView = (WebView) this.findViewById(R.id.webView);
        myWebView.loadUrl(url);//Here it works and displays XML response

    }
}

This URL displays the response in WebView, but shows Unauthorized exception when I try to access through HttpClient as shown above.

Is this is right way to access Basecamp API through Android/Java?
or
Please provide me a right way to do so.

Body:
The HttpClient can't take the login creditals from the URI.

You have to give them with specified methods.

If you use HttpClient 4.x have a look on this:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

But notice if you don't want to use the new version on the HttpClient (Android uses version 3.x), you should look here:

http://hc.apache.org/httpclient-3.x/authentication.html

That was the theory, now we use them:

Basically we use HTTP, but if you want to use HTTPS, you have to edit the following assignment new HttpHost("www.google.com", 80, "http") into new HttpHost("www.google.com", 443, "https").

Furthermore you have to edit the host (www.google.com) for your concerns.

Notice: Only the full qualified domain name (FQDN) is needed not the full URI.

HttpClient 3.x:

package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class Test2aActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HttpClient 4.x:

Attention: You will need the new HttpClient from Apache and additionally you must rearrange the order, that the jar-file is before the Android library.

package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                // Generate BASIC scheme object and add it to the local
                // auth cache
                BasicScheme basicAuth = new BasicScheme();
                authCache.put(targetHost, basicAuth);

                // Add AuthCache to the execution context
                BasicHttpContext localcontext = new BasicHttpContext();
                localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
getting pyarrow.lib.ArrowInvalid: CSV parse error: Expected 9 columns, got 1
so I am trying apache arrow for the first time and want to read an entire directory of txt files into a pyarrow datastructure. I am getting

```<code>
pyarrow.lib.ArrowInvalid: CSV parse error: Expected 9 columns, got 1

</code>```

when I run the code below? no clue how to debug this. any help appreciated. ALSO if there's a book that covers python and pyarrow happy to read it.

```<code>
import pyarrow.csv as csv

import pyarrow as pa

l_all_files = ['x08.txt', 'x21.txt', 'x108.txt']

read_options = csv.ReadOptions( column_names= ('Sol' , 'H20', 'H50', 'H100',  'Date', 'Cv', 'Dys', 'Ple' , 'Cl') ,  skip_rows=26)

df_arrow_all = pa.concat_tables(( csv.read_csv(current_filename,read_options=read_options, ) for current_filename in l_all_files))

</code>```

when the skip_rows = 26 is done this is what the line looks like

```<code>
$sss        3431    3232    3249  25523  35.66    57  56le   77.73
</code>```

答:
```<code>delmt = '\t'
df = csv.read_csv(current_filename
                 ,read_options=read_options
                 ,parse_options=csv.ParseOptions(delimiter=delmt)
</code>```

This worked for me!
credit: @Mike67

Body:
so I am trying apache arrow for the first time and want to read an entire directory of txt files into a pyarrow datastructure. I am getting

pyarrow.lib.ArrowInvalid: CSV parse error: Expected 9 columns, got 1

when I run the code below? no clue how to debug this. any help appreciated. ALSO if there's a book that covers python and pyarrow happy to read it.

import pyarrow.csv as csv

import pyarrow as pa

l_all_files = ['x08.txt', 'x21.txt', 'x108.txt']

read_options = csv.ReadOptions( column_names= ('Sol' , 'H20', 'H50', 'H100',  'Date', 'Cv', 'Dys', 'Ple' , 'Cl') ,  skip_rows=26)

df_arrow_all = pa.concat_tables(( csv.read_csv(current_filename,read_options=read_options, ) for current_filename in l_all_files))

when the skip_rows = 26 is done this is what the line looks like

$sss        3431    3232    3249  25523  35.66    57  56le   77.73

Body:
delmt = '\t'
df = csv.read_csv(current_filename
                 ,read_options=read_options
                 ,parse_options=csv.ParseOptions(delimiter=delmt)

This worked for me!
credit: @Mike67


问:
Pull record between 2 columns
I have 2 tables

table1

```<code>ID    VendorID
100   11190
200   99999
</code>```

table2

```<code>ID    VendorID
100   11190
100   11190
200   12523
200   53266
</code>```

My expect result and my goal if ID and VendorID from table1 match with ID and VendorID from table2  then flag  NO

```<code>table1ID    table1Vendor    table2ID    table2Vendor    Code
100         12345           100         12345           No
100         12345           100         12345           No
100         12345           100         45678           No
200         56489           200         11111           Use
200         56489           200         22222           Use
</code>```

My query

```<code>SELECT a.id as table1ID, a.vendorid as table1Vendor, b.id as table2ID, b.Vendorid as table2Vendor
    , case
    when a.vendorid <> b.Vendorid
    then 'Use' else 'No'
    end as Code
FROM table_1 a
JOIN table_2 b  on a.id = b.id

</code>```

But I got

```<code>table1ID    table1Vendor    table2ID    table2Vendor    Code
100         12345           100         12345           No
100         12345           100         12345           No
100         12345           100         45678           Use
200         56489           200         11111           Use
200         56489           200         22222           Use
</code>```

You can see row 3 is incorrect, should code as NO cause 12345(table1vendor) still match with 12345(table2vendor)

Not sure why, need some help. Thank you.

答:
You are only checking the same row for a match, but according to your logic you need to check all rows, therefore you need another sub-query.</p>
```<code>SELECT a.ID AS table1ID, a.VendorID AS table1Vendor, b.ID AS table2ID, b.VendorID as table2Vendor
  , CASE WHEN EXISTS (SELECT 1 FROM table_2 b1 WHERE b1.id = a.ID AND b1.VendorID = a.VendorID) THEN 'No' ELSE 'Use' END AS Code
FROM table_1 a
JOIN table_2 b ON a.ID = b.ID;
</code>```

Title: Pull record between 2 columns

Body:
I have 2 tables

table1

ID    VendorID
100   11190
200   99999

table2

ID    VendorID
100   11190
100   11190
200   12523
200   53266

My expect result and my goal if ID and VendorID from table1 match with ID and VendorID from table2  then flag  NO

table1ID    table1Vendor    table2ID    table2Vendor    Code
100         12345           100         12345           No
100         12345           100         12345           No
100         12345           100         45678           No
200         56489           200         11111           Use
200         56489           200         22222           Use

My query

SELECT a.id as table1ID, a.vendorid as table1Vendor, b.id as table2ID, b.Vendorid as table2Vendor
    , case
    when a.vendorid <> b.Vendorid
    then 'Use' else 'No'
    end as Code
FROM table_1 a
JOIN table_2 b  on a.id = b.id

But I got

table1ID    table1Vendor    table2ID    table2Vendor    Code
100         12345           100         12345           No
100         12345           100         12345           No
100         12345           100         45678           Use
200         56489           200         11111           Use
200         56489           200         22222           Use

You can see row 3 is incorrect, should code as NO cause 12345(table1vendor) still match with 12345(table2vendor)

Not sure why, need some help. Thank you.

Body:
You are only checking the same row for a match, but according to your logic you need to check all rows, therefore you need another sub-query.

SELECT a.ID AS table1ID, a.VendorID AS table1Vendor, b.ID AS table2ID, b.VendorID as table2Vendor
  , CASE WHEN EXISTS (SELECT 1 FROM table_2 b1 WHERE b1.id = a.ID AND b1.VendorID = a.VendorID) THEN 'No' ELSE 'Use' END AS Code
FROM table_1 a
JOIN table_2 b ON a.ID = b.ID;


问:
Let the user pass a user-defined type as sub-class of the parameter class to define a member
The following is some architecture I have designed.
I have a class X that has a variable member Y that is a pointer (or reference, I haven't decided yet) to class A. Class A is an abstract class. The user of X can create his own derived class from A (for example B:A) and pass it to X (probably, in the constructor) which, somehow, will store it in Y.

To make this work, the user should dynamically allocate an object of type B:A and pass it to X. However, can you think of a simpler way, for the user, of doing this without having to call new? Ideally, I would like the user to simply create an object of type B:A and pass it. Then, the constructor of X, somehow, would define Y using it (maybe creating a copy of B:A). The problem is that X doesn't know which derived type is passed and what size it is.

I want to create a single constructor to which the user could pass any type derived from A as parameter, and would be converted into a member variable. It should allow the user to create his own type for taking advantage of polymorphism.

```<code>   class A {...};   // Abstract class (has pure virtual members)

   class B : public A {...};   // Class defined by the user

   class X
   {
   public:
      X(A &param) { /* abc is defined */ }
      A* abc;
   }
</code>```

Some ideas I had:
Could it work a pure virtual copy assignment operator overloading at A? And having a member at B:A that specifies the size of B:A? However I still don't know how to make it work.

How to solve it? Is there maybe a better way? Thanks in advance.

答:
To make this work, the user should dynamically allocate an object of type B:A and pass it to X. However, can you think of a simpler way, for the user, of doing this without having to call new?

Polymorphism is not dependent on new being used. It simply requires a pointer/reference to the polymorphic object. The caller could create its derived object statically, if it wants to.  Just so long as the object outlives the X object that refers to it.

Then, the constructor of X, somehow, would define Y using it

That is not possible.  The Y member would have to be statically typed at compile-time, ie as an A* pointer or A& reference.  Unless X is written as a template class, so that the user can then specify the actual derived type being passed in.

maybe creating a copy of B:A

That is possible, but only if X is templated, otherwise A will have to declare a virtual clone() method that all derived classes override to make copy of themselves.

The problem is that X doesn't know which derived type is passed and what size it is.

Polymorphism doesn't need to know that info.

Body:
The following is some architecture I have designed.
I have a class X that has a variable member Y that is a pointer (or reference, I haven't decided yet) to class A. Class A is an abstract class. The user of X can create his own derived class from A (for example B:A) and pass it to X (probably, in the constructor) which, somehow, will store it in Y.

To make this work, the user should dynamically allocate an object of type B:A and pass it to X. However, can you think of a simpler way, for the user, of doing this without having to call new? Ideally, I would like the user to simply create an object of type B:A and pass it. Then, the constructor of X, somehow, would define Y using it (maybe creating a copy of B:A). The problem is that X doesn't know which derived type is passed and what size it is.

I want to create a single constructor to which the user could pass any type derived from A as parameter, and would be converted into a member variable. It should allow the user to create his own type for taking advantage of polymorphism.

   class A {...};   // Abstract class (has pure virtual members)

   class B : public A {...};   // Class defined by the user

   class X
   {
   public:
      X(A &param) { /* abc is defined */ }
      A* abc;
   }

Some ideas I had:
Could it work a pure virtual copy assignment operator overloading at A? And having a member at B:A that specifies the size of B:A? However I still don't know how to make it work.

How to solve it? Is there maybe a better way? Thanks in advance.


问:
JIRA - move one sub-task from one story to another
In JIRA, how can we move one sub-task from one story to another?</p>

答:
In my case, as of 2022-02-10 on a customer Jira install, that might be heavily configured to not allow things, the "move" option mentioned in another answer was not available.

I had to convert the subtask to a normal task first, then I could chose to convert the normal task to a subtask again, where I could chose the story that it should be a subtask of from all stories.
By chosing the new one then, it was "moved" from one to another with a little extra steps.


问:
GStreamer vs FFmpeg
I try to record a Video with the OpenCV Framework an would like to save that into an Matroska(mkv) Container together with some additional data streams.

First I thought using FFmpeg is the way that.
But while looking into the OpenCV Sourcecode and searching in the web I found GStreamer.

Because the documentation in GStreamer is much better than the FFmpeg documentation I would prefer using this Framework.

In my understanding GStreamer is primarily used for Streaming, but could also rncode and mux video data.

Is there any disadvantage when using GStreamer instead of FFmpeg?

Thanks in advance
Horst

答:
You can use an OpenCv VideoWriter using either ffmpeg or gstreamer backend and compare. For example (you may adapt to your platform plugins and video mode):

```<code># Using ffmpeg backend
cv::VideoWriter ffmpeg_h264_writer ("test-ffmpeg-h264-writer.mkv",
   cv::CAP_FFMPEG,
   cv::VideoWriter::fourcc ('X', '2', '6', '4'),
   fps,
   cv::Size (width, height));

# Using gstreamer backend:
cv::VideoWriter gst_omxh264_writer ("appsrc ! queue ! videoconvert ! video/x-raw,format=I420 ! queue ! omxh264enc ! video/x-h264,format=byte-stream ! matroskamux ! filesink location=test-gstreamer-omxh264-writer.mkv ",
   cv::CAP_GSTREAMER,
   0,
   fps,
   cv::Size (width, height));
</code>```

where width and height are integer values and fps is a float value.

Title: GStreamer vs FFmpeg

Body:
You can use an OpenCv VideoWriter using either ffmpeg or gstreamer backend and compare. For example (you may adapt to your platform plugins and video mode):

# Using ffmpeg backend
cv::VideoWriter ffmpeg_h264_writer ("test-ffmpeg-h264-writer.mkv",
   cv::CAP_FFMPEG,
   cv::VideoWriter::fourcc ('X', '2', '6', '4'),
   fps,
   cv::Size (width, height));

# Using gstreamer backend:
cv::VideoWriter gst_omxh264_writer ("appsrc ! queue ! videoconvert ! video/x-raw,format=I420 ! queue ! omxh264enc ! video/x-h264,format=byte-stream ! matroskamux ! filesink location=test-gstreamer-omxh264-writer.mkv ",
   cv::CAP_GSTREAMER,
   0,
   fps,
   cv::Size (width, height));

where width and height are integer values and fps is a float value.


问:
having trouble importing CSV
I usually use AWS s3 to import csv files and it is really easy. Trying to import this csv file straight from the file explorer and continuing to get an error. Is it different?</p>
```<code>import pd as pandas

month = pd.read_csv("12Month.csv")
print(month)

Error: [Errno 2] No such file or directory: '12Month.csv'
</code>```

答:
You probably will have to state the full path.

```<code>import pandas as pd
month = pd.read_csv(r"C: etc... 12Month.csv"")
</code>```

or use :

```<code> from pathlib import Path
 wdir = Path.cwd()
 filename = path(wdir,"12Month.csv")
 month = pd.read_csv(filename)
</code>```

Title: having trouble importing CSV

Body:
I usually use AWS s3 to import csv files and it is really easy. Trying to import this csv file straight from the file explorer and continuing to get an error. Is it different?

import pd as pandas

month = pd.read_csv("12Month.csv")
print(month)

Error: [Errno 2] No such file or directory: '12Month.csv'

Body:
You probably will have to state the full path.

import pandas as pd
month = pd.read_csv(r"C: etc... 12Month.csv"")

or use :

 from pathlib import Path
 wdir = Path.cwd()
 filename = path(wdir,"12Month.csv")
 month = pd.read_csv(filename)


问:
PHP Deprecated issue when running artisan command
Whenever I run an artisan command I am getting this issue.

I am using Valet and PHP 8.1. I have tried changing versions of PHP but I still get this issue.

When i run:

```<code>jakefeeley@Jakes-MBP marketing % php artisan plugin:install vojtasvoboda.twigextensions
</code>```

Returns:

```<code>PHP Deprecated:  Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231

Deprecated: Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231
PHP Deprecated:  Return type of Illuminate\Container\Container::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1242

Deprecated: Return type of October\Rain\Config\Repository::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 446
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458

Deprecated: Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469

Deprecated: Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469
PHP Fatal error:  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php:1277
Stack trace:
#0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of ...', '/Users/jakefeel...', 1277)
#1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
#2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
#3

In Collection.php line 11:

  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset
  ): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Col
  lection.php:1277
  Stack trace:
  #0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of
  ...', '/Users/jakefeel...', 1277)
  #1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #3 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/Collection.php(11): Composer\Autoload\ClassLoader->loadClass('Illuminate\\Supp...')
  #4 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #5 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #6 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/helpers.php(269): Composer\Autoload\ClassLoader->loadClass('October\\Rain\\Su...')
  #7 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(89): collect(Array)
  #8 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(78): Illuminate\Foundation\PackageManifest->config('aliases')
  #9 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php(26): Illuminate\Foundation\PackageManifest->aliases()
  #10 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(219): Illuminate\Foundation\Bootstrap\RegisterFacades->bootstrap(Object(October\Rain
  \Foundation\Application))
  #11 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(320): Illuminate\Foundation\Application->bootstrapWith(Array)
  #12 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\Foundation\Console\Kernel->bootstrap()
  #13 /Users/jakefeeley/Sites/certhub/marketing/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\Co
  nsoleOutput))
  #14 {main}
</code>```

答:
I got the same error when I tried to run  Laravel 7.3 on php 8.1

For me i had 2 versions of php installed on my computer, php-7.4 and php-8.1.

When i checked the php version on the terminal, using php --version
the terminal showed me i was using php 7.4

So I thought php 7.4 was what laravel was using, But that was not the case. Somehow the web server (nginx) was redirecting to php 8.1

To know for sure which php version is being used, use the built-in phpinfo() method. Below is one way to do it

backup index.php from your Laravel project

Then remove everything from the index.php file

Add the following on index.php file

```<code><?php
   phpinfo();
?>
</code>```

Then try to access your Laravel project.
That will give you php information page that will include the information about the version of php your Laravel project is actually using.

As I was using homebrew on macOS Big Sur, I used these commands to stop php8.1

```<code>brew services stop php@8.1
brew unlink php@8.1
</code>```

Then I started php 7.4

```<code>brew services start php@7.4
brew link php@7.4
</code>```

For more info on switching php versions

Body:
Whenever I run an artisan command I am getting this issue.

I am using Valet and PHP 8.1. I have tried changing versions of PHP but I still get this issue.

When i run:

jakefeeley@Jakes-MBP marketing % php artisan plugin:install vojtasvoboda.twigextensions

Returns:

PHP Deprecated:  Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231

Deprecated: Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231
PHP Deprecated:  Return type of Illuminate\Container\Container::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1242

Deprecated: Return type of October\Rain\Config\Repository::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 446
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458

Deprecated: Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469

Deprecated: Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469
PHP Fatal error:  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php:1277
Stack trace:
#0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of ...', '/Users/jakefeel...', 1277)
#1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
#2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
#3

In Collection.php line 11:

  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset
  ): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Col
  lection.php:1277
  Stack trace:
  #0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of
  ...', '/Users/jakefeel...', 1277)
  #1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #3 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/Collection.php(11): Composer\Autoload\ClassLoader->loadClass('Illuminate\\Supp...')
  #4 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #5 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #6 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/helpers.php(269): Composer\Autoload\ClassLoader->loadClass('October\\Rain\\Su...')
  #7 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(89): collect(Array)
  #8 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(78): Illuminate\Foundation\PackageManifest->config('aliases')
  #9 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php(26): Illuminate\Foundation\PackageManifest->aliases()
  #10 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(219): Illuminate\Foundation\Bootstrap\RegisterFacades->bootstrap(Object(October\Rain
  \Foundation\Application))
  #11 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(320): Illuminate\Foundation\Application->bootstrapWith(Array)
  #12 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\Foundation\Console\Kernel->bootstrap()
  #13 /Users/jakefeeley/Sites/certhub/marketing/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\Co
  nsoleOutput))
  #14 {main}

Body:
I got the same error when I tried to run  Laravel 7.3 on php 8.1

For me i had 2 versions of php installed on my computer, php-7.4 and php-8.1.

When i checked the php version on the terminal, using php --version
the terminal showed me i was using php 7.4

So I thought php 7.4 was what laravel was using, But that was not the case. Somehow the web server (nginx) was redirecting to php 8.1

To know for sure which php version is being used, use the built-in phpinfo() method. Below is one way to do it

backup index.php from your Laravel project

Then remove everything from the index.php file

Add the following on index.php file

<?php
   phpinfo();
?>

Then try to access your Laravel project.
That will give you php information page that will include the information about the version of php your Laravel project is actually using.

As I was using homebrew on macOS Big Sur, I used these commands to stop php8.1

brew services stop php@8.1
brew unlink php@8.1

Then I started php 7.4

brew services start php@7.4
brew link php@7.4

For more info on switching php versions


问:
HTML5 app routing, pushState
I'm trying to do two things:

Use pushState to change the URL

```<code>//Video
$("a").click(function(){
history.pushState(null, "Video", "/video/");
return false;
});
</code>```

and then be able to route that link to show a div if anyone types it into their browser:

```<code>www.mysite.com/video/ ---> show div
</code>```

I've been looking at a few scripts: davis.js, sammy.js, history.js

Do I need any of these scripts? Is there a way in jQuery to do this?

答:
I'm slightly biased since I'm the author of Davis.js, but I think using a routing lib like Davis.js or Sammy.js is the simplest way to get this done.  Both libraries have code to manage what happens when a link is clicked or the back and forward button are used to navigate between states and all the other peculiarities of the history API.

If you want something really simple then you could code something up yourself, although this may take a little longer than just using a lib.

Here is a rough idea of what you could do:

```<code>$("a").click(function (e) {
  e.preventDefault()
  var link = $(this)
  history.pushState({pushedByMe: true}, link.attr('title'), link.attr('href'))
  yourCodeHere()
})

history.onpopstate = function (event) {
 if (!event.state.pushedByMe) return
 yourCodeHere()
}
</code>```

Title: HTML5 app routing, pushState

Body:
I'm trying to do two things:

Use pushState to change the URL

//Video
$("a").click(function(){
history.pushState(null, "Video", "/video/");
return false;
});

and then be able to route that link to show a div if anyone types it into their browser:

www.mysite.com/video/ ---> show div

I've been looking at a few scripts: davis.js, sammy.js, history.js

Do I need any of these scripts? Is there a way in jQuery to do this?

Body:
I'm slightly biased since I'm the author of Davis.js, but I think using a routing lib like Davis.js or Sammy.js is the simplest way to get this done.  Both libraries have code to manage what happens when a link is clicked or the back and forward button are used to navigate between states and all the other peculiarities of the history API.

If you want something really simple then you could code something up yourself, although this may take a little longer than just using a lib.

Here is a rough idea of what you could do:

$("a").click(function (e) {
  e.preventDefault()
  var link = $(this)
  history.pushState({pushedByMe: true}, link.attr('title'), link.attr('href'))
  yourCodeHere()
})

history.onpopstate = function (event) {
 if (!event.state.pushedByMe) return
 yourCodeHere()
}


问:
FileNotFoundError: [Errno 2] No such file or directory: '2022_06_02/10/22_17_06.txt' error while writing scraped data to a txt file
Code trials:

```<code>def save_data(data):

    name = f"{dt.now().strftime('%Y_%M_%D_%H_%M')}.txt"
    with open(name, 'w') as file:
       file.write(data)
</code>```

I have this function that should save scraped data to a txt file but I keep getting:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '2022_06_02/10/22_17_06.txt'
</code>```

Is there a way to fix this?

答:
This error message...

```<code>FileNotFoundError: [Errno 2] No such file or directory: '2022_06_02/10/22_17_06.txt'
</code>```

...implies that your system was unable to locate the file 2022_06_02/10/22_17_06.txt.

This line of code:

```<code>from datetime import datetime as dt

name = f"{dt.now().strftime('%Y_%M_%D_%H_%M')}.txt"
</code>```

does creates the variable name with the value 2022_06_02/10/22_17_06.txt but atleast my localhost which is windows10 based won't allow to create any file by the name 2022_06_02/10/22_17_06.txt as it is a invalid filename.

Snapshot:

Body:
Code trials:

def save_data(data):

    name = f"{dt.now().strftime('%Y_%M_%D_%H_%M')}.txt"
    with open(name, 'w') as file:
       file.write(data)

I have this function that should save scraped data to a txt file but I keep getting:

FileNotFoundError: [Errno 2] No such file or directory: '2022_06_02/10/22_17_06.txt'

Is there a way to fix this?

Body:
This error message...

FileNotFoundError: [Errno 2] No such file or directory: '2022_06_02/10/22_17_06.txt'

...implies that your system was unable to locate the file 2022_06_02/10/22_17_06.txt.

This line of code:

from datetime import datetime as dt

name = f"{dt.now().strftime('%Y_%M_%D_%H_%M')}.txt"

does creates the variable name with the value 2022_06_02/10/22_17_06.txt but atleast my localhost which is windows10 based won't allow to create any file by the name 2022_06_02/10/22_17_06.txt as it is a invalid filename.

Snapshot:


问:
Django 'NoneType' object has no attribute 'file'
I have my code implemented like this and when there is no file how can i raise exception

```<code>**models.py**

class Template(BaseModel):
    file = models.FileField(
        upload_to='',
        validators=[FileExtensionValidator(['xls', 'xlsx'])]
    )
    uploaded_by = models.ForeignKey(
        'Some Model',
        related_name='',
        null=True,
        on_delete=models.SET_NULL,
    )
</code>```

views.py

```<code>@api_view(('GET',))
def i_view(request):
    data = Model.objects.first()
    response = HttpResponse(
        data.file,
        content_type='application/vnd.openxmlformats
    )
    return response
</code>```

答:
You can simply add condition checking if at least one Model exists. In else add anything you want to happen if there is no Model.

```<code>def i_view(request):
    data = Model.objects.first()
    if data:
        response = HttpResponse(
            data.file,
            content_type='application/vnd.openxmlformats'
        )
        return response
    else:
        # here you can do coding if there is no Model object
</code>```

Body:
I have my code implemented like this and when there is no file how can i raise exception

**models.py**

class Template(BaseModel):
    file = models.FileField(
        upload_to='',
        validators=[FileExtensionValidator(['xls', 'xlsx'])]
    )
    uploaded_by = models.ForeignKey(
        'Some Model',
        related_name='',
        null=True,
        on_delete=models.SET_NULL,
    )

views.py

@api_view(('GET',))
def i_view(request):
    data = Model.objects.first()
    response = HttpResponse(
        data.file,
        content_type='application/vnd.openxmlformats
    )
    return response

Body:
You can simply add condition checking if at least one Model exists. In else add anything you want to happen if there is no Model.

def i_view(request):
    data = Model.objects.first()
    if data:
        response = HttpResponse(
            data.file,
            content_type='application/vnd.openxmlformats'
        )
        return response
    else:
        # here you can do coding if there is no Model object


问:
Cypress how to select option containing text
In Cypress, the select('option-text') command will only work if there is an exact match. How can I tell it to select an option that contains the text instead ?

答:
A slightly improved variant of Can Akgun user is as following (bonus adding as cypress command):

 /**
 * Select an option containing part of string in its text body
 * {String} elementSelector
 * {String} optionTextPart
 */
 Cypress.Commands.add('selectOptionContaining', (elementSelector, optionTextPart) => {
    cy.get(elementSelector)
    .find('option')
    .contains(optionTextPart)
    .then($option => {
        cy.get(elementSelector).select($option.text());
    });
});
```

In this way we do not need global variables.

Body:
A slightly improved variant of Can Akgun user is as following (bonus adding as cypress command):

 /**
 * Select an option containing part of string in its text body
 * {String} elementSelector
 * {String} optionTextPart
 */
 Cypress.Commands.add('selectOptionContaining', (elementSelector, optionTextPart) => {
    cy.get(elementSelector)
    .find('option')
    .contains(optionTextPart)
    .then($option => {
        cy.get(elementSelector).select($option.text());
    });
});

In this way we do not need global variables.


问:
Inserting date in the next row
I'm creating a time-and-motion file in GoogleSheet and I would like to insert a date in the next available cell in a specific column. May I know how do I go about that using Google Script editor?

Thanks!

答:
Basically it can be done this way:

```<code>function insert_date() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var cell = sheet.getRange('A1');
  cell.setValue(new Date());
}
</code>```

This script inserts current date into cell 'A1'.

But in's not quite clear what you're trying to gain.

Here is the code to insert current date into a first empty cell in column A:

```<code>function insert_date_in_first_empty_cell() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var col = sheet.getRange('A1:A');
  var index = col.getValues().flat().findIndex(x => x=='') + 1;
  var cell = sheet.getRange('A' + index);
  cell.setValue(new Date());
}
</code>```

If you want to fill the first empty cell after the last non-empty cell you can change two lines this way:

```<code>var col = sheet.getRange('A1:A').getDisplayValues().flat();
var index = col.length - col.slice().reverse().findIndex(x => x!='') + 1;
</code>```

Title: Inserting date in the next row

Body:
Basically it can be done this way:

function insert_date() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var cell = sheet.getRange('A1');
  cell.setValue(new Date());
}

This script inserts current date into cell 'A1'.

But in's not quite clear what you're trying to gain.

Here is the code to insert current date into a first empty cell in column A:

function insert_date_in_first_empty_cell() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var col = sheet.getRange('A1:A');
  var index = col.getValues().flat().findIndex(x => x=='') + 1;
  var cell = sheet.getRange('A' + index);
  cell.setValue(new Date());
}

If you want to fill the first empty cell after the last non-empty cell you can change two lines this way:

var col = sheet.getRange('A1:A').getDisplayValues().flat();
var index = col.length - col.slice().reverse().findIndex(x => x!='') + 1;


问:
Write F# DataTable to CSV file
I am trying to write an F# DataTable to csv (or output in a txt). The table I have is defined as follows:

```<code>let setup_report_tbl ( tbl : DataTable ) =
    ignore( tbl.Columns.Add("business_date", typeof<System.Int32>) )
    ignore( tbl.Columns.Add("ticker", typeof<System.String>) )
    ignore( tbl.Columns.Add("price", typeof<System.String>) )
    ignore( tbl.Columns.Add("rate", typeof<System.Boolean>) )
    ignore( tbl.Columns.Add("range", typeof<System.Double>) )
</code>```

My goal is to write this empty table with headers into a csv or txt. I'm new to F# and not quite sure where to start here, any help is appreciated thanks!

答:
To write a DataTable as CSV, I would do something like this:

open System
open System.IO
open System.Data

let writeCsv (wtr : StreamWriter) (tbl : DataTable) =

    let writeValues (values : seq<_>) =
        String.Join(',', values)
            |> wtr.WriteLine

    tbl.Columns
        |> Seq.cast<DataColumn>
        |> writeValues

    for row in tbl.Rows do
        row.ItemArray |> writeValues
```
<p>Note that I haven't done anything to check for special characters in the values, such commas or quotes.</p>
<p>Example:</p>
<pre class="lang-ml prettyprint-override"><code>let tbl = new DataTable()
setup_report_tbl tbl
tbl.Rows.Add(1, "moo", "baa", true, 2.0) |> ignore
use wtr = new StreamWriter(Console.OpenStandardOutput())
writeCsv wtr tbl
</code>```

Output is:

```<code>business_date,ticker,price,rate,range
1,moo,baa,True,2
</code>```

Update

To avoid compiler error, perhaps try this:

    let writeValues (values : seq<_>) =
        let s = String.Join(',', values)
        wtr.WriteLine(s)
```

Note that s is a string, so there should be no ambiguity in which version of WriteLine is called.

Title: Write F# DataTable to CSV file

Body:
I am trying to write an F# DataTable to csv (or output in a txt). The table I have is defined as follows:

let setup_report_tbl ( tbl : DataTable ) =
    ignore( tbl.Columns.Add("business_date", typeof<System.Int32>) )
    ignore( tbl.Columns.Add("ticker", typeof<System.String>) )
    ignore( tbl.Columns.Add("price", typeof<System.String>) )
    ignore( tbl.Columns.Add("rate", typeof<System.Boolean>) )
    ignore( tbl.Columns.Add("range", typeof<System.Double>) )

My goal is to write this empty table with headers into a csv or txt. I'm new to F# and not quite sure where to start here, any help is appreciated thanks!

Body:
To write a DataTable as CSV, I would do something like this:

open System
open System.IO
open System.Data

let writeCsv (wtr : StreamWriter) (tbl : DataTable) =

    let writeValues (values : seq<_>) =
        String.Join(',', values)
            |> wtr.WriteLine

    tbl.Columns
        |> Seq.cast<DataColumn>
        |> writeValues

    for row in tbl.Rows do
        row.ItemArray |> writeValues

Note that I haven't done anything to check for special characters in the values, such commas or quotes.

Example:

let tbl = new DataTable()
setup_report_tbl tbl
tbl.Rows.Add(1, "moo", "baa", true, 2.0) |> ignore
use wtr = new StreamWriter(Console.OpenStandardOutput())
writeCsv wtr tbl

Output is:

business_date,ticker,price,rate,range
1,moo,baa,True,2

Update

To avoid compiler error, perhaps try this:

    let writeValues (values : seq<_>) =
        let s = String.Join(',', values)
        wtr.WriteLine(s)

Note that s is a string, so there should be no ambiguity in which version of WriteLine is called.


问:
SwiftUI get rid of AnyView for environment variables
I try to recreate the toolbar modifier for my own implementation of a NavigationStackView. It works now using environment variables.

Now I would like to get rid of using AnyView. I thought about using a computed property with type some View but can't get this to work.

Example:

import Foundation
import SwiftUI

private struct ToolbarEnvironmentKey: EnvironmentKey {
    static let defaultValue: AnyView = AnyView(EmptyView())
}

extension EnvironmentValues {
    var toolbar: AnyView {
        get { self[ToolbarEnvironmentKey.self] }
        set { self[ToolbarEnvironmentKey.self] = newValue }
    }
}

struct NavigationStackView<Content: View>: View {
    @ViewBuilder var content: () -> Content
    @Environment(\.toolbar) var toolbar: AnyView

    var body: some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                toolbar
            }
            Spacer()
            content()
            Spacer()
        }
    }
}

extension NavigationStackView {
    func toolbar<Content: View>(_ content: () -> Content) -> some View {
        self
            .environment(\.toolbar, AnyView(content()))
    }
}

struct NavigationStackView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationStackView {
            Text("Test")
        }
        .toolbar {
            Text("Toolbar")
        }
    }
}
```

答:
Actually it is not needed to pass view via Environment (and it is not very appropriate tool for that) - we can hide everything within a private implementation of NavigationStackView and use it directly, like

```<code>struct NavigationStackView<Content: View>: View {
    private var content: () -> Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }

    private struct _NavigationStackView<Content: View, Toolbar: View>: View {
        private var content: () -> Content
        private var toolbar: () -> Toolbar

        init(@ViewBuilder content: @escaping () -> Content, @ViewBuilder toolbar: @escaping () -> Toolbar) {
            self.content = content
            self.toolbar = toolbar
        }

        var body: some View {
            VStack(spacing: 0) {
                HStack(spacing: 0) {
                    toolbar()
                }
                Spacer()
                content()
                Spacer()
            }
        }
    }

    var body: some View {
        _NavigationStackView(content: content, toolbar: {})
    }

    func toolbar<Toolbar: View>(@ViewBuilder _ toolbar: @escaping () -> Toolbar) -> some View {
        _NavigationStackView(content: self.content, toolbar: toolbar)
    }
}
</code>```

Tested with Xcode 13.2 / iOS 15.2

Body:
Actually it is not needed to pass view via Environment (and it is not very appropriate tool for that) - we can hide everything within a private implementation of NavigationStackView and use it directly, like

struct NavigationStackView<Content: View>: View {
    private var content: () -> Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }

    private struct _NavigationStackView<Content: View, Toolbar: View>: View {
        private var content: () -> Content
        private var toolbar: () -> Toolbar

        init(@ViewBuilder content: @escaping () -> Content, @ViewBuilder toolbar: @escaping () -> Toolbar) {
            self.content = content
            self.toolbar = toolbar
        }

        var body: some View {
            VStack(spacing: 0) {
                HStack(spacing: 0) {
                    toolbar()
                }
                Spacer()
                content()
                Spacer()
            }
        }
    }

    var body: some View {
        _NavigationStackView(content: content, toolbar: {})
    }

    func toolbar<Toolbar: View>(@ViewBuilder _ toolbar: @escaping () -> Toolbar) -> some View {
        _NavigationStackView(content: self.content, toolbar: toolbar)
    }
}

Tested with Xcode 13.2 / iOS 15.2


答:
You could simply require the class to implement the copy operation (the Clone function below):

```<code>class A
{
public:
    virtual ~A() = default;

    virtual std::unique_ptr<A> Clone() const = 0;
};

class B : public A
{
public:
    std::unique_ptr<A> Clone() const override
    {
        return std::make_unique<B>(*this);
    }
};

class X
{
public:
   X(A const& param)
      : abc(param.Clone())
   {
   }

   // allow transferring an object stored in a unique_ptr to the object
   template<class T> requires (std::is_base_of_v<A, T>)
   X(std::unique_ptr<T>&& param)
       : abc(std::move(param))
   {}
private:
   std::unique_ptr<A> abc;
};
</code>```

Note that if you restrict the user to transferring the ownership to of the subclass of A to X, you don't need to Clone functionality at all. You you could remove X::X(A const&) and Clone in this case. The user would still be able to create your object like this:

```<code>X x = std::make_unique<B>();
X x(std::make_unique<B>()); // alternative syntax for the above
</code>```

Title: Let the user pass a user-defined type as sub-class of the parameter class to define a member

Body:
The following is some architecture I have designed.
I have a class X that has a variable member Y that is a pointer (or reference, I haven't decided yet) to class A. Class A is an abstract class. The user of X can create his own derived class from A (for example B:A) and pass it to X (probably, in the constructor) which, somehow, will store it in Y.

To make this work, the user should dynamically allocate an object of type B:A and pass it to X. However, can you think of a simpler way, for the user, of doing this without having to call new? Ideally, I would like the user to simply create an object of type B:A and pass it. Then, the constructor of X, somehow, would define Y using it (maybe creating a copy of B:A). The problem is that X doesn't know which derived type is passed and what size it is.

I want to create a single constructor to which the user could pass any type derived from A as parameter, and would be converted into a member variable. It should allow the user to create his own type for taking advantage of polymorphism.

   class A {...};   // Abstract class (has pure virtual members)

   class B : public A {...};   // Class defined by the user

   class X
   {
   public:
      X(A &param) { /* abc is defined */ }
      A* abc;
   }

Some ideas I had:
Could it work a pure virtual copy assignment operator overloading at A? And having a member at B:A that specifies the size of B:A? However I still don't know how to make it work.

How to solve it? Is there maybe a better way? Thanks in advance.

Body:
You could simply require the class to implement the copy operation (the Clone function below):

class A
{
public:
    virtual ~A() = default;

    virtual std::unique_ptr<A> Clone() const = 0;
};

class B : public A
{
public:
    std::unique_ptr<A> Clone() const override
    {
        return std::make_unique<B>(*this);
    }
};

class X
{
public:
   X(A const& param)
      : abc(param.Clone())
   {
   }

   // allow transferring an object stored in a unique_ptr to the object
   template<class T> requires (std::is_base_of_v<A, T>)
   X(std::unique_ptr<T>&& param)
       : abc(std::move(param))
   {}
private:
   std::unique_ptr<A> abc;
};

Note that if you restrict the user to transferring the ownership to of the subclass of A to X, you don't need to Clone functionality at all. You you could remove X::X(A const&) and Clone in this case. The user would still be able to create your object like this:

X x = std::make_unique<B>();
X x(std::make_unique<B>()); // alternative syntax for the above


问:
Using multiple DBContext with different schemas
I'm testing the possibility to use multiple DbContext with different schema.
I've created a test table in 2 different schemas.
Then I've created a DBContext which accepts schema name in the constructor.

I've tried the following test code.
In this way I get the data from the first schema:

```<code>//FIRST SCHEMA
using (testDbContext db1 = new testDbContext("dbo"))
{
       var firstSchemaResult = (from t0 in db1.xxxtest1
                            select t0).ToList();

}
</code>```

Instead in this way I get the data from the second schema:

```<code>//SECOND SCHEMA
using (testDbContext db2 = new testDbContext("test"))
{

      var secondSchemaResult = (from t0 in db2.xxxtest1
                            select t0).ToList();
}
</code>```

The strange thing is that if I try to access both schemas, one after another, I get the data just from the first one.
For example:

```<code>//FIRST SCHEMA
using (testDbContext db1 = new testDbContext("dbo"))
{
       var firstSchemaResult = (from t0 in db1.xxxtest1
                            select t0).ToList();

}

//SECOND SCHEMA
using (testDbContext db2 = new testDbContext("test"))
{

      var secondSchemaResult = (from t0 in db2.xxxtest1
                            select t0).ToList();
}
</code>```

In this way firstSchemaResult and secondSchemaResult get the data both from "dbo" schema.

Any idea why this happens?

答:
The reason why this happens is explained in the official documentation for the OnModelCreating method:

Typically, this method is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuilder, but note that this can seriously degrade performance. More control over caching is provided through use of the DbModelBuilder and DbContextFactory classes directly.

EDITED

I was able to achieve the desired behavior by implementing a custom IModelCacheKeyFactory as described here, i.e.:

```<code>public class SchemaBasedModelCacheKeyFactory : IModelCacheKeyFactory
{
    public object Create(DbContext context)
        => context is SqlContext
            ? (context.GetType(), ((SqlContext)context).DefaultSchema)
            : (object)context.GetType();
}
</code>```

where "DefaultSchema" is a property in the DbContext implementation (in my sample, the context of a SQL Server).

Body:
I'm testing the possibility to use multiple DbContext with different schema.
I've created a test table in 2 different schemas.
Then I've created a DBContext which accepts schema name in the constructor.

I've tried the following test code.
In this way I get the data from the first schema:

//FIRST SCHEMA
using (testDbContext db1 = new testDbContext("dbo"))
{
       var firstSchemaResult = (from t0 in db1.xxxtest1
                            select t0).ToList();

}

Instead in this way I get the data from the second schema:

//SECOND SCHEMA
using (testDbContext db2 = new testDbContext("test"))
{

      var secondSchemaResult = (from t0 in db2.xxxtest1
                            select t0).ToList();
}

The strange thing is that if I try to access both schemas, one after another, I get the data just from the first one.
For example:

//FIRST SCHEMA
using (testDbContext db1 = new testDbContext("dbo"))
{
       var firstSchemaResult = (from t0 in db1.xxxtest1
                            select t0).ToList();

}

//SECOND SCHEMA
using (testDbContext db2 = new testDbContext("test"))
{

      var secondSchemaResult = (from t0 in db2.xxxtest1
                            select t0).ToList();
}

In this way firstSchemaResult and secondSchemaResult get the data both from "dbo" schema.

Any idea why this happens?

Body:
The reason why this happens is explained in the official documentation for the OnModelCreating method:

Typically, this method is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuilder, but note that this can seriously degrade performance. More control over caching is provided through use of the DbModelBuilder and DbContextFactory classes directly.

EDITED

I was able to achieve the desired behavior by implementing a custom IModelCacheKeyFactory as described here, i.e.:

public class SchemaBasedModelCacheKeyFactory : IModelCacheKeyFactory
{
    public object Create(DbContext context)
        => context is SqlContext
            ? (context.GetType(), ((SqlContext)context).DefaultSchema)
            : (object)context.GetType();
}

where "DefaultSchema" is a property in the DbContext implementation (in my sample, the context of a SQL Server).


问:
Error in Spring Boot - Error Creating Bean - No Property Found
In my Spring Boot Repository I have the following findAll's that work, except for the last findALL that uses the AND feature to select by two columns. The field names are valid as they work in the prior two lines, but when put together using the AND I get the following error:

Error creating bean with name 'siteReportCardDetailScoresController':.......

findAllBysitemasterIdANDsitereportcardmasterId(java.lang.Long,java.lang.Long)! No property ANDsitereportcardmasterId found for type Long

Any idea why? A solution to this mystery would be much appreciated.

```<code>    @Repository
    public interface SiteReportCardDetailScoresRepository extends JpaRepository<SiteReportCardDetailScores, Long>{

        public List<SiteReportCardDetailScores> findAll();

        public List<SiteReportCardDetailScores> findAllBysitemasterId(Long sitemasterid);

        public List<SiteReportCardDetailScores> findAllBysitereportcardmasterId(Long reportcardmasterid);

public List<SiteReportCardDetailScores> findAllBySitemasterIdAndSitereportcardmasterId(Long sitemasterid,
            Long reportcardmasterid);

    }

//Controller
@GetMapping("/sitereportcarddetailscoresbysiteandreportcard/{sitemasterid, reportcardmasterid}")
    public List<SiteReportCardDetailScores> getAllBySitemasterIdAndSitereportcardmasterId(@PathVariable Long sitemasterid, @PathVariable Long reportcardmasterid){
        return sitereportcarddetailscoresRepository.findAllBySitemasterIdAndSitereportcardmasterId(sitemasterid, reportcardmasterid);
    }
</code>```

答:
Case matters!... Correct Syntax for the repository and controller are as follows:
Repository

```<code>public List<SiteReportCardDetailScores> findAllBySitemasterIdAndSitereportcardmasterId(Long sitemasterid,
            Long reportcardmasterid);
</code>```

Controller

```<code>@GetMapping("/sitereportcarddetailscoresbysiteandreportcard/{sitemasterid}/{reportcardmasterid}")
    public List<SiteReportCardDetailScores> getAllBySitemasterIdAndSitereportcardmasterId(@PathVariable Long sitemasterid, @PathVariable Long reportcardmasterid){
        return sitereportcarddetailscoresRepository.findAllBySitemasterIdAndSitereportcardmasterId(sitemasterid, reportcardmasterid);
    }
</code>```

@M. Deinum

Body:
In my Spring Boot Repository I have the following findAll's that work, except for the last findALL that uses the AND feature to select by two columns. The field names are valid as they work in the prior two lines, but when put together using the AND I get the following error:

Error creating bean with name 'siteReportCardDetailScoresController':.......

findAllBysitemasterIdANDsitereportcardmasterId(java.lang.Long,java.lang.Long)! No property ANDsitereportcardmasterId found for type Long

Any idea why? A solution to this mystery would be much appreciated.

    @Repository
    public interface SiteReportCardDetailScoresRepository extends JpaRepository<SiteReportCardDetailScores, Long>{

        public List<SiteReportCardDetailScores> findAll();

        public List<SiteReportCardDetailScores> findAllBysitemasterId(Long sitemasterid);

        public List<SiteReportCardDetailScores> findAllBysitereportcardmasterId(Long reportcardmasterid);

public List<SiteReportCardDetailScores> findAllBySitemasterIdAndSitereportcardmasterId(Long sitemasterid,
            Long reportcardmasterid);

    }

//Controller
@GetMapping("/sitereportcarddetailscoresbysiteandreportcard/{sitemasterid, reportcardmasterid}")
    public List<SiteReportCardDetailScores> getAllBySitemasterIdAndSitereportcardmasterId(@PathVariable Long sitemasterid, @PathVariable Long reportcardmasterid){
        return sitereportcarddetailscoresRepository.findAllBySitemasterIdAndSitereportcardmasterId(sitemasterid, reportcardmasterid);
    }

Body:
Case matters!... Correct Syntax for the repository and controller are as follows:
Repository

public List<SiteReportCardDetailScores> findAllBySitemasterIdAndSitereportcardmasterId(Long sitemasterid,
            Long reportcardmasterid);

Controller

@GetMapping("/sitereportcarddetailscoresbysiteandreportcard/{sitemasterid}/{reportcardmasterid}")
    public List<SiteReportCardDetailScores> getAllBySitemasterIdAndSitereportcardmasterId(@PathVariable Long sitemasterid, @PathVariable Long reportcardmasterid){
        return sitereportcarddetailscoresRepository.findAllBySitemasterIdAndSitereportcardmasterId(sitemasterid, reportcardmasterid);
    }

@M. Deinum