问:
Webpack external module in microfrontend/ multirepos angular gives an error on build
I have created a Angular project to call the microfrontend from other running angular project. I have import the module in my app by using webpack.config.js.
It is working well locally but failed on production build.

When I run ng build it throws exception:

```<code>An unhandled exception occurred: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
See "C:\Users\baps\AppData\Local\Temp\ng-8vJVWd\angular-errors.log" for further details.

[error] HookWebpackError: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at makeWebpackError (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\HookWebpackError.js:48:9)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\Compilation.js:3057:12
    at eval (eval at create (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:98:1)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
-- inner error --
Error: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at failureErrorWithLog (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1557:15)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1346:29
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:637:9
    at handleIncomingPacket (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:734:9)
    at Socket.readFromStdout (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:604:7)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:284:9)
    at Socket.Readable.push (_stream_readable.js:223:10)
    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)
</code>```

答:
Had the same issue in my project. Turns out it was an Angular issue related to .browserslistrc.

Remove the ios_saf 15.2-15.3 & # last 2 Safari major version from your .browserslistrc file.

If the error still persists, check out this thread: https://github.com/angular/angular-cli/issues/22606

Body:
I have created a Angular project to call the microfrontend from other running angular project. I have import the module in my app by using webpack.config.js.
It is working well locally but failed on production build.

When I run ng build it throws exception:

An unhandled exception occurred: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
See "C:\Users\baps\AppData\Local\Temp\ng-8vJVWd\angular-errors.log" for further details.

[error] HookWebpackError: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at makeWebpackError (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\HookWebpackError.js:48:9)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\Compilation.js:3057:12
    at eval (eval at create (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:98:1)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
-- inner error --
Error: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at failureErrorWithLog (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1557:15)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1346:29
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:637:9
    at handleIncomingPacket (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:734:9)
    at Socket.readFromStdout (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:604:7)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:284:9)
    at Socket.Readable.push (_stream_readable.js:223:10)
    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)


来源: stackexchange

问:
Difference between two codes and InputMismatchException
I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:

1st one with the Exception Error:

```<code>public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName, completeName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your complete name and your age: ");

    completeName = sc.next();
    age = sc.nextInt();

    System.out.println("Your complete name is: " + completeName);
    System.out.println("Your age is: " + age);

}
</code>```

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your complete name and your age:

Peter Henrik 22

(InputMismatchException)

2nd one with no error:

```<code>public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your age: ");

    age = sc.nextInt();

    System.out.println("Your complete name is: " + firstName + " " + lastName);
    System.out.println("Your age is: " + age);

}
</code>```

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your age:

22

Your complete name is: Peter Henrik

Your age is: 22

答:
Your first code throws InputMismatchException because sc.next() reads the first complete token ("Peter") up to the whitespace (since whitespace is the default delimiter for Scanner in Java), thus after that, the sc.nextInt() method will read "Henrik" which is a String unlike your expectation to read the age (22).

Here's what you can do instead in order to read the complete name of the user as well as the age [CONDITION: You'll have to enter age in a new line]:

```<code>public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String firstName, lastName,completeName;
int age;

System.out.println("Please enter your first name: ");

firstName = sc.nextLine();

System.out.println("Please enter your last name: ");

lastName = sc.nextLine();

System.out.println("Please enter your complete name: ");

completeName = sc.nextLine();

System.out.println("Please enter your age: ");

age = sc.nextInt();

System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
</code>```

}

PS: An alternate solution can be to read the complete name and the age in a single line as you did and then split up the tokens using the String split() method in Java.

ContentLicense: CC BY-SA 4.0

Body:
I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:

1st one with the Exception Error:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName, completeName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your complete name and your age: ");

    completeName = sc.next();
    age = sc.nextInt();

    System.out.println("Your complete name is: " + completeName);
    System.out.println("Your age is: " + age);

}

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your complete name and your age:

Peter Henrik 22

(InputMismatchException)

2nd one with no error:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your age: ");

    age = sc.nextInt();

    System.out.println("Your complete name is: " + firstName + " " + lastName);
    System.out.println("Your age is: " + age);

}

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your age:

22

Your complete name is: Peter Henrik

Your age is: 22

Body:
Your first code throws InputMismatchException because sc.next() reads the first complete token ("Peter") up to the whitespace (since whitespace is the default delimiter for Scanner in Java), thus after that, the sc.nextInt() method will read "Henrik" which is a String unlike your expectation to read the age (22).

Here's what you can do instead in order to read the complete name of the user as well as the age [CONDITION: You'll have to enter age in a new line]:

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String firstName, lastName,completeName;
int age;

System.out.println("Please enter your first name: ");

firstName = sc.nextLine();

System.out.println("Please enter your last name: ");

lastName = sc.nextLine();

System.out.println("Please enter your complete name: ");

completeName = sc.nextLine();

System.out.println("Please enter your age: ");

age = sc.nextInt();

System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);

}

PS: An alternate solution can be to read the complete name and the age in a single line as you did and then split up the tokens using the String split() method in Java.


问:
FCM Message not Received on iOS App when sent to a topic
I want to send notifications with FCM to an iOS App. It works fine when I send it to the token, but it doesn't work when I send it to a topic. I tried subscribing the App to the topics using this:

```<code>string[] topics = { "all", "test" };
CrossFirebasePushNotification.Current.Subscribe(topics);
</code>```

(This is using the Plugin.FirebasePushNotification) or using this:

```<code>string[] tokens = { e.Token };
FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(tokens, "test");
FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(tokens, "all");
</code>```

(This is using FirebaseAdmin) It's both in the App.xaml.cs, the first one beeing under InitializeComponent(); and the second one beeing in OnTokenRefresh. It works fine on android, but not on iOS. Keep in mind, that e.Token is the Token. I even tried to subscribe in the AppDelegate.cs, but it didn't work there either. I think it could be because it tries to subscribe before I even said "Yes" on the device so it can send me Notifications. I'm using an iPhone SE with iOS 15.3.
Thanks for your help!

答: I figured it out. In the AppDelegate.cs you can override the RegisteredForRemoteNotifications and you can just subscribe there. This means, it will subscribe if the user grants the permission to send remote notifications. After that it worked perfectly.

Body:
I want to send notifications with FCM to an iOS App. It works fine when I send it to the token, but it doesn't work when I send it to a topic. I tried subscribing the App to the topics using this:

string[] topics = { "all", "test" };
CrossFirebasePushNotification.Current.Subscribe(topics);

(This is using the Plugin.FirebasePushNotification) or using this:

string[] tokens = { e.Token };
FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(tokens, "test");
FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(tokens, "all");

(This is using FirebaseAdmin) It's both in the App.xaml.cs, the first one beeing under InitializeComponent(); and the second one beeing in OnTokenRefresh. It works fine on android, but not on iOS. Keep in mind, that e.Token is the Token. I even tried to subscribe in the AppDelegate.cs, but it didn't work there either. I think it could be because it tries to subscribe before I even said "Yes" on the device so it can send me Notifications. I'm using an iPhone SE with iOS 15.3.
Thanks for your help!


问:
problem while creating button with many divs

This is the menu I'm trying to build. Now I'm confused and can't figure out how to make it.

One div (blue arrow) needs negative margin to get outside the box, another div for blue button background and inside the button two another divs or spans for the text colors. But on hover they need to look same (white color).

I've tried many times to build it but i failed. I get some bugs while loading. Maybe it need any jquery code but I'm very new on it, and I have no idea what to do.

I'm working local and I can't give any link to show it, but there is an image of what I want to make.

I hope you understand me because my English is not good.

答:
It seems like you've got a good clue of what you want to do. If I understand correctly your problem is everything turning white on hover.

There should be one div that contains all the others, you can change its children on hover without using Javascript like so.

If you for example have this HTML:

```<code><div class="parent">

    <span class="child_black">I'm black</span>
    <span class="child_red">I'm red</span>

</div>
</code>```

You would use the following CSS to change the color of both children to white on hover:

```<code>.child_black {
    color: #000;
}

.child_red {
    color: #f00;
}

.parent:hover .child_black, .parent:hover .child_red {
    color: #fff;
}
</code>```

http://jsfiddle.net/ptUkg/

You can use the same technique to show and hide the blue arrow on the left.

For just the color this would work too, but not for the arrow:

just for the sake of alternatives, I wouldn't recommend this

```<code>.parent:hover {
    color: #fff !important;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It seems like you've got a good clue of what you want to do. If I understand correctly your problem is everything turning white on hover.

There should be one div that contains all the others, you can change its children on hover without using Javascript like so.

If you for example have this HTML:

<div class="parent">

    <span class="child_black">I'm black</span>
    <span class="child_red">I'm red</span>

</div>

You would use the following CSS to change the color of both children to white on hover:

.child_black {
    color: #000;
}

.child_red {
    color: #f00;
}

.parent:hover .child_black, .parent:hover .child_red {
    color: #fff;
}

http://jsfiddle.net/ptUkg/

You can use the same technique to show and hide the blue arrow on the left.

For just the color this would work too, but not for the arrow:

just for the sake of alternatives, I wouldn't recommend this

.parent:hover {
    color: #fff !important;
}


问:
Network throttling with chrome and selenium
Google Chrome 38 introduced the new "Device Mode & Mobile Emulation" functionality in devtools. In addition to choosing a device for emulation, it is also possible to emulate different network conditions:

Optimizing your site's performance under varying network conditions is
  a key aspect of developing for a mobile audience.

Device mode's network conditioning allows you to test your site on a
  variety of network connections, including Edge, 3G, and even offline.
  Select a connection from the preset dropdown to apply network
  throttling and latency manipulation.

For example, we can set it to be like in good old days - GPRS 50 Kbps:

Now we have a good use case for it - we have an internal application for network speed testing. And this new emulation functionality is very helpful for manual testing. But, we'd like to automate it.

Question is:

Is it possible to start chrome via selenium with specified network conditions? Is it something that can be controlled through chrome preferences or command-line arguments?

There are certainly multiple options to simulate slow internet connection, but the question is specifically about chrome+selenium.

答:
Inspired by the answer from TridentTrue, here is an updated version for Selenium 4.0.0 in C#. If anyone knows how to use it for alpha7 and upwards without beeing version specific feel free to update this. :)

```<code>public void LimitNetwork(int latencyInMilliseconds, long downloadLimitMbps, long uploadLimitMbps)
{
    IDevTools devTools = driver as IDevTools;
    session = devTools.CreateDevToolsSession();
    session.Network.Enable(new EnableCommandSettings());

    EmulateNetworkConditionsCommandSettings command = new EmulateNetworkConditionsCommandSettings();

    command.Latency = latencyInMilliseconds;
    command.DownloadThroughput = downloadLimitMbps * 125000; // Mbps to bytes per second
    command.UploadThroughput = uploadLimitMbps * 125000; // Mbps to bytes per second
    command.Offline = false;

    session.Network.EmulateNetworkConditions(command);
}
</code>```

Update: After I had implemented this for my own, I found a really good article to get an overview in Selenium 4.0, also in Emulating network conditions.

Update 2: My issue was that I forgot to add the Network.Enable command, so don't forget to call it before you do the other stuff.
I have updated the code. :)

Body:
Inspired by the answer from TridentTrue, here is an updated version for Selenium 4.0.0 in C#. If anyone knows how to use it for alpha7 and upwards without beeing version specific feel free to update this. :)

public void LimitNetwork(int latencyInMilliseconds, long downloadLimitMbps, long uploadLimitMbps)
{
    IDevTools devTools = driver as IDevTools;
    session = devTools.CreateDevToolsSession();
    session.Network.Enable(new EnableCommandSettings());

    EmulateNetworkConditionsCommandSettings command = new EmulateNetworkConditionsCommandSettings();

    command.Latency = latencyInMilliseconds;
    command.DownloadThroughput = downloadLimitMbps * 125000; // Mbps to bytes per second
    command.UploadThroughput = uploadLimitMbps * 125000; // Mbps to bytes per second
    command.Offline = false;

    session.Network.EmulateNetworkConditions(command);
}

Update: After I had implemented this for my own, I found a really good article to get an overview in Selenium 4.0, also in Emulating network conditions.

Update 2: My issue was that I forgot to add the Network.Enable command, so don't forget to call it before you do the other stuff.
I have updated the code. :)


问:
Add classpath in manifest using Gradle
I would like my Gradle build script to add the complete Classpath to the manifest file contained in JAR file created after the build.

Example:

```<code>Manifest-Version: 1.0
Class-Path: MyProject.jar SomeLibrary.jar AnotherLib.jar
</code>```

My build script already add some information to the manifest this way:

```<code>jar {
    manifest {
        attributes("Implementation-Title": project.name,
            "Implementation-Version": version,
            "Main-Class": mainClassName,
    }
}
</code>```

How do I get the list of dependencies to add to the manifest?

This page of Java tutorials describes more in detail how and why adding classpath to the manifest: Adding Classes to the JAR File's Classpath

答:
Here is another solution for Kotlin DSL (build.gradle.kts).

When running your app, the library files are supposed to be in libs/ subdirectory of the app.

```<code>tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    manifest.attributes["Class-Path"] = configurations
        .runtimeClasspath
        .get()
        .joinToString(separator = " ") { file ->
            "libs/${file.name}"
        }
}
</code>```

Title: Add classpath in manifest using Gradle

Body:
I would like my Gradle build script to add the complete Classpath to the manifest file contained in JAR file created after the build.

Example:

Manifest-Version: 1.0
Class-Path: MyProject.jar SomeLibrary.jar AnotherLib.jar

My build script already add some information to the manifest this way:

jar {
    manifest {
        attributes("Implementation-Title": project.name,
            "Implementation-Version": version,
            "Main-Class": mainClassName,
    }
}

How do I get the list of dependencies to add to the manifest?

This page of Java tutorials describes more in detail how and why adding classpath to the manifest: Adding Classes to the JAR File's Classpath

Body:
Here is another solution for Kotlin DSL (build.gradle.kts).

When running your app, the library files are supposed to be in libs/ subdirectory of the app.

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    manifest.attributes["Class-Path"] = configurations
        .runtimeClasspath
        .get()
        .joinToString(separator = " ") { file ->
            "libs/${file.name}"
        }
}


问:
Integration test for single Spring Boot @Service class
I'm writing an integration test for this Spring Boot @Service bean

import org.springframework.stereotype.Service;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Locale;
import java.util.Map;

@Service
public class ThymeLeafEmailTemplateService implements EmailTemplateService {

    private final ITemplateEngine springTemplateEngine;

    public ThymeLeafEmailTemplateService(ITemplateEngine springTemplateEngine) {
        this.springTemplateEngine = springTemplateEngine;
    }

    public String generateEmailBody(String template, Map<String, Object> variables) {
        Context context = new Context(Locale.getDefault(), variables);
        return springTemplateEngine.process(template, context);
    }
}
```
<p>Currently, the test class is defined as shown below</p>
<pre class="lang-java prettyprint-override"><code>@SpringBootTest
class ThymeLeafEmailTemplateServiceTests {

    @Autowired
    private EmailTemplateService service;

    @Test
    void generateTaskNotificationEmail() {
      var output = service.generateEmailBody("/template", Map.of());
      assertEquals("Expected Output", output);
    }
}
</code>```

A problem with this approach is that it's very slow/inefficient because the entire application context is loaded, but I really only need the service being tested and its dependencies.

If I change the test class' annotations to

@SpringBootTest
@ContextConfiguration(classes = ThymeLeafEmailTemplateService.class)
```

the test fails, because the dependency ITemplateEngine springTemplateEngine does not exist. I could add this dependency to classes (the list of beans to create), but this seems like a very brittle approach.

Is there an efficient way to integration test a single @Service?

Note:

I know I could mock ITemplateEngine springTemplateEngine and write a unit test instead, but I want to test the template's actual output, so this approach won't work

答:
You can use

```<code>@WebMvcTest(ThymeLeafEmailTemplateService.class)
</code>```

This will load only that bean in your application context along with any default Spring configuration beans.

Body:
I'm writing an integration test for this Spring Boot @Service bean

import org.springframework.stereotype.Service;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Locale;
import java.util.Map;

@Service
public class ThymeLeafEmailTemplateService implements EmailTemplateService {

    private final ITemplateEngine springTemplateEngine;

    public ThymeLeafEmailTemplateService(ITemplateEngine springTemplateEngine) {
        this.springTemplateEngine = springTemplateEngine;
    }

    public String generateEmailBody(String template, Map<String, Object> variables) {
        Context context = new Context(Locale.getDefault(), variables);
        return springTemplateEngine.process(template, context);
    }
}

Currently, the test class is defined as shown below

@SpringBootTest
class ThymeLeafEmailTemplateServiceTests {

    @Autowired
    private EmailTemplateService service;

    @Test
    void generateTaskNotificationEmail() {
      var output = service.generateEmailBody("/template", Map.of());
      assertEquals("Expected Output", output);
    }
}

A problem with this approach is that it's very slow/inefficient because the entire application context is loaded, but I really only need the service being tested and its dependencies.

If I change the test class' annotations to

@SpringBootTest
@ContextConfiguration(classes = ThymeLeafEmailTemplateService.class)

the test fails, because the dependency ITemplateEngine springTemplateEngine does not exist. I could add this dependency to classes (the list of beans to create), but this seems like a very brittle approach.

Is there an efficient way to integration test a single @Service?

Note:

I know I could mock ITemplateEngine springTemplateEngine and write a unit test instead, but I want to test the template's actual output, so this approach won't work

Body:
You can use

@WebMvcTest(ThymeLeafEmailTemplateService.class)

This will load only that bean in your application context along with any default Spring configuration beans.


问:
How to run a function on a separate thread in Julia?
I want to run a function on a separate core.
I wrote a script that runs it asynchronously in parallel two times.

```<code>const results = Channel()

function my_function()
    delay = rand() * 5
    @info "Task with $delay s"
    @info "Thread $(Threads.threadid())"
    sleep(delay)
    put!(results, delay)
end

errormonitor(@async my_function())
errormonitor(@async my_function())

@info "returned $(take!(results))"
@info "returned $(take!(results))"
</code>```

But both times in the same thread.

```<code>[ Info: Task with 2.9497522378270298 s
[ Info: Task with 4.956428193185428 s
[ Info: Thread 1
[ Info: Thread 1
[ Info: returned 2.9497522378270298
[ Info: returned 4.956428193185428
</code>```

How can I run my_function on different threads?

答:
@async tasks run on the thread that scheduled them (thread 1 in your example).
To spawn a task on a thread, use Threads.@spawn (and make sure to start Julia with more than one thread):

```<code>$ cat main.jl
const results = Channel()

function my_function()
    delay = rand() * 5
    @info "Task with $delay s running on thread $(Threads.threadid())"
    sleep(delay)
    put!(results, delay)
end

Threads.@spawn my_function()
Threads.@spawn my_function()

@info "returned $(take!(results))"
@info "returned $(take!(results))"

$ julia --threads=auto main.jl
[ Info: Task with 0.3894362661856865 s running on thread 2
[ Info: Task with 1.4960360211694967 s running on thread 4
[ Info: returned 0.3894362661856865
[ Info: returned 1.4960360211694967
</code>```

Body:
I want to run a function on a separate core.
I wrote a script that runs it asynchronously in parallel two times.

const results = Channel()

function my_function()
    delay = rand() * 5
    @info "Task with $delay s"
    @info "Thread $(Threads.threadid())"
    sleep(delay)
    put!(results, delay)
end

errormonitor(@async my_function())
errormonitor(@async my_function())

@info "returned $(take!(results))"
@info "returned $(take!(results))"

But both times in the same thread.

[ Info: Task with 2.9497522378270298 s
[ Info: Task with 4.956428193185428 s
[ Info: Thread 1
[ Info: Thread 1
[ Info: returned 2.9497522378270298
[ Info: returned 4.956428193185428

How can I run my_function on different threads?

Body:
@async tasks run on the thread that scheduled them (thread 1 in your example).
To spawn a task on a thread, use Threads.@spawn (and make sure to start Julia with more than one thread):

$ cat main.jl
const results = Channel()

function my_function()
    delay = rand() * 5
    @info "Task with $delay s running on thread $(Threads.threadid())"
    sleep(delay)
    put!(results, delay)
end

Threads.@spawn my_function()
Threads.@spawn my_function()

@info "returned $(take!(results))"
@info "returned $(take!(results))"

$ julia --threads=auto main.jl
[ Info: Task with 0.3894362661856865 s running on thread 2
[ Info: Task with 1.4960360211694967 s running on thread 4
[ Info: returned 0.3894362661856865
[ Info: returned 1.4960360211694967


问:
opam init fails - unable to create temp file
I have installed opam 2.1.0 on a Linux Virtualbox VM. When I try opam init, I get the following error:

```<code><><> Fetching repository information ><><><><><><><><><><><><><><><><><><><><><>
[ERROR] Could not update repository "default": OpamDownload.Download_fail(_, "Curl
        failed: \"/snap/bin/curl --write-out %{http_code}\\\\n --retry 3
        --retry-delay 2 --user-agent opam/2.1.0 -L -o
        /tmp/opam-32196-d33843/index.tar.gz.part --
        https://opam.ocaml.org/index.tar.gz\" exited with code 23")
[ERROR] Initial download of repository failed.
</code>```

Running with --disable-sandboxing doesn't help. I know that its a problem creating/writing to /tmp/opam-... directory because if I replace that with my current directory or home directory the command by itself runs fine. It also runs fine with /tmp/opam-... if I use the --create-dirs option in curl but I don't have any way of getting opam init to use that option. Any ideas?

thanks

答:
Update

The reason opam init failed for me was because curl was installed with snap on my system. This exactly what is going on with your VM.
Try to run opam init -verbose and that could reveal more about why you ran into an error.
In my case I needed to install other things with opam and it kept failing every time. So snap uninstall curl and then sudo apt install curl fixed things. (Was only able to figure this out with help from my professor)

Workaround

I ran into the same issue and I found a workaround on the OCaml forum: here. (Credits to UnixJunkie)

You can run:

```<code>opam init github git+https://github.com/ocaml/opam-repository.git
</code>```

This should avoid the certificate issues. This worked for me.

I tried to fix the certificate issues using this answer as well. You could try doing that, but it seems complicated when the workaround is to simply point it to the github repo directly.

This question is similar to this one.

Body:
I have installed opam 2.1.0 on a Linux Virtualbox VM. When I try opam init, I get the following error:

<><> Fetching repository information ><><><><><><><><><><><><><><><><><><><><><>
[ERROR] Could not update repository "default": OpamDownload.Download_fail(_, "Curl
        failed: \"/snap/bin/curl --write-out %{http_code}\\\\n --retry 3
        --retry-delay 2 --user-agent opam/2.1.0 -L -o
        /tmp/opam-32196-d33843/index.tar.gz.part --
        https://opam.ocaml.org/index.tar.gz\" exited with code 23")
[ERROR] Initial download of repository failed.

Running with --disable-sandboxing doesn't help. I know that its a problem creating/writing to /tmp/opam-... directory because if I replace that with my current directory or home directory the command by itself runs fine. It also runs fine with /tmp/opam-... if I use the --create-dirs option in curl but I don't have any way of getting opam init to use that option. Any ideas?

thanks

Body:
Update

The reason opam init failed for me was because curl was installed with snap on my system. This exactly what is going on with your VM.
Try to run opam init -verbose and that could reveal more about why you ran into an error.
In my case I needed to install other things with opam and it kept failing every time. So snap uninstall curl and then sudo apt install curl fixed things. (Was only able to figure this out with help from my professor)

Workaround

I ran into the same issue and I found a workaround on the OCaml forum: here. (Credits to UnixJunkie)

You can run:

opam init github git+https://github.com/ocaml/opam-repository.git

This should avoid the certificate issues. This worked for me.

I tried to fix the certificate issues using this answer as well. You could try doing that, but it seems complicated when the workaround is to simply point it to the github repo directly.

This question is similar to this one.


问:
GKE Autopilot failing to create new deployment after 10-12 deployments saying "Insufficient CPU"
I am having some issue with GKE(autopilot).

I am deploying statefulsets and for each statefulset I deploy a service with public IP.
But after deploying like 10-12 statefulsets, if I try deploying any new it remains  red(Unschedulable) with message "Insufficient cpu".

When I go to cluster section is show a different message saying:

```<code>Can’t scale up because instances in managed instance groups hosting node pools ran out of IPs
</code>```

Image of error: https://i.imgur.com/t8I4Yij.png

I am new to GKE and tried doing what suggested in links of those image but it seems most of steps give error saying its not supported in autopilot mode.

Any help/suggestion is appreciated.

Thanks.

答:
If you are on GKE autopilot ideally it will create the new nodes in cluster if out of CPU or no space left to schedule the PODs.

However if it's issue of IP you can read more : https://cloud.google.com/kubernetes-engine/docs/how-to/alias-ips#not_enough_space

Cluster autoscaler might not have enough unallocated IP address space
to use to add new nodes or Pods, resulting in scale-up failures, which
are indicated by eventResult events with the reason
scale.up.error.ip.space.exhausted. You can add more IP addresses for
nodes by expanding the primary subnet, or add new IP addresses for
Pods using discontiguous multi-Pod CIDR. For more information, see Not
enough free IP space for Pods.

but you are on autopilot so wont be able to access underlaying subnet and node pools of cluster maybe.

Body:
I am having some issue with GKE(autopilot).

I am deploying statefulsets and for each statefulset I deploy a service with public IP.
But after deploying like 10-12 statefulsets, if I try deploying any new it remains  red(Unschedulable) with message "Insufficient cpu".

When I go to cluster section is show a different message saying:

Can’t scale up because instances in managed instance groups hosting node pools ran out of IPs

Image of error: https://i.imgur.com/t8I4Yij.png

I am new to GKE and tried doing what suggested in links of those image but it seems most of steps give error saying its not supported in autopilot mode.

Any help/suggestion is appreciated.

Thanks.


问:
does cd command in a shell script load the rvmrc inside the destination directory?
when you have something like..

given inside projectx an .rvmrc file specifying ruby 1.9.2 and having two rubies on my system (ree-1.8.7 and ruby1.9.2)

```<code>#!/bin/bash

cd applications/projectx
which ruby
ruby -v
</code>```

the last two lines output ree-1.8.7 and its path which was not I intended to use.

答:
If you are using RVM 1.7.0 or later you need to enable project specific .rvmrc files by adding this line to ~/.rvmrc (or system .rvmrc):

rvm_project_rvmrc=1

See: https://rvm.io/workflow/rvmrc/

Body:
when you have something like..

given inside projectx an .rvmrc file specifying ruby 1.9.2 and having two rubies on my system (ree-1.8.7 and ruby1.9.2)

#!/bin/bash

cd applications/projectx
which ruby
ruby -v

the last two lines output ree-1.8.7 and its path which was not I intended to use.


问:
Check to see if a value is within a range?
I have a dataset in a data.table format that looks as such:

```<code>ID     time.s     time.e
1       1         2
2       1         4
3       2         3
4       2         4
</code>```

I want to check to see if the value 1 is within time.s and time.e so that the end result would look like

```<code>[1] TRUE TRUE FALSE FALSE
</code>```

How would I go about this? I have tried to use

```<code> a[1 %in% seq(time.s, time.e)]
</code>```

But all I get is all TRUE values. Any recommendations?

答:
Here is another answer with base r:</p>
```<code>data.frame <- data.frame(ID = 1:4,
                         time.s = c(1,1,2,2),
                         time.e = c(2,4,3,4))

data.frame$OK<-data.frame$ID%in%c(data.frame$time.s:data.frame$time.e)

data.frame
  ID time.s time.e    OK
1  1      1      2  TRUE
2  2      1      4  TRUE
3  3      2      3 FALSE
4  4      2      4 FALSE
</code>```

Body:
I have a dataset in a data.table format that looks as such:

ID     time.s     time.e
1       1         2
2       1         4
3       2         3
4       2         4

I want to check to see if the value 1 is within time.s and time.e so that the end result would look like

[1] TRUE TRUE FALSE FALSE

How would I go about this? I have tried to use

 a[1 %in% seq(time.s, time.e)]

But all I get is all TRUE values. Any recommendations?

Body:
Here is another answer with base r:

data.frame <- data.frame(ID = 1:4,
                         time.s = c(1,1,2,2),
                         time.e = c(2,4,3,4))

data.frame$OK<-data.frame$ID%in%c(data.frame$time.s:data.frame$time.e)

data.frame
  ID time.s time.e    OK
1  1      1      2  TRUE
2  2      1      4  TRUE
3  3      2      3 FALSE
4  4      2      4 FALSE


问:
Pass static method and model class via contructor paramters
I have extracted the DropdownSearch<String> widget and created a independent custom widget extending the features of DropdownSearch<String>. I have done this to reduce code size and encapsulate certain functionality.

On an average a single form contains 5-6 DropdownSearch widgets. Their are multiple such forms.

I am populating the items on the widget via API call using Dio package. I have created model and serializer using built_value packages.

My question is how do I pass the fromJson static method and the model class via const constructor parameters

Code :

```<code>import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:reference_wrapper/reference_wrapper.dart';

class DropDownSearch extends StatefulWidget {
  final Ref<String> itemSelected;
  final String url;
  final String label;
  const DropDownSearch({
    required this.itemSelected,
    required this.url,
    required this.label,
    Key? key,
  }) : super(key: key);

  @override
  State<DropDownSearch> createState() => _DropDownSearchState();
}

class _DropDownSearchState extends State<DropDownSearch> {
  @override
  Widget build(BuildContext context) {
    return DropdownSearch<String>(
      mode: Mode.MENU,
      showSelectedItems: true,
      showSearchBox: true,
      showAsSuffixIcons: true,
      dropdownSearchDecoration: InputDecoration(
        label: Text(widget.label),
        focusColor: Colors.blue,
        border: const OutlineInputBorder(
          borderSide: BorderSide(
            style: BorderStyle.solid,
          ),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please select ${widget.label}';
        }
        return null;
      },
      onFind: (text) async {
        var response = await Dio().get(
          widget.url,
        );
        if (response.statusCode != 200) {}
        final ipcStatusList = IpcStatusList.fromJson(response.data); //How to pass this static method as parameter
        return ipcStatusList.ipcStatus.toList(); //How to pass this as parameter
      },
      onChanged: (value) => setState(
        () {
          widget.itemSelected.ref = value ?? '';
        },
      ),
    );
  }
}
</code>```

答: I think you can make a final variable in your "DropDownSearch" which is the same type of toJson. And when using this Class, pass your static variable.</p>

Body:
I have extracted the DropdownSearch<String> widget and created a independent custom widget extending the features of DropdownSearch<String>. I have done this to reduce code size and encapsulate certain functionality.

On an average a single form contains 5-6 DropdownSearch widgets. Their are multiple such forms.

I am populating the items on the widget via API call using Dio package. I have created model and serializer using built_value packages.

My question is how do I pass the fromJson static method and the model class via const constructor parameters

Code :

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:reference_wrapper/reference_wrapper.dart';

class DropDownSearch extends StatefulWidget {
  final Ref<String> itemSelected;
  final String url;
  final String label;
  const DropDownSearch({
    required this.itemSelected,
    required this.url,
    required this.label,
    Key? key,
  }) : super(key: key);

  @override
  State<DropDownSearch> createState() => _DropDownSearchState();
}

class _DropDownSearchState extends State<DropDownSearch> {
  @override
  Widget build(BuildContext context) {
    return DropdownSearch<String>(
      mode: Mode.MENU,
      showSelectedItems: true,
      showSearchBox: true,
      showAsSuffixIcons: true,
      dropdownSearchDecoration: InputDecoration(
        label: Text(widget.label),
        focusColor: Colors.blue,
        border: const OutlineInputBorder(
          borderSide: BorderSide(
            style: BorderStyle.solid,
          ),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please select ${widget.label}';
        }
        return null;
      },
      onFind: (text) async {
        var response = await Dio().get(
          widget.url,
        );
        if (response.statusCode != 200) {}
        final ipcStatusList = IpcStatusList.fromJson(response.data); //How to pass this static method as parameter
        return ipcStatusList.ipcStatus.toList(); //How to pass this as parameter
      },
      onChanged: (value) => setState(
        () {
          widget.itemSelected.ref = value ?? '';
        },
      ),
    );
  }
}


问:
Set message for duplicate value pandas
i have df like this

```<code>   A   B
0  1   ABC
1  2   XYX
2  1   RTC
3  3   fds
4  2   rtv
5  4   rtoc
</code>```

and i want like this

```<code>    A   B     message
0  1   ABC
1  2   XYX
2  1   RTC     Duplicated
3  3   fds
4  2   rtv     Duplicated
5  4   rtoc
</code>```

if Column A value is duplicated then set the message duplicated in second occurrence.

答:
all duplicates:

Use numpy.where and duplicated:

```<code>df['message'] = np.where(df['A'].duplicated(), 'Duplicated', '')
</code>```

output:

```<code>   A     B     message
0  1   ABC
1  2   XYX
2  1   RTC  Duplicated
3  3   fds
4  2   rtv  Duplicated
5  4  rtoc
</code>```

only for the SECOND occurrence:

Use groupby+cumcount:

```<code>df['message'] = np.where(df.groupby('A').cumcount().eq(1), 'Duplicated', '')
</code>```

example:

```<code>   A                  B     message
0  1   first occurrence
1  2                XYX
2  1  second occurrence  Duplicated
3  1   third occurrence
4  3                fds
5  2                rtv  Duplicated
6  4               rtoc
</code>```

Title: Set message for duplicate value pandas

Body:
i have df like this

   A   B
0  1   ABC
1  2   XYX
2  1   RTC
3  3   fds
4  2   rtv
5  4   rtoc

and i want like this

    A   B     message
0  1   ABC
1  2   XYX
2  1   RTC     Duplicated
3  3   fds
4  2   rtv     Duplicated
5  4   rtoc

if Column A value is duplicated then set the message duplicated in second occurrence.

Body:
all duplicates:

Use numpy.where and duplicated:

df['message'] = np.where(df['A'].duplicated(), 'Duplicated', '')

output:

   A     B     message
0  1   ABC
1  2   XYX
2  1   RTC  Duplicated
3  3   fds
4  2   rtv  Duplicated
5  4  rtoc

only for the SECOND occurrence:

Use groupby+cumcount:

df['message'] = np.where(df.groupby('A').cumcount().eq(1), 'Duplicated', '')

example:

   A                  B     message
0  1   first occurrence
1  2                XYX
2  1  second occurrence  Duplicated
3  1   third occurrence
4  3                fds
5  2                rtv  Duplicated
6  4               rtoc


问:
Please guys what might the cause of this error am recieving
TypeError: Cannot perform 'ror_' with a dtyped [bool] array and scalar of type [NoneType]

###I receive this error whenever i run this code.

print(df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))

Please what am I not doing right?

答:
| is no legal boolean operator in python. You should use the keyword „or“ instead.

////////////////

```<code>print(df < (Q1 - 1.5 * IQR) or df > (Q3 + 1.5 * IQR))
</code>```

Body:
| is no legal boolean operator in python. You should use the keyword „or“ instead.

////////////////

print(df < (Q1 - 1.5 * IQR) or df > (Q3 + 1.5 * IQR))


问:
C++ Polymorphic behaviour with global array of Base Class type
Why is the code below able to demonstrate polymorphic behaviour

```<code>TwoDShapes* s2d[2];

int main()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}
</code>```

BUT the code below throws an error

```<code>void test();

TwoDShapes* s2d[2];

int main()
{
    test();

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}

void test()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;
}
</code>```

I noticed that when I try to initialise the contents of the array within another function other than main(), the Base class'(TwoDShapes) toString() method gets invoked instead of the Derived classes'(Circle and Rectangle) toString() method.
But when I do the same thing within main(), it is able to display polymorphic behaviour.

Below is my Base and Derived classes

```<code>// Base Class
class TwoDShapes
{
public:
    TwoDShapes();
    virtual string toString();

string TwoDShapes::toString()
{
    return "Inside Base Class toString method";
}

// Derived classes
class Circle : public TwoDShapes
{
public:
    Circle(/*parameter*/);
    string toString() override;
};

string Circle::toString()
{
    return "Inside Circle toString method";
}

</code>```

*Edit 1: Included a more complete code

答:
c1 and s1 are local variables to function test.
The moment it finishes, you can no longer access them.

So, s2d[i] contains a pointer to some local variable of test function. By the time this code cout << s2d[i]->toString() << endl; runs, the test function already terminated. So all local variables are destroyed. Calling toString() function of a destroyed object has undefined behavior. You can no longer access them.

Body:
Why is the code below able to demonstrate polymorphic behaviour

TwoDShapes* s2d[2];

int main()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}

BUT the code below throws an error

void test();

TwoDShapes* s2d[2];

int main()
{
    test();

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}

void test()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;
}

I noticed that when I try to initialise the contents of the array within another function other than main(), the Base class'(TwoDShapes) toString() method gets invoked instead of the Derived classes'(Circle and Rectangle) toString() method.
But when I do the same thing within main(), it is able to display polymorphic behaviour.

Below is my Base and Derived classes

// Base Class
class TwoDShapes
{
public:
    TwoDShapes();
    virtual string toString();

string TwoDShapes::toString()
{
    return "Inside Base Class toString method";
}

// Derived classes
class Circle : public TwoDShapes
{
public:
    Circle(/*parameter*/);
    string toString() override;
};

string Circle::toString()
{
    return "Inside Circle toString method";
}

*Edit 1: Included a more complete code


问:
Bootstrap table .js remove event not working
I'm trying to delete row using bootstrap table.

Table:

```<code><table id="checkDataTable">
    <thead style="color: #31708f; background-color: #d9edf7 ">
        <tr>
            <th data-field="AssetReference">Referans</th>
            <th data-field="Customer">Müşteri</th>
            <th data-field="ReceiverCompanyName">Alıcı Firma</th>
            <th data-field="Tools" data-formatter="StatuFormatter" >İşlem</th>
        </tr>
    </thead>
</table>

</code>```

StatuFormatter:

```<code>function StatuFormatter(value, row, index)
{
    return "<a  onclick='removeAssetEconomyCheckBillOfLadingRow("+index+")'><i class='fa fa-trash fa-2x' aria-hidden='true'></i></a>";
}
</code>```

removeAssetEconomyCheckBillOfLadingRow Function:

```<code>function removeAssetEconomyCheckBillOfLadingRow(index)
{
    alert(index);
    $('#checkDataTable').bootstrapTable('remove', {field: '$index',values: index});
}
</code>```

I can get index value in alert box. But row could not be remove.

答: Problem is in values: index it may helps you : https://stackoverflow.com/a/64258424/11143288

Body:
I'm trying to delete row using bootstrap table.

Table:

            Referans
            Müşteri
            Alıcı Firma
            İşlem

StatuFormatter:

function StatuFormatter(value, row, index)
{
    return "";
}

removeAssetEconomyCheckBillOfLadingRow Function:

function removeAssetEconomyCheckBillOfLadingRow(index)
{
    alert(index);
    $('#checkDataTable').bootstrapTable('remove', {field: '$index',values: index});
}

I can get index value in alert box. But row could not be remove.


问:
Place div to the right side of the text
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

答:
This solution uses an addition to the HTML contents, which won't work for dynamic contents, but I'll post it nevertheless – for fixed content it works:

If you just add a linebreak /
 tag beween the words in your long text, it does what you want (no other changes to your code necessary):

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong<br/>teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

Title: Place div to the right side of the text

Body:
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

    Loooooooong teeeeeext

    Short text

Body:
This solution uses an addition to the HTML contents, which won't work for dynamic contents, but I'll post it nevertheless – for fixed content it works:

If you just add a linebreak / <br/> tag beween the words in your long text, it does what you want (no other changes to your code necessary):

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

<div class="parent">
  <div class="first-child">
    <span>Loooooooong<br/>teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div>


答:
I think you have a problem with your parenthesis but Did you try to use or instead of |

btw: you can debug your code by printing each statement alone and see whats not right, something like this:

```<code>n1 = Q1 - 1.5 * IQR
print(df < n1)
n2 = Q3 + 1.5 * IQR
print(df > n2)

print(df < n1 or df > n2)
</code>```

Title: Please guys what might the cause of this error am recieving

Body:
TypeError: Cannot perform 'ror_' with a dtyped [bool] array and scalar of type [NoneType]

###I receive this error whenever i run this code.

print(df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))

Please what am I not doing right?

Body:
I think you have a problem with your parenthesis but Did you try to use or instead of |

btw: you can debug your code by printing each statement alone and see whats not right, something like this:

n1 = Q1 - 1.5 * IQR
print(df < n1)
n2 = Q3 + 1.5 * IQR
print(df > n2)

print(df < n1 or df > n2)


问:
How to represent "no flags" using enum.Flag?
I want to use an enum.Flag in a library function to allow users configuring multiple additive options.
Since some of these options are usually what users would want to do, there is a sensible default.
However it should still be possible to pass in a value to disable all options.

Reading up on enum.Flag and following the advice to "use auto as the value and let Flag select an appropriate value" I came up with something like this:

import enum

class Foo(enum.Flag):
    NONE = enum.auto()
    BAR = enum.auto()
    BAZ = enum.auto()

def do_something(foo: Foo = Foo.BAR):
    pass
```

This works but when combining the Foo.NONE flag with say Foo.BAR I end up with <Foo.BAR|NONE: 3> while I'd want to end up with just <Foo.BAR: 2>.

I also tried not defining the NONE member at all but this requires users to pass in Foo(0) if they want to not specify any flags which is not obvious at all.

How do you define this class so that combining Foo.NONE and Foo.BAR ends up as Foo.BAR and users get to pass an obvious member to not set any of the flags?

答:
To someone not used to how bit operations and flags work this might be a bit confusing.
To those who are Foo.NONE | Foo.BAR resulting in <Foo.BAR|NONE: 3> (note the 3) is probably what gives it away.

So what is happening here?

enum.auto() assigns appropriate values to enum members starting at 1 as explained in its documentation:

Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.

The other important bit to understand what's going on is mentioned in the Flag documentation

Individual flags should have values that are powers of two (1, 2, 4, 8, …)

Thus, the example is equivalent to defining the members explicitly like this:

import enum

class Foo(enum.Flag):
    NONE = 1
    BAR = 2
    BAZ = 4
```
<p>The reason for this is more apparent when thinking about the values in binary representation: <code>Foo.NONE = 1 = 0b001</code>, <code>Foo.BAR = 2 = 0b010</code> and <code>Foo.BAZ = 4 = 0b100</code>.
That allows for easily combining flags e.g. <code>Foo.BAR | Foo.BAZ = 2 | 4 = 0b010 | 0b100 = 0b110 = 6</code>.</p>
<p>Now combining <code>Foo.None</code> and <code>Foo.BAR</code> the same way you end up with <code>3</code> or its binary representation of <code>0b011</code> which is the representation of having the bits for both <code>Foo.NONE</code> and <code>Foo.BAR</code> set.</p>
<p>How to solve the issue?</p>
<p>The "trick" is to think about the bit representation of what is being expressed.
Since individual bits being set correspond to enum members, not having any bits set should correspond to the <code>NONE</code> member i.e.:</p>
<pre class="lang-py prettyprint-override"><code>import enum

class Foo(enum.Flag):
    NONE = 0
    BAR = enum.auto()
    BAZ = enum.auto()
</code>```

Users of your library can easily specify "no flags" using Foo.NONE this way while combining it with "actual" flags now behaves as expected:

```<code>>>> foo = Foo.NONE
>>> foo
<Foo.NONE: 0>
>>> foo |= Foo.BAR
>>> foo
<Foo.BAR: 1>
</code>```

Body:
I want to use an enum.Flag in a library function to allow users configuring multiple additive options.
Since some of these options are usually what users would want to do, there is a sensible default.
However it should still be possible to pass in a value to disable all options.

Reading up on enum.Flag and following the advice to "use auto as the value and let Flag select an appropriate value" I came up with something like this:

import enum

class Foo(enum.Flag):
    NONE = enum.auto()
    BAR = enum.auto()
    BAZ = enum.auto()

def do_something(foo: Foo = Foo.BAR):
    pass

This works but when combining the Foo.NONE flag with say Foo.BAR I end up with <Foo.BAR|NONE: 3> while I'd want to end up with just <Foo.BAR: 2>.

I also tried not defining the NONE member at all but this requires users to pass in Foo(0) if they want to not specify any flags which is not obvious at all.

How do you define this class so that combining Foo.NONE and Foo.BAR ends up as Foo.BAR and users get to pass an obvious member to not set any of the flags?

Body:
To someone not used to how bit operations and flags work this might be a bit confusing.
To those who are Foo.NONE | Foo.BAR resulting in <Foo.BAR|NONE: 3> (note the 3) is probably what gives it away.

So what is happening here?

enum.auto() assigns appropriate values to enum members starting at 1 as explained in its documentation:

Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.

The other important bit to understand what's going on is mentioned in the Flag documentation

Individual flags should have values that are powers of two (1, 2, 4, 8, …)

Thus, the example is equivalent to defining the members explicitly like this:

import enum

class Foo(enum.Flag):
    NONE = 1
    BAR = 2
    BAZ = 4

The reason for this is more apparent when thinking about the values in binary representation: Foo.NONE = 1 = 0b001, Foo.BAR = 2 = 0b010 and Foo.BAZ = 4 = 0b100.
That allows for easily combining flags e.g. Foo.BAR | Foo.BAZ = 2 | 4 = 0b010 | 0b100 = 0b110 = 6.

Now combining Foo.None and Foo.BAR the same way you end up with 3 or its binary representation of 0b011 which is the representation of having the bits for both Foo.NONE and Foo.BAR set.

How to solve the issue?

The "trick" is to think about the bit representation of what is being expressed.
Since individual bits being set correspond to enum members, not having any bits set should correspond to the NONE member i.e.:

import enum

class Foo(enum.Flag):
    NONE = 0
    BAR = enum.auto()
    BAZ = enum.auto()

Users of your library can easily specify "no flags" using Foo.NONE this way while combining it with "actual" flags now behaves as expected:

>>> foo = Foo.NONE
>>> foo
<Foo.NONE: 0>
>>> foo |= Foo.BAR
>>> foo
<Foo.BAR: 1>


问:
suggestion regarding the maintainability of undo-redo states in image editing
I am developing an image editing app in java, which of-course will need undo-redo functionality.
What have i done....
Have created a State class which will contain a bufferedimage, ref to prev state, ref to next state. Then formed a linked list of states, traversing back and forth with clicks of undo and redo buttons.
So what do i want....
I have observed that bufferedimage occupies way too much memory...say 4 MB for just a medium (desktop) size image. Can you people suggest a better approach???

Thank you!!

答:
You should use the Command pattern instead of the Memento pattern if your state uses too much memory.

You will have a linked list of UndoRedo objects, each containing just enough information to be able to run either the command of an undo, or the command of a redo.

You have to different ways to organize the commands:

Have bi-directional commands. For example, when changing the color of a pixel, the operation must contain both the original color and the new one, so that the command can be run in both directions.

Have two different commands for each undoredo bloc. For some commands which change everything on the image (like changing the scale or the brightness, where some information about the original image is lost), you have to store both the command to redo and the command to undo. It it's the full image, the memory footprint will be similar to what you already have.


问:
Use FFmpeg to create MPEG-DASH files
I know using ffmpeg, we can create MPEG-DASH ready files, including the segments and the .mpd manifest file. For instance, I'm trying this command which works:

```<code>ffmpeg -re -i .\video-h264.mkv -map 0 -map 0 -c:a aac -c:v libx264 -b:v:0 800k -b:v:1 300k -s:v:1 320x170 -profile:v:1 baseline -profile:v:0 main -bf 1 -keyint_min 120 -g 120 -sc_threshold 0 -b_strategy 0 -ar:a:1 22050 -use_timeline 1 -use_template 1 -window_size 5 -adaptation_sets "id=0,streams=v id=1,streams=a" -f dash out.mpd
</code>```

But I don't want to segment the video- so a simpler version where we have multiple versions of the whole video, no chunks. Does MPEG-DASH allow it? If so, how can I use ffmpeg to do it without creating the chunks?

答:
I think you mean that you want a single file (for each bit rate), rather than individual files for each segment (again, for a given bit rate).

MPEG DASH supports this - in the manifest each segment is referenced by a base URL and a byte range, rather than an individual URL.

FFmpeg supports generating this format using the single file option:

single_file single_file

Enable (1) or disable (0) storing all segments in one file, accessed using byte ranges.

(https://ffmpeg.org/ffmpeg-formats.html#toc-dash-2)

Title: Use FFmpeg to create MPEG-DASH files

Body:
I know using ffmpeg, we can create MPEG-DASH ready files, including the segments and the .mpd manifest file. For instance, I'm trying this command which works:

ffmpeg -re -i .\video-h264.mkv -map 0 -map 0 -c:a aac -c:v libx264 -b:v:0 800k -b:v:1 300k -s:v:1 320x170 -profile:v:1 baseline -profile:v:0 main -bf 1 -keyint_min 120 -g 120 -sc_threshold 0 -b_strategy 0 -ar:a:1 22050 -use_timeline 1 -use_template 1 -window_size 5 -adaptation_sets "id=0,streams=v id=1,streams=a" -f dash out.mpd

But I don't want to segment the video- so a simpler version where we have multiple versions of the whole video, no chunks. Does MPEG-DASH allow it? If so, how can I use ffmpeg to do it without creating the chunks?


问:
Memcached: why memcached server constantly drops connection?
I have two spring apps, in both I use spymemcached.
And memcached client is created like this

```<code>private MemcachedClient buildClient() {
    String address = this.serverAddress;
    MemcachedClient result;
    if (StringUtils.isNotEmpty(address)) {
      log.info("connecting to memcached server {}", address);

      try {
        result = new MemcachedClient(
            new ConnectionFactoryBuilder()
                .setTranscoder(new CustomSerializingTranscoder())
                .setProtocol(protocol)
                .setTimeoutExceptionThreshold(2)
                .build(),
            AddrUtil.getAddresses(address));
      } catch (IOException e) {
        throw new IllegalStateException("Can't create client", e);
      }

      log.info("connected to memcached server {}", address);
    } else {
      log.warn("cannot initialize memcached client: memcached address is not set");

      result = null;
    }
    return result;
  }
</code>```

One spring app put (always replace one) key:value in memcached.
Another one reads this key. And the app that reads value constantly loose connection.

Memcached config:

```<code>[r.gomboev@netris-gps-stage60-01 netris]$ sudo systemctl status memcached
● memcached.service - Memcached
   Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; vendor preset: disabled)
   Active: active (running) since Пн 2022-01-24 18:29:39 MSK; 1 day 1h ago
 Main PID: 16747 (memcached)
    Tasks: 6
   Memory: 18.9M
   CGroup: /system.slice/memcached.service
           └─16747 /usr/bin/memcached -u memcached -p 11211 -m 64 -c 1024 -vv
</code>```

But a problem is memcached server constantly drops connections.

memcached logs:

```<code>Jan 25 13:21:50 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:22:44 memcached-server-01 memcached: <33 connection closed.
Jan 25 13:23:19 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:23:33 memcached-server-01 memcached: <33 connection closed.
Jan 25 13:23:55 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:26:34 memcached-server-01 memcached: <33 connection closed.
Jan 25 13:31:36 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:45:03 memcached-server-01 memcached: <33 connection closed.
Jan 25 16:11:43 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 18:45:12 memcached-server-01 memcached: <33 connection closed.
Jan 25 19:39:36 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 19:41:11 memcached-server-01 memcached: <33 connection closed.
</code>```

when I look at connection through lsof

```<code>on app server 81.166
[user@test-dmz-02 ~]$ sudo lsof -i -P -n | grep 11211 | grep 82.80
java      12150      cctv   90u  IPv6 1037210363      0t0  TCP 10.200.81.166:35742->10.200.82.80:11211 (ESTABLISHED)
connection established

but on memcached server 82.80
[user@memcached-server-01]$ sudo lsof -i -P -n | grep 11211 | grep 81.166
no connection
</code>```

memcached has next stats

```<code>Escape character is '^]'.
stats
STAT pid 16747
STAT uptime 93258
STAT time 1643131435
STAT version 1.4.15
STAT libevent 2.0.21-stable
STAT pointer_size 64
STAT rusage_user 10.729242
STAT rusage_system 17.056611
STAT curr_connections 15
STAT total_connections 62
STAT connection_structures 20
STAT reserved_fds 20
STAT cmd_get 738
STAT cmd_set 84624
STAT cmd_flush 0
STAT cmd_touch 0
STAT get_hits 737
STAT get_misses 1
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 0
STAT incr_hits 0
STAT decr_misses 0
STAT decr_hits 0
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT touch_hits 0
STAT touch_misses 0
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 156369146
STAT bytes_written 100524068
STAT limit_maxbytes 67108864
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 4
STAT conn_yields 0
STAT hash_power_level 16
STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT bytes 85
STAT curr_items 1
STAT total_items 84623
STAT expired_unfetched 0
STAT evicted_unfetched 0
STAT evictions 0
STAT reclaimed 0
END
</code>```

I can't find the trigger Why connection is closed by memcached server. Can anybody show me the way to find out the solution? Thank you

答:
I found the reason. The idle tcp connection is closed by unix system.
the param is in file /proc/sys/net/ipv4/tcp_keepalive_time in seconds

```<code>cat /proc/sys/net/ipv4/tcp_keepalive_time
7200
</code>```

As the solution I try another one attempt to connect to memcached, if first attempt was failed.

Body:
I have two spring apps, in both I use spymemcached.
And memcached client is created like this

private MemcachedClient buildClient() {
    String address = this.serverAddress;
    MemcachedClient result;
    if (StringUtils.isNotEmpty(address)) {
      log.info("connecting to memcached server {}", address);

      try {
        result = new MemcachedClient(
            new ConnectionFactoryBuilder()
                .setTranscoder(new CustomSerializingTranscoder())
                .setProtocol(protocol)
                .setTimeoutExceptionThreshold(2)
                .build(),
            AddrUtil.getAddresses(address));
      } catch (IOException e) {
        throw new IllegalStateException("Can't create client", e);
      }

      log.info("connected to memcached server {}", address);
    } else {
      log.warn("cannot initialize memcached client: memcached address is not set");

      result = null;
    }
    return result;
  }

One spring app put (always replace one) key:value in memcached.
Another one reads this key. And the app that reads value constantly loose connection.

Memcached config:

[r.gomboev@netris-gps-stage60-01 netris]$ sudo systemctl status memcached
● memcached.service - Memcached
   Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; vendor preset: disabled)
   Active: active (running) since Пн 2022-01-24 18:29:39 MSK; 1 day 1h ago
 Main PID: 16747 (memcached)
    Tasks: 6
   Memory: 18.9M
   CGroup: /system.slice/memcached.service
           └─16747 /usr/bin/memcached -u memcached -p 11211 -m 64 -c 1024 -vv

But a problem is memcached server constantly drops connections.

memcached logs:

Jan 25 13:21:50 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:22:44 memcached-server-01 memcached: <33 connection closed.
Jan 25 13:23:19 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:23:33 memcached-server-01 memcached: <33 connection closed.
Jan 25 13:23:55 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:26:34 memcached-server-01 memcached: <33 connection closed.
Jan 25 13:31:36 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 13:45:03 memcached-server-01 memcached: <33 connection closed.
Jan 25 16:11:43 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 18:45:12 memcached-server-01 memcached: <33 connection closed.
Jan 25 19:39:36 memcached-server-01 memcached: <33 new auto-negotiating client connection
Jan 25 19:41:11 memcached-server-01 memcached: <33 connection closed.

when I look at connection through lsof

on app server 81.166
[user@test-dmz-02 ~]$ sudo lsof -i -P -n | grep 11211 | grep 82.80
java      12150      cctv   90u  IPv6 1037210363      0t0  TCP 10.200.81.166:35742->10.200.82.80:11211 (ESTABLISHED)
connection established

but on memcached server 82.80
[user@memcached-server-01]$ sudo lsof -i -P -n | grep 11211 | grep 81.166
no connection

memcached has next stats

Escape character is '^]'.
stats
STAT pid 16747
STAT uptime 93258
STAT time 1643131435
STAT version 1.4.15
STAT libevent 2.0.21-stable
STAT pointer_size 64
STAT rusage_user 10.729242
STAT rusage_system 17.056611
STAT curr_connections 15
STAT total_connections 62
STAT connection_structures 20
STAT reserved_fds 20
STAT cmd_get 738
STAT cmd_set 84624
STAT cmd_flush 0
STAT cmd_touch 0
STAT get_hits 737
STAT get_misses 1
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 0
STAT incr_hits 0
STAT decr_misses 0
STAT decr_hits 0
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT touch_hits 0
STAT touch_misses 0
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 156369146
STAT bytes_written 100524068
STAT limit_maxbytes 67108864
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 4
STAT conn_yields 0
STAT hash_power_level 16
STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT bytes 85
STAT curr_items 1
STAT total_items 84623
STAT expired_unfetched 0
STAT evicted_unfetched 0
STAT evictions 0
STAT reclaimed 0
END

I can't find the trigger Why connection is closed by memcached server. Can anybody show me the way to find out the solution? Thank you

Body:
I found the reason. The idle tcp connection is closed by unix system.
the param is in file /proc/sys/net/ipv4/tcp_keepalive_time in seconds

cat /proc/sys/net/ipv4/tcp_keepalive_time
7200

As the solution I try another one attempt to connect to memcached, if first attempt was failed.


问:
How to handle AmqpConnectException on pod restart of a spring boot app?
We're using a (reactive) Spring Boot app with RabbitMQ (Spring AMQP), running on a Kubernetes cluster, and lately we noticed some weird behavior in the logs of the application.

When we make a new deploy to the kubernetes cluster we keep getting the following error repeatedly with the correspond exception stack trace until the new pods are up and old ones destroyed:

Failed to check/redeclare auto-delete queue(s).

```<code>org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:61)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:602)
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:724)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:252)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:2163)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:2136)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:2116)
    at org.springframework.amqp.rabbit.core.RabbitAdmin.getQueueInfo(RabbitAdmin.java:407)
    at org.springframework.amqp.rabbit.core.RabbitAdmin.getQueueProperties(RabbitAdmin.java:391)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.attemptDeclarations(AbstractMessageListenerContainer.java:1914)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.redeclareElementsIfNecessary(AbstractMessageListenerContainer.java:1895)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.initialize(SimpleMessageListenerContainer.java:1347)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1193)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.net.ConnectException: Connection refused
    at java.base/sun.nio.ch.Net.pollConnect(Native Method)
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:660)
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333)
    at java.base/java.net.Socket.connect(Socket.java:648)
    at com.rabbitmq.client.impl.SocketFrameHandlerFactory.create(SocketFrameHandlerFactory.java:60)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1220)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1170)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.connectAddresses(AbstractConnectionFactory.java:640)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.connect(AbstractConnectionFactory.java:615)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:565)
    ... 12 common frames omitted
</code>```

We can't seem to find the source of the issue.

I'd love if anyone have any ideas. Thanks in advance!

答:
Caused by: java.net.ConnectException: Connection refused - means the broker can't be reached.

That is normal behavior - the containers are trying to reconnect. You can control the frequency by setting the container's recoveryBackOff property. By default, the container will attempt to connect every 5 seconds, using a FixedBackOff - you can use a fixed backoff with a longer retry interval, or an ExponentialBackOff that will increase the delay each time.

/**
 * Specify the {@link BackOff} for interval between recovery attempts.
 * The default is 5000 ms, that is, 5 seconds.
 * With the {@link BackOff} you can supply the {@code maxAttempts} for recovery before
 * the {@link #stop()} will be performed.
 * @param recoveryBackOff The BackOff to recover.
 * @since 1.5
 */
public void setRecoveryBackOff(BackOff recoveryBackOff) {
```

Body:
We're using a (reactive) Spring Boot app with RabbitMQ (Spring AMQP), running on a Kubernetes cluster, and lately we noticed some weird behavior in the logs of the application.

When we make a new deploy to the kubernetes cluster we keep getting the following error repeatedly with the correspond exception stack trace until the new pods are up and old ones destroyed:

Failed to check/redeclare auto-delete queue(s).

org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:61)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:602)
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:724)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:252)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:2163)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:2136)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:2116)
    at org.springframework.amqp.rabbit.core.RabbitAdmin.getQueueInfo(RabbitAdmin.java:407)
    at org.springframework.amqp.rabbit.core.RabbitAdmin.getQueueProperties(RabbitAdmin.java:391)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.attemptDeclarations(AbstractMessageListenerContainer.java:1914)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.redeclareElementsIfNecessary(AbstractMessageListenerContainer.java:1895)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.initialize(SimpleMessageListenerContainer.java:1347)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1193)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.net.ConnectException: Connection refused
    at java.base/sun.nio.ch.Net.pollConnect(Native Method)
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:660)
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333)
    at java.base/java.net.Socket.connect(Socket.java:648)
    at com.rabbitmq.client.impl.SocketFrameHandlerFactory.create(SocketFrameHandlerFactory.java:60)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1220)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1170)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.connectAddresses(AbstractConnectionFactory.java:640)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.connect(AbstractConnectionFactory.java:615)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:565)
    ... 12 common frames omitted

We can't seem to find the source of the issue.

I'd love if anyone have any ideas. Thanks in advance!


问:
Show text after choosing option from dropdown menu
how Can i change this code to show the contents of File after choosing option on the same page instead of redirecting to new page ?</p>
```<code>    <div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="file1.txt">Option 1</a>
    <a href="file2.txt">Option 2</a>
    <a href="file3.txt">Option 3</a>
  </div>
</div>
</code>```

答:
You can use PHP to open and read the ".txt" file you want.

```<code>function showFile(){
    $myfile = fopen("file1.txt", "r") or die("Unable to open file!");
    echo fread($myfile,filesize("file1.txt"));
    fclose($myfile);
}
</code>```

With this code the content of the file will be displayed in your page. You can use ajax to call this function to open the desired file.

Body:
how Can i change this code to show the contents of File after choosing option on the same page instead of redirecting to new page ?

  <button class="dropbtn">Dropdown</button>

    Option 1
    Option 2
    Option 3

Body:
You can use PHP to open and read the ".txt" file you want.

function showFile(){
    $myfile = fopen("file1.txt", "r") or die("Unable to open file!");
    echo fread($myfile,filesize("file1.txt"));
    fclose($myfile);
}

With this code the content of the file will be displayed in your page. You can use ajax to call this function to open the desired file.


问:
Get "precise" difference between two "near" IEEE754 double values?
I'm not even sure what I'm asking for is possible, but here goes:

Our C++ code performs the following calculation:

```<code>double get_delta(double lhs, double rhs) {
  return lhs - rhs;
}
</code>```

and with the inputs (nearest double to) 655.36 and 655.34 this does not produce the "nearest" double to exactly 0.02, but a value closer to 0.019999...

Of course, one cannot expect precise results from IEEE double, but I'm wondering if the naive delta calculation could be improved to get nearer to what we expect want:

Given that the two input values can be represented pretty precisely (15 digits, see below), it is unfortunate, but expected, that the difference doe not have the same precision (vs. the ideal result):

As can be seen by the following values, by subtracting two values from each other, the resulting delta value has less significant digits than the two starting values.

While the example values are precise up to 16 decimal digits (DBL_DIG is 15 after all), the resulting Delta Value is only precise up to 13 decimal digits. That is, all digits after the 13th are made up of noise after digit 16 in the original values.

So in this case, rounding the delta value to 13 significant decimal digits would again yield the "correct" result, in that it would give me 0.02d.

So, possibly the question then becomes:

Given two subtraction values a - b that are both assumed to be at double-precision, i.e. a precision of 15 significant decimal digits, how do you calculate the precision of the resulting difference?

Specifically:

```<code>655.36 === 6.55360000000000013642420526594 E2  [v1]
655.34 === 6.55340000000000031832314562052 E2  [v2]
           ^                ^
           1                17

  0.02 === 2.00000000000000004163336342344 E-2 [v3]

655.36
-      === 1.9999999999981810106 E-2 (as calculated in MSVC 2019) [v4]
655.34
           ^            ^   ^
           1            13  17
</code>```

As requested, here's a C++ program generating and printing the numbers involved: https://gist.github.com/bilbothebaggins/d8a44d38b4b54bfefbb67feb5baad0f5

The Numbers as printed from C++ are:

```<code>'a'@14: 6.55360000000000e+02
' '@__: ................
'a'@18: 6.553600000000000136e+02
'a'@XX: 0x40847ae147ae147b

'b'@14: 6.55340000000000e+02
' '@__: ................
'b'@18: 6.553400000000000318e+02
'b'@XX: 0x40847ab851eb851f

'd'@14: 1.99999999999818e-02
' '@__: ................
'd'@18: 1.999999999998181011e-02
'd'@XX: 0x3f947ae147ae0000

'2'@14: 2.00000000000000e-02
' '@__: ................
'2'@18: 2.000000000000000042e-02
'2'@XX: 0x3f947ae147ae147b
</code>```

The delta is later used for some multiplication which naturally worsens the error even more.

Is there a way to do the delta calculation in a more sophisticated way so that we get closer to the "correct" answer?

My current thoughts are along the lines of:

If we were to calculate using an infinite precision type, given an input of double, we would first have to decide how to round the given doubles to our infinite precision type.

Say, we round to 15 decimal digits (that would be way enough for our use case's inputs), we would get exact values -- i.e. 655.3? exactly. And if we then calculate the infinite precision delta, we would get 0.02 exactly. And if we then would convert that value back to double, we'd get the value v3and not the "wrong" value v4.

So, would there be a way to normalize the starting values so that this (rounding) process could be replicated in pure IEEE754 calculations?

答:
Get "precise" difference between two "near" IEEE754 double values?

This is generally not possible using finite floating point arithmetic, because the precise difference is not necessarily representable by the floating point type.

This can be achieved by converting the floating point numbers to an arbitrary precision representation, and calculating the result using that arbitrary precision. There are no arbitrary precision types in the standard library.

Body:
I'm not even sure what I'm asking for is possible, but here goes:

Our C++ code performs the following calculation:

double get_delta(double lhs, double rhs) {
  return lhs - rhs;
}

and with the inputs (nearest double to) 655.36 and 655.34 this does not produce the "nearest" double to exactly 0.02, but a value closer to 0.019999...

Of course, one cannot expect precise results from IEEE double, but I'm wondering if the naive delta calculation could be improved to get nearer to what we expect want:

Given that the two input values can be represented pretty precisely (15 digits, see below), it is unfortunate, but expected, that the difference doe not have the same precision (vs. the ideal result):

As can be seen by the following values, by subtracting two values from each other, the resulting delta value has less significant digits than the two starting values.

While the example values are precise up to 16 decimal digits (DBL_DIG is 15 after all), the resulting Delta Value is only precise up to 13 decimal digits. That is, all digits after the 13th are made up of noise after digit 16 in the original values.

So in this case, rounding the delta value to 13 significant decimal digits would again yield the "correct" result, in that it would give me 0.02d.

So, possibly the question then becomes:

Given two subtraction values a - b that are both assumed to be at double-precision, i.e. a precision of 15 significant decimal digits, how do you calculate the precision of the resulting difference?

Specifically:

655.36 === 6.55360000000000013642420526594 E2  [v1]
655.34 === 6.55340000000000031832314562052 E2  [v2]
           ^                ^
           1                17

  0.02 === 2.00000000000000004163336342344 E-2 [v3]

655.36
-      === 1.9999999999981810106 E-2 (as calculated in MSVC 2019) [v4]
655.34
           ^            ^   ^
           1            13  17

As requested, here's a C++ program generating and printing the numbers involved: https://gist.github.com/bilbothebaggins/d8a44d38b4b54bfefbb67feb5baad0f5

The Numbers as printed from C++ are:

'a'@14: 6.55360000000000e+02
' '@__: ................
'a'@18: 6.553600000000000136e+02
'a'@XX: 0x40847ae147ae147b

'b'@14: 6.55340000000000e+02
' '@__: ................
'b'@18: 6.553400000000000318e+02
'b'@XX: 0x40847ab851eb851f

'd'@14: 1.99999999999818e-02
' '@__: ................
'd'@18: 1.999999999998181011e-02
'd'@XX: 0x3f947ae147ae0000

'2'@14: 2.00000000000000e-02
' '@__: ................
'2'@18: 2.000000000000000042e-02
'2'@XX: 0x3f947ae147ae147b

The delta is later used for some multiplication which naturally worsens the error even more.

Is there a way to do the delta calculation in a more sophisticated way so that we get closer to the "correct" answer?

My current thoughts are along the lines of:

If we were to calculate using an infinite precision type, given an input of double, we would first have to decide how to round the given doubles to our infinite precision type.

Say, we round to 15 decimal digits (that would be way enough for our use case's inputs), we would get exact values -- i.e. 655.3? exactly. And if we then calculate the infinite precision delta, we would get 0.02 exactly. And if we then would convert that value back to double, we'd get the value v3and not the "wrong" value v4.

So, would there be a way to normalize the starting values so that this (rounding) process could be replicated in pure IEEE754 calculations?


问:
How to remove all empty lines from beginning and end of file
I have a file that looks like

```<code>Blank Line
Blank Line
Blank Line
Blank Line
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi a justo egestas, malesuada lacus ut, euismod purus.
Etiam faucibus felis ac orci varius cursus.

Praesent tincidunt nibh condimentum, finibus odio non, euismod tortor.
Quisque eget ligula eu turpis consequat rutrum.

Cras non ipsum vel ipsum sodales ullamcorper non vitae dui.
Blank Line
Blank Line
Blank Line
Blank Line
</code>```

The Blank Line is literally blank line. I could not put blank lines in the beginning and end in the code block so using the text Blank Line.

I need to remove all the blank lines from the beginning and end of this file. Please notice that there are blank lines in between lines. I do not want to remove those.

I have come up with the following code that remove all blank lines from the beginning of the file. But I could not manage to remove all the blank lines at the end of the file.

```<code>#!/usr/bin/env python3

import sys
import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
parser.add_argument(
    '-d',
    '--debug',
    help="Print lots of debugging statements",
    action="store_const",
    dest="loglevel",
    const=logging.DEBUG,
    default=logging.WARNING,
)
parser.add_argument(
    '-v',
    '--verbose',
    help="Be verbose",
    action="store_const",
    dest="loglevel",
    const=logging.INFO,
)
args = parser.parse_args()

if sys.stdin.isatty() and args.infile.name == "<stdin>":
    sys.exit("Please give some input")

logging.basicConfig(level=args.loglevel)

# Business Logic Here
do_not_print_all_lines = True

for line in args.infile:
    if not line.strip() and do_not_print_all_lines:
        pass
    else:
        do_not_print_all_lines = False

    if not do_not_print_all_lines:
        print(line)
</code>```

How can I do that?

答:
Can you just first read the file into a list?
Then, you can address empty lines from the beginning and the end of the list</p>

Body:
I have a file that looks like

Blank Line
Blank Line
Blank Line
Blank Line
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi a justo egestas, malesuada lacus ut, euismod purus.
Etiam faucibus felis ac orci varius cursus.

Praesent tincidunt nibh condimentum, finibus odio non, euismod tortor.
Quisque eget ligula eu turpis consequat rutrum.

Cras non ipsum vel ipsum sodales ullamcorper non vitae dui.
Blank Line
Blank Line
Blank Line
Blank Line

The Blank Line is literally blank line. I could not put blank lines in the beginning and end in the code block so using the text Blank Line.

I need to remove all the blank lines from the beginning and end of this file. Please notice that there are blank lines in between lines. I do not want to remove those.

I have come up with the following code that remove all blank lines from the beginning of the file. But I could not manage to remove all the blank lines at the end of the file.

#!/usr/bin/env python3

import sys
import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
parser.add_argument(
    '-d',
    '--debug',
    help="Print lots of debugging statements",
    action="store_const",
    dest="loglevel",
    const=logging.DEBUG,
    default=logging.WARNING,
)
parser.add_argument(
    '-v',
    '--verbose',
    help="Be verbose",
    action="store_const",
    dest="loglevel",
    const=logging.INFO,
)
args = parser.parse_args()

if sys.stdin.isatty() and args.infile.name == "<stdin>":
    sys.exit("Please give some input")

logging.basicConfig(level=args.loglevel)

# Business Logic Here
do_not_print_all_lines = True

for line in args.infile:
    if not line.strip() and do_not_print_all_lines:
        pass
    else:
        do_not_print_all_lines = False

    if not do_not_print_all_lines:
        print(line)

How can I do that?


问:
How to integrate smarty in cakephp 1.2?
Can any1 suggest me some good and COMPLETE documentation on integrating smarty templates in cakephp 1.2 and which version of smarty should I use with cakephp 1.2?</p>

答:
CakePHP has a pretty good template engine that nearly all developers are more than happy with - so there isn't much out there for adding Smarty. There are two articles in the bakery which may be worth a read:

http://bakery.cakephp.org/articles/tclineks/2006/10/27/how-to-use-smarty-with-cake-smartyview

http://bakery.cakephp.org/articles/HyperCas/2008/06/11/the-cakephp-blog-tutorial-with-smarty

But I would urge you to check out:

http://book.cakephp.org/view/1078/Views

Which is a pretty handy guide on just what can be achieved with the CakePHP views.

Title: How to integrate smarty in cakephp 1.2?