问:
How do I load controls in different ContentControls of a Shell using CaliburnMicro
By default when you use "ActivateItem(new Control());" your control is loaded into a ContentControl which with the name ActiveItem, fro example. . If I have multiple content controls on my page how would I load controls into them whilst retaining the ability to use the default functionality of being able to load controls into the the active item control.

for example I want to have a login control to be loaded into the Login ContentControl, and when a user successfully login I want a new control to be loaded into the ActiveItem ContentControl.

Thanx in advance.

答:
This is an old question, but in case anyone is having the same issue, here is my solution:

Your main window that contain both (or even more than two) of your User Controls must be inherited from Caliburn.Micro.Conductor<Screen>.Collection.AllActive;

Your User Controls must be inherited from Caliburn.Micro.Screen;

You must also keep naming conventions in mind. If you use MenuUC as the name of a ContentControl in your View, also create a property named MenuUC in your ViewModel;

Initialize your UserControl as I do in Constructor;

Now you can use ActivateItem(MenuUC) and DeactivateItem(MenuUC) everywhere in your code. Caliburn.Micro automatically detects which one you want to work with.

Example XAML View code:

<Window x:Class="YourProject.Views.YourView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="YourViewTitle" Width="900" Height="480">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="4*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ContentControl Grid.Row="0" Grid.Column="0" x:Name="MenuUC" />

        <Border Grid.Column="1" Grid.RowSpan="2" BorderThickness="1,0,0,0" BorderBrush="#FF707070" >
            <ContentControl x:Name="PanelUC" />
        </Border>
    </Grid>
</Window>
```

<blockquote>
  <p>Example C# ViewModel code:</p>
</blockquote>

<pre class="lang-cs prettyprint-override"><code>class YourViewModel : Conductor<Screen>.Collection.AllActive
{
    // Menu Side Bar
    private MenuUCViewModel _menuUC;
    public MenuUCViewModel MenuUC
    {
        get { return _menuUC; }
        set { _menuUC = value; NotifyOfPropertyChange(() => MenuUC); }
    }

    // Panel
    private Screen _panelUC;
    public Screen PanelUC
    {
        get { return _panelUC; }
        set { _panelUC = value; NotifyOfPropertyChange(() => PanelUC); }
    }

    // Constructor
    public YourViewModel()
    {
        MenuUC = new MenuUCViewModel();
        ActivateItem(MenuUC);

        PanelUC = new FirstPanelUCViewModel();
        ActivateItem(PanelUC);
    }

    // Some method that changes PanelUC (previously FirstPanelUCViewModel) to SecondPanelUCViewModel
    public void ChangePanels()
    {
        DeactivateItem(PanelUC);
        PanelUC = new SecondPanelUCViewModel();
        ActivateItem(PanelUC);
    }
}
</code>```

In the above example, ChangePanels() acts as a method to load new User Control into your ContentControl.

Also read this question, it might be help you further.

Body:
This is an old question, but in case anyone is having the same issue, here is my solution:

Your main window that contain both (or even more than two) of your User Controls must be inherited from Caliburn.Micro.Conductor<Screen>.Collection.AllActive;

Your User Controls must be inherited from Caliburn.Micro.Screen;

You must also keep naming conventions in mind. If you use MenuUC as the name of a ContentControl in your View, also create a property named MenuUC in your ViewModel;

Initialize your UserControl as I do in Constructor;

Now you can use ActivateItem(MenuUC) and DeactivateItem(MenuUC) everywhere in your code. Caliburn.Micro automatically detects which one you want to work with.

Example XAML View code:

<Window x:Class="YourProject.Views.YourView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="YourViewTitle" Width="900" Height="480">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="4*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Menu Side Bar -->
        <ContentControl Grid.Row="0" Grid.Column="0" x:Name="MenuUC" />

        <!-- Panel -->
        <Border Grid.Column="1" Grid.RowSpan="2" BorderThickness="1,0,0,0" BorderBrush="#FF707070" >
            <ContentControl x:Name="PanelUC" />
        </Border>
    </Grid>
</Window>

Example C# ViewModel code:

class YourViewModel : Conductor<Screen>.Collection.AllActive
{
    // Menu Side Bar
    private MenuUCViewModel _menuUC;
    public MenuUCViewModel MenuUC
    {
        get { return _menuUC; }
        set { _menuUC = value; NotifyOfPropertyChange(() => MenuUC); }
    }

    // Panel
    private Screen _panelUC;
    public Screen PanelUC
    {
        get { return _panelUC; }
        set { _panelUC = value; NotifyOfPropertyChange(() => PanelUC); }
    }

    // Constructor
    public YourViewModel()
    {
        MenuUC = new MenuUCViewModel();
        ActivateItem(MenuUC);

        PanelUC = new FirstPanelUCViewModel();
        ActivateItem(PanelUC);
    }

    // Some method that changes PanelUC (previously FirstPanelUCViewModel) to SecondPanelUCViewModel
    public void ChangePanels()
    {
        DeactivateItem(PanelUC);
        PanelUC = new SecondPanelUCViewModel();
        ActivateItem(PanelUC);
    }
}

In the above example, ChangePanels() acts as a method to load new User Control into your ContentControl.

Also read this question, it might be help you further.


来源: stackexchange

问:
Debugging a service
I have written a service with a remote interface and installed it on my PC's Eclipse AVD. I have a client test harness which starts and invokes methods in the service. Initially I had the service installed by a control class and activity, which I have now removed, so that the manifest for the service looks like:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myname.gridservice"
android:versionCode="1"
android:versionName="1.0">
<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:debuggable="true">
    <service
        android:enabled="true"
        android:debuggable="true"
        android:name="OverlayService">
        <intent-filter>
            <action android:name="com.myname.OverlayService.SERVICE"/>
            <action android:name="com.myname.gridservice.IRemoteInterface" />
        </intent-filter>
    </service>
 </application>
</manifest>
</code>```

so there's no activity tag.

When I launch it from the debug icon in Eclipse, the console tells me that it's installing the apk (which it is), but it does not appear as a debug thread and breakpoints aren't triggered, although the service's behaviour is OK as far as the client sees it. If I wrap the service tag in an activity tag which has an associated class and launch that, then I can debug it.

Is it possible to debug the service without wrapping it in an activity?

答:
Some of the answers correctly mention that you'd want to insert

```<code>android.os.Debug.waitForDebugger();
</code>```

into the first interesting method of the service. However, it's not clear from those answers, that the Android Studio debugger will not start automatically when the service is started.

Instead, you also need to wait till the service has started, then press the button to attach to process (see screenshot for Android Studio 3.6.1 .. it is the 3rd button to the right from the debug button). You will be given a choice of processes to attach to, one of which would be the service's separate process. You can then select it to complete the process of attaching the debugger to the service.

Edit, Aug 2020: the button icon is the same in Android Studio 4.0

ContentLicense: CC BY-SA 4.0

Title: Debugging a service

Body:
I have written a service with a remote interface and installed it on my PC's Eclipse AVD. I have a client test harness which starts and invokes methods in the service. Initially I had the service installed by a control class and activity, which I have now removed, so that the manifest for the service looks like:

<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myname.gridservice"
android:versionCode="1"
android:versionName="1.0">
<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:debuggable="true">
    <service
        android:enabled="true"
        android:debuggable="true"
        android:name="OverlayService">
        <intent-filter>
            <action android:name="com.myname.OverlayService.SERVICE"/>
            <action android:name="com.myname.gridservice.IRemoteInterface" />
        </intent-filter>
    </service>
 </application>
</manifest>

so there's no activity tag.

When I launch it from the debug icon in Eclipse, the console tells me that it's installing the apk (which it is), but it does not appear as a debug thread and breakpoints aren't triggered, although the service's behaviour is OK as far as the client sees it. If I wrap the service tag in an activity tag which has an associated class and launch that, then I can debug it.

Is it possible to debug the service without wrapping it in an activity?

Body:
Some of the answers correctly mention that you'd want to insert

android.os.Debug.waitForDebugger();

into the first interesting method of the service. However, it's not clear from those answers, that the Android Studio debugger will not start automatically when the service is started.

Instead, you also need to wait till the service has started, then press the button to attach to process (see screenshot for Android Studio 3.6.1 .. it is the 3rd button to the right from the debug button). You will be given a choice of processes to attach to, one of which would be the service's separate process. You can then select it to complete the process of attaching the debugger to the service.

Edit, Aug 2020: the button icon is the same in Android Studio 4.0


问:
is it possible to block form submit with only nodejs?
The HTML file where form is in doesn't have any client side javascript code. That I cannot change directly because my task is nodejs and express.

```<code>app.post('/',function(request,response){
const htmlCode = fs.readFileSync(__dirname + '/loggain.html');
const loggaInDom = new jsDOM.JSDOM(htmlCode);
const input = request.body.nickname;
try{
    if(input.length<3){
        throw new Error("nickname must be at least 3 characters");
    }
    else{
        response.cookie('nickName',input);
        response.redirect('index.html');
        console.log(request.cookies.nickName);
    }
}
catch(error){
    console.log(error);
}
});
</code>```

This is part of my nodejs code.
I would like to block form submit when input.length is smaller than 3. Like event.preventDefault() in client javascript code.
Now it throws error in console, which is correct, but browser keeps loading page permanently.

I cannot directly change HTML file but probably can insert client javascript file to HTML with nodejs, but I would like to know if it is possible to do with only nodeJS

答:
Instead of throwing the error you need to send a response to the client with an error status:

```<code>if(input.length<3){
    response.status(400).send("nickname must be at least 3 characters");
}
</code>```

Choose the appropriate error code depending on your error: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

You can also send json instead of text if you want some structure that your frontend can use:

```<code>if(input.length<3){
    response.status(400).json({
        type: "validation error",
        message: "nickname must be at least 3 characters"
    });
}
</code>```

Centralized error handling

Alternatively you may not want standardize error handling and do the response.status() thing at one location. Express has a way to catch errors but you cannot use the throw keyword. Instead you pass your error to the next function:

```<code>app.post('/',function(request, response, next){ // NOTE: next
  const htmlCode = fs.readFileSync(__dirname + '/loggain.html');
  const loggaInDom = new jsDOM.JSDOM(htmlCode);
  const input = request.body.nickname;
  try{
    if(input.length<3){
        throw new Error("nickname must be at least 3 characters");
    }
    else{
        response.cookie('nickName',input);
        response.redirect('index.html');
        console.log(request.cookies.nickName);
    }
  }
  catch(error){
    next(error); // This is how errors are handled in Express
  }
});
</code>```

Now all you need to do is write a default error handler which is a special middleware that accepts four arguments instead of three or two. Make sure this middleware is loaded last after all your routes:

```<code>app.use((error, request, response, next) => {
    response.status(500).send(error.message);
});
</code>```

When used with error types you can send different responses to the browser depending on types of error:

```<code>class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError"; // (2)
  }
}
</code>```

Then you can throw:

```<code>next(new ValidationError("nickname must be at least 3 characters"))
</code>```

Which you can handle with:

```<code>app.use((error, request, response, next) => {
    switch(error.name) {
        case "ValidationError":
            response.status(400);
            break;
        default:
            response.status(500);
    }
    response.send(error.message);
});
</code>```

Body:
The HTML file where form is in doesn't have any client side javascript code. That I cannot change directly because my task is nodejs and express.

app.post('/',function(request,response){
const htmlCode = fs.readFileSync(__dirname + '/loggain.html');
const loggaInDom = new jsDOM.JSDOM(htmlCode);
const input = request.body.nickname;
try{
    if(input.length<3){
        throw new Error("nickname must be at least 3 characters");
    }
    else{
        response.cookie('nickName',input);
        response.redirect('index.html');
        console.log(request.cookies.nickName);
    }
}
catch(error){
    console.log(error);
}
});

This is part of my nodejs code.
I would like to block form submit when input.length is smaller than 3. Like event.preventDefault() in client javascript code.
Now it throws error in console, which is correct, but browser keeps loading page permanently.

I cannot directly change HTML file but probably can insert client javascript file to HTML with nodejs, but I would like to know if it is possible to do with only nodeJS

Body:
Instead of throwing the error you need to send a response to the client with an error status:

if(input.length<3){
    response.status(400).send("nickname must be at least 3 characters");
}

Choose the appropriate error code depending on your error: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

You can also send json instead of text if you want some structure that your frontend can use:

if(input.length<3){
    response.status(400).json({
        type: "validation error",
        message: "nickname must be at least 3 characters"
    });
}

Centralized error handling

Alternatively you may not want standardize error handling and do the response.status() thing at one location. Express has a way to catch errors but you cannot use the throw keyword. Instead you pass your error to the next function:

app.post('/',function(request, response, next){ // NOTE: next
  const htmlCode = fs.readFileSync(__dirname + '/loggain.html');
  const loggaInDom = new jsDOM.JSDOM(htmlCode);
  const input = request.body.nickname;
  try{
    if(input.length<3){
        throw new Error("nickname must be at least 3 characters");
    }
    else{
        response.cookie('nickName',input);
        response.redirect('index.html');
        console.log(request.cookies.nickName);
    }
  }
  catch(error){
    next(error); // This is how errors are handled in Express
  }
});

Now all you need to do is write a default error handler which is a special middleware that accepts four arguments instead of three or two. Make sure this middleware is loaded last after all your routes:

app.use((error, request, response, next) => {
    response.status(500).send(error.message);
});

When used with error types you can send different responses to the browser depending on types of error:

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError"; // (2)
  }
}

Then you can throw:

next(new ValidationError("nickname must be at least 3 characters"))

Which you can handle with:

app.use((error, request, response, next) => {
    switch(error.name) {
        case "ValidationError":
            response.status(400);
            break;
        default:
            response.status(500);
    }
    response.send(error.message);
});


问:
display blob 2 times
There is a way to copy a node with a blob src?

I need to clone the image blob which is over in a new div.

this is what I have when I log my HTML blob element when I over it:

```

<p>or </p>

<pre class="lang-html prettyprint-override"><code><img src="blob:http://127.0.0.1:5500/1cd7dcbf-b6eb-412d-a37e-2c7709815e32" class="img" style="width: 25%; height: 60px;">
</code>```

for example. Theses images working correctly.

And if I try to do this, for copying these Html node and put them in a div which have divResult as name :

let clone = srcEl.cloneNode(true);
divResult.appendChild(clone)
```

the image not appear in my divResult but the src is here.

Any solution?

答:
Ensure divResult doesn't have a style which causes elements inside it to be hidden.

Example

const divResult = document.querySelector("#divResult");
const url = "https://i.picsum.photos/id/440/50/50.jpg"

fetch(url)
  .then((response) => response.blob())
  .then((blob) => {
    const image1 = document.createElement("img");
    image1.src = URL.createObjectURL(blob);
    const parent = document.body;

    parent.appendChild(image1);

    const clonedElement = image1.cloneNode(true);
    divResult.appendChild(clonedElement)
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#divResult {

  /* display: none; */

  /* visibility: hidden; */

  /* height: 0;
   overflow: hidden; */
}

#divResult img {
 /* same as above */
}</code>```

```

Title: display blob 2 times

Body:
There is a way to copy a node with a blob src?

I need to clone the image blob which is over in a new div.

this is what I have when I log my HTML blob element when I over it:

or

for example. Theses images working correctly.

And if I try to do this, for copying these Html node and put them in a div which have divResult as name :

let clone = srcEl.cloneNode(true);
divResult.appendChild(clone)

the image not appear in my divResult but the src is here.

Any solution?

Body:
Ensure divResult doesn't have a style which causes elements inside it to be hidden.

Example

const divResult = document.querySelector("#divResult");
const url = "https://i.picsum.photos/id/440/50/50.jpg"

fetch(url)
  .then((response) => response.blob())
  .then((blob) => {
    const image1 = document.createElement("img");
    image1.src = URL.createObjectURL(blob);
    const parent = document.body;

    parent.appendChild(image1);

    const clonedElement = image1.cloneNode(true);
    divResult.appendChild(clonedElement)
  });

#divResult {

  /* display: none; */

  /* visibility: hidden; */

  /* height: 0;
   overflow: hidden; */
}

#divResult img {
 /* same as above */
}

<div id="divResult"></div>


问:
arrayWithContentsOfFile can't read plist file
i have a plist with an array that contain 2 strings see image :

http://imageshack.us/photo/my-images/263/myplist.png/

and in my viewDidLoad i add this :

```<code>NSString *file = [[NSBundle  mainBundle] pathForResource:@"Data"    ofType:@"plist"];

NSArray *array = [NSArray    arrayWithContentsOfFile:file];

NSLog(@"array = %@", array);
</code>```

But i got always null why? Thanks for help.

UPDATE : the solution is that you need to manually edit the plist file (Xcode4 use Dictionnary by default)

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <array>
        <string>HO</string>
        <string>HI</string>
    </array>
</array>
</plist>
</code>```

答:
Most likely, your plist is a dictionary that contains an array (Xcode 4 doesn't allow to create plists with an array as the root object). Try something like this:</p>

```<code>NSString *file = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];
NSArray *array = [dict objectForKey:@"Array"];
NSLog(@"%@", array);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have a plist with an array that contain 2 strings see image :

http://imageshack.us/photo/my-images/263/myplist.png/

and in my viewDidLoad i add this :

NSString *file = [[NSBundle  mainBundle] pathForResource:@"Data"    ofType:@"plist"];

NSArray *array = [NSArray    arrayWithContentsOfFile:file];

NSLog(@"array = %@", array);

But i got always null why? Thanks for help.

UPDATE : the solution is that you need to manually edit the plist file (Xcode4 use Dictionnary by default)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <array>
        <string>HO</string>
        <string>HI</string>
    </array>
</array>
</plist>

Body:
Most likely, your plist is a dictionary that contains an array (Xcode 4 doesn't allow to create plists with an array as the root object). Try something like this:

NSString *file = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];
NSArray *array = [dict objectForKey:@"Array"];
NSLog(@"%@", array);


问:
Convert "only/except" clauses to "rules" clause in Gitlab CI

Problem Summary:

My goal is to add a rules clause to configure a Gitlab CI job to run if an environment variable is set, or if manual action is performed. Unfortunately, the step currently makes use of only and except clauses so I'll have to also convert them into rules syntax, which I've not fully grasped yet.

Current Job Definition:

deploy:
  only:
    - branches
  except:
    refs:
      - /flux-.*$/
      - master
  stage: deploy
  when: manual
```
<h3>Required Changes:</h3>
<p>I'll be replacing</p>
<pre class="lang-yaml prettyprint-override"><code>when: manual
</code>```

with

rules:
  - if: '$CI_ENVIRONMENT_NAME'
  - when: manual
```

Now I'd like to learn how to translate the only/except clauses. I think it'll be completely based on predefined environment variable tests, though I'm unsure which variables are of interest for this translation.

Many thanks for any suggestions or pointers.

答:
As you pointed out using predefined environment variables is the way to go with rules. Many of them can be used to achieve the same thing, it really depends on your needs (For example: $CI_COMMIT_REF_NAME vs $CI_COMMIT_REF_SLUG vs $CI_COMMIT_BRANCH).

My goal is to add a rules clause to configure a Gitlab CI job to run if an environment variable is set, or if manual action is performed.

Just to be sure to understand what you mean by that:

If $CI_ENVIRONMENT_NAME then always run the deploy job, otherwise if the branch is not master and doesn't match /flux-.*$/, then allow the deploy job to be triggered manually.

Is that correct?

If yes, one implementation would look like this below. (You can also use || operators to merge the 2 first rules if you want)

```<code>deploy:
  stage: deploy
  rules:
    - if: '$CI_COMMIT_REF_NAME == "master"'
      when: never
    - if: '$CI_COMMIT_REF_NAME =~ /flux-.*$/'
      when: never
    - if: '$CI_ENVIRONMENT_NAME'
    - when: manual
</code>```

Keep in mind that rules are evaluated in order. Hope that helps.

Body:
Problem Summary:

My goal is to add a rules clause to configure a Gitlab CI job to run if an environment variable is set, or if manual action is performed. Unfortunately, the step currently makes use of only and except clauses so I'll have to also convert them into rules syntax, which I've not fully grasped yet.

Current Job Definition:

deploy:
  only:
    - branches
  except:
    refs:
      - /flux-.*$/
      - master
  stage: deploy
  when: manual

Required Changes:

I'll be replacing

when: manual

with

rules:
  - if: '$CI_ENVIRONMENT_NAME'
  - when: manual

Now I'd like to learn how to translate the only/except clauses. I think it'll be completely based on predefined environment variable tests, though I'm unsure which variables are of interest for this translation.

Many thanks for any suggestions or pointers.

Body:
As you pointed out using predefined environment variables is the way to go with rules. Many of them can be used to achieve the same thing, it really depends on your needs (For example: $CI_COMMIT_REF_NAME vs $CI_COMMIT_REF_SLUG vs $CI_COMMIT_BRANCH).

My goal is to add a rules clause to configure a Gitlab CI job to run if an environment variable is set, or if manual action is performed.

Just to be sure to understand what you mean by that:

If $CI_ENVIRONMENT_NAME then always run the deploy job, otherwise if the branch is not master and doesn't match /flux-.*$/, then allow the deploy job to be triggered manually.

Is that correct?

If yes, one implementation would look like this below. (You can also use || operators to merge the 2 first rules if you want)

deploy:
  stage: deploy
  rules:
    - if: '$CI_COMMIT_REF_NAME == "master"'
      when: never
    - if: '$CI_COMMIT_REF_NAME =~ /flux-.*$/'
      when: never
    - if: '$CI_ENVIRONMENT_NAME'
    - when: manual

Keep in mind that rules are evaluated in order. Hope that helps.


问:
How do I use Apache Tailer within a Spring Boot App?

Main Question

I'm writing an app (available here on GitHub - build/run instructions below) that scrapes a log file and reacts to certain events written to the log (in this case, making an HTTP request to a REST API).  I've chosen Java, Spring Boot 2.x, Apache Tailer and OpenFeign as the primary vehicles to that end.

I suspect I'm not understanding how Apache Tailer and the threading it does in the background work, or how to properly leverage it within a Spring Boot app.  What's a correct way to initialize and run a Tailer in the context of a Spring Boot app?

Additional Info

To test this, I'm starting the app locally, and echoing lines of text into the given log file via a shell.
As of writing (commit 1fed906), when I run the app it seems that:

The Tailer initializes (I can see TailerListenerAdapter.init() is called on the TailerListenerAdapter I constructed it with)

The Tailer runs (I see everything I write to the log file it watches passed to TailerListenerAdapter.handle()).

As soon as I write something to the log that my TailerListenerAdapter knows it should react to,  it looks like control exits from the Tailer.run() method call, and the app exits (gracefully).  I want it to keep running and tailing the log until I stop the app though.

I wasn't really sure where to call Tailer.run() in this context so I have it in a @PostConstruct method in my custom Tailer subclass. I've never used @PostConstruct before, so I'm not 100% sure I'm using it correctly, or if there's a better place to put it to ensure that run() gets called at start up while also allowing me to inject all of my my config-file / bean driven options into it.

Build / Run Instructions

Clone the project

Run this in a shell:
mvn spring-boot:run -Dspring-boot.run.arguments=--tailer.logFile=/path/to/any/test.log,--logging.level.com.github.ubunfu.mclogbot=DEBUG

OR

Set up an equivalent run configuration in your IDE. There's an application-local.yml Spring Boot config file with a place to specify the path to the test log file. In IntelliJ, set up a Maven run config with the following in Command Line: spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=local

答:
I'm pretty sure now that the right way to run the Tailer in a Spring Boot app is to modify the main class to implement CommandLineRunner (as described in this nice little Mkyong article), and run the Tailer from there.  I believe this is because Spring boot assumes that you're writing a web app where the entry-point is an inbound request to be handled by Tomcat or something.  If you want to change the entry-point (e.g. it's not a web app), you'd do the above and essentially override the default behavior.

Also, I had a problem where the app would stop gracefully unexpectedly after reading a line that was supposed to result in the Feign client making an API call.  It turns out the reason for that was that the Feign client was throwing a RuntimeException that I wasn't handling.  It was not immediately apparent that any exception had occurred because there wasn't a stack trace or anything.  I suspect this is because the Tailer is running in another thread? I'm not really sure.  Point is - watch out for that when you're using Tailer!

I hope this helps somebody!


问:
What rotation should I apply to my hamburger?
I'm trying to animate a simple two-line span which transforms into an 'X' shape when you click on it - but can't for the life of me work out what rotation I should do to align them properly. They just aren't rotating/translating to be a perfect 'X' shape.

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 30px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  cursor: pointer;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translate(10px, 10px) rotate(-45deg);
}

#line-2.active {
  transform: translate(10px, -10px) rotate(45deg)
}</code>```

  ```

If anybody can explain how they'd work it out too, that'd be great. I can't find the right resource out there for it.

答:
You can create a CSS rule for #hamburger-container.active which changes the containers height to 40px in order to change the vertical distance between the lines to fit the 45°  angle between them, and add a line to the active() function to toggle that class.

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
  hamburger.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 30px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  cursor: pointer;
  transition: all .5s ease-in-out;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translate(10px, 10px) rotate(-45deg);
}

#line-2.active {
  transform: translate(10px, -10px) rotate(45deg)
}
#hamburger-container.active {
  height: 40px;
}</code>```

  ```

Body:
I'm trying to animate a simple two-line span which transforms into an 'X' shape when you click on it - but can't for the life of me work out what rotation I should do to align them properly. They just aren't rotating/translating to be a perfect 'X' shape.

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 30px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  cursor: pointer;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translate(10px, 10px) rotate(-45deg);
}

#line-2.active {
  transform: translate(10px, -10px) rotate(45deg)
}

If anybody can explain how they'd work it out too, that'd be great. I can't find the right resource out there for it.

Body:
You can create a CSS rule for #hamburger-container.active which changes the containers height to 40px in order to change the vertical distance between the lines to fit the 45°  angle between them, and add a line to the active() function to toggle that class.

// Variables

let line1 = document.getElementById("line-1");
let line2 = document.getElementById("line-2");
let hamburger = document.getElementById("hamburger-container");

// Function

function active() {
  line1.classList.toggle("active");
  line2.classList.toggle("active");
  hamburger.classList.toggle("active");
}

// Event Listener

hamburger.addEventListener("click", active);

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #999;
}

#hamburger-container {
  height: 30px;
  width: 40px;
  margin-right: 10%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  cursor: pointer;
  transition: all .5s ease-in-out;
}

.hamburger-line {
  height: 5px;
  width: 30px;
  background-color: #fff;
  transition: all .5s ease-in-out;
  cursor: pointer;
}

#line-1.active {
  transform: translate(10px, 10px) rotate(-45deg);
}

#line-2.active {
  transform: translate(10px, -10px) rotate(45deg)
}
#hamburger-container.active {
  height: 40px;
}

<header class="header-section">
    <div id="hamburger-container">
      <span id="line-1" class="hamburger-line"></span>
      <span id="line-2" class="hamburger-line"></span>
    </div>
  </header>


问:
Unity error: 'Animator' does not contain a definition for 'Setbool'
Hello I am new to coding in c# and I don't know what the problem is with this code, I am trying to make a game where you can walk left and right and an animation plays and if you press down or up it takes out a parasol. </p>

```<code>public int idleCheck = 5;

Animator A_anim;

// Start is called before the first frame update
void Start()
{
    A_anim = gameObject.GetComponent<Animator>();
}

// Update is called once per frame
void Update()
{
    if (Input.GetButtonDown("LeftRight"))
    {
        idleCheck = 2;
    }

    if (Input.GetButtonDown("Vertical"))
    {
        idleCheck = 1;
    }

    if (Input.GetButtonDown("LeftRight"))
    {
        idleCheck = 3;
    }

    if (idleCheck == 3)
    {
        A_anim.Setbool("ParaRun", true);
    }
    else if (idleCheck == 3)
    {
        A_anim.Setbool("ParaRun", false);
    }
    if (idleCheck == 2)
    {
        A_anim.Setbool("RunNor", true);
    }
    else if (idleCheck == 2)
    {
        A_anim.Setbool("RunNor", false);
    }
    if (idleCheck == 1)
    {
        A_anim.Setbool("parasole ability", true);
    }
    else if (idleCheck == 1)
    {
        A_anim.Setbool("parasole ability", false);
    }
}
</code>```

答: Yes Setbool does not exist but SetBool does :). Just a typo, you can check their documentation for more details.</p>

Body:
Hello I am new to coding in c# and I don't know what the problem is with this code, I am trying to make a game where you can walk left and right and an animation plays and if you press down or up it takes out a parasol.

public int idleCheck = 5;

Animator A_anim;

// Start is called before the first frame update
void Start()
{
    A_anim = gameObject.GetComponent<Animator>();
}

// Update is called once per frame
void Update()
{
    if (Input.GetButtonDown("LeftRight"))
    {
        idleCheck = 2;
    }

    if (Input.GetButtonDown("Vertical"))
    {
        idleCheck = 1;
    }

    if (Input.GetButtonDown("LeftRight"))
    {
        idleCheck = 3;
    }

    if (idleCheck == 3)
    {
        A_anim.Setbool("ParaRun", true);
    }
    else if (idleCheck == 3)
    {
        A_anim.Setbool("ParaRun", false);
    }
    if (idleCheck == 2)
    {
        A_anim.Setbool("RunNor", true);
    }
    else if (idleCheck == 2)
    {
        A_anim.Setbool("RunNor", false);
    }
    if (idleCheck == 1)
    {
        A_anim.Setbool("parasole ability", true);
    }
    else if (idleCheck == 1)
    {
        A_anim.Setbool("parasole ability", false);
    }
}


问:
Why am I getting empty Array outside of FOR loop in Typescript (Angular CLI)?
Before raising this question, I have gone through the similar issues raised, but no luck in fixing my issue. So I'm raising this question again to understand on why exactly this is happening.

I started creating one web application where in one of my page users can download data by just clicking the button provided. Everything worked fine till I started using FOR loop to get some additional data and adding it to new array. Here is my code for better explaination.

employee-list.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { RestApiService } from "../shared/rest-api.service";

@Component({
  selector: 'app-employees-list',
  templateUrl: './employees-list.component.html',
  styleUrls: ['./employees-list.component.css']
})
export class EmployeesListComponent implements OnInit {

  term: string;
  Employee: any = [];
  assets: any = [];
  reportData: any = [];

  constructor(
    public restApi: RestApiService
  ) { }

  ngOnInit() {
    this.loadEmployees()
  }

  // Get employees list
  loadEmployees() {
    return this.restApi.getEmployees().subscribe((data: {}) => {
      this.Employee = data;
    })
  }

  //Download Employee report
  download() {
    let fileName = 'EmployeeReport.csv';
    let columnNames = ["Emp ID", "Employee ID", "First Name", "Last Name","Email","Department ID","Designation",
    "Emp Active","Inventory ID","Device Name","Device Type ID","Device Type Name","Serial No","Model","Processor",
    "RAm ID","HDD ID","OS ID","Warranty Date","Purchase Date","Description","Repair","Inv Active","RAM Size","HDD Size","OS Name","Asset Status"];
    let header = columnNames.join(',');
    let csv = header;
    csv += '\r\n';

    ####create an reportData array####
    //*******parent for loop**********
    for(let emp of this.Employee){
      this.restApi.getEmployeeAsset(emp.id).subscribe((data: {}) => {
        this.assets = data;
        if(this.assets.length !== 0){
          //*****child for loop****
          for(let asset of this.assets){
             this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,        "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active,"invId":asset.id,"deviceName":asset.device_name,         "deviceTypeId":asset.device_type_id,"deviceTypeName":asset.device_type_name,"serialNo":asset.serial_no,"model":asset.model,"processor":asset.processor,          "ramId":asset.ram_id,"hddId":asset.hdd_id,"osId":asset.os_id,"warrantyDate":asset.warranty_date,"purchaseDate":asset.purchased_date,          "description":asset.description,"repair":asset.repair,"invActive":asset.is_active,"ramSize":asset.ram_size,"hddSize":asset.hdd_size,"osName":asset.os_name,"assetStatus":asset.asset_status})
          }
        }
        else {
          this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,
          "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active})
        }

          console.log("Report Data is available here"+JSON.stringify(this.reportData))
      })
      console.log("Report data is empty here"+JSON.stringify(this.reportData))

  }
    this.reportData.map(c => {csv += [c["eid"], c["employeeId"],c["firstName"],c["lastName"],c["email"],c["departmentId"],c["designation"],c["eActive"], c["invId"],c["deviceName"],c["deviceTypeId"],c["deviceTypeName"],c["serialNo"],c["model"],c["processor"],c["ramId"],  c["hddId"],c["osId"],c["warrantyDate"],c["purchaseDate"],c["description"],c["repair"],c["invActive"],c["ramSize"],c["hddSize"],c["osName"],c["assetStatus"]].join(',');
      csv += '\r\n';
    })

    var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });

    var link = document.createElement("a");
    if (link.download !== undefined) {
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }

}

</code>```

Here in this code, under download() method, I'm creating an array reportData which later I'm converting it to csv format which can be downloaded.

But this particular array reportData is empty once we are out of this.restApi.getEmployeeAsset(emp.id).subscribe call with in the parent for loop. This seems to be weird for me and I'm really not understanding why this is happening.

I found this by logging results to the console at 2 different places with in the for loop.
one is console.log("Report Data is available here"+JSON.stringify(this.reportData)) with in the subscribe method of API call where I can see the reportData and another one is console.log("Report data is empty here"+JSON.stringify(this.reportData)) where reportData is empty.

Can someone please explain what mistake I'm doing here and why exactly this is happening?

I don't have any errors showing and I was able to download the required file, but with empty data which has only Header column. :(

Work around that currently I had in place

I placed the For loop logic from download() to loadEmployees() which in turn is being called under ngOnInIt(). So the necessary data will loaded when component is invoked or executed. (But I know this is not an efficient way)

```<code>loadEmployees() {
    this.restApi.getEmployees().subscribe((data: {}) => {
      this.Employee = data;
      for(let emp of this.Employee){
        this.restApi.getEmployeeAsset(emp.id).subscribe((data: {}) => {
          this.assets = data;
          if(this.assets.length !== 0){
          for(let asset of this.assets){
            this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,
            "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active,"invId":asset.id,"deviceName":asset.device_name,
            "deviceTypeId":asset.device_type_id,"deviceTypeName":asset.device_type_name,"serialNo":asset.serial_no,"model":asset.model,"processor":asset.processor,
            "ramId":asset.ram_id,"hddId":asset.hdd_id,"osId":asset.os_id,"warrantyDate":asset.warranty_date,"purchaseDate":asset.purchased_date,
            "description":asset.description,"repair":asset.repair,"invActive":asset.is_active,"ramSize":asset.ram_size,"hddSize":asset.hdd_size,
            "osName":asset.os_name,"assetStatus":asset.asset_status})
            }
          }
          else {
            this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,
            "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active})
          }
        })
      }
    })
  }

</code>```

I know this approach is not that efficient, because the reportData array will be created at the backend irrespective of whether Download button is clicked or not. But Since I'm not getting how to handle this using Promises or to handle Asynchronous coding, I ended up doing this.

答:
You are mixing async code with synchronous code in a way that results in your data array not being populated with the results. The async code is still executing by the time this.reportData.map() is being called. Need to consider using some of the rxjs operators on your API request.

```<code>download() {
  ...csv setup here
  // Create an array of observables based on the Employee array
  forkJoin(this.Employee.map(emp => this.restApi.getEmployeeAsset(emp.id))
    // Pipe the Observables through the map operator to set up data
    .pipe(
      map(assets => {
        assets.forEach(
          if(assets.length !== 0){
            this.reportData.push(...the data you want)
          } else {
            this.reportData.push(...the other data you want)
          }
      })
    ).subscribe(() => {
      ...do what you need here with mapping over this.reportData to create your csv
    })
}
</code>```

Body:
Before raising this question, I have gone through the similar issues raised, but no luck in fixing my issue. So I'm raising this question again to understand on why exactly this is happening.

I started creating one web application where in one of my page users can download data by just clicking the button provided. Everything worked fine till I started using FOR loop to get some additional data and adding it to new array. Here is my code for better explaination.

employee-list.component.ts

import { Component, OnInit } from '@angular/core';
import { RestApiService } from "../shared/rest-api.service";

@Component({
  selector: 'app-employees-list',
  templateUrl: './employees-list.component.html',
  styleUrls: ['./employees-list.component.css']
})
export class EmployeesListComponent implements OnInit {

  term: string;
  Employee: any = [];
  assets: any = [];
  reportData: any = [];

  constructor(
    public restApi: RestApiService
  ) { }

  ngOnInit() {
    this.loadEmployees()
  }

  // Get employees list
  loadEmployees() {
    return this.restApi.getEmployees().subscribe((data: {}) => {
      this.Employee = data;
    })
  }

  //Download Employee report
  download() {
    let fileName = 'EmployeeReport.csv';
    let columnNames = ["Emp ID", "Employee ID", "First Name", "Last Name","Email","Department ID","Designation",
    "Emp Active","Inventory ID","Device Name","Device Type ID","Device Type Name","Serial No","Model","Processor",
    "RAm ID","HDD ID","OS ID","Warranty Date","Purchase Date","Description","Repair","Inv Active","RAM Size","HDD Size","OS Name","Asset Status"];
    let header = columnNames.join(',');
    let csv = header;
    csv += '\r\n';

    ####create an reportData array####
    //*******parent for loop**********
    for(let emp of this.Employee){
      this.restApi.getEmployeeAsset(emp.id).subscribe((data: {}) => {
        this.assets = data;
        if(this.assets.length !== 0){
          //*****child for loop****
          for(let asset of this.assets){
             this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,        "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active,"invId":asset.id,"deviceName":asset.device_name,         "deviceTypeId":asset.device_type_id,"deviceTypeName":asset.device_type_name,"serialNo":asset.serial_no,"model":asset.model,"processor":asset.processor,          "ramId":asset.ram_id,"hddId":asset.hdd_id,"osId":asset.os_id,"warrantyDate":asset.warranty_date,"purchaseDate":asset.purchased_date,          "description":asset.description,"repair":asset.repair,"invActive":asset.is_active,"ramSize":asset.ram_size,"hddSize":asset.hdd_size,"osName":asset.os_name,"assetStatus":asset.asset_status})
          }
        }
        else {
          this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,
          "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active})
        }

          console.log("Report Data is available here"+JSON.stringify(this.reportData))
      })
      console.log("Report data is empty here"+JSON.stringify(this.reportData))

  }
    this.reportData.map(c => {csv += [c["eid"], c["employeeId"],c["firstName"],c["lastName"],c["email"],c["departmentId"],c["designation"],c["eActive"], c["invId"],c["deviceName"],c["deviceTypeId"],c["deviceTypeName"],c["serialNo"],c["model"],c["processor"],c["ramId"],  c["hddId"],c["osId"],c["warrantyDate"],c["purchaseDate"],c["description"],c["repair"],c["invActive"],c["ramSize"],c["hddSize"],c["osName"],c["assetStatus"]].join(',');
      csv += '\r\n';
    })

    var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });

    var link = document.createElement("a");
    if (link.download !== undefined) {
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }

}

Here in this code, under download() method, I'm creating an array reportData which later I'm converting it to csv format which can be downloaded.

But this particular array reportData is empty once we are out of this.restApi.getEmployeeAsset(emp.id).subscribe call with in the parent for loop. This seems to be weird for me and I'm really not understanding why this is happening.

I found this by logging results to the console at 2 different places with in the for loop.
one is console.log("Report Data is available here"+JSON.stringify(this.reportData)) with in the subscribe method of API call where I can see the reportData and another one is console.log("Report data is empty here"+JSON.stringify(this.reportData)) where reportData is empty.

Can someone please explain what mistake I'm doing here and why exactly this is happening?

I don't have any errors showing and I was able to download the required file, but with empty data which has only Header column. :(

Work around that currently I had in place

I placed the For loop logic from download() to loadEmployees() which in turn is being called under ngOnInIt(). So the necessary data will loaded when component is invoked or executed. (But I know this is not an efficient way)

loadEmployees() {
    this.restApi.getEmployees().subscribe((data: {}) => {
      this.Employee = data;
      for(let emp of this.Employee){
        this.restApi.getEmployeeAsset(emp.id).subscribe((data: {}) => {
          this.assets = data;
          if(this.assets.length !== 0){
          for(let asset of this.assets){
            this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,
            "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active,"invId":asset.id,"deviceName":asset.device_name,
            "deviceTypeId":asset.device_type_id,"deviceTypeName":asset.device_type_name,"serialNo":asset.serial_no,"model":asset.model,"processor":asset.processor,
            "ramId":asset.ram_id,"hddId":asset.hdd_id,"osId":asset.os_id,"warrantyDate":asset.warranty_date,"purchaseDate":asset.purchased_date,
            "description":asset.description,"repair":asset.repair,"invActive":asset.is_active,"ramSize":asset.ram_size,"hddSize":asset.hdd_size,
            "osName":asset.os_name,"assetStatus":asset.asset_status})
            }
          }
          else {
            this.reportData.push({"eid": emp.id,"employeeId":emp.employee_id,"firstName":emp.first_name,"lastName":emp.last_name,"email":emp.email,
            "departmentId":emp.department_id,"designation":emp.designation,"eActive":emp.is_active})
          }
        })
      }
    })
  }

I know this approach is not that efficient, because the reportData array will be created at the backend irrespective of whether Download button is clicked or not. But Since I'm not getting how to handle this using Promises or to handle Asynchronous coding, I ended up doing this.

Body:
You are mixing async code with synchronous code in a way that results in your data array not being populated with the results. The async code is still executing by the time this.reportData.map() is being called. Need to consider using some of the rxjs operators on your API request.

download() {
  ...csv setup here
  // Create an array of observables based on the Employee array
  forkJoin(this.Employee.map(emp => this.restApi.getEmployeeAsset(emp.id))
    // Pipe the Observables through the map operator to set up data
    .pipe(
      map(assets => {
        assets.forEach(
          if(assets.length !== 0){
            this.reportData.push(...the data you want)
          } else {
            this.reportData.push(...the other data you want)
          }
      })
    ).subscribe(() => {
      ...do what you need here with mapping over this.reportData to create your csv
    })
}


问:
base64 to hex string
I am trying to make a hex string out of a base64 string.
The original string is: M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc==
It should become:

```<code>3344af61e4473d60d85481bf822a6d04 5a8131075639babc6ebd510ea59f3b5a ef932e915b41e21823100b59a1c9b633 15e494902e62c38eb83f99c26147
</code>```

My code is:

```<code>str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
d1 = d.decode('utf-8')
print(d1)
</code>```

However, I get the message in decode utf-8:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaf in position 2: invalid start byte
</code>```

The output of d1 is:

```<code>b'3D\xafa\xe4G=`\xd8T\x81\xbf\x82*m\x04Z\x811\x07V9\xba\xbcn\xbdQ\x0e\xa5\x9f;Z\xef\x93.\x91[A\xe2\x18#\x10\x0bY\xa1\xc9\xb63\x15\xe4\x94\x90.b\xc3\x8e\xb8?\x99\xc2aG'
</code>```

Where is my mistake?
I would also like to see the backwards version from the hex string to base64.
I use python 3.

答:
The result of base64.b64decode(str1) is:

a bytes object already in Python 3.

a str object in Python 2 (and str and bytes are synonyms here).

The following commented script covers both Python versions:

```<code>import base64
str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
print(type(d))
print(type(d) is bytes)

# python 2
if type(d) is str:
    d = bytearray(d)

# The old format style was the %-syntax:
d1=''.join(['%02x'%i for i in d])
print(d1)

# The more modern approach is the .format method:
d1=''.join(['{:02x}'.format(i) for i in d])
print(d1)
</code>```

Result:

```<code>py -3 .\SO3\62087693.py
</code>```

```<code><class 'bytes'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
</code>```

```<code>py -2 .\SO3\62087693.py
</code>```

```<code><type 'str'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
</code>```

Note: more recently, from Python 3.6 upwards there is a f-string syntax (but I had frozen at version 3.5.1 so this isn't proved by an example):

```<code>''.join([f'{i:02x}' for i in d])
</code>```

Title: base64 to hex string

Body:
I am trying to make a hex string out of a base64 string.
The original string is: M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc==
It should become:

3344af61e4473d60d85481bf822a6d04 5a8131075639babc6ebd510ea59f3b5a ef932e915b41e21823100b59a1c9b633 15e494902e62c38eb83f99c26147

My code is:

str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
d1 = d.decode('utf-8')
print(d1)

However, I get the message in decode utf-8:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaf in position 2: invalid start byte

The output of d1 is:

b'3D\xafa\xe4G=`\xd8T\x81\xbf\x82*m\x04Z\x811\x07V9\xba\xbcn\xbdQ\x0e\xa5\x9f;Z\xef\x93.\x91[A\xe2\x18#\x10\x0bY\xa1\xc9\xb63\x15\xe4\x94\x90.b\xc3\x8e\xb8?\x99\xc2aG'

Where is my mistake?
I would also like to see the backwards version from the hex string to base64.
I use python 3.

Body:
The result of base64.b64decode(str1) is:

a bytes object already in Python 3.

a str object in Python 2 (and str and bytes are synonyms here).

The following commented script covers both Python versions:

import base64
str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
print(type(d))
print(type(d) is bytes)

# python 2
if type(d) is str:
    d = bytearray(d)

# The old format style was the %-syntax:
d1=''.join(['%02x'%i for i in d])
print(d1)

# The more modern approach is the .format method:
d1=''.join(['{:02x}'.format(i) for i in d])
print(d1)

Result:

py -3 .\SO3\62087693.py

<class 'bytes'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147

py -2 .\SO3\62087693.py

<type 'str'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147

Note: more recently, from Python 3.6 upwards there is a f-string syntax (but I had frozen at version 3.5.1 so this isn't proved by an example):

''.join([f'{i:02x}' for i in d])


问:
Is there a portable (Windows, Linux, MacOS, Android) way of opening memory mapped files?
I have an application that writes relatively large files (compared to its input, not compared to the memory of the system) and spends roughly 80% of its time simply writing the output.  The application also supports a "-diff" option that tells it not to write the files, but instead compare what it would write to what is already there and generate an error message if there is a difference.

In the implementation of the -diff option.  I fopen the file and use fgetc to read it character by character to compare character by character to the stuff I would normally write.  Something like this pseudo-code (although the real code is much more complex, since I have various things where I want to ignore differences:

```<code>void my_fputs(new_text, file_to_diff_to) {
   for (c = *new_text; *c; ++c) {
      x = fgetc(file_to_diff_to);
      if (c != x) generated_error_message();
      }
}
</code>```

My profiling indicates, that I spend most of my time in fgetc.  I presume dealing with buffering.  What I'd prefer is portable code that looked like this.

```<code>void my_fputs(new_text, file_to_diff_to) {
   for (c = *new_text; *c; ++c) {
      x = *file_to_diff_to;
      if (c != x) generated_error_message();
      ++file_to_diff_to;
      }
}
</code>```

Is there something relatively portable that would let me do that?  If it matters, I am reading the files in binary (not text mode).  I deal with cr/lf issues myself.

答: mmap is quite portable and even works on Windows (I tried it with MinGW-w64) using the Windows port from: https://github.com/witwall/mman-win32/

Body:
I have an application that writes relatively large files (compared to its input, not compared to the memory of the system) and spends roughly 80% of its time simply writing the output.  The application also supports a "-diff" option that tells it not to write the files, but instead compare what it would write to what is already there and generate an error message if there is a difference.

In the implementation of the -diff option.  I fopen the file and use fgetc to read it character by character to compare character by character to the stuff I would normally write.  Something like this pseudo-code (although the real code is much more complex, since I have various things where I want to ignore differences:

void my_fputs(new_text, file_to_diff_to) {
   for (c = *new_text; *c; ++c) {
      x = fgetc(file_to_diff_to);
      if (c != x) generated_error_message();
      }
}

My profiling indicates, that I spend most of my time in fgetc.  I presume dealing with buffering.  What I'd prefer is portable code that looked like this.

void my_fputs(new_text, file_to_diff_to) {
   for (c = *new_text; *c; ++c) {
      x = *file_to_diff_to;
      if (c != x) generated_error_message();
      ++file_to_diff_to;
      }
}

Is there something relatively portable that would let me do that?  If it matters, I am reading the files in binary (not text mode).  I deal with cr/lf issues myself.


问:
ASPNET Core 3.x - Appending data to all API responses
I've been googling for past 3 hours and I couldn't find anything helpful.
I'm trying to transform all my requests to a specific RESTful standard.

Right now, each and every controller returns data in this format:

```<code>[
    {
        "id": 3,
        "title": "Test",
        "content": "Content Test",
        "userId": 1,
        "user": null,
        "categoryId": null,
        "category": null,
        "comments": null,
        "tags": null,
        "createdOn": null,
        "updatedOn": null
    }
]
</code>```

What I want is to wrap all of these responses in a container, that also consists of metadata - as seen below:

```<code>{
    "statusCode": 200,
    "statusMessage": "success",
    "meta":
    {
        "count": 1,
        "total": 1,
        "pagination":
        {
            "page": 1,
            "pages": 1,
            "limit": 20
        },
        "filters": [],
        "sorters": []
    },
    "data":
    {
        [
            {
                "id": 3,
                "title": "Test",
                "content": "Content Test",
                "userId": 1,
                "user": null,
                "categoryId": null,
                "category": null,
                "comments": null,
                "tags": null,
                "createdOn": null,
                "updatedOn": null
            }
        ]
    }
}
</code>```

Is the proper approach to just make a class called ResponseContainer and make all controllers return it? Because I feel like that's a viable solution.

答:
In one of my projects, I used a generic class as response, such as MyApiResponse<T>. This class contains properties for meta data like the HttpStatusCode of the response, error messages, etc. They are set upon each response.

Within this class, I have a List<T> called Data.

Each API method returns MyApiResponse<T> where T is being the concrete data class. For instance, it could be MyApiResponse<Weather> where Data would store a List<Weather.

I'll definetly use this approach for my next API project as well.

Body:
I've been googling for past 3 hours and I couldn't find anything helpful.
I'm trying to transform all my requests to a specific RESTful standard.

Right now, each and every controller returns data in this format:

[
    {
        "id": 3,
        "title": "Test",
        "content": "Content Test",
        "userId": 1,
        "user": null,
        "categoryId": null,
        "category": null,
        "comments": null,
        "tags": null,
        "createdOn": null,
        "updatedOn": null
    }
]

What I want is to wrap all of these responses in a container, that also consists of metadata - as seen below:

{
    "statusCode": 200,
    "statusMessage": "success",
    "meta":
    {
        "count": 1,
        "total": 1,
        "pagination":
        {
            "page": 1,
            "pages": 1,
            "limit": 20
        },
        "filters": [],
        "sorters": []
    },
    "data":
    {
        [
            {
                "id": 3,
                "title": "Test",
                "content": "Content Test",
                "userId": 1,
                "user": null,
                "categoryId": null,
                "category": null,
                "comments": null,
                "tags": null,
                "createdOn": null,
                "updatedOn": null
            }
        ]
    }
}

Is the proper approach to just make a class called ResponseContainer and make all controllers return it? Because I feel like that's a viable solution.


问:
How to combine vectors of different length in a cell array into matrix in MATLAB
How to efficiently combined cell array vectors with different length into a matrix, filling the vectors to max length with 0s or NaNs? It would be a nice option for cell2mat().

For example, if I have

```<code>C = {1:3; 1:5; 1:4};
</code>```

I'd like to get either

```<code>M = [1 2 3 0 0
     1 2 3 4 5
     1 2 3 4 0];
</code>```

or

```<code>M = [1 2 3 NaN NaN
     1 2 3 4 5
     1 2 3 4 NaN];
</code>```

答:
EDIT:

For a cell of row vectors as in your case, this will pad vectors with zeros to form a matrix

```<code>out=cell2mat(cellfun(@(x)cat(2,x,zeros(1,maxLength-length(x))),C,'UniformOutput',false))

out =

     1     2     3     0     0
     1     2     3     4     5
     1     2     3     4     0
</code>```

A similar question was asked earlier today, and although the question was worded slightly differently, my answer basically does what you want.

Copying the relevant parts here, a cell of uneven column vectors can be zero padded into a matrix as:

```<code>out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),C,'UniformOutput',false));
</code>```

where maxLength is assumed to be known. In your case, you have row vectors, which is just a slight modification from this.

If maxLength is not known, you can get it as

```<code>maxLength=max(cellfun(@(x)numel(x),C));
</code>```

Body:
How to efficiently combined cell array vectors with different length into a matrix, filling the vectors to max length with 0s or NaNs? It would be a nice option for cell2mat().

For example, if I have

C = {1:3; 1:5; 1:4};

I'd like to get either

M = [1 2 3 0 0
     1 2 3 4 5
     1 2 3 4 0];

or

M = [1 2 3 NaN NaN
     1 2 3 4 5
     1 2 3 4 NaN];

Body:
EDIT:

For a cell of row vectors as in your case, this will pad vectors with zeros to form a matrix

out=cell2mat(cellfun(@(x)cat(2,x,zeros(1,maxLength-length(x))),C,'UniformOutput',false))

out =

     1     2     3     0     0
     1     2     3     4     5
     1     2     3     4     0

A similar question was asked earlier today, and although the question was worded slightly differently, my answer basically does what you want.

Copying the relevant parts here, a cell of uneven column vectors can be zero padded into a matrix as:

out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),C,'UniformOutput',false));

where maxLength is assumed to be known. In your case, you have row vectors, which is just a slight modification from this.

If maxLength is not known, you can get it as

maxLength=max(cellfun(@(x)numel(x),C));


问:
No such file or directory - when running git add
I'm going to upload my code to the github repository and execute the git add . command. I get this error and I do not know what to do in this case.

```<code>fatal: Unable to create '/Documents/GitHub/repo/.git/index.lock': No such file or directory
</code>```

答: Check the option in windows security centre for Allow and app through Controlled Folder Access and add git.exe to the allowed list of apps.</p>

Body:
I'm going to upload my code to the github repository and execute the git add . command. I get this error and I do not know what to do in this case.

fatal: Unable to create '/Documents/GitHub/repo/.git/index.lock': No such file or directory


问:
Can anyone suggest a good papers or articles on the architecture of graphics drivers?
I'm wondering about how exactly OpenGL and DirectX drivers work. From what I know, they basically take in calls in their various APIs, and output a stream of bytecode instructions that head off to the GPU to be executed. </p>

<p>I know GPU chipmakers are extremely secretive about the details of their specifications. Are there any documents that describe how the APIs themselves are implemented on a level above the card itself? </p>

答:
AMD has released some specification documents that you may find interesting.

The Gallium3D folks are building on top of that to produce open drivers for recent Radeon cards.  You can check out the source.

Body:
I'm wondering about how exactly OpenGL and DirectX drivers work. From what I know, they basically take in calls in their various APIs, and output a stream of bytecode instructions that head off to the GPU to be executed.

I know GPU chipmakers are extremely secretive about the details of their specifications. Are there any documents that describe how the APIs themselves are implemented on a level above the card itself?


问:
write a query to this..?
Students and Grades. Students contains three columns ID, Name and Marks, Grades-(grade,min_mark,max_mark)

Ketty gives Eve a task to generate a report containing three columns:  Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (1-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and list them by their marks in ascending order.

Write a query to help Eve.

Note
Print "NULL"  as the name if the grade is less than 8.

I have written this query :

```<code>select name,grade,marks from students s join grades g on marks between min_mark and max_mark
where grade>7
order by 2 desc,name

select translate(name,name,'NULL'),grade,marks from students s join grades g on marks between min_mark and max_mark
where grade<=7
order by 3 desc
</code>```

but don't know how to join these both queries.

答:
Tried and tested code on hackerrank...

```<code>select s.name, g.grade, s.marks from students s, grades g where g.grade>=8 and s.marks between g.min_mark and g.max_mark order by g.grade desc, s.name;

select 'NULL', g.grade, s.marks from students s, grades g where g.grade<8 and s.marks between g.min_mark and g.max_mark order by g.grade desc, s.marks;
</code>```

Title: write a query to this..?

Body:
Students and Grades. Students contains three columns ID, Name and Marks, Grades-(grade,min_mark,max_mark)

Ketty gives Eve a task to generate a report containing three columns:  Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (1-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and list them by their marks in ascending order.

Write a query to help Eve.

Note
Print "NULL"  as the name if the grade is less than 8.

I have written this query :

select name,grade,marks from students s join grades g on marks between min_mark and max_mark
where grade>7
order by 2 desc,name

select translate(name,name,'NULL'),grade,marks from students s join grades g on marks between min_mark and max_mark
where grade<=7
order by 3 desc

but don't know how to join these both queries.

Body:
Tried and tested code on hackerrank...

select s.name, g.grade, s.marks from students s, grades g where g.grade>=8 and s.marks between g.min_mark and g.max_mark order by g.grade desc, s.name;

select 'NULL', g.grade, s.marks from students s, grades g where g.grade<8 and s.marks between g.min_mark and g.max_mark order by g.grade desc, s.marks;


问:
Springboot mongo exception with Docker
I am new to docker and trying to connect a spring boot app with mongo db which is running on docker at port 27017. In my pom I have this:

```<code>        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
</code>```

I have not specified anything in application.properties. Below are logs from spring boot failure:

```<code>com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:67) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.8.2.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:579) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:339) ~[na:na]
    at java.base/java.net.Socket.connect(Socket.java:603) ~[na:na]
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.8.2.jar:na]
</code>```

And logs from mongodb(docker)

```<code>2020-05-30T00:31:55.387+0000 I  NETWORK  [listener] Listening on /tmp/mongodb-27017.sock
2020-05-30T00:31:55.388+0000 I  NETWORK  [listener] Listening on 0.0.0.0
2020-05-30T00:31:55.391+0000 I  NETWORK  [listener] waiting for connections on port 27017
2020-05-30T00:31:55.405+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index _id_ on ns config.system.sessions
2020-05-30T00:31:55.425+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: starting on config.system.sessions properties: { v: 2, key: { lastUse: 1 }, name: "lsidTTLIndex", ns: "config.system.sessions", expireAfterSeconds: 1800 } using method: Hybrid
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] build may temporarily use up to 200 megabytes of RAM
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: collection scan done. scanned 0 total records in 0 seconds
2020-05-30T00:31:55.429+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: inserted 0 keys from external sorter into index in 0 seconds
2020-05-30T00:31:55.431+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index lsidTTLIndex on ns config.system.sessions
2020-05-30T00:31:55.434+0000 I  SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: <unsharded>
2020-05-30T00:31:56.006+0000 I  SHARDING [ftdc] Marking collection local.oplog.rs as collection version: <unsharded>
</code>```

Can someone please help me out?

Thanks!

答:
The solution to above problem:-

By getting the Windows 2004 version upgrade and then installing Docker Desktop for Windows(after uninstalling the Docker Toolbox legacy one, which was required for previous windows versions).

I would suggest you to run your containers via docker-compose and check the below docker-compose.yml for reference.

```<code>version: "3"
services:
  api-database:
    image: mongo:3.2.4
    container_name: "api-database"
    ports:
      - 27017:27017
    command: --smallfiles
  api:
    image: XXXX
    ports:
      - XXXX:XXXX
    links:
      - api-database
</code>```

Configure mongodb host name using spring config property using service name defined in docker-compose.

```<code>spring.data.mongodb.host=api-database
</code>```

and then run

```<code>docker-compose up
</code>```

Ref:- https://nirajsonawane.github.io/2019/12/16/Spring-Boot-Mongodb-Docker-Compose/

Title: Springboot mongo exception with Docker

Body:
I am new to docker and trying to connect a spring boot app with mongo db which is running on docker at port 27017. In my pom I have this:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

I have not specified anything in application.properties. Below are logs from spring boot failure:

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:67) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.8.2.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:579) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:339) ~[na:na]
    at java.base/java.net.Socket.connect(Socket.java:603) ~[na:na]
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64) ~[mongodb-driver-core-3.8.2.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.8.2.jar:na]

And logs from mongodb(docker)

2020-05-30T00:31:55.387+0000 I  NETWORK  [listener] Listening on /tmp/mongodb-27017.sock
2020-05-30T00:31:55.388+0000 I  NETWORK  [listener] Listening on 0.0.0.0
2020-05-30T00:31:55.391+0000 I  NETWORK  [listener] waiting for connections on port 27017
2020-05-30T00:31:55.405+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index _id_ on ns config.system.sessions
2020-05-30T00:31:55.425+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: starting on config.system.sessions properties: { v: 2, key: { lastUse: 1 }, name: "lsidTTLIndex", ns: "config.system.sessions", expireAfterSeconds: 1800 } using method: Hybrid
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] build may temporarily use up to 200 megabytes of RAM
2020-05-30T00:31:55.426+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: collection scan done. scanned 0 total records in 0 seconds
2020-05-30T00:31:55.429+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: inserted 0 keys from external sorter into index in 0 seconds
2020-05-30T00:31:55.431+0000 I  INDEX    [LogicalSessionCacheRefresh] index build: done building index lsidTTLIndex on ns config.system.sessions
2020-05-30T00:31:55.434+0000 I  SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: <unsharded>
2020-05-30T00:31:56.006+0000 I  SHARDING [ftdc] Marking collection local.oplog.rs as collection version: <unsharded>

Can someone please help me out?

Thanks!

Body:
The solution to above problem:-

By getting the Windows 2004 version upgrade and then installing Docker Desktop for Windows(after uninstalling the Docker Toolbox legacy one, which was required for previous windows versions).

I would suggest you to run your containers via docker-compose and check the below docker-compose.yml for reference.

version: "3"
services:
  api-database:
    image: mongo:3.2.4
    container_name: "api-database"
    ports:
      - 27017:27017
    command: --smallfiles
  api:
    image: XXXX
    ports:
      - XXXX:XXXX
    links:
      - api-database

Configure mongodb host name using spring config property using service name defined in docker-compose.

spring.data.mongodb.host=api-database

and then run

docker-compose up

Ref:- https://nirajsonawane.github.io/2019/12/16/Spring-Boot-Mongodb-Docker-Compose/


问:
Un-define constants with define/apc_define_constants in PHP
I'm using constants for output messages in different languages.
For example, if a user chooses "English", a file with this constant would be required:

```<code>define('welcomeMessage','Welcome!');
</code>```

If she chooses "Spanish":

```<code>define('welcomeMessage','Bien Venidos!');
</code>```

etc etc...

The problem occurs when a user iterates through languages. I can't redefine constants with either define/apc_define_constants (as far as I know). Can I delete and redefine them?

Is there a good solution for this?

答:
Here is what I do when I need "constants" that need to be redefined (as funny as it sounds):

```<code>// somewhere in your global file

function config($key, $value) {
    $GLOBALS[$key] = $value;
}

function conf($key) {
    return $GLOBALS[$key];
}

function configured($key) {
    return isset($GLOBALS[$key]);
}
</code>```

Now whenever you need to define your "constant" just use:

```<code>config('SHOW_AVATAR', true);
</code>```

When you need to access it, use:

```<code>if(conf('SHOW_AVATAR') === true)
  echo "AVATAR";
</code>```

If you need to check if it's been defined already, use:

```<code>if(configured('SHOW_AVATAR'))
  echo "Setting set";
</code>```

Why I use this? Because it looks like define() function in my code. That makes it easier to separate settings from variables. I mainly use it in my partial views where I need to have a variable with global scope (like constants) but be able to redefine it at any time.

Hope it helps you.

ContentLicense: CC BY-SA 2.5

Body:
I'm using constants for output messages in different languages.
For example, if a user chooses "English", a file with this constant would be required:

define('welcomeMessage','Welcome!');

If she chooses "Spanish":

define('welcomeMessage','Bien Venidos!');

etc etc...

The problem occurs when a user iterates through languages. I can't redefine constants with either define/apc_define_constants (as far as I know). Can I delete and redefine them?

Is there a good solution for this?

Body:
Here is what I do when I need "constants" that need to be redefined (as funny as it sounds):

// somewhere in your global file

function config($key, $value) {
    $GLOBALS[$key] = $value;
}

function conf($key) {
    return $GLOBALS[$key];
}

function configured($key) {
    return isset($GLOBALS[$key]);
}

Now whenever you need to define your "constant" just use:

config('SHOW_AVATAR', true);

When you need to access it, use:

if(conf('SHOW_AVATAR') === true)
  echo "AVATAR";

If you need to check if it's been defined already, use:

if(configured('SHOW_AVATAR'))
  echo "Setting set";

Why I use this? Because it looks like define() function in my code. That makes it easier to separate settings from variables. I mainly use it in my partial views where I need to have a variable with global scope (like constants) but be able to redefine it at any time.

Hope it helps you.


问:
React native flatlist rerenders to top when any item changed in tab view
I'm using react-native-community/react-native-tab-view to render two flatlists which are basically checklists with tickboxes in them.

The code for the flatlist is returned from:

```<code>const ListRoute = () => {
return (
 <FlatList
   data={data}
   renderItem={({item, index}) => {
     return (
       <View>
         <Item
           ...checkbox code
         />
       </View>
     );
   }}
   keyExtractor={(item, index) => item.id + '1'}
   listKey={(item, index) => item.id + '2'}
   removeClippedSubviews={true}
   extraData={(updateItem, subscriptionItems)}
 />
);
};
</code>```

And the tab view code is

```<code><TabView
renderTabBar={ChallengeTabBar}
navigationState={{index, routes}}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
</code>```

With render scene as

```<code>  const renderScene = SceneMap({
    first: ListRoute,
    second: FriendRoute,
  });
</code>```

The checkbox takes the updateItem function from the main functional class and adds it's ID to the list of ticked boxes. When I use the listRoute function, clicking a tickbox leads to the whole flatlist rerendering and the user being taken to the top of the list. If I don't use a function and just put the flatlist in by itself then this doesn't happen.

Edit:
After further investigation, it looks like if I remove the tab view part completely I still get the same problem. If I just put the flatlist in then the list doesn't rerender to the top but If I put the  component in then it does.

答:
You should use useEffect for avoiding rerenders of FlatList.
You need to check immutability means that you want to replace the data of flatlist.
use filter method for checkbox tick. </p>

Body:
I'm using react-native-community/react-native-tab-view to render two flatlists which are basically checklists with tickboxes in them.

The code for the flatlist is returned from:

const ListRoute = () => {
return (
 <FlatList
   data={data}
   renderItem={({item, index}) => {
     return (
       <View>
         <Item
           ...checkbox code
         />
       </View>
     );
   }}
   keyExtractor={(item, index) => item.id + '1'}
   listKey={(item, index) => item.id + '2'}
   removeClippedSubviews={true}
   extraData={(updateItem, subscriptionItems)}
 />
);
};

And the tab view code is

<TabView
renderTabBar={ChallengeTabBar}
navigationState={{index, routes}}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>

With render scene as

  const renderScene = SceneMap({
    first: ListRoute,
    second: FriendRoute,
  });

The checkbox takes the updateItem function from the main functional class and adds it's ID to the list of ticked boxes. When I use the listRoute function, clicking a tickbox leads to the whole flatlist rerendering and the user being taken to the top of the list. If I don't use a function and just put the flatlist in by itself then this doesn't happen.

Edit:
After further investigation, it looks like if I remove the tab view part completely I still get the same problem. If I just put the flatlist in then the list doesn't rerender to the top but If I put the  component in then it does.


问:
stm32 timers: starts and resets on same trigger
I has a periodic signal (22 kHz square), connected to IC1 of TIM3. I need to measure a duration of this signal.

Current realisation is:

1. TIM2 is programmed as one-pulse, arr = signal period + little deviation, trigger mode slave, with CEN as master output, trigger INT  enabled.

2. in TIM2 ISR just do TIM2->CNT = 0;

3. TIM3 is slave timer in gated mode, connected to tim2. trigger INT enabled.

4. in TIM3 ISR just count a diffrence current CNT and prev CNT to meas  ure a signal duration.

It is works, but times is not 100% accurate due to ISR calling & execution time.

Questions:

1. Can i use same external event for starting AND reseting same timer?

2. Can i use input capure registers in my realisation?

3. Some better ideas for my task?

i'm realy break my brains for a days. Please help... ;-)

答:
@P__J__ is right - you should configure and use the input capture mode many timers on STM32 offer you. Then you won't need any ISR (software) in the moments when the signal flanks are recognized because the MCU will do that for you. You'll only need some software to read out the measurements from the Input Capture, but you'll be more or less free to do this in ISR or poll from main program.

The TIMx peripherals are pretty complex.
Therefore, I suggest to have a look at
this Application Note from ST
as well as
that one.


问:
java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20
Im doing a thing for a thing and I have to "Multiply each element in list2 by its element index number and place the value in array list1."
and so my code is

```<code>public static void main(String[] args) {
        int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
        int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        int L1= 0;
        int L2= 0;

        for( L2=0 ;L2<List2.length;L2++) {
            List2[L2]= (int) (100*Math.random());
            System.out.print(" "+List2[L2]);
        }//end of list2 for loop

System.out.println("");

        for( L1 = 0;L1<List1.length;L1++)
        {
            List1[L1]= List2[L2]*L2;
            System.out.print(" "+List1[L1]);
        }//end of list1 for loop
)
</code>```

and it throws this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20"

答:
Because at line List1[L1]= List2[L2]xL2;* L2 = 20, but the max index of the array is 19. You must write:

```<code>public static void main(String[] args) {
    int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
    int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
    int L1= 0;
    int L2= 0;

    for( L2=0 ;L2<List2.length;L2++) {
        List2[L2]= (int) (100*Math.random());
        System.out.print(" "+List2[L2]);
    }//end of list2 for loop

    System.out.println("");

    for( L1 = 0;L1<List1.length;L1++)
    {
        List1[L1]= List2[L2 - 1]*L2; //Here the change
        System.out.print(" "+List1[L1]);
    }//end of list1 for loop
}
</code>```

or

```<code>public static void main(String[] args) {
    int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
    int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
    int L1= 0;
    int L2= 0;

    for( L2=0 ;L2<List2.length;L2++) {
        List2[L2]= (int) (100*Math.random());
        System.out.print(" "+List2[L2]);
    }//end of list2 for loop

    System.out.println("");

    for( L1 = 0;L1<List1.length;L1++)
    {
        List1[L1]= List2[L1]*L2; //Here the change
        System.out.print(" "+List1[L1]);
    }//end of list1 for loop
}
</code>```

Body:
Im doing a thing for a thing and I have to "Multiply each element in list2 by its element index number and place the value in array list1."
and so my code is

public static void main(String[] args) {
        int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
        int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        int L1= 0;
        int L2= 0;

        for( L2=0 ;L2<List2.length;L2++) {
            List2[L2]= (int) (100*Math.random());
            System.out.print(" "+List2[L2]);
        }//end of list2 for loop

System.out.println("");

        for( L1 = 0;L1<List1.length;L1++)
        {
            List1[L1]= List2[L2]*L2;
            System.out.print(" "+List1[L1]);
        }//end of list1 for loop
)

and it throws this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20"

Body:
Because at line List1[L1]= List2[L2]xL2;* L2 = 20, but the max index of the array is 19. You must write:

public static void main(String[] args) {
    int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
    int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
    int L1= 0;
    int L2= 0;

    for( L2=0 ;L2<List2.length;L2++) {
        List2[L2]= (int) (100*Math.random());
        System.out.print(" "+List2[L2]);
    }//end of list2 for loop

    System.out.println("");

    for( L1 = 0;L1<List1.length;L1++)
    {
        List1[L1]= List2[L2 - 1]*L2; //Here the change
        System.out.print(" "+List1[L1]);
    }//end of list1 for loop
}

or

public static void main(String[] args) {
    int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
    int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
    int L1= 0;
    int L2= 0;

    for( L2=0 ;L2<List2.length;L2++) {
        List2[L2]= (int) (100*Math.random());
        System.out.print(" "+List2[L2]);
    }//end of list2 for loop

    System.out.println("");

    for( L1 = 0;L1<List1.length;L1++)
    {
        List1[L1]= List2[L1]*L2; //Here the change
        System.out.print(" "+List1[L1]);
    }//end of list1 for loop
}


问:
SQL query to sum separate columns with separate Where conditions
SQL noob here. I want to sum two columns separately, using 2 separate where conditions.

```<code>ID  NAME    VALUE1   VALUE2
--- ------- -------  -------
1   Orange  5        30
2   Orange  11       30
3   Orange  7        15
4   Pear    12       12
5   Pear    13       25
6   Pear    4        25
</code>```

Sum of VALUE1 column where values are > 10

Sum of VALUE2 column where values are > 20

Grouped by NAME

Desired output:

```<code>NAME    VALUE1   VALUE2
------- -------  -------
Orange  11       60
Pear    25       50
</code>```

Thanks!

答:
Use conditional aggregation:</p>

```<code>select name, sum(case when value1 > 10 then value1 end),
       sum(case when value2 > 20 then value2 end)
from t
group by name;
</code>```

Body:
SQL noob here. I want to sum two columns separately, using 2 separate where conditions.

ID  NAME    VALUE1   VALUE2
--- ------- -------  -------
1   Orange  5        30
2   Orange  11       30
3   Orange  7        15
4   Pear    12       12
5   Pear    13       25
6   Pear    4        25

Sum of VALUE1 column where values are > 10

Sum of VALUE2 column where values are > 20

Grouped by NAME

Desired output:

NAME    VALUE1   VALUE2
------- -------  -------
Orange  11       60
Pear    25       50

Thanks!

Body:
Use conditional aggregation:

select name, sum(case when value1 > 10 then value1 end),
       sum(case when value2 > 20 then value2 end)
from t
group by name;


问:
NSFetchedResultsController and multiple relationships
I have a UITableView which displays historical data. This is broken up into one section per day. Each day can have multiple things happening (eg. during a certain day I slept, ate some food, did some exercise, etc). Each "thing" is represented by a different entity. So going off the previous example, I have Day, Sleep, Food and Exercise entities. Sleep, Food and Exercise all have the Day entity as a parent, through a one-to-many relationship.

Currently what I am doing is loading all the Day entities, then for each Day I will load the Sleep, Food and Exercise entities into one single array, and sort it by date. Needless to say this gets slow when there is a lot of data.

Is it possible to use a NSFetchedResultsController in this instance?

答:
This is just a guess, but I think the following would work:

EDIT - I have just verified with a simple case, that this does work

Have all of your event entities (Sleep, Food, Exercise) inherit from a base class entity (you could call it something like "Event") and then use the following when you are setting up your NSFetchRequest that your NSFetchedResultsController will use:

```<code>NSFetchRequest *fr = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:_managedObjectContext];
[fr setEntity:entity];
</code>```

In theory, this would cause your results controller to return all of your existing entities that inherit from Event.  You could also put the relationship to Day in the base class (Event) because all your subclasses have that in common.  Also, you would need to specify a predicate for your fetch request to only grab the events for the specific Day you are after.

Let me know if this works!

Body:
This is just a guess, but I think the following would work:

EDIT - I have just verified with a simple case, that this does work

Have all of your event entities (Sleep, Food, Exercise) inherit from a base class entity (you could call it something like "Event") and then use the following when you are setting up your NSFetchRequest that your NSFetchedResultsController will use:

NSFetchRequest *fr = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:_managedObjectContext];
[fr setEntity:entity];

In theory, this would cause your results controller to return all of your existing entities that inherit from Event.  You could also put the relationship to Day in the base class (Event) because all your subclasses have that in common.  Also, you would need to specify a predicate for your fetch request to only grab the events for the specific Day you are after.

Let me know if this works!