问:
How to save Tempfile to External storage using ACTION_OPEN_DOCUMENT_TREE?
unable to save the zip file to external storage after picking a folder using ACTION_OPEN_DOCUMENT_TREE.

I'm creating a project which creates and manipulate files and document, in that task I want to save that stuff in external storage but I can't do that with android developer documentation, so please explain additionally.

I want to save this file

```<code>/data/user/0/com.mobilix.docscanner/cache/abc.zip
</code>```

to

```<code>content://com.android.externalstorage.documents/tree/primary%3ADocument
</code>```

what should I do?

here is my code,

- code for picking a directory to save a file into.

```<code>saveBinding.btnInternalStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

                startActivityForResult(intent, PICKER_RESULT);
            }
        });
</code>```

- Code to be executed after selecting a directory,

```<code>@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == PICKER_RESULT) {

                if (data != null) {
                    Uri uri = data.getData();
                    String path = uri.getPath();
                    Log.d(TAG, "onActivityResult: uri -> " + uri);
                    Log.d(TAG, "onActivityResult: path -> " + path);

                    getContentResolver().takePersistableUriPermission(
                            uri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION
                    );

                    new BgExecuter().execute(new Runnable() {
                        @Override
                        public void run() {
                            FileManager.saveFile(PDFTools.this,selectedFile, Uri); //selectedFile is that file that is saved by default in the Temp directory
                        }
                    });
                }
            }else {
                Toast.makeText(PDFTools.this, "dome thing happen great", Toast.LENGTH_SHORT).show();
            }
        }
    }
</code>```

method saveFile

```<code>public static void saveFile(Activity context, File selectedFile, Uri uri) {
        context.getContentResolver().getPersistedUriPermissions();

        try {
            InputStream inputStream = context.getContentResolver().openInputStream(Uri.fromFile(selectedFile));
            OutputStream outputStream = context.getContentResolver().openOutputStream(uri);

            // get the content in bytes
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            byte[] byteArray = new byte[1024];
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            try {
                byte bytes = (byte) bufferedInputStream.read(byteArray);
                if (bytes >= 0) {
                    bufferedOutputStream.write(byteArray, 0, bytes);
                    bufferedOutputStream.flush();
                }
                inputStream.close();
                outputStream.close();
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
</code>```

答:
So Asking for a file instead of directory to be nicer to the user and lessen overwriting issues.

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);

// Create a file with the requested MIME type.
intent.setType(mimeType);
// Suggest a filename
intent.putExtra(Intent.EXTRA_TITLE, "abc.zip");
// You can suggest a starting directory here see note about this later
//intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
// OK, this is deprecated and user probably has set their own request code
startActivityForResult(intent, 601);

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);

        if (requestCode == 601 && resultCode == RESULT_OK) {
            // The document selected by the user won't be returned in the intent.
            // Instead, a URI to that document will be contained in the return intent
            // provided to this method as a parameter.
            // Pull that URI using resultData.getData().
            Uri uri;
            if (resultData != null) {
                uri = resultData.getData();
                new BgExecuter().execute(new Runnable() {
                        @Override
                        public void run() {
 // Now that the Uri returned is for a file not a directory, your exist "saveFile" method should work
                            copyFileOut(PDFTools.this, selectedFile, Uri);
//selectedFile is that file that is saved by default in the Temp directory
                        }
                    });
            }
        }
    }

private Boolean copyFileOut(Context context,File copyFile, Uri uri){

        BufferedInputStream bis;
        BufferedOutputStream bos = null;

        // Now read the file
        try{
            InputStream input = new FileInputStream(copyFile);
            int originalSize = input.available();

            bis = new BufferedInputStream(input);
            bos = new BufferedOutputStream(context.getContentResolver().openOutputStream(uri));
            byte[] buf = new byte[originalSize];
            //noinspection ResultOfMethodCallIgnored
            bis.read(buf);
            do {
                bos.write(buf);
            } while (bis.read(buf) != -1);
            bis.close();

        } catch (Exception e) {
            if (BuildConfig.LOG) {
                Log.e(Constants.TAG, "copyFileOut:" + e);
            }
            // Notify User of fail
            return false;
        } finally {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
            } catch (Exception ignored) {
            }
        }
        return true;
    }

```
<p>Note for initial start directory see How I set the ACTION_OPEN_DOCUMENT_TREE start path the first time a user uses my app?</p>
<p>Also note that in your "saveFile" method</p>
```InputStream inputStream = context.getContentResolver().openInputStream(Uri.fromFile(selectedFile));
```
<p>could be replaced with</p>
```InputStream inputStream = new FileInputStream(selectedFile);
```

As you say that this file is in your Apps private Cache directory, so won't have any permissions problems.

Body:
unable to save the zip file to external storage after picking a folder using ACTION_OPEN_DOCUMENT_TREE.

I'm creating a project which creates and manipulate files and document, in that task I want to save that stuff in external storage but I can't do that with android developer documentation, so please explain additionally.

I want to save this file

/data/user/0/com.mobilix.docscanner/cache/abc.zip

to

content://com.android.externalstorage.documents/tree/primary%3ADocument

what should I do?

here is my code,

- code for picking a directory to save a file into.

saveBinding.btnInternalStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

                startActivityForResult(intent, PICKER_RESULT);
            }
        });

- Code to be executed after selecting a directory,

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == PICKER_RESULT) {

                if (data != null) {
                    Uri uri = data.getData();
                    String path = uri.getPath();
                    Log.d(TAG, "onActivityResult: uri -> " + uri);
                    Log.d(TAG, "onActivityResult: path -> " + path);

                    getContentResolver().takePersistableUriPermission(
                            uri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION
                    );

                    new BgExecuter().execute(new Runnable() {
                        @Override
                        public void run() {
                            FileManager.saveFile(PDFTools.this,selectedFile, Uri); //selectedFile is that file that is saved by default in the Temp directory
                        }
                    });
                }
            }else {
                Toast.makeText(PDFTools.this, "dome thing happen great", Toast.LENGTH_SHORT).show();
            }
        }
    }

method saveFile

public static void saveFile(Activity context, File selectedFile, Uri uri) {
        context.getContentResolver().getPersistedUriPermissions();

        try {
            InputStream inputStream = context.getContentResolver().openInputStream(Uri.fromFile(selectedFile));
            OutputStream outputStream = context.getContentResolver().openOutputStream(uri);

            // get the content in bytes
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            byte[] byteArray = new byte[1024];
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            try {
                byte bytes = (byte) bufferedInputStream.read(byteArray);
                if (bytes >= 0) {
                    bufferedOutputStream.write(byteArray, 0, bytes);
                    bufferedOutputStream.flush();
                }
                inputStream.close();
                outputStream.close();
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

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

Body:
So Asking for a file instead of directory to be nicer to the user and lessen overwriting issues.

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);

// Create a file with the requested MIME type.
intent.setType(mimeType);
// Suggest a filename
intent.putExtra(Intent.EXTRA_TITLE, "abc.zip");
// You can suggest a starting directory here see note about this later
//intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
// OK, this is deprecated and user probably has set their own request code
startActivityForResult(intent, 601);

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);

        if (requestCode == 601 && resultCode == RESULT_OK) {
            // The document selected by the user won't be returned in the intent.
            // Instead, a URI to that document will be contained in the return intent
            // provided to this method as a parameter.
            // Pull that URI using resultData.getData().
            Uri uri;
            if (resultData != null) {
                uri = resultData.getData();
                new BgExecuter().execute(new Runnable() {
                        @Override
                        public void run() {
 // Now that the Uri returned is for a file not a directory, your exist "saveFile" method should work
                            copyFileOut(PDFTools.this, selectedFile, Uri);
//selectedFile is that file that is saved by default in the Temp directory
                        }
                    });
            }
        }
    }

private Boolean copyFileOut(Context context,File copyFile, Uri uri){

        BufferedInputStream bis;
        BufferedOutputStream bos = null;

        // Now read the file
        try{
            InputStream input = new FileInputStream(copyFile);
            int originalSize = input.available();

            bis = new BufferedInputStream(input);
            bos = new BufferedOutputStream(context.getContentResolver().openOutputStream(uri));
            byte[] buf = new byte[originalSize];
            //noinspection ResultOfMethodCallIgnored
            bis.read(buf);
            do {
                bos.write(buf);
            } while (bis.read(buf) != -1);
            bis.close();

        } catch (Exception e) {
            if (BuildConfig.LOG) {
                Log.e(Constants.TAG, "copyFileOut:" + e);
            }
            // Notify User of fail
            return false;
        } finally {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
            } catch (Exception ignored) {
            }
        }
        return true;
    }

Note for initial start directory see How I set the ACTION_OPEN_DOCUMENT_TREE start path the first time a user uses my app?

Also note that in your "saveFile" method

InputStream inputStream = context.getContentResolver().openInputStream(Uri.fromFile(selectedFile));

could be replaced with

InputStream inputStream = new FileInputStream(selectedFile);

As you say that this file is in your Apps private Cache directory, so won't have any permissions problems.


来源: stackexchange

问:
Error in Decimal variable to text datatype comparison
While comparing  variable with data from ADODB.Recordset  gives results as tabulated below:

AssYear string variable = “2022-2023”

rs1!FromAY     text column in mssaccess = “2020”

typename(rs1!FromAY)                    -  Field

```<code> Double(variable in vb6) and text(datatype in mdb)
 val(Mid(AssYear, 1, 4)) >= rs1!FromAY                   TRUE

 Decimal(variable in vb6) and text(datatype in mdb)
 cdec(Mid(AssYear, 1, 4)) >= rs1!FromAY                  FALSE
</code>```

While comparing Decimal variable and text(datatype in mdb) via ADODB.Recordset  it returns false(incorrect result) but for Double variable and text(datatype in mdb) comparison it returns true.

I can't use Double due to roundoff error.
How to compare Decimal variable to text in ADODB.Recordset ?

The below methods works. what is the reason for the above error?

```<code>cdec("2022") >= cdec(rs1!FromAY)                        TRUE
cdec("2022") >= cstr(rs1!FromAY)                        TRUE
</code>```

答:
This works:

```<code>CDec(Mid("2022-2023", 1, 4)) >= "2020"
</code>```

so try with:

```<code>CDec(Mid(AssYear, 1, 4)) >= rs1!FromAY.Value
</code>```

or:

```<code>CDec(Mid(AssYear, 1, 4)) >= Val(rs1!FromAY.Value)
</code>```

But no reason to use CDec here. So, as you wish to compare integer numbers, why not:

```<code>Val(Mid(AssYear, 1, 4)) >= Val(rs1!FromAY.Value)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
While comparing  variable with data from ADODB.Recordset  gives results as tabulated below:

AssYear string variable = “2022-2023”

rs1!FromAY     text column in mssaccess = “2020”

typename(rs1!FromAY)                    -  Field

 Double(variable in vb6) and text(datatype in mdb)
 val(Mid(AssYear, 1, 4)) >= rs1!FromAY                   TRUE

 Decimal(variable in vb6) and text(datatype in mdb)
 cdec(Mid(AssYear, 1, 4)) >= rs1!FromAY                  FALSE

While comparing Decimal variable and text(datatype in mdb) via ADODB.Recordset  it returns false(incorrect result) but for Double variable and text(datatype in mdb) comparison it returns true.

I can't use Double due to roundoff error.
How to compare Decimal variable to text in ADODB.Recordset ?

The below methods works. what is the reason for the above error?

cdec("2022") >= cdec(rs1!FromAY)                        TRUE
cdec("2022") >= cstr(rs1!FromAY)                        TRUE

Body:
This works:

CDec(Mid("2022-2023", 1, 4)) >= "2020"

so try with:

CDec(Mid(AssYear, 1, 4)) >= rs1!FromAY.Value

or:

CDec(Mid(AssYear, 1, 4)) >= Val(rs1!FromAY.Value)

But no reason to use CDec here. So, as you wish to compare integer numbers, why not:

Val(Mid(AssYear, 1, 4)) >= Val(rs1!FromAY.Value)


问:
SSR - Status code 301 is missing when the page comes from the cache ( Always returns 200 )
We currently have a problem with SSR optimized engine. The scenario is that a product has been removed or renamed on the catalog, and the user tends to access that old none existing URL directly. Then we have implemented a redirected behavior sending a status code of 301 so that the customer gets redirected to a relevant page where its URL is retrieved from BE. (Through a generic HTTP interceptor catchError)

```<code>catchError((error: any) => {
 if (error instanceof HttpErrorResponse) {
  ...
  this.response.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
  this.response.set('location',this.service.urlBuilder(redirectUrl));
  return this.setMovedPermanentlyStatus();
  }
}
</code>```

However, we also have those pages cached, so the next time that the page comes from the cache, it returns 200 instead of 301, which we tried to implement in the first place. We tried to rule out those with 301 not to be treated like others, but it still returns with 200 when they're coming from the cache. ( By extending SSR optimized engine with an exception like )

```<code>   protected fallbackToCsr(response: Response, filePath: string, callback: SsrCallbackFn): void {
    if (response.statusCode !== HttpResponseStatus.MOVED_PERMANENTLY) {
      response.set('Cache-Control', 'no-store');
      callback(undefined, this.getDocument(filePath));
    }
  }
</code>```

We're looking for a solution to ensure that all 'the redirected pages' will always respond with 301 and not 200, even if they come from the cache.

答:
By extending SSR optimized engine

How did you extended (and used) optimized engine? I'm curious about this, because as I see it, the instance is hardcoded (and not injected), just like this:

```<code>// apply optimization wrapper if optimization options were defined
    return optimizationOptions
      ? new OptimizedSsrEngine(engineInstance, optimizationOptions)
          .engineInstance
      : engineInstance;
</code>```

If you actually managed to use your own instance of Optimized Engine, then you could do this:
Override renderResponse

```<code>  protected renderResponse(
    filePath: string,
    options: any,
    callback: (err?: Error | null, html?: string) => void
  ): void {
    super.renderResponse(filePath, options, callback);
    const response: Response = options.res || options.req.res;
    if (response.statusCode === HttpResponseStatus.MOVED_PERMANENTLY) {
      // remove the result from cache so that it's executed again
      const request: Request = options.req;
      const key = this.getRenderingKey(request);
      this.renderingCache.clear(key);
    }
  }
</code>```

However, this might not be too optimum. One way to improve: Use an additional internal Map<string,string> cache, and add code to store the renderingKey of the request and the Location value of the header inside the if above; so that, before calling super.renderResponse you will add code to check the map with the key; if present, then redirect to the result, and avoid the call to super.renderResponse.

Additionally, supposing that it's not possible to extend from OptimizedSsrEngine, the way to go would be to add a middleware on express server (see at server.ts file in your project), and make the implementation at low-level: the same approach, using a Map to store the redirects. You could add one middleware before the default to check that map, and calling next() only if the request key it's not in the map; and one after, to store the request key and the redirect if it's a redirect (ensure to add a call to next() from the default implementation).

Body:
We currently have a problem with SSR optimized engine. The scenario is that a product has been removed or renamed on the catalog, and the user tends to access that old none existing URL directly. Then we have implemented a redirected behavior sending a status code of 301 so that the customer gets redirected to a relevant page where its URL is retrieved from BE. (Through a generic HTTP interceptor catchError)

catchError((error: any) => {
 if (error instanceof HttpErrorResponse) {
  ...
  this.response.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
  this.response.set('location',this.service.urlBuilder(redirectUrl));
  return this.setMovedPermanentlyStatus();
  }
}

However, we also have those pages cached, so the next time that the page comes from the cache, it returns 200 instead of 301, which we tried to implement in the first place. We tried to rule out those with 301 not to be treated like others, but it still returns with 200 when they're coming from the cache. ( By extending SSR optimized engine with an exception like )

   protected fallbackToCsr(response: Response, filePath: string, callback: SsrCallbackFn): void {
    if (response.statusCode !== HttpResponseStatus.MOVED_PERMANENTLY) {
      response.set('Cache-Control', 'no-store');
      callback(undefined, this.getDocument(filePath));
    }
  }

We're looking for a solution to ensure that all 'the redirected pages' will always respond with 301 and not 200, even if they come from the cache.

Body:
By extending SSR optimized engine

How did you extended (and used) optimized engine? I'm curious about this, because as I see it, the instance is hardcoded (and not injected), just like this:

// apply optimization wrapper if optimization options were defined
    return optimizationOptions
      ? new OptimizedSsrEngine(engineInstance, optimizationOptions)
          .engineInstance
      : engineInstance;

If you actually managed to use your own instance of Optimized Engine, then you could do this:
Override renderResponse

  protected renderResponse(
    filePath: string,
    options: any,
    callback: (err?: Error | null, html?: string) => void
  ): void {
    super.renderResponse(filePath, options, callback);
    const response: Response = options.res || options.req.res;
    if (response.statusCode === HttpResponseStatus.MOVED_PERMANENTLY) {
      // remove the result from cache so that it's executed again
      const request: Request = options.req;
      const key = this.getRenderingKey(request);
      this.renderingCache.clear(key);
    }
  }

However, this might not be too optimum. One way to improve: Use an additional internal Map<string,string> cache, and add code to store the renderingKey of the request and the Location value of the header inside the if above; so that, before calling super.renderResponse you will add code to check the map with the key; if present, then redirect to the result, and avoid the call to super.renderResponse.

Additionally, supposing that it's not possible to extend from OptimizedSsrEngine, the way to go would be to add a middleware on express server (see at server.ts file in your project), and make the implementation at low-level: the same approach, using a Map to store the redirects. You could add one middleware before the default to check that map, and calling next() only if the request key it's not in the map; and one after, to store the request key and the redirect if it's a redirect (ensure to add a call to next() from the default implementation).


问:
Register custom filter in django
My filter is not being registered and not sure where it's getting tripped up.

In test/templatetags

```<code>__init__.py
test_tags.py
</code>```

test_tags.py includes

```<code>from django import template

register.filter('intcomma', intcomma)

def intcomma(value):
    return value + 1
</code>```

test/templates includes pdf_test.html with the following contents

```<code>{% load test_tags %}
<ul>
    <li>{{ value |intcomma |floatformat:"0"</li>
</ul>
</code>```

float format works fine but no luck on intcomma

答:
import register from django.template.defaulttags

```<code>from django.template.defaulttags import register
</code>```

views.py

```<code>        from django.template.defaulttags import register

    @register.filter
    def intcomma(value):
        return value + 1
..........................other code.................................
</code>```

list.html

```<code>{% extends "base.html" %}

    {% block content %}

      <ul>
        <li><h1>{{ 2.568|intcomma|floatformat:"0" }}</h1></li>
      </ul>

    {% endblock content %}
</code>```

Output like this:-

ContentLicense: CC BY-SA 3.0

Title: Register custom filter in django

Body:
My filter is not being registered and not sure where it's getting tripped up.

In test/templatetags

__init__.py
test_tags.py

test_tags.py includes

from django import template

register.filter('intcomma', intcomma)

def intcomma(value):
    return value + 1

test/templates includes pdf_test.html with the following contents

{% load test_tags %}

{{ value |intcomma |floatformat:"0"

float format works fine but no luck on intcomma

Body:
import register from django.template.defaulttags

from django.template.defaulttags import register

views.py

        from django.template.defaulttags import register

    @register.filter
    def intcomma(value):
        return value + 1
..........................other code.................................

list.html

{% extends "base.html" %}

    {% block content %}

      <ul>
        <li><h1>{{ 2.568|intcomma|floatformat:"0" }}</h1></li>
      </ul>

    {% endblock content %}

Output like this:-


问:
How to register custom program to handle mailto protocol on Windows 7
OK, it might be a problem with my system but I'm having a very difficult time getting Windows 7 to recognize my custom exe as the default handler of the mailto protocol.

First, I've seen this:
Register Windows program with the mailto protocol programmatically

Next, I've seen these:

How to Register an Internet Browser or Email Client With the Windows Start Menu

Registering an Application to a URL Protocol

I've added what seemed the appropriate registry entries but I still get Windows Live Mail coming up every time I click a mailto link (whether in a browser or via the Run window). I've set the registry entries for all users and for the current user, still it doesn't work.

When I go to the 'default programs' app and scroll down to the mailto protocol, I only see Outlook and Windows Live Mail listed. My custom app doesn't even appear.

I figure that it's either something special with Windows 7 or it's something with my computer.

My custom app is a WinForms .Net app but I don't think that matters.

Any ideas are greatly welcome.

答:
The way described in the answer which you referenced in your question seems correct way for Windows 7 as for other operation systems.

I suppose that you use 64-bit version of Windows 7 and your program is 32-bit application. So if your application write in the HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command key it modifies only the key HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\mailto\shell\open\command used for 32-bit applications. You can read more about registry virtualisation here and here.

If it's your case you can call directly native Win32 API RegOpenKeyEx with the KEY_WOW64_64KEY flag which will be ignored on 32-bit operation system.


问:
How to display the bootstrap alert based on the status code returned from server
I have just started learning express and bootstrap. Please help me in displaying the Bootstrap alert message based on the status code.

so far what I Did :

created a form using bootstrap

connected the form with mailchimp server

what i need :

when i click submit, based on the response  from mailchimp, if status code is 200, then i want to show the bootstrap alert in the client side

Requesting for help and it is highly appreciated.

Thanks

答:
```<code>if(responseCode=="200"){
    let a = document.createElement("div");
    a.classList.add("alert")
    a.classList.add("alert-info")
    a.innerText = "Success!"
    document.querySelector("#body").appendChild(a);
}
else if(responseCode=="403"){
    let a = document.createElement("div");
    a.classList.add("alert")
    a.classList.add("alert-danger")
    a.innerText = "unauthorized"
    document.querySelector("#body").appendChild(a);
}
</code>```

instead of selecting body to append you can choose any other element. also you can add various response codes

Body:
if(responseCode=="200"){
    let a = document.createElement("div");
    a.classList.add("alert")
    a.classList.add("alert-info")
    a.innerText = "Success!"
    document.querySelector("#body").appendChild(a);
}
else if(responseCode=="403"){
    let a = document.createElement("div");
    a.classList.add("alert")
    a.classList.add("alert-danger")
    a.innerText = "unauthorized"
    document.querySelector("#body").appendChild(a);
}

instead of selecting body to append you can choose any other element. also you can add various response codes


问:
react-native style opacity for parent and child
react-native : I have one View and the child of View is an Image , I applied opacity: 0.5 for View and opacity: 0.9 for an Image but it doesn't apply for Image ,the parent opacity is applying for child , the child doesn't take independent opacity  </p>

答:
If you want to change the opacity of a view that doesn't recognize the opacity prop (such as a TouchableOpacity), wrap it in a View first and change the opacity prop of that.

```<code><View opacity={0.3}>
<TouchableOpacity>
</TouchableOpacity>
</View>
</code>```

Body:
If you want to change the opacity of a view that doesn't recognize the opacity prop (such as a TouchableOpacity), wrap it in a View first and change the opacity prop of that.

<View opacity={0.3}>
<TouchableOpacity>
</TouchableOpacity>
</View>


问:
while error thrown by artisan custom command, it is not getting caught in laravel exception handler
When running custom artisan command which dispatches job, if any exception occur in job it should call handler.php but it doesn't get called.
I need to send an email for each type of exception caught in job.</p>

答:
=====edited=====

I see. so you want the jobs to retry a certain number of times and if it fails you want to send an email with the specific reason.

In this case you should not catch the exceptions inside your job with try-catch blocks. instead create the failed-table using php artisan queue:failed-table and handle the exceptions inside the failed function which you can create in the job like:

```<code>public function failed(Throwable $exception)
{
    // Send user notification of failure, etc...
}
</code>```

for further information see the laravel docs:
https://laravel.com/docs/8.x/queues#dealing-with-failed-jobs

Body:
=====edited=====

I see. so you want the jobs to retry a certain number of times and if it fails you want to send an email with the specific reason.

In this case you should not catch the exceptions inside your job with try-catch blocks. instead create the failed-table using php artisan queue:failed-table and handle the exceptions inside the failed function which you can create in the job like:

public function failed(Throwable $exception)
{
    // Send user notification of failure, etc...
}

for further information see the laravel docs:
https://laravel.com/docs/8.x/queues#dealing-with-failed-jobs


问:
Error in Django channels: ValueError: No application configured for scope type 'websocket'
I am going to develop chat application using Django Channelsby following tutorials: https://channels.readthedocs.io/en/stable/tutorial/part_2.html

My Project level routing.py

```<code>import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import chat.routing

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})
</code>```

App level routing.py file
from django.urls import re_path
from . import consumers

```<code>websocket_urlpatterns = [
    re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer)
]
</code>```

asgi.py file

```<code>import os
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    # Just HTTP for now. (We can add other protocols later.)
})
</code>```

答:
I believe that you switched the contents of project level routing.py with asgi.py file. I recreated the working version of the project according to the documentation you mentioned. Then I switched the contents of routing.py (project level) and asgi.py, and I got the same error as you on an attempt to connect to a WebSocket:

```<code>Django version 4.0.2, using settings 'django_channels_example.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
HTTP GET / 200 [0.01, 127.0.0.1:53043]
WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:53045]
Exception inside application: No application configured for scope type 'websocket'
Traceback (most recent call last):
</code>```

The command I used in browser's JavaScript console to connect to the websocket:

webSocket = new WebSocket('ws://localhost:8000/ws/chat/lobby/');
```
<hr />
<p>You were also missing <code>.as_asgi()</code> in the app level <code>routing.py</code> file (i.e., <code>chat/routing.py</code>):</p>
```    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi())
```
<p>See: https://channels.readthedocs.io/en/stable/tutorial/part_2.html#write-your-first-consumer</p>
<p>However, I doubt that this is what caused an error. The error you got is raised, e.g., when the <code>'websocket'</code> key is missing in the routing settings (see this answer), so be careful about that too.</p>
<p>Also make sure that your you have this in your <code>settings.py</code>:</p>
```INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'chat'
]

...

# Where `django_channels_example` is the name of your application
WSGI_APPLICATION = 'django_channels_example.wsgi.application'
ASGI_APPLICATION = 'django_channels_example.asgi.application'

```

Body:
I am going to develop chat application using Django Channelsby following tutorials: https://channels.readthedocs.io/en/stable/tutorial/part_2.html

My Project level routing.py

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import chat.routing

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

App level routing.py file
from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer)
]

asgi.py file

import os
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    # Just HTTP for now. (We can add other protocols later.)
})

Body:
I believe that you switched the contents of project level routing.py with asgi.py file. I recreated the working version of the project according to the documentation you mentioned. Then I switched the contents of routing.py (project level) and asgi.py, and I got the same error as you on an attempt to connect to a WebSocket:

Django version 4.0.2, using settings 'django_channels_example.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
HTTP GET / 200 [0.01, 127.0.0.1:53043]
WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:53045]
Exception inside application: No application configured for scope type 'websocket'
Traceback (most recent call last):

The command I used in browser's JavaScript console to connect to the websocket:

webSocket = new WebSocket('ws://localhost:8000/ws/chat/lobby/');

You were also missing .as_asgi() in the app level routing.py file (i.e., chat/routing.py):

    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi())

See: https://channels.readthedocs.io/en/stable/tutorial/part_2.html#write-your-first-consumer

However, I doubt that this is what caused an error. The error you got is raised, e.g., when the 'websocket' key is missing in the routing settings (see this answer), so be careful about that too.

Also make sure that your you have this in your settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'chat'
]

...

# Where `django_channels_example` is the name of your application
WSGI_APPLICATION = 'django_channels_example.wsgi.application'
ASGI_APPLICATION = 'django_channels_example.asgi.application'


问:
Rails 6: How to disable Action Mailbox and Action Text from loading into Memory?
I want a new Rails 6 app without Action Mailbox or Action Text, so I create one with

rails new myapp --skip-action-mailbox --skip-action-text

I then remove them in application.rb

But when I run bundle exec derailed bundle:mem it shows that they are still there:

```<code>rails/all: 36.2539 MiB
    action_mailbox/engine: 13.5313 MiB
</code>```

How can I remove them to save on memory?

答:
Ran into the same issue, which actually is somewhat of a red herring. It's the derailed_benchmark gem itself that loads all of rails. See this issue:

https://github.com/rails/rails/issues/41361

I think that's because rails/all is required when running derailed bundle:mem here.

The (as yet unreleased) main branch of the gem provides the environment variable DERAILED_SKIP_RAILS_REQUIRES, but that just caused exceptions when run on my particular rails app with derailed bundle:mem.

So the solution is to either ignore this and take into account that action_mailbox is not in fact loaded by your app, or use dynamic benchmarking as described in the README:

bundle exec derailed perf:mem
```

Body:
I want a new Rails 6 app without Action Mailbox or Action Text, so I create one with

rails new myapp --skip-action-mailbox --skip-action-text

I then remove them in application.rb

But when I run bundle exec derailed bundle:mem it shows that they are still there:

rails/all: 36.2539 MiB
    action_mailbox/engine: 13.5313 MiB

How can I remove them to save on memory?


问:
Webpacker can't find hello_react.js
I am setting up a new react with rails (learning) application but can't get past this error. I am using rails 6. I have webpacker installed and setup in my app.

I am getting error at this line in my application.html.erb

```<code><%= javascript_pack_tag 'hello_react' %>
</code>```

When i hit / i get this error:

```<code>Webpacker can't find hello_react.js in /Users/apple/www/projects/react/example/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:
{
  "application.js": "/packs/js/application-3dd0dc24d9c39bc09227.js",
  "application.js.map": "/packs/js/application-3dd0dc24d9c39bc09227.js.map",
  "entrypoints": {
    "application": {
      "js": [
        "/packs/js/application-3dd0dc24d9c39bc09227.js"
      ],
      "js.map": [
        "/packs/js/application-3dd0dc24d9c39bc09227.js.map"
      ]
    }
  }
}
</code>```

Can someone please guide me on what i might be doing wrong? I have removed node_modules and re-installed webpack and yarn in my application but the error persists.

答:
I would suggest to run bin/webpack-dev-server as described on the Rails Guide

I think your problem is a mapping problem that will be solve locally with this.

Do not forget add the requirement of hello_react.js on your packs folder in case you're using it.

Title: Webpacker can't find hello_react.js

Body:
I am setting up a new react with rails (learning) application but can't get past this error. I am using rails 6. I have webpacker installed and setup in my app.

I am getting error at this line in my application.html.erb

<%= javascript_pack_tag 'hello_react' %>

When i hit / i get this error:

Webpacker can't find hello_react.js in /Users/apple/www/projects/react/example/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:
{
  "application.js": "/packs/js/application-3dd0dc24d9c39bc09227.js",
  "application.js.map": "/packs/js/application-3dd0dc24d9c39bc09227.js.map",
  "entrypoints": {
    "application": {
      "js": [
        "/packs/js/application-3dd0dc24d9c39bc09227.js"
      ],
      "js.map": [
        "/packs/js/application-3dd0dc24d9c39bc09227.js.map"
      ]
    }
  }
}

Can someone please guide me on what i might be doing wrong? I have removed node_modules and re-installed webpack and yarn in my application but the error persists.


问:
Unable to locate package openal-soft
I'm trying to install openal-soft on Ubuntu Focal, but without luck.

This is the package I would like to install:

https://packages.ubuntu.com/source/focal/openal-soft

What I tried:

```<code>sudo apt update
sudo add-apt-repository universe
sudo apt install openal-soft
</code>```

Am I missing something?

答:
The package openal-soft does not exist.

If you want to install the OpenAL SDK, use this command:

```<code>sudo apt-get install libopenal-dev
</code>```

If you only need the lib on your system, run:

```<code>sudo apt install libopenal1
</code>```

You also don't need to add the universe repository because it is enabled by default.

Title: Unable to locate package openal-soft

Body:
I'm trying to install openal-soft on Ubuntu Focal, but without luck.

This is the package I would like to install:

https://packages.ubuntu.com/source/focal/openal-soft

What I tried:

sudo apt update
sudo add-apt-repository universe
sudo apt install openal-soft

Am I missing something?

Body:
The package openal-soft does not exist.

If you want to install the OpenAL SDK, use this command:

sudo apt-get install libopenal-dev

If you only need the lib on your system, run:

sudo apt install libopenal1

You also don't need to add the universe repository because it is enabled by default.


问:
The selected value of the select attribute is not displayed. TypeScript/Angular
I don't see anything in the item selection window. The elements are loaded from the Web APi server. Here is the photo of problem.

Component class

```<code>carsDynamic!: Array<Car>

private loadDynamicData(){
  this.dynamic.getDynamicCars().subscribe((data: Car[]) => {
  this.carsDynamic = data
})
</code>```

HTML page

```<code><select  class="form-control" [(ngModel)]="editedSale.carId">
  <option disabled selected>--Select--</option>
  <option *ngFor="let car of carsDynamic"
          value={{car.id}}>
          {{car.brandName}}
  </option>
</select>
</code>```

How to fix this problem ?

答: I found the cause of the malfunction. The fact is that I downloaded the wrong data model from the server</p>

Body:
I don't see anything in the item selection window. The elements are loaded from the Web APi server. Here is the photo of problem.

Component class

carsDynamic!: Array<Car>

private loadDynamicData(){
  this.dynamic.getDynamicCars().subscribe((data: Car[]) => {
  this.carsDynamic = data
})

HTML page

<select  class="form-control" [(ngModel)]="editedSale.carId">
  <option disabled selected>--Select--</option>
  <option *ngFor="let car of carsDynamic"
          value={{car.id}}>
          {{car.brandName}}
  </option>
</select>

How to fix this problem ?


问:
getting seg fault on malloc'ing for a string array. please help
```<code>#include<stdio.h>
------------------
#include<stdlib.h>
--------------------
#include<string.h
--------------------

enum { buf = BUFSIZ };

char line[buf], **tab = NULL;

 int cur_buf, count_lineMax = -1, count_line = -1,
    i, j, k, l;

int main (int argc, char **argv) {

        FILE *file1;
        file1 = fopen(argv[1], "r");

        cur_buf = buf;

        /*printf("%d\n", cur_buf);*/

                while(fgets(line, cur_buf, file1) != NULL) {

                        i = strlen(line);

                        for(j=0;j<i;j++) {
                                if(line[j] == '\n') {
                                        count_lineMax++;
                                }
                                /*printf("%c", line[j]);*/
                        }

                }
                /*printf("%d\n", count_lineMax);*/

                rewind(file1);

                tab = malloc(count_lineMax);
                memset(tab, 0, count_lineMax);

                for(k=0;k<count_lineMax;k++) {
                        tab[k] = malloc(cur_buf+1);
                        memset(tab[k], 0, cur_buf+1);
                }

                        while(fgets(line, cur_buf, file1) != NULL) {
                                i = strlen(line);

                                for(j=0;j<i;j++) {
                                        if(line[j] == '\n') {
                                                count_line++;
                                        }
                                }
                        tab[count_line] = line;
                        printf("%s", tab[count_line]);
                        }
        return 0;
        for(l=0;l<count_lineMax;l++) {
                free(tab[l]);
        }

        free(tab);
        fclose(file1);
}
## Heading ##
</code>```

答:
You haven't allocated enough memory for your lines.

```<code>char **tab;

tab = malloc(count_lineMax);
memset(tab, 0, count_lineMax);
</code>```

count_lineMax is the number of lines that are in the file and you are trying to allocate memory to store that many lines.  You only allocate count_lineMax bytes of memory but that's not enough for count_lineMax pointers.  Those lines should read:

```<code>tab = malloc(count_lineMax * sizeof(*tab));
memset(tab, 0, count_lineMax * sizeof(*tab));
</code>```

After that, you attempt to allocate more memory to store count_lineMax pointers and you overflow your memory corrupting the heap.

Furthermore, the second time you read in your file, you are writing to your file buffer and storing that buffer in your tab array.  You're leaking the memory you had previously allocated and you attempt to free() this buffer which is wrong.  So any of those problems are causing the segmentation fault.

```<code>while(fgets(line, cur_buf, file1) != NULL) { /* read into `line` */
    /* ... */
    tab[count_line] = line; /* DEATH! */
}
/* ... */
for(l = 0; l < count_lineMax; l++) {
    free(tab[l]); /* DOUBLE DEATH! *?
}
</code>```

You need to either read your lines directly into your allocated buffers correctly:

```<code>count_line = 0;
while(fgets(&tab[count_line], cur_buf, file1) != NULL) { /* read into `line` */
    /* ... */
    count_line++;
}
</code>```

Or copy the contents of the line buffer into your allocated ones.  That way you're not leaking your memory and freeing the wrong ones.

```<code>count_line = 0;
while(fgets(line, cur_buf, file1) != NULL) { /* read into `line` */
    /* ... */
    strcpy(tab[count_line], line);
    count_line++;
}
</code>```

There are other issues with the code but I won't go over them as these are higher priority.

Body:
You haven't allocated enough memory for your lines.

char **tab;

tab = malloc(count_lineMax);
memset(tab, 0, count_lineMax);

count_lineMax is the number of lines that are in the file and you are trying to allocate memory to store that many lines.  You only allocate count_lineMax bytes of memory but that's not enough for count_lineMax pointers.  Those lines should read:

tab = malloc(count_lineMax * sizeof(*tab));
memset(tab, 0, count_lineMax * sizeof(*tab));

After that, you attempt to allocate more memory to store count_lineMax pointers and you overflow your memory corrupting the heap.

Furthermore, the second time you read in your file, you are writing to your file buffer and storing that buffer in your tab array.  You're leaking the memory you had previously allocated and you attempt to free() this buffer which is wrong.  So any of those problems are causing the segmentation fault.

while(fgets(line, cur_buf, file1) != NULL) { /* read into `line` */
    /* ... */
    tab[count_line] = line; /* DEATH! */
}
/* ... */
for(l = 0; l < count_lineMax; l++) {
    free(tab[l]); /* DOUBLE DEATH! *?
}

You need to either read your lines directly into your allocated buffers correctly:

count_line = 0;
while(fgets(&tab[count_line], cur_buf, file1) != NULL) { /* read into `line` */
    /* ... */
    count_line++;
}

Or copy the contents of the line buffer into your allocated ones.  That way you're not leaking your memory and freeing the wrong ones.

count_line = 0;
while(fgets(line, cur_buf, file1) != NULL) { /* read into `line` */
    /* ... */
    strcpy(tab[count_line], line);
    count_line++;
}

There are other issues with the code but I won't go over them as these are higher priority.


问:
How to load sql file in spark using python
My pySpark version is 2.4 and python version is 2.7. I have multiple line sql file which needs to run in spark. Instead of running line by line, is it possible to keep the sql file in python (which initialize spark) and execute it using spark-submit ? I am trying to write a generic script in python so that we just need to replace sql file from hdfs folder later. Below is my code snippet.

```<code>import sys
from pyspark.sql import SparkSession
import pyspark.sql.functions as F

args = str(sys.argv[1]).split(',')

fd = args[0]
ld = args[1]
sd = args[2]

#Below line does not work
df = open("test.sql")
query = df.read().format(fd,ld,sd)

#Initiating SparkSession.
spark = SparkSession.builder.appName("PC").enableHiveSupport().getOrCreate()

#Below line works fine
df_s=spark.sql("""select * from test_tbl where batch_date='2021-08-01'""")

#Execute the sql (Does not work now)
df_s1=spark.sql(query)
</code>```

spark-submit  throws following error for the above code.

Exception in thread "main" org.apache.spark.SparkException:
Application application_1643050700073_7491 finished with failed status
at org.apache.spark.deploy.yarn.Client.run(Client.scala:1158)
at org.apache.spark.deploy.yarn.YarnClusterApplication.start(Client.scala:1606)
at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:847)
at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:161)
at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:184)
at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:86)
at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:922)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:931)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) 22/02/10 01:24:52 INFO util.ShutdownHookManager: Shutdown hook called

I am relatively new in pyspark. Can anyone please guide me what I am missing here ?

答:
You cant run pyspark on your local directory. If  you want to do an sql statement on a File in HDFS, you have to put your file from HDFS, first on your local directory.

Referred to spark 2.4.0 Spark Documentation, you can simply use the pyspark API.

```<code>from os.path import expanduser, join, abspath
from pyspark.sql import SparkSession
from pyspark.sql import Row

spark.sql("YOUR QUERY").show()
</code>```

or query files directly with:

```<code>df = spark.sql("SELECT * FROM parquet.`examples/src/main/resources/users.parquet`")
</code>```

Body:
My pySpark version is 2.4 and python version is 2.7. I have multiple line sql file which needs to run in spark. Instead of running line by line, is it possible to keep the sql file in python (which initialize spark) and execute it using spark-submit ? I am trying to write a generic script in python so that we just need to replace sql file from hdfs folder later. Below is my code snippet.

import sys
from pyspark.sql import SparkSession
import pyspark.sql.functions as F

args = str(sys.argv[1]).split(',')

fd = args[0]
ld = args[1]
sd = args[2]

#Below line does not work
df = open("test.sql")
query = df.read().format(fd,ld,sd)

#Initiating SparkSession.
spark = SparkSession.builder.appName("PC").enableHiveSupport().getOrCreate()

#Below line works fine
df_s=spark.sql("""select * from test_tbl where batch_date='2021-08-01'""")

#Execute the sql (Does not work now)
df_s1=spark.sql(query)

spark-submit  throws following error for the above code.

Exception in thread "main" org.apache.spark.SparkException:
Application application_1643050700073_7491 finished with failed status
at org.apache.spark.deploy.yarn.Client.run(Client.scala:1158)
at org.apache.spark.deploy.yarn.YarnClusterApplication.start(Client.scala:1606)
at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:847)
at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:161)
at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:184)
at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:86)
at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:922)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:931)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) 22/02/10 01:24:52 INFO util.ShutdownHookManager: Shutdown hook called

I am relatively new in pyspark. Can anyone please guide me what I am missing here ?

Body:
You cant run pyspark on your local directory. If  you want to do an sql statement on a File in HDFS, you have to put your file from HDFS, first on your local directory.

Referred to spark 2.4.0 Spark Documentation, you can simply use the pyspark API.

from os.path import expanduser, join, abspath
from pyspark.sql import SparkSession
from pyspark.sql import Row

spark.sql("YOUR QUERY").show()

or query files directly with:

df = spark.sql("SELECT * FROM parquet.`examples/src/main/resources/users.parquet`")


问:
How can I get black axes, but also a (default) grey grid in a pyqtgraph diagram?
I'm trying to change the color of the axes of a pyqtgraph diagram to black, but if I use self.graphWidget.getAxis('bottom').setPen('k') the grid is also black and I would like to have it in default grey. I didn't find any solution. Is there a way to achieve this and additionally color the tick numbers black?

```<code>import sys
from PyQt5 import QtWidgets
import pyqtgraph as pg

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.plot()

    def plot(self):
        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)
        self.graphWidget.setBackground('w')
        pen = pg.mkPen(color=('b'), width=2)

        styles = {'color':'r', 'font-size':'15px'}

        self.graphWidget.setLabel('left', 'x-values', **styles)
        self.graphWidget.setLabel('bottom', 'y-values', **styles)
        self.graphWidget.showGrid(x=True, y=True)

        self.graphWidget.getAxis('bottom').setPen('k')
        self.graphWidget.getAxis('left').setPen('k')

        x_values = [1, 2, 3, 4, 5]
        y_values = [2, 1, 2, 4, 3]

        self.graphWidget.plot(x_values, y_values, pen=pen, symbol='o',
                                   symbolSize=8, symbolPen='k', symbolBrush='k')

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

I'm using Python 3.8, PyQt5 5.15.0, PyCharm 2020.2 and Linux Mint 19.3.

答:
PyqtGraph uses default pen to draw all lines, ticks and grid in AxisItem. That's why it draws everything in the same color. Changing tick text color is easy, You can use textPen attribute for pg.AxisItem. Or set textPen for already created axis with  self.graphWidget.getAxis('bottom').setTextPen(black_pen).

To make axis line in specific color, we must re-implement drawPicture method of pg.AxisItem. We can introduce new init parameter called axisPen, which will be used only for axis line.

Here is full working code:

```<code>import sys

from PyQt5 import QtWidgets
import pyqtgraph as pg
from pyqtgraph import debug as debug

class ColoredAxis(pg.AxisItem):

    def __init__(self, orientation, pen=None, textPen=None, axisPen=None, linkView=None, parent=None,
                 maxTickLength=-5, showValues=True, text='', units='', unitPrefix='', **args):
        super().__init__(orientation, pen=pen, textPen=textPen, linkView=linkView, parent=parent,
                         maxTickLength=maxTickLength,
                         showValues=showValues, text=text, units=units, unitPrefix=unitPrefix, **args)
        self.axisPen = axisPen
        if self.axisPen is None:
            self.axisPen = self.pen()

    def drawPicture(self, p, axisSpec, tickSpecs, textSpecs):
        profiler = debug.Profiler()

        p.setRenderHint(p.RenderHint.Antialiasing, False)
        p.setRenderHint(p.RenderHint.TextAntialiasing, True)

        ## draw long line along axis
        pen, p1, p2 = axisSpec
        # Use axis pen to draw axis line
        p.setPen(self.axisPen)
        p.drawLine(p1, p2)
        # Switch back to normal pen
        p.setPen(pen)
        # p.translate(0.5,0)  ## resolves some damn pixel ambiguity

        ## draw ticks
        for pen, p1, p2 in tickSpecs:
            p.setPen(pen)
            p.drawLine(p1, p2)
        profiler('draw ticks')

        # Draw all text
        if self.style['tickFont'] is not None:
            p.setFont(self.style['tickFont'])
        p.setPen(self.textPen())
        bounding = self.boundingRect().toAlignedRect()
        p.setClipRect(bounding)
        for rect, flags, text in textSpecs:
            p.drawText(rect, int(flags), text)

        profiler('draw text')

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.plot()

    def plot(self):
        black_pen = pg.mkPen(color='black', width=2)
        self.axis_x = ColoredAxis(orientation='bottom', axisPen=black_pen)
        self.axis_y = ColoredAxis(orientation='left', axisPen=black_pen)
        self.graphWidget = pg.PlotWidget(background="w", axisItems={'bottom': self.axis_x, 'left': self.axis_y})
        self.setCentralWidget(self.graphWidget)

        styles = {'color': 'b', 'font-size': '15px'}

        self.graphWidget.setLabel('left', 'x-values', **styles)
        self.graphWidget.setLabel('bottom', 'y-values', **styles)
        self.graphWidget.showGrid(x=True, y=True)

        x_values = [1, 2, 3, 4, 5]
        y_values = [2, 1, 2, 4, 3]

        pen = pg.mkPen(color='b', width=2)
        self.graphWidget.plot(x_values, y_values, pen=pen, symbol='o',
                              symbolSize=8, symbolPen='k', symbolBrush='k')

        self.axis_x.setTextPen(black_pen)
        self.axis_y.setTextPen(black_pen)

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

Body:
I'm trying to change the color of the axes of a pyqtgraph diagram to black, but if I use self.graphWidget.getAxis('bottom').setPen('k') the grid is also black and I would like to have it in default grey. I didn't find any solution. Is there a way to achieve this and additionally color the tick numbers black?

import sys
from PyQt5 import QtWidgets
import pyqtgraph as pg

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.plot()

    def plot(self):
        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)
        self.graphWidget.setBackground('w')
        pen = pg.mkPen(color=('b'), width=2)

        styles = {'color':'r', 'font-size':'15px'}

        self.graphWidget.setLabel('left', 'x-values', **styles)
        self.graphWidget.setLabel('bottom', 'y-values', **styles)
        self.graphWidget.showGrid(x=True, y=True)

        self.graphWidget.getAxis('bottom').setPen('k')
        self.graphWidget.getAxis('left').setPen('k')

        x_values = [1, 2, 3, 4, 5]
        y_values = [2, 1, 2, 4, 3]

        self.graphWidget.plot(x_values, y_values, pen=pen, symbol='o',
                                   symbolSize=8, symbolPen='k', symbolBrush='k')

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

I'm using Python 3.8, PyQt5 5.15.0, PyCharm 2020.2 and Linux Mint 19.3.

Body:
PyqtGraph uses default pen to draw all lines, ticks and grid in AxisItem. That's why it draws everything in the same color. Changing tick text color is easy, You can use textPen attribute for pg.AxisItem. Or set textPen for already created axis with  self.graphWidget.getAxis('bottom').setTextPen(black_pen).

To make axis line in specific color, we must re-implement drawPicture method of pg.AxisItem. We can introduce new init parameter called axisPen, which will be used only for axis line.

Here is full working code:

import sys

from PyQt5 import QtWidgets
import pyqtgraph as pg
from pyqtgraph import debug as debug

class ColoredAxis(pg.AxisItem):

    def __init__(self, orientation, pen=None, textPen=None, axisPen=None, linkView=None, parent=None,
                 maxTickLength=-5, showValues=True, text='', units='', unitPrefix='', **args):
        super().__init__(orientation, pen=pen, textPen=textPen, linkView=linkView, parent=parent,
                         maxTickLength=maxTickLength,
                         showValues=showValues, text=text, units=units, unitPrefix=unitPrefix, **args)
        self.axisPen = axisPen
        if self.axisPen is None:
            self.axisPen = self.pen()

    def drawPicture(self, p, axisSpec, tickSpecs, textSpecs):
        profiler = debug.Profiler()

        p.setRenderHint(p.RenderHint.Antialiasing, False)
        p.setRenderHint(p.RenderHint.TextAntialiasing, True)

        ## draw long line along axis
        pen, p1, p2 = axisSpec
        # Use axis pen to draw axis line
        p.setPen(self.axisPen)
        p.drawLine(p1, p2)
        # Switch back to normal pen
        p.setPen(pen)
        # p.translate(0.5,0)  ## resolves some damn pixel ambiguity

        ## draw ticks
        for pen, p1, p2 in tickSpecs:
            p.setPen(pen)
            p.drawLine(p1, p2)
        profiler('draw ticks')

        # Draw all text
        if self.style['tickFont'] is not None:
            p.setFont(self.style['tickFont'])
        p.setPen(self.textPen())
        bounding = self.boundingRect().toAlignedRect()
        p.setClipRect(bounding)
        for rect, flags, text in textSpecs:
            p.drawText(rect, int(flags), text)

        profiler('draw text')

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.plot()

    def plot(self):
        black_pen = pg.mkPen(color='black', width=2)
        self.axis_x = ColoredAxis(orientation='bottom', axisPen=black_pen)
        self.axis_y = ColoredAxis(orientation='left', axisPen=black_pen)
        self.graphWidget = pg.PlotWidget(background="w", axisItems={'bottom': self.axis_x, 'left': self.axis_y})
        self.setCentralWidget(self.graphWidget)

        styles = {'color': 'b', 'font-size': '15px'}

        self.graphWidget.setLabel('left', 'x-values', **styles)
        self.graphWidget.setLabel('bottom', 'y-values', **styles)
        self.graphWidget.showGrid(x=True, y=True)

        x_values = [1, 2, 3, 4, 5]
        y_values = [2, 1, 2, 4, 3]

        pen = pg.mkPen(color='b', width=2)
        self.graphWidget.plot(x_values, y_values, pen=pen, symbol='o',
                              symbolSize=8, symbolPen='k', symbolBrush='k')

        self.axis_x.setTextPen(black_pen)
        self.axis_y.setTextPen(black_pen)

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


问:
Simple way to send a var to another js file and return
Im new into js (not into programing) and want to make a thing that I think is simple but I am struggling to make it.

Basically: Script.js take the parameters of the url (I have this done) and I want that parameter to go to a other that operate with it (and a database value but that is for atoher day cause y know how to that) and return the value operate.

All of this is to make an operation in a page but no one can see the operation , just the imput and the output.
Like the only visible files I want in my page is index.html and script.js , but not script2.

(Im open to use php but I have no idea how to use it so please simple :( )

Really sorry for my bad english

答:
Solution 1

I don't really understand your problem but if you just want to call a function on script2.js and pass it Params from script.js you can just import it into script.js. See (How do I include a JavaScript file in another JavaScript file?).

Solution 2

If you want your backend as you said in your comment to execute script2, it just needs to be an actual service or helper or whatelse accessible by your controllers.


问:
What is the correct pathway for Django OTP body message?
I'm doing a Django project and I'm at where I want to have a custom OTP email to the users. I have tried everything I could think of to have the OTP email not just display the OTP code but also the HTML but it just displays the path of "text"

I have read the docs but couldn't find much help.

settings.py:

```<code>text = 'Templates/email.txt'
html = 'Templates/email.html'
#OTP settings
OTP_EMAIL_SENDER=""
OTP_EMAIL_SUBJECT="Verification Code"
OTP_EMAIL_TOKEN_TEMPLATE=text
OTP_EMAIL_BODY_TEMPLATE=text
OTP_EMAIL_BODY_TEMPLATE_PATH=html
OTP_EMAIL_TOKEN_VALIDITY=300
</code>```

email.html:

```<code><tr>
    <td bgcolor="#fdfbf0" style="padding:25px">
        <p style="margin: 0;">
            <!--the safe parameter allows us to generate html. always make sure you are passing valid html markup to the email body-->
            {{email_body|safe}}
        </p>
    </td>
</tr>
</code>```

email.txt:

```<code>{{email_body}}
</code>```

答:
I was going through the same problem where I needed to use my customized email template. The code responsible for sending email is in django_otp.plugins.otp_email.models.py file. You can see the generate_challenge() in EmailDevice Model class. I solved it by adding html_message parameter in send_mail() as follow:

django_otp.plugins.otp_email.models.py
...

```<code>send_mail(settings.OTP_EMAIL_SUBJECT,
      strip_tags(body),
      settings.OTP_EMAIL_SENDER,
      [self.email or self.user.email],
      html_message=body)

      ...
</code>```

My use-case was different so, I forked the original django-otp package and then install it into my docker environment.

You can also do this by writing your own Device. Here's the link to Extending Django-OTP documentation.

Body:
I'm doing a Django project and I'm at where I want to have a custom OTP email to the users. I have tried everything I could think of to have the OTP email not just display the OTP code but also the HTML but it just displays the path of "text"

I have read the docs but couldn't find much help.

settings.py:

text = 'Templates/email.txt'
html = 'Templates/email.html'
#OTP settings
OTP_EMAIL_SENDER=""
OTP_EMAIL_SUBJECT="Verification Code"
OTP_EMAIL_TOKEN_TEMPLATE=text
OTP_EMAIL_BODY_TEMPLATE=text
OTP_EMAIL_BODY_TEMPLATE_PATH=html
OTP_EMAIL_TOKEN_VALIDITY=300

email.html:

            {{email_body|safe}}

email.txt:

{{email_body}}

Body:
I was going through the same problem where I needed to use my customized email template. The code responsible for sending email is in django_otp.plugins.otp_email.models.py file. You can see the generate_challenge() in EmailDevice Model class. I solved it by adding html_message parameter in send_mail() as follow:

django_otp.plugins.otp_email.models.py
...

send_mail(settings.OTP_EMAIL_SUBJECT,
      strip_tags(body),
      settings.OTP_EMAIL_SENDER,
      [self.email or self.user.email],
      html_message=body)

      ...

My use-case was different so, I forked the original django-otp package and then install it into my docker environment.

You can also do this by writing your own Device. Here's the link to Extending Django-OTP documentation.


问:
Global Object in singleton
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

```<code>class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};
</code>```

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

答:
Assuming this is part of a header file, then you'll get one definition of instance1 for each translation unit that includes it, and so a multiple definition error if more than one includes it. You'll get this problem whether it's a global or a static member.

To fix the error, you need a declaration in the header file (extern Singleton * instance1; if you want it to be global for some reason, or a private static member declaration if you want to prevent arbitrary access to it), and then a definition in a source file.

Alternatively, you could make the instance a static local object in getinstance(), which will fix the memory leak and, in C++11 at least, the thread safety problem:

```<code>static Singleton & getinstance()
{
    static Singleton instance;
    return instance;
}
</code>```

Or you could not use a singleton at all - it's almost certainly not a good idea.

Title: Global Object in singleton

Body:
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

Body:
Assuming this is part of a header file, then you'll get one definition of instance1 for each translation unit that includes it, and so a multiple definition error if more than one includes it. You'll get this problem whether it's a global or a static member.

To fix the error, you need a declaration in the header file (extern Singleton * instance1; if you want it to be global for some reason, or a private static member declaration if you want to prevent arbitrary access to it), and then a definition in a source file.

Alternatively, you could make the instance a static local object in getinstance(), which will fix the memory leak and, in C++11 at least, the thread safety problem:

static Singleton & getinstance()
{
    static Singleton instance;
    return instance;
}

Or you could not use a singleton at all - it's almost certainly not a good idea.


问:
Reload page when upload complete
I have a shiny app for uploading CSV file. I used the function sendSweetAlert from shinyWidgets package to send custom message but I would like to reload the page when user clik on "Ok" button

I tried to use shinyalert from shinyalert package but i dont get the desired result.

This is what I did :

```<code>library(shiny)
library(shinyWidgets)
library(shinyalert)

ui <- fluidPage(

  fileInput("file1", "Choose CSV File",
            multiple = FALSE,
            accept = c("text/csv",
                       "text/comma-separated-values,text/plain",
                       ".csv"),
            width = "80%")
)

server <- function(input, output,session) {

  # a progress bar
  observeEvent(
    input$file1,
    {  withProgress(message = "Progress...",value = 0, {
      for (i in seq_len(50)) {
        Sys.sleep(0.1)
        incProgress(1 / 50)

        setProgress(NULL, detail = paste(round(((i+1)*100/50),digits = 0),"%"))
      }

      setProgress(1, detail = "100%")

      # the custom message when progress reach 100%
      sendSweetAlert(
        session = session,
        title = "Great",
        text = "Done !",
        type = "success"
      )

      # my second attempt but doest work

      # shinyalert::shinyalert('Succes', callbackR = mycallback)
      # mycallback <- function(value) {
      #   "javascript:window.location.reload(true)"
      # }

    })}
  )

}

shinyApp(ui,server)
</code>```

Some help would be appreciated

答:
You can use callbackJS in shinyalert():

```<code>server <- function(input, output,session) {

  # a progress bar
  observeEvent(
    input$file1,
    {  withProgress(message = "Progress...",value = 0, {
      for (i in seq_len(50)) {
        Sys.sleep(0.1)
        incProgress(1 / 50)

        setProgress(NULL, detail = paste(round(((i+1)*100/50),digits = 0),"%"))
      }

      setProgress(1, detail = "100%")

      shinyalert::shinyalert('Succes', callbackJS = "function() {location.reload()}")

    })}
  )

}
</code>```

With this, the page will reload when you click on "Ok" in the modal.

Title: Reload page when upload complete

Body:
I have a shiny app for uploading CSV file. I used the function sendSweetAlert from shinyWidgets package to send custom message but I would like to reload the page when user clik on "Ok" button

I tried to use shinyalert from shinyalert package but i dont get the desired result.

This is what I did :

library(shiny)
library(shinyWidgets)
library(shinyalert)

ui <- fluidPage(

  fileInput("file1", "Choose CSV File",
            multiple = FALSE,
            accept = c("text/csv",
                       "text/comma-separated-values,text/plain",
                       ".csv"),
            width = "80%")
)

server <- function(input, output,session) {

  # a progress bar
  observeEvent(
    input$file1,
    {  withProgress(message = "Progress...",value = 0, {
      for (i in seq_len(50)) {
        Sys.sleep(0.1)
        incProgress(1 / 50)

        setProgress(NULL, detail = paste(round(((i+1)*100/50),digits = 0),"%"))
      }

      setProgress(1, detail = "100%")

      # the custom message when progress reach 100%
      sendSweetAlert(
        session = session,
        title = "Great",
        text = "Done !",
        type = "success"
      )

      # my second attempt but doest work

      # shinyalert::shinyalert('Succes', callbackR = mycallback)
      # mycallback <- function(value) {
      #   "javascript:window.location.reload(true)"
      # }

    })}
  )

}

shinyApp(ui,server)

Some help would be appreciated

Body:
You can use callbackJS in shinyalert():

server <- function(input, output,session) {

  # a progress bar
  observeEvent(
    input$file1,
    {  withProgress(message = "Progress...",value = 0, {
      for (i in seq_len(50)) {
        Sys.sleep(0.1)
        incProgress(1 / 50)

        setProgress(NULL, detail = paste(round(((i+1)*100/50),digits = 0),"%"))
      }

      setProgress(1, detail = "100%")

      shinyalert::shinyalert('Succes', callbackJS = "function() {location.reload()}")

    })}
  )

}

With this, the page will reload when you click on "Ok" in the modal.


问:
Better egonomics for TypeScript union-narrowing typeguard function
We have a utility in our codebase to generate a typeguard to narrow a discriminated union:

```<code>export type ExtractBranchFromUnion<
  UNION,
  DISCRIMINANT extends keyof UNION,
  BRANCH extends UNION[DISCRIMINANT],
> = UNION extends Record<DISCRIMINANT, BRANCH> ? UNION : never;

export function narrow<
  UNION,
  DISCRIMINANT extends keyof UNION,
  BRANCH extends UNION[DISCRIMINANT],
>(
  discriminate: DISCRIMINANT,
  branch: BRANCH,
): (
  item: UNION,
) => item is ExtractBranchFromUnion<UNION, DISCRIMINANT, BRANCH> {
  return (item): item is ExtractBranchFromUnion<UNION, DISCRIMINANT, BRANCH> =>
    item[discriminate] === branch;
}
</code>```

It can be used easily in a filter call to narrow an array down to a specific union member, however it requires that you remember to add as const after a string literal branch argument, otherwise it infers the type incorrectly and gives you too wide of a result:

```<code>type A = {type: 'A'; a: string};
type B = {type: 'B'; b: string};
type SimpleUnion = A | B;
const arr: SimpleUnion[] = [];

// BAD: type is SimpleUnion[]
const badListOfBs = arr.filter(narrow('type', 'B'));

// GOOD: type is B[]
const goodListOfBs = arr.filter(narrow('type', 'B' as const));
</code>```

While this issue can be partially alleviated with a premade constants,

```<code>const Types = {
  'A': 'A',
  'B': 'B',
} as const;

// OKAY: type is B[] but it requires a premade constant
const okayListOfBs = arr.filter(narrow('type', Types.B));
</code>```

it still doesn't prevent the issue of people forgetting as const with a literal value and getting confused why things don't work (as well as the fact that as const just looks ugly in the example two codeblocks above).

Is there a way to get TS to automatically infer a narrower type when provided with a string literal in narrow as shown above? Or at least a way to get a nice error message to show up?

Playground link for all of the above code.

答:
You just need to add extra restriction to Branch generic:

export type ExtractBranchFromUnion<
  Union,
  Discriminant extends keyof Union,
  Branch extends Union[Discriminant],
  > = Union extends Record<Discriminant, Branch> ? Union : never;

export function narrow<
  Union,
  Discriminant extends keyof Union,
  Branch extends Union[Discriminant] & PropertyKey, // <------ change is here
  >(
    discriminate: Discriminant,
    Branch: Branch,
): (
    item: Union,
  ) => item is ExtractBranchFromUnion<Union, Discriminant, Branch> {
  return (item): item is ExtractBranchFromUnion<Union, Discriminant, Branch> =>
    item[discriminate] === Branch;
}

type A = { type: 'A'; a: string };
type B = { type: 'B'; b: string };

type SimpleUnion = A | B;
const arr: SimpleUnion[] = [];

const badListOfBs = arr.filter(narrow('type', 'B')); // B[]
const goodListOfBs = arr.filter(narrow('type', 'A')); // A[]
```

Playground

I have added this: Branch extends Union[Discriminant] & PropertyKey.

I'd willing to bet that discriminator value should be string | number | symbol

As you might have noticed, I Capitalized all generic names because I found it hard to read. However this is the matter of preferences.

Body:
We have a utility in our codebase to generate a typeguard to narrow a discriminated union:

export type ExtractBranchFromUnion<
  UNION,
  DISCRIMINANT extends keyof UNION,
  BRANCH extends UNION[DISCRIMINANT],
> = UNION extends Record<DISCRIMINANT, BRANCH> ? UNION : never;

export function narrow<
  UNION,
  DISCRIMINANT extends keyof UNION,
  BRANCH extends UNION[DISCRIMINANT],
>(
  discriminate: DISCRIMINANT,
  branch: BRANCH,
): (
  item: UNION,
) => item is ExtractBranchFromUnion<UNION, DISCRIMINANT, BRANCH> {
  return (item): item is ExtractBranchFromUnion<UNION, DISCRIMINANT, BRANCH> =>
    item[discriminate] === branch;
}

It can be used easily in a filter call to narrow an array down to a specific union member, however it requires that you remember to add as const after a string literal branch argument, otherwise it infers the type incorrectly and gives you too wide of a result:

type A = {type: 'A'; a: string};
type B = {type: 'B'; b: string};
type SimpleUnion = A | B;
const arr: SimpleUnion[] = [];

// BAD: type is SimpleUnion[]
const badListOfBs = arr.filter(narrow('type', 'B'));

// GOOD: type is B[]
const goodListOfBs = arr.filter(narrow('type', 'B' as const));

While this issue can be partially alleviated with a premade constants,

const Types = {
  'A': 'A',
  'B': 'B',
} as const;

// OKAY: type is B[] but it requires a premade constant
const okayListOfBs = arr.filter(narrow('type', Types.B));

it still doesn't prevent the issue of people forgetting as const with a literal value and getting confused why things don't work (as well as the fact that as const just looks ugly in the example two codeblocks above).

Is there a way to get TS to automatically infer a narrower type when provided with a string literal in narrow as shown above? Or at least a way to get a nice error message to show up?

<a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBDAnmYcCiIZQIYGMYBCOAdrgBYBiUEAtgKrECWExAPAFBxx0ByAkgHkeAGk5wAInwDKAYQBKfALJ8eAQR4AVOKBjBiAEwDOcANbBEEAGbd%20Q0VwJz1MgBLbMeozcE8A2pNkFZTVNAF1RAD44AF5vIXddA2M5YFxofVYA%20SUVdQ1hOEdnFyiAfjieOAAuOGJgADdgKABudnZQSFg4SwBXUhhmYlrsKGoAdw4uXh97CWls4LyEz2MzC2tpuzEinldlpIr-eaDcsMiACjF9RkNcKEYaRmJsXRqsk5D8sQAjEnIanauUQAShqly4jF0NBqmxE7GBMSikOANDgN3QmBw%20CI2FIlGo9CYLFYsIK7xynwKgJKcAA3mIoMAYD0oENzsiaKC0VC0cYMFg8IQ-vjaAxBiTbCI5oEKXkqU5djTohExBCob5rrd7o9nrpQjForFfrjyK0AL5tNpIFBwVQxOnW4A1ADkqmdzTg2BqhiwTwA5mbWo7CvbaY6XQR3XBvt7fcQA0HkKgpA8wAAbYBilj2u0AH0KrTSxB9ntGNRTNHTmaJxF8%20tidda7AA9M3CqpxDVg%20iK1Ws7XQuwiyXvth9AAZG4wASWAjGWIjKAAOksjDTuig52eowgY3OzsdzoKzsjwOBrVbcAA4gIBJ2EEneYU60OWCW-RAIBOpzO5-bFyua4blui67vuh7HpGnrGMOMBnk2sFwBoSbznSYius6LpurMJ6YXAuGiGa0FwLBTaXgIADSqgAJpdo%206IEHW0Y9PAkJwIyACOPSMIyxjYHAYCMjQY6oLBuIwK%20xbwBAJjYIgk4%20r%20qEAau65NCBO57geSZHkhKFLgQ8FAA" rel="noreferrer">Playground link for all of the above code.

Body:
You just need to add extra restriction to Branch generic:

export type ExtractBranchFromUnion<
  Union,
  Discriminant extends keyof Union,
  Branch extends Union[Discriminant],
  > = Union extends Record<Discriminant, Branch> ? Union : never;

export function narrow<
  Union,
  Discriminant extends keyof Union,
  Branch extends Union[Discriminant] & PropertyKey, // <------ change is here
  >(
    discriminate: Discriminant,
    Branch: Branch,
): (
    item: Union,
  ) => item is ExtractBranchFromUnion<Union, Discriminant, Branch> {
  return (item): item is ExtractBranchFromUnion<Union, Discriminant, Branch> =>
    item[discriminate] === Branch;
}

type A = { type: 'A'; a: string };
type B = { type: 'B'; b: string };

type SimpleUnion = A | B;
const arr: SimpleUnion[] = [];

const badListOfBs = arr.filter(narrow('type', 'B')); // B[]
const goodListOfBs = arr.filter(narrow('type', 'A')); // A[]

Playground

I have added this: Branch extends Union[Discriminant] & PropertyKey.

I'd willing to bet that discriminator value should be string | number | symbol

As you might have noticed, I Capitalized all generic names because I found it hard to read. However this is the matter of preferences.


问:
How can I set state on individual elements in a mapped function using React?
I have an array of questions that I'm mapping through and displaying them in the UI, there is about 70+ questions.

Each question has a '+' button that reveals an answer when clicked, I want to reveal the answer using state but only for the specific question that is clicked, not the entire list. Currently I have it so when a button is clicked, it reveals all 70+ answers, what's the best way to do this so it only reveals one?

This is my code:

```<code>  const [open, setOpen] = useState(false);

 <div className='md:mt-8 pb-20'>
            {results[0].data.glossary_boxes.map((item, i) => (
              <>
                <div
                  key={i}
                  className='w-full border-3 border-yellow-500 flex-grow p-2 md:p-2 my-8'>
                  <div className='flex h-full items-center'>
                    <div className='bg-yellow-500 px-3 py-1 flex items-center justify-start ml-2'>
                      <a
                        onClick={() => setOpen(!open)}
                        className='text-white text-3xl cursor-pointer'>
                        {open ? '-' : '+'}
                      </a>
                    </div>
                    <div className='flex flex-col items-start'>
                      <p className='text-gray-500 font-sansbold text-md md:text-xl px-12'>
                        {item.question}
                      </p>

                      <p
                        className={`text-xl gray-500 font-quote text-md md:text-lg px-12 ${
                          open ? 'block' : 'hidden'
                        }`}>
                        {item.answer}
                      </p>
                    </div>
                  </div>
                </div>
              </>
            ))}
          </div>
</code>```

When the state is true, it also displays a '-' in place of where the '+' was until clicked again to set to false (hide the answer).

Thanks in advance!

答:
Change the state variable to hold a unique value rather than a boolean value. For example

```<code>const [openedItem, setOpenedItem] = useState(null);
</code>```

Change the onClick event handler to something like this. Where i is from your map function.

```<code>onClick={() => setOpenedItem(i)}
</code>```

Change showing (+)(-) logic to this.

```<code>{openedItem === i ? '-' : '+'}
</code>```

Change the dynamic class generation (block/hidden) logic to the same condition above.

Body:
I have an array of questions that I'm mapping through and displaying them in the UI, there is about 70+ questions.

Each question has a '+' button that reveals an answer when clicked, I want to reveal the answer using state but only for the specific question that is clicked, not the entire list. Currently I have it so when a button is clicked, it reveals all 70+ answers, what's the best way to do this so it only reveals one?

This is my code:

  const [open, setOpen] = useState(false);

            {results[0].data.glossary_boxes.map((item, i) => (
              <>

                       setOpen(!open)}
                        className='text-white text-3xl cursor-pointer'>
                        {open ? '-' : '+'}

                        {item.question}

                        {item.answer}

              </>
            ))}

When the state is true, it also displays a '-' in place of where the '+' was until clicked again to set to false (hide the answer).

Thanks in advance!

Body:
Change the state variable to hold a unique value rather than a boolean value. For example

const [openedItem, setOpenedItem] = useState(null);

Change the onClick event handler to something like this. Where i is from your map function.

onClick={() => setOpenedItem(i)}

Change showing (+)(-) logic to this.

{openedItem === i ? '-' : '+'}

Change the dynamic class generation (block/hidden) logic to the same condition above.


问:
implement external_stylesheets with dash-bootstrap only to accordion component
in below code which represents main section of my app I need to apply external_stylesheets which works only with accordion component. What should I change in below code because currently this style is applied for whole app and it cause unwanted style changes. Thanks in advance for help!!!!</p>
```<code>import numpy
import pandas as pd
from jupyter_dash import JupyterDash
from dash.dependencies import Input, Output
from dash import dcc
from dash import html
import plotly.express as px
import plotly.graph_objects as go
import dash
import dash_bootstrap_components as dbc
from dash import dash_table
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

 external_stylesheets = [dbc.themes.UNITED]
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)

#sets up entire layout of the site
app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-content', style = {'font-family': 'Roche Sans'}),
])

app.config.suppress_callback_exceptions = True

# Update the index/page
@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/building-report-intro':
        return brp_intro_layout
    elif pathname == '/building-report-creation':
        return brp_creation_layout
    elif pathname == '/process-technology-intro':
        return ptr_intro_layout
    elif pathname == '/process-technology-report-creation':
        return ptr_creation_layout
    elif pathname == '/brp-view':
        return brp_report_view
    else:
        return index_page
    # You could also return a 404 "URL not found" page here

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

答:
Yes this is possible. Here is a guide:

Stop applying the external_stylesheet "dbc.themes.BOOTSTRAP", as this will affect all components on the dashboard

You add a css file to the assets folder that sits next to your application python file. In this file, you add the bootstrap styling that you want to apply depending on the components. So in your case, you only want to apply bootstrapping to accordions, so only have the accordion code in this css file. You can get this styling from the official bootstrap accordion style located here between lines 4646 and 4753 (as of the time of writing this answer).

Restart your server and you should only have bootstrap styling to the accordions in your app.

Body:
in below code which represents main section of my app I need to apply external_stylesheets which works only with accordion component. What should I change in below code because currently this style is applied for whole app and it cause unwanted style changes. Thanks in advance for help!!!!

import numpy
import pandas as pd
from jupyter_dash import JupyterDash
from dash.dependencies import Input, Output
from dash import dcc
from dash import html
import plotly.express as px
import plotly.graph_objects as go
import dash
import dash_bootstrap_components as dbc
from dash import dash_table
from IPython.core.display import display, HTML
display(HTML(""))

 external_stylesheets = [dbc.themes.UNITED]
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)

#sets up entire layout of the site
app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-content', style = {'font-family': 'Roche Sans'}),
])

app.config.suppress_callback_exceptions = True

# Update the index/page
@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/building-report-intro':
        return brp_intro_layout
    elif pathname == '/building-report-creation':
        return brp_creation_layout
    elif pathname == '/process-technology-intro':
        return ptr_intro_layout
    elif pathname == '/process-technology-report-creation':
        return ptr_creation_layout
    elif pathname == '/brp-view':
        return brp_report_view
    else:
        return index_page
    # You could also return a 404 "URL not found" page here

if __name__ == '__main__':
    app.run_server(debug=True)


问:
(discord.js) TypeError: Cannot read property 'send' when trying to send a direct message
I was trying to use the following code to send a welcome message, but it seems that it can't read the property 'send'
Here's the code:

```<code>
client.on("guildMemberAdd", (member) => {
    member.guild.channels.cache.get(welcomeChannelId).send(`<@${member.id}> Welcome to the server!`)
})
</code>```

Error message:

```<code>    member.guild.channels.cache.get(welcomeChannelId).send(`<@${member.id}> Welcome to the server!`)
                                                     ^

TypeError: Cannot read properties of undefined (reading 'send')
    at Client.<anonymous> (/Users/admin/Desktop/Discord Bot/index.js:25:54)
    at Client.emit (node:events:520:28)
    at Object.module.exports [as GUILD_MEMBER_ADD] (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js:16:14)
    at WebSocketManager.handlePacket (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
    at WebSocketShard.onPacket (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/Users/admin/Desktop/Discord Bot/node_modules/ws/lib/event-target.js:199:18)
    at WebSocket.emit (node:events:520:28)
    at Receiver.receiverOnMessage (/Users/admin/Desktop/Discord Bot/node_modules/ws/lib/websocket.js:1137:20)
    at Receiver.emit (node:events:520:28)
</code>```

Please help me.

答:
The channel might not be stored in the cache yet. You can do

```<code>member.guild.channels.fetch(welcomeChannelId).then(chan=>
member.guild.channels
      .fetch(welcomeChannelId)
      .then((chan) => chan.send(`<@${member.id}> Welcome to the server!`))
      .catch(() => null);
</code>```

Fetch will check if the channel is in the cache and if it isn't it will fetch it.

Body:
I was trying to use the following code to send a welcome message, but it seems that it can't read the property 'send'
Here's the code:

client.on("guildMemberAdd", (member) => {
    member.guild.channels.cache.get(welcomeChannelId).send(`<@${member.id}> Welcome to the server!`)
})

Error message:

    member.guild.channels.cache.get(welcomeChannelId).send(`<@${member.id}> Welcome to the server!`)
                                                     ^

TypeError: Cannot read properties of undefined (reading 'send')
    at Client.<anonymous> (/Users/admin/Desktop/Discord Bot/index.js:25:54)
    at Client.emit (node:events:520:28)
    at Object.module.exports [as GUILD_MEMBER_ADD] (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js:16:14)
    at WebSocketManager.handlePacket (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
    at WebSocketShard.onPacket (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/Users/admin/Desktop/Discord Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/Users/admin/Desktop/Discord Bot/node_modules/ws/lib/event-target.js:199:18)
    at WebSocket.emit (node:events:520:28)
    at Receiver.receiverOnMessage (/Users/admin/Desktop/Discord Bot/node_modules/ws/lib/websocket.js:1137:20)
    at Receiver.emit (node:events:520:28)

Please help me.

Body:
The channel might not be stored in the cache yet. You can do

member.guild.channels.fetch(welcomeChannelId).then(chan=>
member.guild.channels
      .fetch(welcomeChannelId)
      .then((chan) => chan.send(`<@${member.id}> Welcome to the server!`))
      .catch(() => null);

Fetch will check if the channel is in the cache and if it isn't it will fetch it.


问:
Problem with kv file in visual studio code
I'm trying to setup Visual Studio Code for python and everything is good except Kivy.

I have simple code

```<code>import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget

class MyGrid(Widget):
    pass

class MyApp(App):
    def build(self):
        return MyGrid()

if __name__ == "__main__":
    MyApp().run()
</code>```

and simple kivy file

```<code>    #:kivy
<MyGrid>:
    GridLayout:
        cols:1
        size: root.width, root.height

        GridLayout:
            cols:2

            Label:
                text: "Name: "

            TextInput:
                multinline:False

            Label:
                text: "Email: "

            TextInput:
                multiline:False

        Button:
            text:"Submit"
</code>```

And when I'm trying to run python file I got

kivy.lang.parser.ParserException: Parser: File "c:\Users\Paweł\Documents\projects vscode\WeatherProject\my.kv", line 1:
1:#:kivy
2::
3:GridLayout:
Unknown directive

Google isn't helpful at all. Please tell me what should I do.

答: Solution from the OPs comment: I haven't saved the file after editing :)</p>

Body:
I'm trying to setup Visual Studio Code for python and everything is good except Kivy.

I have simple code

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget

class MyGrid(Widget):
    pass

class MyApp(App):
    def build(self):
        return MyGrid()

if __name__ == "__main__":
    MyApp().run()

and simple kivy file

    #:kivy
<MyGrid>:
    GridLayout:
        cols:1
        size: root.width, root.height

        GridLayout:
            cols:2

            Label:
                text: "Name: "

            TextInput:
                multinline:False

            Label:
                text: "Email: "

            TextInput:
                multiline:False

        Button:
            text:"Submit"

And when I'm trying to run python file I got

kivy.lang.parser.ParserException: Parser: File "c:\Users\Paweł\Documents\projects vscode\WeatherProject\my.kv", line 1:
1:#:kivy
2::
3:GridLayout:
Unknown directive

Google isn't helpful at all. Please tell me what should I do.