问:
How to add multiple url in "CURLOPT_URL ="
I am trying to get response from multiple url using API call and change color based on response. Problem is I want to get response from multiple url at the same time. But the program only can take the last url from the array.

I also tried using array for multiple url and looping but didn't work. Below is my code.

```<code><?php

// An array of URLs to make requests to
$urls = array(
    'https://example.com/v1/objects/services?service=1',
    'https://example.com/v1/objects/services?service=2'
);

// Create a new cURL multi handle
$mh = curl_multi_init();

$username = "root";
$password = "apipass";
$headers = array(
        'Accept: application/json',
        'X-HTTP-Method-Override: GET'
// Add each URL to the cURL multi handle
foreach ($urls as $i => $url) {
    $ch[$i] = curl_init();
    curl_setopt_array($ch[$i], array(
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_USERPWD => $username . ":" . $password,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0
    ));
    curl_multi_add_handle($mh, $ch[$i]);
}

// Execute the cURL multi handle
do {
    $status = curl_multi_exec($mh, $active);
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);

// Get the responses from each handle
foreach ($urls as $i => $url) {
    $response[$i] = curl_multi_getcontent($ch[$i]);
}

// Close the cURL multi handle and each individual handle
foreach ($urls as $i => $url) {
    curl_multi_remove_handle($mh, $ch[$i]);
}
curl_multi_close($mh);

foreach ($response as $i => $response) {
   // check response and change color based on it
   if(strpos($response, "Unreachable") !== false) {
   $color[$i] = 'red';
      // success response
   } else {
   $color[$i] = 'green';
   }
}
print $status;
print $color[$i];
?>
</code>```

Body:
I am trying to get response from multiple url using API call and change color based on response. Problem is I want to get response from multiple url at the same time. But the program only can take the last url from the array.

I also tried using array for multiple url and looping but didn't work. Below is my code.

<?php

// An array of URLs to make requests to
$urls = array(
    'https://example.com/v1/objects/services?service=1',
    'https://example.com/v1/objects/services?service=2'
);

// Create a new cURL multi handle
$mh = curl_multi_init();

$username = "root";
$password = "apipass";
$headers = array(
        'Accept: application/json',
        'X-HTTP-Method-Override: GET'
// Add each URL to the cURL multi handle
foreach ($urls as $i => $url) {
    $ch[$i] = curl_init();
    curl_setopt_array($ch[$i], array(
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_USERPWD => $username . ":" . $password,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0
    ));
    curl_multi_add_handle($mh, $ch[$i]);
}

// Execute the cURL multi handle
do {
    $status = curl_multi_exec($mh, $active);
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);

// Get the responses from each handle
foreach ($urls as $i => $url) {
    $response[$i] = curl_multi_getcontent($ch[$i]);
}

// Close the cURL multi handle and each individual handle
foreach ($urls as $i => $url) {
    curl_multi_remove_handle($mh, $ch[$i]);
}
curl_multi_close($mh);

foreach ($response as $i => $response) {
   // check response and change color based on it
   if(strpos($response, "Unreachable") !== false) {
   $color[$i] = 'red';
      // success response
   } else {
   $color[$i] = 'green';
   }
}
print $status;
print $color[$i];
?>


来源: stackexchange

问:
How to add Tweet HTML Block to react-quilljs
I'm using 'react-quilljs' package, and I want to add Tweet HTML Block to the toolbar, I couldn't find any tutorial how to in their webpage

The Code I'm Using:

```<code>import { useQuill } from 'react-quilljs';
import 'quill/dist/quill.snow.css';

export default function NewPost() {

const [content, setContent] = useState("");

     //Quill Editor Toolbar
     const modules = {
         toolbar:{
             container: [
                 [{'header': '1'}, {'header':'2'}, {'font':'[]'}],
                 [{size:[]}],
                 ['bold', 'italic', 'underline', 'strike', 'blockquote'],
                 [{'list': 'ordered'}, {'list': 'bullet'}, {'indent':'-1'}, {'indent':'+1'}],
                 ['link', 'image', imageHandler],
                 ['clean'], ['code-block']
             ],
         },
         clipboard: {
             matchVisual: false,
         },
     };

    const { quill, quillRef } = useQuill();
    useEffect(() => {
        if (quill){
            quill.on('text-change', () => {
                console.log(quillRef.current.firstChild.innerHTML);
                setContent(quillRef.current.firstChild.innerHTML)
            });
        }
    }, [quill]);

    console.log(content, "this is quill editor")

return (

            <div className="newPostContentContainer">
              <label className="newPostFormLabel">Post Content:</label
                <div className="newPostContentTextareaContainer">
                    <div dir="auto" style={{ height: '300px', width: '100%', boxSizing: 'border-box'}}>
                        <div ref={quillRef} />
                    </div>
                </div>
            </div>

)
}
</code>```

the problem is that the toolbar I have right now don't have the tweet HTML block or code sample, I have to add them by myself, which I failed to know how, any help would be appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I'm using 'react-quilljs' package, and I want to add Tweet HTML Block to the toolbar, I couldn't find any tutorial how to in their webpage

The Code I'm Using:

import { useQuill } from 'react-quilljs';
import 'quill/dist/quill.snow.css';

export default function NewPost() {

const [content, setContent] = useState("");

     //Quill Editor Toolbar
     const modules = {
         toolbar:{
             container: [
                 [{'header': '1'}, {'header':'2'}, {'font':'[]'}],
                 [{size:[]}],
                 ['bold', 'italic', 'underline', 'strike', 'blockquote'],
                 [{'list': 'ordered'}, {'list': 'bullet'}, {'indent':'-1'}, {'indent':'+1'}],
                 ['link', 'image', imageHandler],
                 ['clean'], ['code-block']
             ],
         },
         clipboard: {
             matchVisual: false,
         },
     };

    const { quill, quillRef } = useQuill();
    useEffect(() => {
        if (quill){
            quill.on('text-change', () => {
                console.log(quillRef.current.firstChild.innerHTML);
                setContent(quillRef.current.firstChild.innerHTML)
            });
        }
    }, [quill]);

    console.log(content, "this is quill editor")

return (

              Post Content:</label

)
}

the problem is that the toolbar I have right now don't have the tweet HTML block or code sample, I have to add them by myself, which I failed to know how, any help would be appreciated.


问:
The "configparser" library detects/does not detect some sections in an .ini file
First of all I specify that the library is configparser and the file is a file with an .ini extension.

Previously I implemented a code like this to detect if these sections existed or not and I have not had any problem, the code was something like this:

if not config.has_section('user'):print(configparser.NoSectionError)
if not config.has_section('app'):print(configparser.NoSectionError)
```
<p>These prints have not jumped me at any time. The problem comes from the fact that when performing this action, I was getting the error that the section was not found (error: <code>configparser.NoSectionError</code>)</p>
<pre class="lang-py prettyprint-override"><code>try:config.set('app', 'num-scripts', f'{self.w_num_files}')
except configparser.NoSectionError:print("[Error 404] Section not found")
  finally:config.write(configfile)
</code>```

So to solve this (although it seemed strange to me) I have modified the first lines to these.

if not config.has_section('user'):config.add_section('user')
if not config.has_section('app'):config.add_section('app')
```
<p>Another problem comes that now, instead of rewriting the already existing data, that is, for example: change <code>username = root</code> to <code>username = Example</code>, which makes it write it, all the data that I want to change, again in a new section at the bottom. How can I prevent this from happening?</p>
<p>I expected that when executing this line of code: try:config.set('user', 'username', f'{self.logfile_last_line[1]}') this line would change</p>
```[user]
username = root
```
<p>for this (example):</p>
```[user]
username = example
```
<p>I did the checks to detect and there was no problem until it was time to write the file: <code>config.write(configfile)</code>
Here I was getting an error that it did not exist, so I programmed a conditional where I checked if the section existed or not, and if this conditional was negative, I created the section. The problem is that the section did exist. And after doing the aforementioned, what it does is the following</p>
```[user]
username = root[user]
username = example
```

Body:
First of all I specify that the library is configparser and the file is a file with an .ini extension.

Previously I implemented a code like this to detect if these sections existed or not and I have not had any problem, the code was something like this:

if not config.has_section('user'):print(configparser.NoSectionError)
if not config.has_section('app'):print(configparser.NoSectionError)

These prints have not jumped me at any time. The problem comes from the fact that when performing this action, I was getting the error that the section was not found (error: configparser.NoSectionError)

try:config.set('app', 'num-scripts', f'{self.w_num_files}')
except configparser.NoSectionError:print("[Error 404] Section not found")
  finally:config.write(configfile)

So to solve this (although it seemed strange to me) I have modified the first lines to these.

if not config.has_section('user'):config.add_section('user')
if not config.has_section('app'):config.add_section('app')

Another problem comes that now, instead of rewriting the already existing data, that is, for example: change username = root to username = Example, which makes it write it, all the data that I want to change, again in a new section at the bottom. How can I prevent this from happening?

I expected that when executing this line of code: try:config.set('user', 'username', f'{self.logfile_last_line[1]}') this line would change

[user]
username = root

for this (example):

[user]
username = example

I did the checks to detect and there was no problem until it was time to write the file: config.write(configfile)
Here I was getting an error that it did not exist, so I programmed a conditional where I checked if the section existed or not, and if this conditional was negative, I created the section. The problem is that the section did exist. And after doing the aforementioned, what it does is the following

[user]
username = root[user]
username = example


问:
How to generate a trusted ssl certificate for the backend of an application developed with spring-boot
I have a web application developed with spring boot and Angular. The frontend is running on ngnix web server , the backend is running on embedded tomcat for spring boot , both of them are hosted on a Debian VM on ovh cloud, so it's secured with ovh basic Let's Encypt basic security for ssl offered by OVH.
My problem is that the certificate is regenerated (each 3 months ovh regenerate a new one ) and my backend could not recognize anymore the calls coming from the front end.

I made some researches on how to use the certificates generated by ovh ( use the privatekey.pem and fullchain.pem (under /etc/letsencrypt/live/mydomain)  with openssl to generate a PKCS12 file to be put on the backend server )
I put the generated .p12 file in my spring app and configured mu application.properties but with no success!

```<code>server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore/my-keystore.p12
# The password used to generate the certificate
server.ssl.key-store-password=mypassword
# The alias mapped to the certificate
server.ssl.key-alias=myalias
</code>```

So how do I generate a trusted SSL certificate for my  backend server?
I don't know if I'm in a good way with these steps or not, since I'm totally new with all this stuff but If someone could explain me the flow, how to proceed I will be so much grateful !

Thanks in advance

Body:
I have a web application developed with spring boot and Angular. The frontend is running on ngnix web server , the backend is running on embedded tomcat for spring boot , both of them are hosted on a Debian VM on ovh cloud, so it's secured with ovh basic Let's Encypt basic security for ssl offered by OVH.
My problem is that the certificate is regenerated (each 3 months ovh regenerate a new one ) and my backend could not recognize anymore the calls coming from the front end.

I made some researches on how to use the certificates generated by ovh ( use the privatekey.pem and fullchain.pem (under /etc/letsencrypt/live/mydomain)  with openssl to generate a PKCS12 file to be put on the backend server )
I put the generated .p12 file in my spring app and configured mu application.properties but with no success!

server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore/my-keystore.p12
# The password used to generate the certificate
server.ssl.key-store-password=mypassword
# The alias mapped to the certificate
server.ssl.key-alias=myalias

So how do I generate a trusted SSL certificate for my  backend server?
I don't know if I'm in a good way with these steps or not, since I'm totally new with all this stuff but If someone could explain me the flow, how to proceed I will be so much grateful !

Thanks in advance


问:
Error when creating a process in C# and using relative path with folders

I'm writing a program in C# that has to call an external process (a jar file in this case).
If I put the jar and all the files that it uses in the same folder of my exe the call succeed, but if I place all these files in a folder (even on the same level of the exe) the arguments that I pass the the jar seem to be off.

This is a small program I used for testing:

```<code>private static async Task Main()
{
    // Build the process arguments
    string arguments = $"-jar {JarPath}";

    // Create the process
    Process process = CreateProcess(ExePath, arguments, "1", "file.json", "file");
    Console.WriteLine($"Process arguments: {process.StartInfo.Arguments}");

    // Then wait for it to complete (custom made extension method)
    await process.WaitForExitAsync();

    // Print process generated output
    string standardOutput = await process.StandardOutput.ReadToEndAsync();
    Console.WriteLine(standardOutput);

    Console.Write("Press 'ENTER' to exit: ");
    Console.ReadLine();
}

private static Process CreateProcess(string exePath, params string[] arguments)
{
    string args = string.Empty;
    for (int i = 0; i < arguments.Length; i++)
        args += $"{arguments[i]} ";

    ProcessStartInfo startInfo = new ProcessStartInfo
    {
        CreateNoWindow = true,
        UseShellExecute = false,
        WindowStyle = ProcessWindowStyle.Hidden,
        FileName = exePath,
        Arguments = args.TrimEnd(),
        RedirectStandardOutput = true
    };

    Process process = Process.Start(startInfo);
    return process;
}
</code>```

In the code above ExePath is the path of java.exe and JarPath is the path to the jar file that I have to execute.
If it is something like "jarFileName.jar" the code works fine and I have a certain standard output, but if it's something like "folder\jarFileName.jar" the output changes from the previous case and the jar actually doesn't work as intended.

Any ideas? I'm not that familiar with cdm arguments, maybe is something related to that

Body:
I'm writing a program in C# that has to call an external process (a jar file in this case).
If I put the jar and all the files that it uses in the same folder of my exe the call succeed, but if I place all these files in a folder (even on the same level of the exe) the arguments that I pass the the jar seem to be off.

This is a small program I used for testing:

private static async Task Main()
{
    // Build the process arguments
    string arguments = $"-jar {JarPath}";

    // Create the process
    Process process = CreateProcess(ExePath, arguments, "1", "file.json", "file");
    Console.WriteLine($"Process arguments: {process.StartInfo.Arguments}");

    // Then wait for it to complete (custom made extension method)
    await process.WaitForExitAsync();

    // Print process generated output
    string standardOutput = await process.StandardOutput.ReadToEndAsync();
    Console.WriteLine(standardOutput);

    Console.Write("Press 'ENTER' to exit: ");
    Console.ReadLine();
}

private static Process CreateProcess(string exePath, params string[] arguments)
{
    string args = string.Empty;
    for (int i = 0; i < arguments.Length; i++)
        args += $"{arguments[i]} ";

    ProcessStartInfo startInfo = new ProcessStartInfo
    {
        CreateNoWindow = true,
        UseShellExecute = false,
        WindowStyle = ProcessWindowStyle.Hidden,
        FileName = exePath,
        Arguments = args.TrimEnd(),
        RedirectStandardOutput = true
    };

    Process process = Process.Start(startInfo);
    return process;
}

In the code above ExePath is the path of java.exe and JarPath is the path to the jar file that I have to execute.
If it is something like "jarFileName.jar" the code works fine and I have a certain standard output, but if it's something like "folder\jarFileName.jar" the output changes from the previous case and the jar actually doesn't work as intended.

Any ideas? I'm not that familiar with cdm arguments, maybe is something related to that


问:
How to add some alternative authentication with token on Asp.Net Core?
We have built some Asp.Net Core web API, with the authentication/authorization built on top of Asp.Net Core identy, with some JWT token exchange for our angular frontend. Basically, the users can login with username+password, this provide them a JWT with a short validity that the frontend regularly refresh. If the token is not valid anymore, the user will have to login again.
This part works great.

Now, we have to add another concept, a bit like on Azure Devop, we need to add "agent", those are not users, they will just need to be authenticated, in a slightly different way:

They will run on unnattended(locked) computers

They will be configured once and then run forever

Each agent should NOT be considered as a user. They should not be stored as such(or at least provide a way to distinguish them)

Those agent should only have some kind of token/private key to authenticate themself, that doesn't expire. This method of authentication should not be allowed to other users

So based on this:

Is this something that already exists, or have this pattern a name?

Is there a way to achieve this through Asp.Net Core identity or am I better off ?

Any link or lead on how to implement in parallel of an existing auth would be highly appreciated.


问:
Swiper slide numbers if more than one slide visible
There is a layout that requires the user to show the number of the current slide, while more than two slides can be shown on the screen at the same time. I made a conclusion for one slide, but how to make the remaining slides increase their value?</p>
```<code><div class="swiper-slide">
  <h1>@name</h1>
  <div class="numberSlides">
    0/0
  </div>
</div>
<div class="swiper-slide">
  <h1>@name</h1>
  <div class="numberSlides">
    0/0
  </div>
</div> ...
</code>```
```<code>swiper.on('transitionEnd', function() {
 console.log('start', swiper.realIndex );
    var offer = document.querySelectorAll('.sliderCounter');
    for (let i = 0; i < offer.length; i++) {
        offer[i].innerHTML = (swiper.realIndex +  1) + '/' + swiper.slides.length;
    }
});
</code>```

Body:
There is a layout that requires the user to show the number of the current slide, while more than two slides can be shown on the screen at the same time. I made a conclusion for one slide, but how to make the remaining slides increase their value?

@name

    0/0

@name

    0/0

 ...

swiper.on('transitionEnd', function() {
 console.log('start', swiper.realIndex );
    var offer = document.querySelectorAll('.sliderCounter');
    for (let i = 0; i < offer.length; i++) {
        offer[i].innerHTML = (swiper.realIndex +  1) + '/' + swiper.slides.length;
    }
});


问:
JOIN SQL query with two tables
```<code>SELECT u.id, u.name, u.surname, p.id as p_id, SUM(t.summa)
FROM users u
LEFT JOIN pupils p ON p.userid = u.id
LEFT JOIN tulovlar t ON t.pupilid = p.id
WHERE u.turi = 3
GROUP BY u.id
ORDER BY u.surname
</code>```

sql response is showing this error

```<code>#1055 - Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'crm_test.p.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
</code>```

Title: JOIN SQL query with two tables

Body:
SELECT u.id, u.name, u.surname, p.id as p_id, SUM(t.summa)
FROM users u
LEFT JOIN pupils p ON p.userid = u.id
LEFT JOIN tulovlar t ON t.pupilid = p.id
WHERE u.turi = 3
GROUP BY u.id
ORDER BY u.surname

sql response is showing this error

#1055 - Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'crm_test.p.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by


问:
Bootstrap selectpicker sort by selected option
I have a <select> with lot of parameters, some of the parameters are selected by default. I want to show first all the parameters selected.

HTML code

```<code><select id='selectUsers' class="selectpicker selectpickerUsers" name="users[]" data-width="100%" multiple data-live-search="true">
    @foreach($users as $user)
        <option data-tokens="{{$user->id}}">{{$user->Name}}</option>
    @endforeach
</select>
</code>```

JavaScript code

```<code>$('.selectpickerUsers').selectpicker({
        sortBy: 'selected'
      });
</code>```

I try to do this, but it doesn't work.

I need to sort all the options from the list by selected values.

Body:
I have a <select> with lot of parameters, some of the parameters are selected by default. I want to show first all the parameters selected.

HTML code

<select id='selectUsers' class="selectpicker selectpickerUsers" name="users[]" data-width="100%" multiple data-live-search="true">
    @foreach($users as $user)
        <option data-tokens="{{$user->id}}">{{$user->Name}}</option>
    @endforeach
</select>

JavaScript code

$('.selectpickerUsers').selectpicker({
        sortBy: 'selected'
      });

I try to do this, but it doesn't work.

I need to sort all the options from the list by selected values.


问:
Android HiltTest: The component was not created. Check that you have added the HiltAndroidRule
I have a util method which will go some actiivty by routing.

// RoutingUtil.java
public static void goRouting(Context context, String routing);
```
<p>And I want test this method.</p>
<p>So I did something like this</p>
<pre class="lang-java prettyprint-override"><code>@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
public class RoutingUiUtilsTest {

    @Rule
    public HiltAndroidRule hiltRule = new HiltAndroidRule(this);

    @Before
    public void setUp() {
        hiltRule.inject();
    }

    @Test
    public void testSmartGo() {
        ActivityScenario.launch(MainActivity.class);
        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
        RoutingUtil.goRouting(context, "", "schema://a_activity_path");
    }

}
</code>```

The dest Activity is AActivity which used the hilt by annoutation @AndroidEntryPoint

@AndroidEntryPoint
class AActivity extends Activity {
}
```
<p>Then I run test in terminal</p>
```./gradlew connectedAndroidTest
```

And error throws

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.somepackage/com.somepackage.AActivity}:
java.lang.IllegalStateException: The component was not created. Check
that you have added the HiltAndroidRule

I think the reason is I didn't start AActivity by hilt test componet, like ActivityScenario.launch(AActivity.class);, but what I want test is RoutingUtil.goRouting so I can't use hilt test component.

So how to test RoutingUtil.goRouting?

Body:
I have a util method which will go some actiivty by routing.

// RoutingUtil.java
public static void goRouting(Context context, String routing);

And I want test this method.

So I did something like this

@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
public class RoutingUiUtilsTest {

    @Rule
    public HiltAndroidRule hiltRule = new HiltAndroidRule(this);

    @Before
    public void setUp() {
        hiltRule.inject();
    }

    @Test
    public void testSmartGo() {
        ActivityScenario.launch(MainActivity.class);
        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
        RoutingUtil.goRouting(context, "", "schema://a_activity_path");
    }

}

The dest Activity is AActivity which used the hilt by annoutation @AndroidEntryPoint

@AndroidEntryPoint
class AActivity extends Activity {
}

Then I run test in terminal

./gradlew connectedAndroidTest

And error throws

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.somepackage/com.somepackage.AActivity}:
java.lang.IllegalStateException: The component was not created. Check
that you have added the HiltAndroidRule

I think the reason is I didn't start AActivity by hilt test componet, like ActivityScenario.launch(AActivity.class);, but what I want test is RoutingUtil.goRouting so I can't use hilt test component.

So how to test RoutingUtil.goRouting?


问:
It is possible to grab process memory using ftrace?
I have two applications one writing requests to and reading responses from stdin/stdout of another. I should not modify the applications, but I have root permission. I need to intercept requests, and responses and measure time when some messages passed as precise as possible.

Currently I'm using ptrace, trace read and write syscalls on fd=0 and fd=1 and grab memory from /proc/<pid>/mem, but the overhead is too big, we cannot use such imprecise timestamps. I'm trying to use ftrace, but, I cannot read from /proc/<pid>/mem, because ftrace doesn't stop the tracee application.

It seems, ftrace only give me arguments of functions and registers, but I cannot google how to grab the buffer at the pointer given as argument. Is it even possible?

Could you suggest another approach for my problem?


问:
How to use below Firestore map field type to display price according to size
Database:
enter image description here

I want to display the size (SizePrice field) in a list view and price should be changed according to the selected size.


问:
Remote Desktop blocks Alt Gr key combinations in VS Code
Sometimes when I have a Remote Desktop-connection enabled, VS Code refuses to allow me to type curly braces or other symbols which require the Alt Gr-key on my keyboard (norwegian layout).

However, in other apps and the Start Menu, I'm able to type the symbol properly, so it's not a keyboard / changed language-issue.

Quitting or restarting the Remote Desktop-session allows it to work again for a while. I suspected that it might be the login screen after a timeout on the Remote Desktop being involved, but locking the remote computer manually did not provoke the issue in VS Code.

This same "solution" is found in an answer to a similar question (36780208), but is there now an actual fix to this issue? Some configuration issue on the Remote Desktop computer or in VS Code maybe?

My google-fu seems to be failing me on this, and while having to restart a remote desktop-connection from time-to-time isn't the end of the world, it's really annoying when I forget that that's the solution


问:
How to find all the dependencies that have a peer dependency on a specific library?
How do I find, within my project, all the dependencies that have a peer dependency on a specific library?

The use case is that I have to update the version of the library X, and I want to know which library peer-depends on X so that I know in advance what other libraries I have to check to be sure to not break the compatibility.

I'm thinking about something like yarn why <x>, but for peer dependencies.


问:
Docker compose to turn on multiple container based on each other
I am having three container , db , nginx and app . I need to turn on container in particular order to make sure things works without any issue.

Order of container is

db

nginx  (Once db container is turned on completely )

app (Once db container is turned on Nginx localhost is responding)

I tried using depends on and healthcheck of docker-compose , I couldn't successful

```<code>version: "3.3"

services:
  db:
    image: ubuntu:latest
    container_name: db
    build:
      context: ./
      dockerfile: Dockerfile.db
 nginx:
    image: ubuntu:latest
    container_name: nginx
    healthcheck:
      test: curl --noproxy '*' https://localhost --insecure;
    depends_on
      db:
        condition: service_started
    build:
      context: ./
      dockerfile: Dockerfile.nginx
 app:
    image: ubuntu:latest
    container_name: ubuntu
    build:
      context: ./
      dockerfile: Dockerfile.app
    depends_on:
      nginx:
        condition: service_healthy
      db:
        condition: service_started
</code>```

Let me know what changes , I need to do so that it will run in correct order as mentioned before

db container

nginx (Wait till db container runs completely)

app ( wait till db and nginx runs and nginx responds to https://localhost)

I have tried the multiple answers which are present , still I am not able to fix this issue .

I am observing app running initially only as it's an exe before nginx and db container running

Body:
I am having three container , db , nginx and app . I need to turn on container in particular order to make sure things works without any issue.

Order of container is

db

nginx  (Once db container is turned on completely )

app (Once db container is turned on Nginx localhost is responding)

I tried using depends on and healthcheck of docker-compose , I couldn't successful

version: "3.3"

services:
  db:
    image: ubuntu:latest
    container_name: db
    build:
      context: ./
      dockerfile: Dockerfile.db
 nginx:
    image: ubuntu:latest
    container_name: nginx
    healthcheck:
      test: curl --noproxy '*' https://localhost --insecure;
    depends_on
      db:
        condition: service_started
    build:
      context: ./
      dockerfile: Dockerfile.nginx
 app:
    image: ubuntu:latest
    container_name: ubuntu
    build:
      context: ./
      dockerfile: Dockerfile.app
    depends_on:
      nginx:
        condition: service_healthy
      db:
        condition: service_started

Let me know what changes , I need to do so that it will run in correct order as mentioned before

db container

nginx (Wait till db container runs completely)

app ( wait till db and nginx runs and nginx responds to https://localhost)

I have tried the multiple answers which are present , still I am not able to fix this issue .

I am observing app running initially only as it's an exe before nginx and db container running


问:
Generation Allure Reporter
I have the following Jenkins Pipline

```<code>node('api50analysis') {

    def err = null
    currentBuild.result = "SUCCESS"

    try {
        dir ('/var/www/TMS/tests') {

        stage 'Delete old report'
        sh 'rm -Rf ./allure-report'
        sh 'rm -Rf ./allure-results'

        stage 'Get AutoTest from git'
        git credentialsId: '9d6d49c0-9e6c-4e81-8893-cb5993b6fd83', url: '$git_url_test', branch: '$branch_test'

        stage 'Install dependencies'
        sh 'sudo chown -R $(whoami) /var/www/TMS/tests'
        sh 'npm install'

        stage 'WEB tests as admin'
        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite adminSuites'

        sh 'npm run clearDB'
    sh 'npx wdio run wdio.conf.ts --suite aidLimit'

        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite limit'

        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite configuration'

        sh 'npm run clearDB'
    sh 'npx wdio run wdio.conf.ts --suite merchant'
        sh 'npx wdio run wdio.conf.ts --suite terminal'
        sh 'npx wdio run wdio.conf.ts --suite deviceType'

        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite device'

        sh 'npm run clearDB'
        }
  }
  catch (caughtError) {
        err = caughtError
        currentBuild.result = "FAILURE"
                          build job: 'telegram_job',
         parameters: [string(name: 'msg',
         value: "----------\n"+
                 "Job name: ${JOB_NAME}\n"+
            "Status: $currentBuild.result\n"+
        "Build number: ${BUILD_NUMBER}\n"+
            "Build URL ${BUILD_URL}\n"+
               "----------")]

  } finally {
        stage 'Allure'
            script {allure([
                    includeProperties: false,
                    jdk: '',
                    properties: [],
                    reportBuildPolicy: 'ALWAYS',
                    results: [[path: 'target/allure-results']]
            ])}

        if (err) {
            throw err
        }
  }
}
</code>```

The Allure report is always generated, however, if at least one test has failed, it generates an empty report, instead of generating it with data on which tests passed, which tests failed and attach a screenshot to the place where the test fell (configured in the Webdriver IO config )

What could be the problem? The server where autotests run is managed by CentOS 7 enter image description here. Here is an example of a report when all tests pass enter image description here

In the console in this case

```<code>[Pipeline] stage (Allure)
Using the ‘stage’ step without a block argument is deprecated
Entering stage Allure
Proceeding
[Pipeline] script
[Pipeline] {
[Pipeline] allure
[TMS_AUTOTEST] $ /opt/jenkins/tools/ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation/Allure/bin/allure generate -c -o /opt/jenkins/workspace/TMS_AUTOTEST/allure-report
allure-results does not exist
Report successfully generated to /opt/jenkins/workspace/TMS_AUTOTEST/allure-report
Allure report was successfully generated.
Creating artifact for the build.
Artifact was added to the build.
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 3
Finished: FAILURE
</code>```

Title: Generation Allure Reporter

Body:
I have the following Jenkins Pipline

node('api50analysis') {

    def err = null
    currentBuild.result = "SUCCESS"

    try {
        dir ('/var/www/TMS/tests') {

        stage 'Delete old report'
        sh 'rm -Rf ./allure-report'
        sh 'rm -Rf ./allure-results'

        stage 'Get AutoTest from git'
        git credentialsId: '9d6d49c0-9e6c-4e81-8893-cb5993b6fd83', url: '$git_url_test', branch: '$branch_test'

        stage 'Install dependencies'
        sh 'sudo chown -R $(whoami) /var/www/TMS/tests'
        sh 'npm install'

        stage 'WEB tests as admin'
        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite adminSuites'

        sh 'npm run clearDB'
    sh 'npx wdio run wdio.conf.ts --suite aidLimit'

        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite limit'

        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite configuration'

        sh 'npm run clearDB'
    sh 'npx wdio run wdio.conf.ts --suite merchant'
        sh 'npx wdio run wdio.conf.ts --suite terminal'
        sh 'npx wdio run wdio.conf.ts --suite deviceType'

        sh 'npm run clearDB'
        sh 'npx wdio run wdio.conf.ts --suite device'

        sh 'npm run clearDB'
        }
  }
  catch (caughtError) {
        err = caughtError
        currentBuild.result = "FAILURE"
                          build job: 'telegram_job',
         parameters: [string(name: 'msg',
         value: "----------\n"+
                 "Job name: ${JOB_NAME}\n"+
            "Status: $currentBuild.result\n"+
        "Build number: ${BUILD_NUMBER}\n"+
            "Build URL ${BUILD_URL}\n"+
               "----------")]

  } finally {
        stage 'Allure'
            script {allure([
                    includeProperties: false,
                    jdk: '',
                    properties: [],
                    reportBuildPolicy: 'ALWAYS',
                    results: [[path: 'target/allure-results']]
            ])}

        if (err) {
            throw err
        }
  }
}

The Allure report is always generated, however, if at least one test has failed, it generates an empty report, instead of generating it with data on which tests passed, which tests failed and attach a screenshot to the place where the test fell (configured in the Webdriver IO config )

What could be the problem? The server where autotests run is managed by CentOS 7 enter image description here. Here is an example of a report when all tests pass enter image description here

In the console in this case

[Pipeline] stage (Allure)
Using the ‘stage’ step without a block argument is deprecated
Entering stage Allure
Proceeding
[Pipeline] script
[Pipeline] {
[Pipeline] allure
[TMS_AUTOTEST] $ /opt/jenkins/tools/ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation/Allure/bin/allure generate -c -o /opt/jenkins/workspace/TMS_AUTOTEST/allure-report
allure-results does not exist
Report successfully generated to /opt/jenkins/workspace/TMS_AUTOTEST/allure-report
Allure report was successfully generated.
Creating artifact for the build.
Artifact was added to the build.
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 3
Finished: FAILURE


问:
How to enforce a method argument type?
How to enforce that types are part of a super type, that has no properties? The idea is to enforce that only types that share a super type can be passed to a method and no other types.

Assume we have different types that are intended to update something.

```<code>type DateUpdateObj= {newDate:Date}
type LengthUpdateObj= {newLength:number, unit: 'm'|'cm'}
type ...UpdateObj = {...} //it should be possible to add many more Update Objects types
</code>```

A function should only accept sub-types as argument. But how to do it properly?

My first attempt was to use some kind of marker interface (UpdateObj) like in Java or Kotlin.

```<code>class UpdateObj { private readonly _ :never} // acts as a marker interface
type MyUpdateObj = { foo:string} & UpdateObj  //the new update obj type

function send<T extends UpdateObj>(updateObj:T){} //the function only accepts UpdateObj
</code>```

Compile test:

```<code>send("") //ok, doesn't compile as expected
send(new Date())  //ok, doesn't compile as expected
send({foo:'hurray'} as MyUpdateObj) //ok, compiles es expected

const myUpdate:MyUpdateObj=  { foo:"err"} //should compile but doesn't, since '_' is missing and adding a cast is not possible in my case cause it would break source compatibility
send(myUpdate)
</code>```

TSPlayground example

Title: How to enforce a method argument type?

Body:
How to enforce that types are part of a super type, that has no properties? The idea is to enforce that only types that share a super type can be passed to a method and no other types.

Assume we have different types that are intended to update something.

type DateUpdateObj= {newDate:Date}
type LengthUpdateObj= {newLength:number, unit: 'm'|'cm'}
type ...UpdateObj = {...} //it should be possible to add many more Update Objects types

A function should only accept sub-types as argument. But how to do it properly?

My first attempt was to use some kind of marker interface (UpdateObj) like in Java or Kotlin.

class UpdateObj { private readonly _ :never} // acts as a marker interface
type MyUpdateObj = { foo:string} & UpdateObj  //the new update obj type

function send<T extends UpdateObj>(updateObj:T){} //the function only accepts UpdateObj

Compile test:

send("") //ok, doesn't compile as expected
send(new Date())  //ok, doesn't compile as expected
send({foo:'hurray'} as MyUpdateObj) //ok, compiles es expected

const myUpdate:MyUpdateObj=  { foo:"err"} //should compile but doesn't, since '_' is missing and adding a cast is not possible in my case cause it would break source compatibility
send(myUpdate)

<a href="https://www.typescriptlang.org/play?#code/PTDOFNwAgQwG1AeygCwC5oA6gFwgLYCWAxivAF7zjEDWhAdMYvsAHbOGvwC0aAnpk4Bzbp14DwoYgCdCmNMACwAKBUr+maABEYacAFVMAE13gA8gCMAVgF4oAb1bgA7jr0434AL7qJUADLgrEJoKIYmepa2Dk7OgcGhOKwArvgW4NIANFDJrIRoOFAA5PhFAD5FxKU+qsrEcDCgoFDhplEOUJiyAG6mUNLgMEaIrHB8xUVQSeDdGV5QILDEaM2NsFD4MNI0GVCcetIAZjDE4L6aUACyfK2R1lB29lCHiIg4oGiywfMAZC3GbXuC2AoWgsRyAL0UEQ9w0Z2UUBUh1yy0IIygEFYRgAPAAVKDgAAeeixzVu5msAD4ABTJSEUqw4XEASns8xAoOeKLQaNY0NG4xOp3kZPpUTUCJAiBo2WGklYRTQUCY+EEcGga2cMFYeiMKkxRmpACIjcyJSopTKoHLQAqlSq1RrmlqdeA9coDdTwZ5qczmVBEbULcBpdkHYR1atndrdfqgob7C83kUUMlpNIYHwivM1tdyVF-eblCB2ErQxiUIhknAjMrmI6oBZkkqbXbsqBOKdigB9SaEZpEJrCAPB2BGIzDmDKxpK-tQUudRBDizqvZ8-DjZIQafb4gwLfQfJQZxVmuNgYwGgYqvSLsO3SECwR-J8FRMVgfDY3ek4PNi6x2B0SY4EaGTSEa8xxli1IbuSzJAA" rel="nofollow noreferrer">TSPlayground example


问:
python - FEniCS How do I convert a tensor expression into a scalar expression?
I'm new to FEniCS and optimization. Trying to run my code I receive the Error
UFLException: Can't add expressions with different shapes.
The Code:

```<code>from dolfin import *
from dolfin_adjoint import *
mesh = Mesh("beam.xml")         # beam x[0] 0 - 5, x[1] 0 - 1, x[2] 0 - 1
V = VectorFunctionSpace(mesh, "CG", 1)
y = Function(V, name="State")   # Trialfunction State
d = y.geometric_dimension()     # space dimension
u = Function(V, name="Control") # Trialfunction Control
v = TestFunction(V)             # Testfunction
x = SpatialCoordinate(mesh)

alpha = Constant(10e-6)
beta = Constant(0.2)

rho = Constant(7800) # Density of steel [kg/m³]
E = Constant(210000)  # Young's modulus steel [MN/m²]
nu = Constant(0.3)  # Poisson's ratio steel

lmbda = E*nu/(1+nu)/(1-2*nu) # Lame's constant
mu = E/(2*(1+nu)) # Shear modulus

G = Constant(pi**2) #gravity

F_z = Constant(rho*G) #weight force
F = Constant((0,0,-F_z))
g_z = Constant(2.9575e5)
g = Constant((0,0,g_z))

y_Desired = Constant((0,0,0.0))

top = AutoSubDomain(lambda x: near(x[1], 1))

boundaries = MeshFunction("size_t", mesh, mesh.topology().dim()-1)
boundaries.set_all(0)

top.mark(boundaries, 1)
ds_N = ds(subdomain_data=boundaries) # use in ds_N(1) as in inner(g,v)*ds_N(1)

bottom = AutoSubDomain(lambda x: near(x[1], 0))

boundaries = MeshFunction("size_t", mesh, mesh.topology().dim()-1)
boundaries.set_all(0)

bottom.mark(boundaries, 1)
ds_0 = ds(subdomain_data=boundaries) # use in ds_0(1) as in beta(abs(u))*ds_O(1)

def bottom(x, on_boundary):
    return(on_boundary and near (x[1], 0.0))

bc_bottom = DirichletBC(V, u, bottom)

def left(x, on_boundary):
    return(on_boundary and near (x[0], 0.0))
bc_left = DirichletBC(V, Constant((0, 0, 0)), left)

def right(x, on_boundary):
    return(on_boundary and near (x[0], 5.0))
bc_right = DirichletBC(V, Constant((0, 0, 0)), right)

bcs = [bc_left, bc_right, bc_bottom]

def epsilon(y):
    return 0.5*(nabla_grad(y) + nabla_grad(y).T)

def sigma (y):
    return lmbda*div(y)*Identity(d) + 2*mu*epsilon(y)

S = inner(sigma(y),epsilon(v))*dx - inner((F+u),v)*dx - inner(g,v)*ds_N(1)

solve(S == 0, y, bcs)

J = assemble((0.5*inner(y- y_Desired, y - y_Desired))*dx + alpha / 2 * inner((F+u), v)* dx + beta*abs(u)*ds_0)
</code>```

I tried to make y_Desired also 3D but then I receive UFLException: Can only integrate scalar expressions. The integrand is a tensor expression with value shape (3,) and free indices with labels ().

Can anyone help me on this?

Body:
I'm new to FEniCS and optimization. Trying to run my code I receive the Error
UFLException: Can't add expressions with different shapes.
The Code:

from dolfin import *
from dolfin_adjoint import *
mesh = Mesh("beam.xml")         # beam x[0] 0 - 5, x[1] 0 - 1, x[2] 0 - 1
V = VectorFunctionSpace(mesh, "CG", 1)
y = Function(V, name="State")   # Trialfunction State
d = y.geometric_dimension()     # space dimension
u = Function(V, name="Control") # Trialfunction Control
v = TestFunction(V)             # Testfunction
x = SpatialCoordinate(mesh)

alpha = Constant(10e-6)
beta = Constant(0.2)

rho = Constant(7800) # Density of steel [kg/m³]
E = Constant(210000)  # Young's modulus steel [MN/m²]
nu = Constant(0.3)  # Poisson's ratio steel

lmbda = E*nu/(1+nu)/(1-2*nu) # Lame's constant
mu = E/(2*(1+nu)) # Shear modulus

G = Constant(pi**2) #gravity

F_z = Constant(rho*G) #weight force
F = Constant((0,0,-F_z))
g_z = Constant(2.9575e5)
g = Constant((0,0,g_z))

y_Desired = Constant((0,0,0.0))

top = AutoSubDomain(lambda x: near(x[1], 1))

boundaries = MeshFunction("size_t", mesh, mesh.topology().dim()-1)
boundaries.set_all(0)

top.mark(boundaries, 1)
ds_N = ds(subdomain_data=boundaries) # use in ds_N(1) as in inner(g,v)*ds_N(1)

bottom = AutoSubDomain(lambda x: near(x[1], 0))

boundaries = MeshFunction("size_t", mesh, mesh.topology().dim()-1)
boundaries.set_all(0)

bottom.mark(boundaries, 1)
ds_0 = ds(subdomain_data=boundaries) # use in ds_0(1) as in beta(abs(u))*ds_O(1)

def bottom(x, on_boundary):
    return(on_boundary and near (x[1], 0.0))

bc_bottom = DirichletBC(V, u, bottom)

def left(x, on_boundary):
    return(on_boundary and near (x[0], 0.0))
bc_left = DirichletBC(V, Constant((0, 0, 0)), left)

def right(x, on_boundary):
    return(on_boundary and near (x[0], 5.0))
bc_right = DirichletBC(V, Constant((0, 0, 0)), right)

bcs = [bc_left, bc_right, bc_bottom]

def epsilon(y):
    return 0.5*(nabla_grad(y) + nabla_grad(y).T)

def sigma (y):
    return lmbda*div(y)*Identity(d) + 2*mu*epsilon(y)

S = inner(sigma(y),epsilon(v))*dx - inner((F+u),v)*dx - inner(g,v)*ds_N(1)

solve(S == 0, y, bcs)

J = assemble((0.5*inner(y- y_Desired, y - y_Desired))*dx + alpha / 2 * inner((F+u), v)* dx + beta*abs(u)*ds_0)

I tried to make y_Desired also 3D but then I receive UFLException: Can only integrate scalar expressions. The integrand is a tensor expression with value shape (3,) and free indices with labels ().

Can anyone help me on this?


问:
Error while running espresso test cases more than 150 case failed with an error (Out Of Memory)
When we have more than 150–200 automation test cases written for our application which takes around 1 to 1.5 hours to run completely. There we can face an issue of OOM (Out Of Memory) error while running test cases.

Tried solution methods :

Increasing the RAM size

Android Test Orchestrator

JacocoTestReport

**Increasing the RAM size : **

Increased the RAM size heap memory size in android studio but still it showing the out of memory exception while running the test case.

enter image description here

**
Android Test Orchestrator : **

Implemented the orchestrator test case method. all test cases are running but all test cases are failing.

Reference Link : https://medium.com/globant/oom-out-of-memory-error-while-running-espresso-test-cases-power-of-android-test-orchestrator-721ac7012f86

**JacocoTestReport : **

Implemented the Jacoco test report while running the test cases. It throwing the out of memory exception
while running the test case.

Reference Link :
https://about.codecov.io/blog/code-coverage-for-android-development-using-kotlin-jacoco-github-actions-and-codecov/

enter image description here

Need to run all the testcases Without any error.


问:
Multi feature clustering using optics
While working with optics clistering algorithm, facing issues of outliers.

I have used default ep and min samples, for 2 datasets I am getting 80 percent of datapoints as outlier/noise

How to reduce outliers and capture more and more data to get optimum cluster

Title: Multi feature clustering using optics


问:
Python request cookies setting does not work
I want to crawl the data from this website:'http://www.stcn.com/article/search.html?search_type=all&page_time=1', but the website needs to have cookies on the homepage first, so I first get the cookies he needs from this website('http://www.stcn.com/article/search.html') and set them into the request, but it doesn't work after many attempts.

My code looks like this:

```<code>
import requests

headers = {
    'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36','Host':'www.stcn.com'}
def _getStcnCookie(keyWords='all'):
    url = "http://www.stcn.com/article/search.html"
    data = {'keyword': keyWords}
    r = requests.get(url, data, headers=headers, timeout=10)

    if r.status_code != 200:
        return None
    return requests.utils.dict_from_cookiejar(r.cookies)

def searchStcnData(url,keyWords) :
    myHeader = dict.copy(headers)
    myHeader['X-Requested-With'] = 'XMLHttpRequest'
    cookies = _getStcnCookie(keyWords=keyWords)
    print(cookies)
    jar = requests.cookies.cookiejar_from_dict(cookies)
    data = {'keyword':'Paxlovid', 'page_time': 1, 'search_type': 'all'}
    #Option One
    s = requests.Session()
    response = s.post(url, data, headers=myHeader, timeout=5, cookies=cookies)
    print(response.text)

    # Option two
    # myHeader['Cookie'] = 'advanced-stcn_web=potef1789mm5nqgmd6jc1rcih3; path=/; HttpOnly;'+cookiesStr

    # Option three
    r = requests.post(url, data, headers=myHeader, timeout=5, cookies=cookies)
    print(r.json())
    return r.json()

searchStcnData('http://www.stcn.com/article/search.html?search_type=all&page_time=1','Paxlovid')
</code>```

I've tried options 1, 2, and 3 to no avail.

I set cookies in Postman, and only set 'advanced-stcn_web=5sdfitvu42qggmnjvop4dearj4' can get the data, like this :

```<code>{
    "state": 1,
    "msg": "操作成功",
    "data": "<li class=\"\">\n    <div class=\"content\">\n        <div class=\"tt\">\n            <a href=\"/article/detail/769123.html\" target=\"_blank\">\n  ......
  "page_time": 2
}
</code>```

Body:
I want to crawl the data from this website:'http://www.stcn.com/article/search.html?search_type=all&page_time=1', but the website needs to have cookies on the homepage first, so I first get the cookies he needs from this website('http://www.stcn.com/article/search.html') and set them into the request, but it doesn't work after many attempts.

My code looks like this:

import requests

headers = {
    'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36','Host':'www.stcn.com'}
def _getStcnCookie(keyWords='all'):
    url = "http://www.stcn.com/article/search.html"
    data = {'keyword': keyWords}
    r = requests.get(url, data, headers=headers, timeout=10)

    if r.status_code != 200:
        return None
    return requests.utils.dict_from_cookiejar(r.cookies)

def searchStcnData(url,keyWords) :
    myHeader = dict.copy(headers)
    myHeader['X-Requested-With'] = 'XMLHttpRequest'
    cookies = _getStcnCookie(keyWords=keyWords)
    print(cookies)
    jar = requests.cookies.cookiejar_from_dict(cookies)
    data = {'keyword':'Paxlovid', 'page_time': 1, 'search_type': 'all'}
    #Option One
    s = requests.Session()
    response = s.post(url, data, headers=myHeader, timeout=5, cookies=cookies)
    print(response.text)

    # Option two
    # myHeader['Cookie'] = 'advanced-stcn_web=potef1789mm5nqgmd6jc1rcih3; path=/; HttpOnly;'+cookiesStr

    # Option three
    r = requests.post(url, data, headers=myHeader, timeout=5, cookies=cookies)
    print(r.json())
    return r.json()

searchStcnData('http://www.stcn.com/article/search.html?search_type=all&page_time=1','Paxlovid')

I've tried options 1, 2, and 3 to no avail.

I set cookies in Postman, and only set 'advanced-stcn_web=5sdfitvu42qggmnjvop4dearj4' can get the data, like this :

{
    "state": 1,
    "msg": "操作成功",
    "data": "
\n
\n
\n            \n  ......
  "page_time": 2
}


问:
Rob J Hyndman's Arima function in R vs SARIMAX in python
I am trying to replicate results of the Hyndman's R version of Arima function with SARIMAX function in Python, but the coefficients are not matching given the same dataset.

R code:

md1 = Arima(y, xreg = as.matrix(df[,c('x1', 'x2'), drop = False]), order = c(1,0,1), include mean = TRUE)
```
<p>Python code:</p>
<pre class="lang-py prettyprint-override"><code>md2 = SARIMAX(y, exog = df[np.array(['x1', 'x2']), trend = 'c', mle_regression = True)
</code>```

Body:
I am trying to replicate results of the Hyndman's R version of Arima function with SARIMAX function in Python, but the coefficients are not matching given the same dataset.

R code:

md1 = Arima(y, xreg = as.matrix(df[,c('x1', 'x2'), drop = False]), order = c(1,0,1), include mean = TRUE)

Python code:

md2 = SARIMAX(y, exog = df[np.array(['x1', 'x2']), trend = 'c', mle_regression = True)


问:
How to add a "where class is either of the following classes" selector to an existing selector?
I have the following selector:

```<code>let elements = $(.class1:not(.class2,.class3) a.class4);
</code>```

I also get a string of extra classes to check against:

```<code>let stringOfClasses = ".extraClass1,.extraClass2";
</code>```

I want the original selector to match only if the items has either of the classes separated by comma. So it will find the same elements (i.e. .class1:not(.class2,.class3) a.class4, but also only if they have either extraClass1 or extraClass2.

The following did not work:

```<code>let elements = $(.class1:not(.class2,.class3) a.class4).find(`${stringOfClasses}`);
</code>```

How can I do it?

Example snippet:

let extraClasses =".extraclass1,.extraclass2";

let selectorWithOutExtraClasses = $(`.myselect:not() a.item`);
let selectorWithExtraClasses = $(`.myselect:not() a.item`).find(`${extraClasses}`);

console.log(selectorWithOutExtraClasses.length);
console.log(selectorWithExtraClasses.length);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="myselect">
item
item
item
item
</div></code>```

Body:
I have the following selector:

let elements = $(.class1:not(.class2,.class3) a.class4);

I also get a string of extra classes to check against:

let stringOfClasses = ".extraClass1,.extraClass2";

I want the original selector to match only if the items has either of the classes separated by comma. So it will find the same elements (i.e. .class1:not(.class2,.class3) a.class4, but also only if they have either extraClass1 or extraClass2.

The following did not work:

let elements = $(.class1:not(.class2,.class3) a.class4).find(`${stringOfClasses}`);

How can I do it?

Example snippet:

let extraClasses =".extraclass1,.extraclass2";

let selectorWithOutExtraClasses = $(`.myselect:not() a.item`);
let selectorWithExtraClasses = $(`.myselect:not() a.item`).find(`${extraClasses}`);

console.log(selectorWithOutExtraClasses.length);
console.log(selectorWithExtraClasses.length);

item
item
item
item


问:
npm create-react-app or npx create-react-app is not working
this is the error i got every time
I try all-most everything re-installing npm  re-installing node</p>
```<code>npm ERR! code ENOENT
npm ERR! syscall spawn pwsh
npm ERR! path C:\Users\Dipan\react-data
npm ERR! errno -4058
npm ERR! enoent spawn pwsh ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Dipan\AppData\Local\npm-cache\_logs\2023-01-10T09_37_51_103Z-debug-0.log

</code>```

Body:
this is the error i got every time
I try all-most everything re-installing npm  re-installing node

npm ERR! code ENOENT
npm ERR! syscall spawn pwsh
npm ERR! path C:\Users\Dipan\react-data
npm ERR! errno -4058
npm ERR! enoent spawn pwsh ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Dipan\AppData\Local\npm-cache\_logs\2023-01-10T09_37_51_103Z-debug-0.log


问:
Can't use trial purchase id `android.test.purchased`
I prefer to use android.test.purchased for in-app purchase flow testing. but recently got an error and can't use it, i can't click buy in test box.
This is my code

```<code>ProductDetails productDetails = skuDetailsINAPMap.get(productId);

if (productDetails == null) {
    return "Product ID invalid";
}
ImmutableList<BillingFlowParams.ProductDetailsParams> productDetailsParamsList =
        ImmutableList.of(
                BillingFlowParams.ProductDetailsParams.newBuilder()
                        .setProductDetails(productDetails)
                        .build()
        );

BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
        .setProductDetailsParamsList(productDetailsParamsList)
        .build();

BillingResult billingResult = billingClient.launchBillingFlow(activity, billingFlowParams);
</code>```

Any suggestion or tips would be appreciated.Thanks

image error

Body:
I prefer to use android.test.purchased for in-app purchase flow testing. but recently got an error and can't use it, i can't click buy in test box.
This is my code

ProductDetails productDetails = skuDetailsINAPMap.get(productId);

if (productDetails == null) {
    return "Product ID invalid";
}
ImmutableList<BillingFlowParams.ProductDetailsParams> productDetailsParamsList =
        ImmutableList.of(
                BillingFlowParams.ProductDetailsParams.newBuilder()
                        .setProductDetails(productDetails)
                        .build()
        );

BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
        .setProductDetailsParamsList(productDetailsParamsList)
        .build();

BillingResult billingResult = billingClient.launchBillingFlow(activity, billingFlowParams);

Any suggestion or tips would be appreciated.Thanks

image error


问:
expected string or bytes-like object, got 'NoneType' error on using xhtml2pdf module of python
I am facing the following error while rendering HTML to PDF by using xhtml2pdf of python.

expected string or bytes-like object, got 'NoneType'

Need a valid file name!

''

Need a valid file name!

''

Need a valid file name!

''

Please check the following sample code.

```<code>import sys
from xhtml2pdf import pisa

OUTPUT_FILENAME = "test.pdf"
TEMPLATE_FILE = "templates/test.html"

def html_to_pdf(content, output):

    # Open file to write
    result_file = open(output, "w+b")

    # convert HTML to PDF
    pisa_status = pisa.CreatePDF(
        content,  # the HTML to convert
        dest=result_file,  # file handle to recieve result
    )

    # close output file
    result_file.close()

    result = pisa_status.err

    if not result:
        print("Successfully created PDF")
    else:
        print("Error: unable to create the PDF")

    # return False on success and True on errors
    return result

def from_template(template, output):
    # Reading our template
    source_html = open(template, "r")
    content = source_html.read()  # the HTML to convert
    source_html.close()  # close template file

    html_to_pdf(content, output)

from_template(TEMPLATE_FILE, OUTPUT_FILENAME)
</code>```

Body:
I am facing the following error while rendering HTML to PDF by using xhtml2pdf of python.

expected string or bytes-like object, got 'NoneType'

Need a valid file name!

''

Need a valid file name!

''

Need a valid file name!

''

Please check the following sample code.

import sys
from xhtml2pdf import pisa

OUTPUT_FILENAME = "test.pdf"
TEMPLATE_FILE = "templates/test.html"

def html_to_pdf(content, output):

    # Open file to write
    result_file = open(output, "w+b")

    # convert HTML to PDF
    pisa_status = pisa.CreatePDF(
        content,  # the HTML to convert
        dest=result_file,  # file handle to recieve result
    )

    # close output file
    result_file.close()

    result = pisa_status.err

    if not result:
        print("Successfully created PDF")
    else:
        print("Error: unable to create the PDF")

    # return False on success and True on errors
    return result

def from_template(template, output):
    # Reading our template
    source_html = open(template, "r")
    content = source_html.read()  # the HTML to convert
    source_html.close()  # close template file

    html_to_pdf(content, output)

from_template(TEMPLATE_FILE, OUTPUT_FILENAME)


问:
Tabindex skipps over Link
My HTML5 tabindex skips over a link element. Even when using tabindex=0, the tabindex skips right over and ignores the  element. AFAIK  should already be in the tabindex (even without the tabindex attribute) as long as it has a href attribute.

sample code:

Hello world!

Title: Tabindex skipps over Link


问:
GitHub maven packages integration with Jenkins using GitHub App authentication
Is there a possibility to authenticate to GitHub as an GitHub App and publish packages as the GitHub App identity from Jenkins? Personal access tokens can be used but they use an identity of a separate user.</p>


问:
Node mailer ICS event isn't appearing in outlook
I am trying to send a meeting request using nodemailer, I am able to generate and send an ICS file
when I send it to a gmail account I can see the meeting
But when I send it to an outlook account I only see the attachment, is there a way to send it as a normal meeting request?

Currently I am getting the email as this
current

The result I want
correct result

I've tried this code

my event

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//ical.marudot.com//iCal Event Maker
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Asia/Damascus
LAST-MODIFIED:20201011T015911Z
TZURL:http://tzurl.org/zoneinfo-outlook/Asia/Damascus
X-LIC-LOCATION:Asia/Damascus
BEGIN:STANDARD
TZNAME:EET
TZOFFSETFROM:+0300
TZOFFSETTO:+0200
DTSTART:19701030T000000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1FR
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:EEST
TZOFFSETFROM:+0200
TZOFFSETTO:+0300
DTSTART:19700327T000000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1FR
END:DAYLIGHT
END:VTIMEZONE
BEGIN:VEVENT
DTSTAMP:20230110T090929Z
UID:1673341756244-67351@ical.marudot.com
DTSTART;TZID=Asia/Damascus:20230110T120000
DTEND;TZID=Asia/Damascus:20230110T150000
SUMMARY:Test
URL:lkamslkdmalksdml
DESCRIPTION:asdklmalksmdkl
LOCATION:lkasmdlkaml
END:VEVENT
END:VCALENDAR
</code>```

my code

```<code>const mailOptions = {
    from: 'from@test.com',
    to: 'to@test.com',
    subject: 'Appointment test',
    html: 'Hello',
    icalEvent: {
        filename: 'invitation.ics',
        method: 'request',
        content: content
    }
}

transporter.sendMail(mailOptions, function (error, response) {
    if (error) {
        console.log(error)
    } else {
        console.log('Message sent: ', response)
    }
})

</code>```

Body:
I am trying to send a meeting request using nodemailer, I am able to generate and send an ICS file
when I send it to a gmail account I can see the meeting
But when I send it to an outlook account I only see the attachment, is there a way to send it as a normal meeting request?

Currently I am getting the email as this
current

The result I want
correct result

I've tried this code

my event

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//ical.marudot.com//iCal Event Maker
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Asia/Damascus
LAST-MODIFIED:20201011T015911Z
TZURL:http://tzurl.org/zoneinfo-outlook/Asia/Damascus
X-LIC-LOCATION:Asia/Damascus
BEGIN:STANDARD
TZNAME:EET
TZOFFSETFROM:+0300
TZOFFSETTO:+0200
DTSTART:19701030T000000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1FR
END:STANDARD
BEGIN:DAYLIGHT
TZNAME:EEST
TZOFFSETFROM:+0200
TZOFFSETTO:+0300
DTSTART:19700327T000000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1FR
END:DAYLIGHT
END:VTIMEZONE
BEGIN:VEVENT
DTSTAMP:20230110T090929Z
UID:1673341756244-67351@ical.marudot.com
DTSTART;TZID=Asia/Damascus:20230110T120000
DTEND;TZID=Asia/Damascus:20230110T150000
SUMMARY:Test
URL:lkamslkdmalksdml
DESCRIPTION:asdklmalksmdkl
LOCATION:lkasmdlkaml
END:VEVENT
END:VCALENDAR

my code

const mailOptions = {
    from: 'from@test.com',
    to: 'to@test.com',
    subject: 'Appointment test',
    html: 'Hello',
    icalEvent: {
        filename: 'invitation.ics',
        method: 'request',
        content: content
    }
}

transporter.sendMail(mailOptions, function (error, response) {
    if (error) {
        console.log(error)
    } else {
        console.log('Message sent: ', response)
    }
})


问:
Xcode 14 forces me into Bitcode for Unity builds. Why?
Since I updated Xcode to version 14, it requires that all pods included in my Unity project have been built for Bitcode. This is especially strange since Xcode has deprecated Bitcode now. Can anyone explain why it requires something that it did not require before, if this feature is not recommended anymore? This does not make any sense to me.

I would also appreciate any link to a Unity build script that sets the Bitcode flag automatically on all pods. Thanks.


问:
How do I programmatically get the previous version of an item in a TFS changeset?
Using the TFS APIs it is trivial to loop through changes in a changeset and then get the files using the ServerItem and ChangesetId.

But suppose I want to diff the modified files, how can I get the VersionSpec for the previous versions?

The trick of subtracting one from the ChangesetId seems to break if the file was renamed or branched?

ContentLicense: CC BY-SA 3.0


问:
how useEffect clearup function works in react?
My idea was when user types the email in the input box when stops for 500  milliseconds that time only useEffects side effect will run other wise user continusly types side effects will not run that will clear with help of  cleanUp function. side effects runs frist time when the app starts. After that any dependency changed cleanup function runs therafter  side effects runs. so if i create setTimeout function in the side effects with 500 milliseconds and I clear the timeout function in the cleanup function it will clear the side effect. But when user stops typing in the input box in that time also dependency changed clenup function need to  clear the side effects. But cleanup function runs properly but not clear the side effects side effects also runs how it possible? why cleanup function not clear the side effects in the user stop typing

useEffect(() => {
  const timeoutHandler = setTimeout(() => {
    setFormIsValid(
      enteredEmail.includes("@") && enteredPassword.trim().length > 6
    );
    console.log("side effect");
  }, 500);

  return () => {
    clearTimeout(timeoutHandler);
    console.log("cleanUp function");
  };
}, [enteredEmail, enteredPassword]);
```


问:
AWS cloudwatch MSK metrics -> Firehose
I want to stream some metrics from the namespace AWS/Kafka to Kinesis Firehose and from there to a third-party application.
When I choose the namespace AWS/Kafka, I stream all the metrics from this namespace and it's a ton of data that I don't want.
If I want to choose only two metrics from this namespace (MaxOffsetLag & SumOffsetLag), there is a way to do this?
I heard there is a way by using a log group but I couldn't figure out how.</p>

Title: AWS cloudwatch MSK metrics -> Firehose


问:
Investigating an issue with my Uniswap tokens scraper that errors out after 7 requests to the Graph API
I'm making a scraper that will grab every Uniswap pair and save it to an array using the Graph API.

My problem occurs when I make my 7th request to the API.

Initially, I thought I was being rate limited because I was fetching 1000 tokens at a time, but after adding a 10 second wait between calls and decreasing the fetched tokens from 1000 to 10, it still stops on the 7th loop.
The script works perfectly until this point.

```<code>const axios = require('axios');
const fs = require('fs');

async function getTokens(skip) {
    try {
        const query = `
            query tokens($skip: Int!) {
                tokens(first: 10, skip: $skip) {
                    id
                    name
                    symbol
                }
            }
        `;

        const variables = {
            skip: skip
        };

        const headers = {
            "Content-Type": "application/json"
        };

        const { data } = await axios.post("https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3", {
            query,
            variables
        }, {
            headers
        });

        return data.data.tokens;
    } catch (err) {
        console.error(err);
        return []
    }
}

async function saveTokens(tokens) {
    try {
        await fs.promises.writeFile("uniTokens.json", JSON.stringify(tokens), { flag: "w" });
    } catch (err) {
        console.error(err);
    }
}

async function main() {
    let skip = 0;
    let tokens = [];
    const retrievedIds = new Set();

    while (true) {
        const newTokens = await getTokens(skip);
        if (newTokens.length === 0) {
            console.log("Reached end of tokens, finishing up...");
            break;
        }

        // Only save tokens that haven't been retrieved before
        const newIds = new Set(newTokens.map(token => token.id));
        newIds.forEach(id => {
            if (!retrievedIds.has(id)) {
                tokens.push(newTokens.find(token => token.id === id));
                retrievedIds.add(id);
            }
        });

        console.log(`Retrieved ${tokens.length} tokens`);
        await saveTokens(tokens);
        skip += 1000;
        // delay the next request by 10 seconds
        //await new Promise(resolve => setTimeout(resolve, 10000));
    }
}

main();

</code>```

This is the error that it produces:

```<code>TypeError: Cannot read properties of undefined (reading 'tokens')
    at getTokens (/root/unipairs/uni:31:26)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async main (/root/unipairs/uni:52:27)
Reached end of tokens, finishing up...
</code>```

Body:
I'm making a scraper that will grab every Uniswap pair and save it to an array using the Graph API.

My problem occurs when I make my 7th request to the API.

Initially, I thought I was being rate limited because I was fetching 1000 tokens at a time, but after adding a 10 second wait between calls and decreasing the fetched tokens from 1000 to 10, it still stops on the 7th loop.
The script works perfectly until this point.

const axios = require('axios');
const fs = require('fs');

async function getTokens(skip) {
    try {
        const query = `
            query tokens($skip: Int!) {
                tokens(first: 10, skip: $skip) {
                    id
                    name
                    symbol
                }
            }
        `;

        const variables = {
            skip: skip
        };

        const headers = {
            "Content-Type": "application/json"
        };

        const { data } = await axios.post("https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3", {
            query,
            variables
        }, {
            headers
        });

        return data.data.tokens;
    } catch (err) {
        console.error(err);
        return []
    }
}

async function saveTokens(tokens) {
    try {
        await fs.promises.writeFile("uniTokens.json", JSON.stringify(tokens), { flag: "w" });
    } catch (err) {
        console.error(err);
    }
}

async function main() {
    let skip = 0;
    let tokens = [];
    const retrievedIds = new Set();

    while (true) {
        const newTokens = await getTokens(skip);
        if (newTokens.length === 0) {
            console.log("Reached end of tokens, finishing up...");
            break;
        }

        // Only save tokens that haven't been retrieved before
        const newIds = new Set(newTokens.map(token => token.id));
        newIds.forEach(id => {
            if (!retrievedIds.has(id)) {
                tokens.push(newTokens.find(token => token.id === id));
                retrievedIds.add(id);
            }
        });

        console.log(`Retrieved ${tokens.length} tokens`);
        await saveTokens(tokens);
        skip += 1000;
        // delay the next request by 10 seconds
        //await new Promise(resolve => setTimeout(resolve, 10000));
    }
}

main();

This is the error that it produces:

TypeError: Cannot read properties of undefined (reading 'tokens')
    at getTokens (/root/unipairs/uni:31:26)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async main (/root/unipairs/uni:52:27)
Reached end of tokens, finishing up...


问:
Getting " ValueError: No route found for path 'socket/order' ' " in Django Channels when trying to connect with Angular frontend
I am trying Django Channels for the first time. I am trying to connect it with an existing Angular frontend application. But for some reason the routing isn't working I cannot figure out why. I have written the codes exactly how the Django Channels documentation instructs to.

The error message goes as such -

```<code>Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
January 10, 2023 - 15:34:50
Django version 4.1.3, using settings 'BrokerBackEnd.settings'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
WebSocket HANDSHAKING /socket/order [127.0.0.1:63732]
HTTP GET /orders/ 200 [0.07, 127.0.0.1:63731]
Exception inside application: No route found for path 'socket/order'.
Traceback (most recent call last):
  File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__
    return await self.application(scope, receive, send)
  File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 62, in __call__
    return await application(scope, receive, send)
  File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 134, in __call__
    raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'socket/order'.
WebSocket DISCONNECT /socket/order [127.0.0.1:63732]
</code>```

Would really appreciate if anyone could suggest anything. Thank you.

settings.py

```<code>INSTALLED_APPS = [
    'daphne',
    'channels',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',

    'Orders'
]

ASGI_APPLICATION = 'BrokerBackEnd.asgi.application'
</code>```

asgi.py

```<code>import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
import Orders.routing as route

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

application = ProtocolTypeRouter({
    'http': get_asgi_application(),

    'websocket': URLRouter(
            route.websocket_urlpatterns
        )
})
</code>```

consumer.py

```<code>class OrderConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def receive(self, text_data=None, bytes_data=None):
        self.send(text_data="Message = " + text_data)

    def disconnect(self, code):
        return super().disconnect(code)
</code>```

routing.py

```<code>from django.urls import re_path
from .consumer import OrderConsumer

websocket_urlpatterns = [
    re_path(r"socket/order/", OrderConsumer.as_asgi())
]
</code>```

This is the frontend code -

```<code>import { catchError, map } from 'rxjs/operators';
import { Injectable } from "@angular/core";
import { EMPTY, Observable } from "rxjs";
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { Order } from './order.model';
import { MatSnackBar } from '@angular/material/snack-bar';

@Injectable({
    providedIn: 'root'
})
export class OrderWebSocketService {

    myWebSocket: WebSocketSubject<Order> = webSocket('ws://localhost:8000/socket/order');

    constructor(private snackBar: MatSnackBar) { }

    public connect(): Observable<Order> {
        return this.myWebSocket.asObservable().pipe(
            map((obj) => obj),
            catchError((error) => this.errorHandler(error))
        );
    }

    public close(): void {
        this.myWebSocket.complete();
    }

    errorHandler(e: any): Observable<any> {
        this.showMessage('Something wrong happened with websocket!', true);
        return EMPTY;
    }

    showMessage(msg: string, isError: boolean = false): void {
        this.snackBar.open(msg, 'X', {
            duration: 3000,
            horizontalPosition: "right",
            verticalPosition: "top",
            panelClass: isError ? ['msg-error'] : ['msg-success']
        });
    }

}
</code>```

Body:
I am trying Django Channels for the first time. I am trying to connect it with an existing Angular frontend application. But for some reason the routing isn't working I cannot figure out why. I have written the codes exactly how the Django Channels documentation instructs to.

The error message goes as such -

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
January 10, 2023 - 15:34:50
Django version 4.1.3, using settings 'BrokerBackEnd.settings'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
WebSocket HANDSHAKING /socket/order [127.0.0.1:63732]
HTTP GET /orders/ 200 [0.07, 127.0.0.1:63731]
Exception inside application: No route found for path 'socket/order'.
Traceback (most recent call last):
  File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__
    return await self.application(scope, receive, send)
  File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 62, in __call__
    return await application(scope, receive, send)
  File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 134, in __call__
    raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'socket/order'.
WebSocket DISCONNECT /socket/order [127.0.0.1:63732]

Would really appreciate if anyone could suggest anything. Thank you.

settings.py

INSTALLED_APPS = [
    'daphne',
    'channels',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',

    'Orders'
]

ASGI_APPLICATION = 'BrokerBackEnd.asgi.application'

asgi.py

import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
import Orders.routing as route

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

application = ProtocolTypeRouter({
    'http': get_asgi_application(),

    'websocket': URLRouter(
            route.websocket_urlpatterns
        )
})

consumer.py

class OrderConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def receive(self, text_data=None, bytes_data=None):
        self.send(text_data="Message = " + text_data)

    def disconnect(self, code):
        return super().disconnect(code)

routing.py

from django.urls import re_path
from .consumer import OrderConsumer

websocket_urlpatterns = [
    re_path(r"socket/order/", OrderConsumer.as_asgi())
]

This is the frontend code -

import { catchError, map } from 'rxjs/operators';
import { Injectable } from "@angular/core";
import { EMPTY, Observable } from "rxjs";
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { Order } from './order.model';
import { MatSnackBar } from '@angular/material/snack-bar';

@Injectable({
    providedIn: 'root'
})
export class OrderWebSocketService {

    myWebSocket: WebSocketSubject<Order> = webSocket('ws://localhost:8000/socket/order');

    constructor(private snackBar: MatSnackBar) { }

    public connect(): Observable<Order> {
        return this.myWebSocket.asObservable().pipe(
            map((obj) => obj),
            catchError((error) => this.errorHandler(error))
        );
    }

    public close(): void {
        this.myWebSocket.complete();
    }

    errorHandler(e: any): Observable<any> {
        this.showMessage('Something wrong happened with websocket!', true);
        return EMPTY;
    }

    showMessage(msg: string, isError: boolean = false): void {
        this.snackBar.open(msg, 'X', {
            duration: 3000,
            horizontalPosition: "right",
            verticalPosition: "top",
            panelClass: isError ? ['msg-error'] : ['msg-success']
        });
    }

}


问:
Call `recvfrom` multiple times from different task on the same server socket
I am developing a system whereby I have to communicate with 18-different subsystems.

All 18-subsystems are UDP clients. I have created UDP server.

I'm using recvfrom to receive data these 18-subsystems.

```<code>char buf[1000];
int buf_len = 1000;
int sockfd;
//Code to configure socket
//Code to create Socket
//Code to bind socket
FOREVER
{
bytes_read = recvfrom(sockfd, (void *)buf, buf_len, 0,
                     (struct sockaddr *)&client_addr, &sock_addr_size);
//Spawn New Task to process data
}
</code>```

I have three options process received data

Process the data immediately after receiving new data. This approach is not feasible as it will increase the latency in processing message and system will loose its deterministic hard-real time capabilities.

Spawn a new task after receiving new data. This new task will process incoming data and forward the processed data to appropriate task that will consume this data.

Create multiple task each running recvfrom on the same socket and will process data immediately after receiving the new data and forward the processed data to appropriate task that will consume this data.

I am more inclined towards Option 3. I wish to know is it allowed in vxWorks to call recvfrom multiple times from different task (disjoint task) on the same server socket or will it cause some complication.

Body:
I am developing a system whereby I have to communicate with 18-different subsystems.

All 18-subsystems are UDP clients. I have created UDP server.

I'm using recvfrom to receive data these 18-subsystems.

char buf[1000];
int buf_len = 1000;
int sockfd;
//Code to configure socket
//Code to create Socket
//Code to bind socket
FOREVER
{
bytes_read = recvfrom(sockfd, (void *)buf, buf_len, 0,
                     (struct sockaddr *)&client_addr, &sock_addr_size);
//Spawn New Task to process data
}

I have three options process received data

Process the data immediately after receiving new data. This approach is not feasible as it will increase the latency in processing message and system will loose its deterministic hard-real time capabilities.

Spawn a new task after receiving new data. This new task will process incoming data and forward the processed data to appropriate task that will consume this data.

Create multiple task each running recvfrom on the same socket and will process data immediately after receiving the new data and forward the processed data to appropriate task that will consume this data.

I am more inclined towards Option 3. I wish to know is it allowed in vxWorks to call recvfrom multiple times from different task (disjoint task) on the same server socket or will it cause some complication.


问:
Not receiving notifications in thread when sending messages as bot
I am facing a weird bug when using my bot app to send messages in a thread.

I am sending DMs as a bot app user - the message will appear in the app channel.

When I send the first message, I get a notification from this message (right).
I get the thread ts, and then send a message again as a bot, replying in a thread. I receive the message in the channel, as a thread, but I don't get any notification.

Next I reply it as the user receiving this DM - works ok

Then, from the moment I reply to this thread, after the first interaction from the user, I start to get notifications from my own bot messages.

The issue? I'd like to get notifications from the start, doesn't matter if the user interacted with me in this thread or not. Any way to do it?

Thanks!

I am using https://slack.com/api/chat.postMessage to do it all.


问:
How to exclude PII data and some Org level words from translation
I am building a translation pipeline for my organization using Helsinki-NLP Out Of Box translation models (no fine-tuning involved). I have a requirement where I have to retain certain PII data (like email, mobile number, and geographic data) and a few organization-based glossary words as-is in the translated text.

I understand that the quality of translation might get affected but I am ok with it.

Can someone suggest a way to achieve this with pre-trained models?


问:
Generate .aab file for cordova application in visusal studio 2017
I want to add android application to play store , I have apk file when run the application in visual studio 2017 ,but play store required .aab file , So how to generate aab file from visual studio to submit to play store</p>


问:
Why does the python list parsing work differently inline?
In our project we try to work with the output of an aggregation, which is more challenging than expected. The following code throws an IndexError, even though our object looks (when using the print command) like this [{'_id': None, 'sum': 2700}].

output = get_mongo_collection().aggregate([
        {'$match': {'topic_name': topic, 'internal_id': self.internal_id }},
        {'$group': {'_id': None, 'sum': {'$sum': '$payload.val'}}}])

print(list(output)[0]["sum"])
```
<p>Things we tried and were confused by</p>
<pre class="lang-py prettyprint-override"><code>out = list(output)
print(out)  # [{'_id': None, 'sum': 2700}]
print(len(out))  # 1
print(out[0]["sum"])  # 2700

print(list(output))  # []
print(len(list(output)))  # 0
</code>```

It seems that this has something to do with the inline list keyword usage. Maybe this has something to do with the pymongo aggregation object? Because trying to reproduce it with a list created manually, it behaves as expected.

Body:
In our project we try to work with the output of an aggregation, which is more challenging than expected. The following code throws an IndexError, even though our object looks (when using the print command) like this [{'_id': None, 'sum': 2700}].

output = get_mongo_collection().aggregate([
        {'$match': {'topic_name': topic, 'internal_id': self.internal_id }},
        {'$group': {'_id': None, 'sum': {'$sum': '$payload.val'}}}])

print(list(output)[0]["sum"])

Things we tried and were confused by

out = list(output)
print(out)  # [{'_id': None, 'sum': 2700}]
print(len(out))  # 1
print(out[0]["sum"])  # 2700

print(list(output))  # []
print(len(list(output)))  # 0

It seems that this has something to do with the inline list keyword usage. Maybe this has something to do with the pymongo aggregation object? Because trying to reproduce it with a list created manually, it behaves as expected.


问:
Is gitlab-ci.yml extends keyword always parsed first in a job?
Here is a sample of gitlab-yml file:

```<code>.job1:
  script:
    - |-
      echo "1"
      echo "2"
  extends:
    - .job2
    - .job3
    - .job4
  allow_failure: true
</code>```

I would like to run script object first but seems that extends object has priority and always runs first.

Any idea how I can make jobs within executes to run after my scripts have executed within the same job?

Body:
Here is a sample of gitlab-yml file:

.job1:
  script:
    - |-
      echo "1"
      echo "2"
  extends:
    - .job2
    - .job3
    - .job4
  allow_failure: true

I would like to run script object first but seems that extends object has priority and always runs first.

Any idea how I can make jobs within executes to run after my scripts have executed within the same job?


问:
JsonSerializer not throwing error when using enums C#
I have a class with an enum and this class is used as an argument for an endpoint.

Class with Enum

```<code>public enum ChangeTime
{
   Immediate, Later
}

public class Request
{
    public ChangeTime ChangeTime {get; set; }
}
</code>```

The Endpoint

```<code>[HttpPost("test")]
public async Task<ActionResult> Post([FromBody]Request request)

</code>```

The Request
{
"currency": "2"
}

When I send this request rather than returning an error as the enum for that value does not exist it sets the ChangeTime variable as Immediate. I have searched the web for this and seen various documents stating that this has been resolved in version 5.0 of .net which rejects enums with undefined values, but version 3.1 model binding succeeds. A work around is I could convert changetime to a string type and then do the conversion, check and throw error manually later on in a service or whatever as part of validation but will incur unnecessary performance penalties on a request that will rejected anyway. Is there a cleaner way around this?

Body:
I have a class with an enum and this class is used as an argument for an endpoint.

Class with Enum

public enum ChangeTime
{
   Immediate, Later
}

public class Request
{
    public ChangeTime ChangeTime {get; set; }
}

The Endpoint

[HttpPost("test")]
public async Task<ActionResult> Post([FromBody]Request request)

The Request
{
"currency": "2"
}

When I send this request rather than returning an error as the enum for that value does not exist it sets the ChangeTime variable as Immediate. I have searched the web for this and seen various documents stating that this has been resolved in version 5.0 of .net which rejects enums with undefined values, but version 3.1 model binding succeeds. A work around is I could convert changetime to a string type and then do the conversion, check and throw error manually later on in a service or whatever as part of validation but will incur unnecessary performance penalties on a request that will rejected anyway. Is there a cleaner way around this?


问:
Can formulas reference a duplicate spreadsheet with different names
I am creating a dashboard that I want to pull data from a daily updated external spreadsheet.

The format is identical each time, however just the data is different and sometimes size of the tables.

Would excel have issues pulling data from an external doc if I changed the file each day, even if the format is identical?

I have tried doing this intra-spreadsheet (copy and past the data in) but the demands are more complex now.


问:
Chrome mobile annoying popup to open Android app intent
Let's assume we have installed Android app in the mobile phone with intent filter scheme android-app-scheme and some registered host with path pattern in data of intent filter.

If we use this code in webpage for the Android Chrome:

```<code>   addEventListener("load", (event) => {
            setTimeout(() => {
              window.location.href = "android-app-scheme://some/url/intent"
            }, 5000);
    });
</code>```

Annoying popup will appear to ask permission to open the app ("this website wants to open the ... app"):

Interestingly if we just use direct link for example Open App

And user will click explicitly the link then no popup will appear and app will launch straightaway.

Is there any way to avoid this popup without asking user about explicit click?

Body:
Let's assume we have installed Android app in the mobile phone with intent filter scheme android-app-scheme and some registered host with path pattern in data of intent filter.

If we use this code in webpage for the Android Chrome:

   addEventListener("load", (event) => {
            setTimeout(() => {
              window.location.href = "android-app-scheme://some/url/intent"
            }, 5000);
    });

Annoying popup will appear to ask permission to open the app ("this website wants to open the ... app"):

Interestingly if we just use direct link for example Open App

And user will click explicitly the link then no popup will appear and app will launch straightaway.

Is there any way to avoid this popup without asking user about explicit click?


问:
On cmd, the files doesn't open everytime, why?
I'm trying to open some files on cmd, like "file name.docx". Some of files are opened but some of aren't. I didn't get an error.
Here is ss:
cmd ss
first one is didn't open.
second one is opened.</p>


问:
create-react-app fails for various NodeJS versions
I am trying to create a React app as per this guide. However, whichever node version I choose with nvm it always fails with an error. v16.19.0:

```<code>Creating a new React app in /home/user/react-deploy.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

(#########⠂⠂⠂⠂⠂⠂⠂⠂⠂) ⠸ reify:fsevents: sill reify mark deleted [ '/home/user/react-deploy/node_modules/fsevents' ]
Aborting installation.
  npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file... node_modules
Deleting generated file... package.json
Deleting react-deploy/ from /home/user
Done.
</code>```

With node v14.21.0, it gets stuck at

```<code>[   ...............] | fetchMetadata: sill resolveWithNewModule source-map@0.6.1 checking installable status
</code>```

v14.15.0:

```<code>[      ............] | diffTrees: sill install generateActionsToTake
</code>```

v18.13.0 and v18.0.0:

```<code>node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)
</code>```

My guess is, my Ubuntu version may be too old (18.04) or I should not have done sudo npm clean -f in the past.

Edit

I found out that the error occurs trying to install react-scripts.

Body:
I am trying to create a React app as per this guide. However, whichever node version I choose with nvm it always fails with an error. v16.19.0:

Creating a new React app in /home/user/react-deploy.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

(#########⠂⠂⠂⠂⠂⠂⠂⠂⠂) ⠸ reify:fsevents: sill reify mark deleted [ '/home/user/react-deploy/node_modules/fsevents' ]
Aborting installation.
  npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file... node_modules
Deleting generated file... package.json
Deleting react-deploy/ from /home/user
Done.

With node v14.21.0, it gets stuck at

[   ...............] | fetchMetadata: sill resolveWithNewModule source-map@0.6.1 checking installable status

v14.15.0:

[      ............] | diffTrees: sill install generateActionsToTake

v18.13.0 and v18.0.0:

node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

My guess is, my Ubuntu version may be too old (18.04) or I should not have done sudo npm clean -f in the past.

Edit

I found out that the error occurs trying to install react-scripts.


问:
Excluding or filtering out ranges from search in Javascript Word API
I am working on a Word Add-in which uses the Javascript Word API.

I have a function which searches for all template tags which use the syntax {{tag}} and returns a Word.RangeCollection object.

```<code>const tagsToExclude = context.document.body.search("[{][{]*[}][}]", { matchWildcards: true });tagsToExclude.load("text");

await context.sync();
</code>```

I would like to perform an additional search on the document that excludes the ranges found by this initial search.

In pseudocode, something to this effect?

```<code>wholeDoc = document.body.search(*);

cleanedDoc = wholeDoc.filter(exclude=tagsToExclude)
</code>```

I want to perform an additional search on the whole document, bar the ranges that were included in the tags to exclude search, but I'm not sure it's possible with the word API.

I have reviewed the API documentation for hours and can't seem to understand if there are coordinates associated with the range objects and whether I should be storing them in an array, then deleting them, or what.

Any direction is greatly appreciated.

Body:
I am working on a Word Add-in which uses the Javascript Word API.

I have a function which searches for all template tags which use the syntax {{tag}} and returns a Word.RangeCollection object.

const tagsToExclude = context.document.body.search("[{][{]*[}][}]", { matchWildcards: true });tagsToExclude.load("text");

await context.sync();

I would like to perform an additional search on the document that excludes the ranges found by this initial search.

In pseudocode, something to this effect?

wholeDoc = document.body.search(*);

cleanedDoc = wholeDoc.filter(exclude=tagsToExclude)

I want to perform an additional search on the whole document, bar the ranges that were included in the tags to exclude search, but I'm not sure it's possible with the word API.

I have reviewed the API documentation for hours and can't seem to understand if there are coordinates associated with the range objects and whether I should be storing them in an array, then deleting them, or what.

Any direction is greatly appreciated.


问:
React Native Document Picker Android 7 crash
I have a problem with react-native-document-picker library (v.8.1.3) and Android 7, React Native version 0.63.5.

When I try to launch the plugin to open system folders and pick a file, I get this error. It happens exclusively on Android 7 Nougat.

error screenshot

I tried to downgrade the library, searched git and other stack threads but found nothing about it.


问:
how to configure .ssh/config file when login remotely a target server via a jump machine using vscode-remote
I can not login my target machine due to Intranet limitation. So I need to login a jump machine and use ssh on it to login my target machine. How can I use vscode Remote-ssh extension to login target machine by specific setting in .ssh/config file?</p>