问:
Input control in Angular: invalid input not detected
I'm using Angular 8 for my client application.
I want an error message to be displayed under the input box for the user when she inserts a wrong input. I'm using this inside my HTML:

```<code>  <!-- Score input -->
  <div class="form-group">
    <label for="score">Score</label>
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [(ngModel)]="model.score"
           #score="ngModel">
    <div [hidden]="score.valid" class="alert alert-danger">
      Insert a value between 0.0 and 10.0
    </div>
  </div>
</code>```

I would expect it to be displayed if the user was to input "asdf" for example instead of a number like "6.7". But it never appears. I tried removing [hidden]="score.valid" and it gets correctly displayed. Why is Angular considering "asdf" a valid input even if I set all those attributes: type="number" min="0.0" max="10.0" step="0.1" ?

答:
Why let the browser decide the behaviour?

Use a directive

```<code><input appDecimalOnly />
</code>```

```<code>/**
 * Credit: omeralper stackoverflow user
 * https://stackoverflow.com/questions/41465542/angular2-input-field-to-accept-only-numbers
 */
@Directive({
  selector: "[appDecimalOnly]"
})
export class DecimalOnlyDirective {
  constructor(private el: ElementRef) {}

  @HostListener("keydown", ["$event"]) onKeyDown(event) {
    let e = <KeyboardEvent>event;

    // console.log(e.keyCode)

    if (
      [46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
      // Allow: Ctrl+A
      (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+C
      (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+V
      (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+X
      (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
      // Allow: home, end, left, right
      (e.keyCode >= 35 && e.keyCode <= 39)
    ) {
      // let it happen, don't do anything
      return;
    }
    // Ensure that it is a number and stop the keypress
    if (
      (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
      (e.keyCode < 96 || e.keyCode > 105)
    ) {
      e.preventDefault();
    }
  }
}

</code>```

Stackblitz

Body:
I'm using Angular 8 for my client application.
I want an error message to be displayed under the input box for the user when she inserts a wrong input. I'm using this inside my HTML:

    Score
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [(ngModel)]="model.score"
           #score="ngModel">

      Insert a value between 0.0 and 10.0

I would expect it to be displayed if the user was to input "asdf" for example instead of a number like "6.7". But it never appears. I tried removing [hidden]="score.valid" and it gets correctly displayed. Why is Angular considering "asdf" a valid input even if I set all those attributes: type="number" min="0.0" max="10.0" step="0.1" ?

Body:
Why let the browser decide the behaviour?

Use a directive

<input appDecimalOnly />

/**
 * Credit: omeralper stackoverflow user
 * https://stackoverflow.com/questions/41465542/angular2-input-field-to-accept-only-numbers
 */
@Directive({
  selector: "[appDecimalOnly]"
})
export class DecimalOnlyDirective {
  constructor(private el: ElementRef) {}

  @HostListener("keydown", ["$event"]) onKeyDown(event) {
    let e = <KeyboardEvent>event;

    // console.log(e.keyCode)

    if (
      [46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
      // Allow: Ctrl+A
      (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+C
      (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+V
      (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+X
      (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
      // Allow: home, end, left, right
      (e.keyCode >= 35 && e.keyCode <= 39)
    ) {
      // let it happen, don't do anything
      return;
    }
    // Ensure that it is a number and stop the keypress
    if (
      (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
      (e.keyCode < 96 || e.keyCode > 105)
    ) {
      e.preventDefault();
    }
  }
}

Stackblitz


来源: stackexchange

问:
handle separate transaction in java batch (JSR-352)
I'm using jberet implementation of JSR 352 java batch specs.

Actually I need a separate transaction for doing a singular update, something like this:

```<code>class MyItemWriter implements ItemWriter

@Inject
UserTransaction transaction

void resetLastProductsUpdateDate(String uidCli) throws BusinessException {
    try {
        if (transaction.getStatus() != Status.STATUS_ACTIVE) {
            transaction.begin();
        }
        final Customer customer = dao.findById(id);
        customer.setLastUpdate(null);
        customer.persist(cliente);
        transaction.commit();
    } catch (RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException | NotSupportedException e) {
        logger.error("error while updating user products last update");
        throw new BusinessException();
    }
}
</code>```

I first tried marking resetLastProductsUpdateDate methoad as @Transactional(REQUIRES_NEW), however it didn't worked.

My question is:

Is there any more elegant way to achieve this singular transaction without manually handle of transaction?

While does UserTransation works, EntityManager.transaction doesn't. I don't get it why.

Class below, which is injected from a Batchlet, works properly; Why I can't get to make work the @Transactional annotation on resetLastProductsUpdateDate method instead?

```<code>public class DynamicQueryDAO {

@Inject
EntityManager entityManager;

@Inject
private Logger logger;

@Transactional(Transactional.TxType.REQUIRED)
public void executeQuery(String query) {

    logger.info("executing query: {}", query);

    final int output = entityManager.createNativeQuery(query).executeUpdate();

    logger.info("rows updated: {}", output);
}
</code>```

}

EDIT

Actually I guess neither usertransaction  is a good solution, because it affects entire itemwriter transaction management. Still Don't know how to deal with transaction isolation :(

答: In general the batch application should avoid directly handling transaction. You can have your batch component to throw some business exceptions upon certain conditions, and configure your job.xml to trigger retry upon this business exception.  During retry, each individual data will be processed and committed in its own chunk.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm using jberet implementation of JSR 352 java batch specs.

Actually I need a separate transaction for doing a singular update, something like this:

class MyItemWriter implements ItemWriter

@Inject
UserTransaction transaction

void resetLastProductsUpdateDate(String uidCli) throws BusinessException {
    try {
        if (transaction.getStatus() != Status.STATUS_ACTIVE) {
            transaction.begin();
        }
        final Customer customer = dao.findById(id);
        customer.setLastUpdate(null);
        customer.persist(cliente);
        transaction.commit();
    } catch (RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException | NotSupportedException e) {
        logger.error("error while updating user products last update");
        throw new BusinessException();
    }
}

I first tried marking resetLastProductsUpdateDate methoad as @Transactional(REQUIRES_NEW), however it didn't worked.

My question is:

Is there any more elegant way to achieve this singular transaction without manually handle of transaction?

While does UserTransation works, EntityManager.transaction doesn't. I don't get it why.

Class below, which is injected from a Batchlet, works properly; Why I can't get to make work the @Transactional annotation on resetLastProductsUpdateDate method instead?

public class DynamicQueryDAO {

@Inject
EntityManager entityManager;

@Inject
private Logger logger;

@Transactional(Transactional.TxType.REQUIRED)
public void executeQuery(String query) {

    logger.info("executing query: {}", query);

    final int output = entityManager.createNativeQuery(query).executeUpdate();

    logger.info("rows updated: {}", output);
}

}

EDIT

Actually I guess neither usertransaction  is a good solution, because it affects entire itemwriter transaction management. Still Don't know how to deal with transaction isolation :(


问:
How do I get two pieces of data back from a string using try catch?
So I am pretty new to coding and I am trying to make a scouting app for my robotics team. I am using API from The Blue Alliance, and right now I am trying to get only one piece of data back from a certain api at a time.

I have gotten it so that I get back one piece (the city) when pressing a button but now I want to add a second button to get back something else. How would I go about this?

Once again I am very new to this.

Thank you in advanced
This is the One that does work. I have to comment the second return out because it won't work

```<code>    import com.thebluealliance.api.v3.models.Team;

import java.io.IOException;

public class TBAAsyncGetter extends AsyncTask<TBA, Void, String> {

    @Override
    protected String doInBackground(TBA... tbas) {

        try {
            Event[] ourEvents = tbas[0].teamRequest.getEvents(5496);
            Event event = ourEvents[0];

            return ourEvents[0].event_code;
            //return ourEvents[0].event_code;

        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }

    }

}
</code>```

these are the Buttons and such. (ignore all the comments)

```<code>package com.example.scoutingapp4;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.thebluealliance.api.v3.TBA;

import java.util.concurrent.ExecutionException;

public class OurTeamFragment extends Fragment implements View.OnClickListener {
    Gson gson = new Gson();
    String authKey = "tatIjlJ60oDWTv9aDk1ZDTL5GM1IJyafzPeJpWk4dR5adIgsdJt3sXvimEHA3MrI";
    TBA tba = new TBA(authKey);

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        return inflater.inflate(R.layout.fragment_ourteam, container, false);
    }

    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button btnGet = (Button) getView().findViewById(R.id.btnRegional);
        assert btnGet != null;
        btnGet.setOnClickListener(this);

        Button btnGet2 = (Button) getView().findViewById(R.id.btnEventCode);
        assert btnGet2 != null;
        btnGet2.setOnClickListener(this);

    }

    public void onClick(final View v) {
        v.setEnabled(false);
        switch (v.getId()) {

            case R.id.btnRegional:

                try {

                    TextView textHeyo = (TextView) getView().findViewById(R.id.text_regional);
                    textHeyo.setText(new TBAAsyncGetter().execute(tba).get());

                } catch (  ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
//                AsyncHttpClient client = new AsyncHttpClient();
//                client.addHeader("X-TBA-Auth-Key", "tatIjlJ60oDWTv9aDk1ZDTL5GM1IJyafzPeJpWk4dR5adIgsdJt3sXvimEHA3MrI");
//                client.get("https://www.thebluealliance.com/api/v3/team/frc5496/events/2019", new AsyncHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                        if (responseBody != null) {
//                            TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                            assert textHeyo != null;
//                            gson.toJson(new String(responseBody));
//
//                            System.out.println("body=" + new String(responseBody));
//                            textHeyo.setText(new String(responseBody));
//
//                        }
//                        v.setEnabled(true);
//                    }
//
//                    @Override
//                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//
//                        TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                        textHeyo.setText(new String("Boom! ") + new String(responseBody));
//
//                        v.setEnabled(true);
//                    }
//
//                });
                break;

            case R.id.btnEventCode:
                try {

                    TextView textHeyo = (TextView) getView().findViewById(R.id.text_event_code);
                    textHeyo.setText(new TBAAsyncGetter().execute(tba).get());

                } catch (  ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
//                AsyncHttpClient client2 = new AsyncHttpClient();
//                client2.addHeader("X-TBA-Auth-Key", "tatIjlJ60oDWTv9aDk1ZDTL5GM1IJyafzPeJpWk4dR5adIgsdJt3sXvimEHA3MrI");
//                client2.get("https://www.thebluealliance.com/api/v3/event/2020cadm/teams", new AsyncHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                        if (responseBody != null) {
//                            TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                            assert textHeyo != null;
//                            System.out.println("body=" + new String(responseBody));
//                            textHeyo.setText(new String(responseBody));
//                        }
//                        v.setEnabled(true);
//                    }
//
//                    @Override
//                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//
//                        TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                        textHeyo.setText(new String("Boom! ") + new String(responseBody));
//
//                        v.setEnabled(true);
//                    }
//
//                });
                break;
        }
    }
}

</code>```

答:
It looks like with the way you have it setup you could change it to either accept an additional parameter on the TBAAsyncGetter class's doInBackground method where you can also pass in something to specify which value you want back. Another way as mentioned is to change the return type from String to an object of your creation that holds the info, or even just returning the whole Event array info and picking out what you need in your OurTeamFragment class.

Another way would be to have two separate doInBackground methods that you call, one for each set of data you are trying to get back and you just call the one you need at each time. For instance, this could be doInBackgroundGetCity and doInBackgroundGetOther and each is hardcoded to return that specific value. It isn't the cleanest solution but these may give you a nudge in the right direction for something to help yo solve this.

Body:
So I am pretty new to coding and I am trying to make a scouting app for my robotics team. I am using API from The Blue Alliance, and right now I am trying to get only one piece of data back from a certain api at a time.

I have gotten it so that I get back one piece (the city) when pressing a button but now I want to add a second button to get back something else. How would I go about this?

Once again I am very new to this.

Thank you in advanced
This is the One that does work. I have to comment the second return out because it won't work

    import com.thebluealliance.api.v3.models.Team;

import java.io.IOException;

public class TBAAsyncGetter extends AsyncTask<TBA, Void, String> {

    @Override
    protected String doInBackground(TBA... tbas) {

        try {
            Event[] ourEvents = tbas[0].teamRequest.getEvents(5496);
            Event event = ourEvents[0];

            return ourEvents[0].event_code;
            //return ourEvents[0].event_code;

        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }

    }

}

these are the Buttons and such. (ignore all the comments)

package com.example.scoutingapp4;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.thebluealliance.api.v3.TBA;

import java.util.concurrent.ExecutionException;

public class OurTeamFragment extends Fragment implements View.OnClickListener {
    Gson gson = new Gson();
    String authKey = "tatIjlJ60oDWTv9aDk1ZDTL5GM1IJyafzPeJpWk4dR5adIgsdJt3sXvimEHA3MrI";
    TBA tba = new TBA(authKey);

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        return inflater.inflate(R.layout.fragment_ourteam, container, false);
    }

    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button btnGet = (Button) getView().findViewById(R.id.btnRegional);
        assert btnGet != null;
        btnGet.setOnClickListener(this);

        Button btnGet2 = (Button) getView().findViewById(R.id.btnEventCode);
        assert btnGet2 != null;
        btnGet2.setOnClickListener(this);

    }

    public void onClick(final View v) {
        v.setEnabled(false);
        switch (v.getId()) {

            case R.id.btnRegional:

                try {

                    TextView textHeyo = (TextView) getView().findViewById(R.id.text_regional);
                    textHeyo.setText(new TBAAsyncGetter().execute(tba).get());

                } catch (  ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
//                AsyncHttpClient client = new AsyncHttpClient();
//                client.addHeader("X-TBA-Auth-Key", "tatIjlJ60oDWTv9aDk1ZDTL5GM1IJyafzPeJpWk4dR5adIgsdJt3sXvimEHA3MrI");
//                client.get("https://www.thebluealliance.com/api/v3/team/frc5496/events/2019", new AsyncHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                        if (responseBody != null) {
//                            TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                            assert textHeyo != null;
//                            gson.toJson(new String(responseBody));
//
//                            System.out.println("body=" + new String(responseBody));
//                            textHeyo.setText(new String(responseBody));
//
//                        }
//                        v.setEnabled(true);
//                    }
//
//                    @Override
//                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//
//                        TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                        textHeyo.setText(new String("Boom! ") + new String(responseBody));
//
//                        v.setEnabled(true);
//                    }
//
//                });
                break;

            case R.id.btnEventCode:
                try {

                    TextView textHeyo = (TextView) getView().findViewById(R.id.text_event_code);
                    textHeyo.setText(new TBAAsyncGetter().execute(tba).get());

                } catch (  ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
//                AsyncHttpClient client2 = new AsyncHttpClient();
//                client2.addHeader("X-TBA-Auth-Key", "tatIjlJ60oDWTv9aDk1ZDTL5GM1IJyafzPeJpWk4dR5adIgsdJt3sXvimEHA3MrI");
//                client2.get("https://www.thebluealliance.com/api/v3/event/2020cadm/teams", new AsyncHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                        if (responseBody != null) {
//                            TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                            assert textHeyo != null;
//                            System.out.println("body=" + new String(responseBody));
//                            textHeyo.setText(new String(responseBody));
//                        }
//                        v.setEnabled(true);
//                    }
//
//                    @Override
//                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//
//                        TextView textHeyo = (TextView) getView().findViewById(R.id.text_view_result);
//                        textHeyo.setText(new String("Boom! ") + new String(responseBody));
//
//                        v.setEnabled(true);
//                    }
//
//                });
                break;
        }
    }
}


问:
Looping and scanning a list of e.g., 200 strings against a column with string data (Excel, VBA, Macros)
To the best of my efforts (VBA novice) I have been trying to write using stack and other resources a macro which would allow me to scan a given list of strings in excel against another much larger list for possible partial matches (Vlookup seems not to do a trick and Instr is a lot better for this it seems). I have been able to get some code working which leverages a loop to scan through a specific range and look for a single string of interest. For example let's say I have 20 cells in Column C with various names of fruits and vegetables and I would like to highlight only specifc ones of interest for me. In the code's case below I have included a string "Cher" (for Cherry) to be searched for against the range which if found creates a hit to the right of the column searched.

My major question would be how to adjust the code so that I could not only search for a single string like "Cherry", but how to run it against a very long list e.g. of 200 items when dealing with a couple of thousands of rows of data?

```<code>Sub listchecker()

    Dim cell As Range
        For Each cell In Range("C2:C20")
            If InStr(cell.Value, "Cher") > 0 Then
                cell.Offset(0, 1).Value = cell.Value
            End If
        Next cell

    End Sub
</code>```

Thank you in advance for anyone's help!

Thank you NautMeg and SRJ for the suggestions below. I did adjust the code and it seems to be working now against an array as noted below (hooray)

```<code>Dim wordsArray() As Variant
wordsArray = Worksheets("Keywords").Range("B2:B439").Value
Dim word As Variant

  Dim cell As Range
       For Each cell In Worksheets("Normalized").Range("J2:J49010")
           For Each word In wordsArray
               If InStr(cell.Value, word) > 0 Then
                   cell.Offset(0, -1).Value = cell.Value
               End If
           Next word
       Next cell
</code>```

The only thing I realized now though is that it would be better for 'cell.Offset(0, -1).Value = cell.Value' actually to populate with the array match (the keyword) rather than the cell's value. This is because the keyword might be too broad or too generic and result in false positives. Returning the cells value instead of the match from the array makes life more difficult to troubleshoot/identify a bad broad/generic keyword e.g., ("is").

答:
as SJR mentions above you could store the 200 search items in an array and then amend your code to something like the following:

```<code>    Dim cell As Range
        For Each cell In Range("C2:C20")
            '// Add Another For Loop here to loop through your words array
            For Each wrd in wordsArray
                If InStr(cell.Value, wrd) > 0 Then
                    cell.Offset(0, 1).Value = cell.Value
                End If
            Next word
        Next cell
    End Sub
</code>```

Possible issue with this kind of search is that it will pick up the first match, for example a search for "mang" could turn up "mango" or "mangetout" depending on which item comes up in the list first. This may or may not be desirable but something to look out for.

Body:
To the best of my efforts (VBA novice) I have been trying to write using stack and other resources a macro which would allow me to scan a given list of strings in excel against another much larger list for possible partial matches (Vlookup seems not to do a trick and Instr is a lot better for this it seems). I have been able to get some code working which leverages a loop to scan through a specific range and look for a single string of interest. For example let's say I have 20 cells in Column C with various names of fruits and vegetables and I would like to highlight only specifc ones of interest for me. In the code's case below I have included a string "Cher" (for Cherry) to be searched for against the range which if found creates a hit to the right of the column searched.

My major question would be how to adjust the code so that I could not only search for a single string like "Cherry", but how to run it against a very long list e.g. of 200 items when dealing with a couple of thousands of rows of data?

Sub listchecker()

    Dim cell As Range
        For Each cell In Range("C2:C20")
            If InStr(cell.Value, "Cher") > 0 Then
                cell.Offset(0, 1).Value = cell.Value
            End If
        Next cell

    End Sub

Thank you in advance for anyone's help!

Thank you NautMeg and SRJ for the suggestions below. I did adjust the code and it seems to be working now against an array as noted below (hooray)

Dim wordsArray() As Variant
wordsArray = Worksheets("Keywords").Range("B2:B439").Value
Dim word As Variant

  Dim cell As Range
       For Each cell In Worksheets("Normalized").Range("J2:J49010")
           For Each word In wordsArray
               If InStr(cell.Value, word) > 0 Then
                   cell.Offset(0, -1).Value = cell.Value
               End If
           Next word
       Next cell

The only thing I realized now though is that it would be better for 'cell.Offset(0, -1).Value = cell.Value' actually to populate with the array match (the keyword) rather than the cell's value. This is because the keyword might be too broad or too generic and result in false positives. Returning the cells value instead of the match from the array makes life more difficult to troubleshoot/identify a bad broad/generic keyword e.g., ("is").

Body:
as SJR mentions above you could store the 200 search items in an array and then amend your code to something like the following:

    Dim cell As Range
        For Each cell In Range("C2:C20")
            '// Add Another For Loop here to loop through your words array
            For Each wrd in wordsArray
                If InStr(cell.Value, wrd) > 0 Then
                    cell.Offset(0, 1).Value = cell.Value
                End If
            Next word
        Next cell
    End Sub

Possible issue with this kind of search is that it will pick up the first match, for example a search for "mang" could turn up "mango" or "mangetout" depending on which item comes up in the list first. This may or may not be desirable but something to look out for.


问:
PostgreSQL union two tables and join with a third table
I want to union to tables and join them with a third metadata table and I would like to know which approach is the best/fastest?

The database is a PostgreSQL.

Below is my two suggestions, but other approaches are welcome.

To do the join before the union on both tables:

```<code>SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table1 a, metadata b WHERE a.metadata_id = b.id
UNION ALL
SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table2 a, metadata b WHERE a.metadata_id = b.id
</code>```

Or to do the union first and then do the join:

```<code>SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM
(
    SELECT id, feature_type, metadata_id FROM table1
    UNION ALL
    SELECT id, feature_type, metadata_id FROM table2
)a, metadata b
WHERE a.metadata_id = b.id
</code>```

答: Run an EXPLAIN ANALYZE on both statements then you will see which one is more efficient.</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to union to tables and join them with a third metadata table and I would like to know which approach is the best/fastest?

The database is a PostgreSQL.

Below is my two suggestions, but other approaches are welcome.

To do the join before the union on both tables:

SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table1 a, metadata b WHERE a.metadata_id = b.id
UNION ALL
SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table2 a, metadata b WHERE a.metadata_id = b.id

Or to do the union first and then do the join:

SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM
(
    SELECT id, feature_type, metadata_id FROM table1
    UNION ALL
    SELECT id, feature_type, metadata_id FROM table2
)a, metadata b
WHERE a.metadata_id = b.id


问:
Check if belongsToMany relation exists - Laravel
Two of my tables (clients and products) have a ManyToMany relation using Laravel's blongToMany and a pivot table.
Now I want to check if a certain client has a certain product.

I could create a model to check in the pivot table but since Laravel does not require this model for the belongsToMany method I was wondering if there is another way to check if a certain relationship exists without having a model for the pivot table.

答:
This has time but maybe I can help someone

```<code>if($client->products()->find($product->id)){
 exists!!
}
</code>```

It should be noted that you must have the product and customer model, I hope it helps,

Body:
This has time but maybe I can help someone

if($client->products()->find($product->id)){
 exists!!
}

It should be noted that you must have the product and customer model, I hope it helps,


答:
You can use db.Raw and check the field has the name "Id" like this:

type Table struct {
 Id string `json:"Id" db:"Id" column:"Id" gorm:"column:Id"`
}

func getTable() {
 t := []Table{}
 db := config.ConnectDB()
 defer db.Close()

 db.Raw(" SELECT idEvaluacionAnual as Id FROM EvaluacionesAnuales ").Scan(&t)
 fmt.Println(t.Id)
 fmt.Println("len(table)")
}```

Hope this help you

Title: Returning the right number of columns, but all rows are empty

Body:
I am trying to do a simple Read from mysql using Gorm.

type Table struct {
    Id string `json:"Id" db:"Id" column:"Id" gorm:"column:Id"`
}

func getTable(w http.ResponseWriter, r *http.Request) {
    t:= []Table{}
    db.Debug().Table("Table").Find(&t)
    fmt.Println(table)
    fmt.Println("len(table)")
}

MySql has a table with column id as primary_key

The result im getting is a table with the correct size, but all rows are empty...

....[{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}]

But the total number of row count is correct len(t) = 20523

I think what I am doing wrong is in the definition of the Table struct, maybe I incorrectly specifying the name of the Id column? Any advice is appreciated.

Body:
You can use db.Raw and check the field has the name "Id" like this:

type Table struct {
 Id string `json:"Id" db:"Id" column:"Id" gorm:"column:Id"`
}

func getTable() {
 t := []Table{}
 db := config.ConnectDB()
 defer db.Close()

 db.Raw(" SELECT idEvaluacionAnual as Id FROM EvaluacionesAnuales ").Scan(&t)
 fmt.Println(t.Id)
 fmt.Println("len(table)")
}

Hope this help you


问:
Long running VBA macros are interrupted by svchost.exe
I have some Excel VBA macros that run for hours. The macros do millions of COM calls to get some information from a CAD application, crunch some numbers, then other millions of COM calls to the same CAD application to create some drawings. The macros write the status and the progress on a text file every second.

I have a Python process that checks whether the progress file has been updated in the last few seconds, and if it is not it will kill Excel and the CAD and notify of the failure.

The problem is that every 10 or 20 minutes I see an svchost.exe process in the task manager that takes 100% of a core for a few seconds, Excel CPU usage goes down to zero and most (not all) applications become not responsive. When svchost.exe goes back to 0%, Excel restarts running and continues its job.

Everything has worked well for years, but recently we started working with larger drawings and the svchost.exe started keeping Excel in hostage for longer and longer.

I increased the timeout from 20 seconds to 40, then to 60. But I just had a few instances where svchost.exe takes longer than a minute to do whatever it does.

If I right click on the svchost.exe process on the task manager, then on "go to services", I see two highlighted services: "RPC Endpoint Mapper" and "Remote Procedure Call (RPC)".

I have tried to add a 3 second pause every 10 seconds, hoping that svchost.exe would take advantage of the free time, but it didn't help.

The pauses appear to happen at random moments, usually when Excel loads data into a large collection, sometimes 2 or 3 times while the collection grows in size, or when the large collection goes out of scope.

I don't like to increase a timeout without knowing the reason and what is a good value.

Is there a way to avoid these long pauses?

答:
This is a good time to consider limitations of using Excel for long-running processes.

Without seeing the code, all I can do is speculate that there's a memory leak in how the COM calls are processed. Perhaps Objects are not being properly disposed even with Set = Nothing ?

Could you consider re-writing the procedures in Python or VB.Net and taking advantage of the more effective trouble shooting / application design features?

I don't thin svchost.exe has anything to do with the crash, it might be represenative or symptomatic to the COM object's DLL interfaces? But not sure exactly without knowing what DLL's and Objects are used.


问:
Device selection disabled in Xcode 4, green light in organizer
I'm trying to test an app on a 3G with 4.2.1 installed, but I'm unable to select the device in the scheme in Xcode (4.0.2).  The app is built on the 4.3 SDK, but targeted for deployment to 4.2.

Any ideas?

答: Me too. I have found that editing the active scheme ( cmd-< )and briefly switching the build configuration and then switching back fixes the issue.</p>


问:
Message box confirmation on button press
I have a problem where my code clears regardless if I press yes or no inside my message box. I believe i could probably get rid of my if statments as well i dont know why i included them like that

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
    If MsgBox("Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question = DialogResult.Yes) Then

        If (chkLevel3Support.Checked) Then
            chkLevel3Support.Checked = False
        End If

        If (chkOnSiteTraining.Checked) Then
            chkOnSiteTraining.Checked = False
        End If

        If (chkCloudBackup.Checked) Then
            chkCloudBackup.Checked = False
        End If

        If (rdbYearlyLicense.Checked) Then
            rdbYearlyLicense.Checked = False
        End If

        If (rdbOneTIme.Checked) Then
            rdbOneTIme.Checked = False
        End If

        lbCostofLicenseOutput.Text = " "

        lbCostofOptionalOutput.Text = " "

        lbTotalCostSale.Text = " "
    End If
End Sub
```

答:
I think your right parenthesis in in the wrong spot.  Try this:

```<code>If MsgBox("Are you sure?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question) = MsgBoxResult.Yes Then
</code>```

or doing it the .NET way as proposed by Andrew:

```<code>If MessageBox.Show("Are you sure?", "Confirm clear", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
</code>```

Body:
I think your right parenthesis in in the wrong spot.  Try this:

If MsgBox("Are you sure?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question) = MsgBoxResult.Yes Then

or doing it the .NET way as proposed by Andrew:

If MessageBox.Show("Are you sure?", "Confirm clear", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then


问:
Django form is not valid but no error is sent
I started to learn Django today, but I am stuck at using forms. I have created two forms: /contact and /blog-new. The form at the Contact page is working fine, but the one at /blog-new is redirecting me to the home page after the submission button is pressed and no information is printed in the terminal nor saved in the database.

Code on Github

I appreciate if someone can explain to me what I did wrong as I cannot figure it out. Thank you!

mysite/blog/forms.py

```<code>from django import forms

from .models import BlogPost

class BlogPostModelForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'slug', 'content']
</code>```

mysite/blog/views.py

```<code>from .forms import BlogPostModelForm
def blog_post_create_view(request):
    # create objects
    # ? use a form
    # request.user -> return something
    form = BlogPostModelForm(request.POST or None)
    if form.is_valid():
        print(form.cleaned_data)
        form.save()
        form = BlogPostModelForm()
    template_name = 'form.html'
    context = {'form': form}
    return render(request, template_name, context)
</code>```

mysite/blog/models.py

```<code>from django.db import models

# Create your models here.
class BlogPost(models.Model):
    title = models.TextField()
    slug = models.SlugField(unique=True)
    content = models.TextField(null=True, blank=True)
</code>```

mysite/mysite/urls.py

```<code>from blog.views import (
    blog_post_create_view,
)

urlpatterns = [
    ..
    path('blog-new', blog_post_create_view),
    ..
]
</code>```

mysite/templates/form.html

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

{% block content %}

{% if title %}
    <h1>{{ title }}</h1>
{% endif %}

<form method='POST' action='.'> {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Send</button>
</form>

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

答:
You need to point to right url in action attribute of form.

```<code><form action="/blog-new/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>
</code>```

I think it's not necessary in your case but you could also refactor your view to match the docs.

```<code>from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import SomeForm

def some_view(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = SomeForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = SomeForm()

    return render(request, 'template_name.html', {'form': form})
</code>```

Body:
I started to learn Django today, but I am stuck at using forms. I have created two forms: /contact and /blog-new. The form at the Contact page is working fine, but the one at /blog-new is redirecting me to the home page after the submission button is pressed and no information is printed in the terminal nor saved in the database.

Code on Github

I appreciate if someone can explain to me what I did wrong as I cannot figure it out. Thank you!

mysite/blog/forms.py

from django import forms

from .models import BlogPost

class BlogPostModelForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'slug', 'content']

mysite/blog/views.py

from .forms import BlogPostModelForm
def blog_post_create_view(request):
    # create objects
    # ? use a form
    # request.user -> return something
    form = BlogPostModelForm(request.POST or None)
    if form.is_valid():
        print(form.cleaned_data)
        form.save()
        form = BlogPostModelForm()
    template_name = 'form.html'
    context = {'form': form}
    return render(request, template_name, context)

mysite/blog/models.py

from django.db import models

# Create your models here.
class BlogPost(models.Model):
    title = models.TextField()
    slug = models.SlugField(unique=True)
    content = models.TextField(null=True, blank=True)

mysite/mysite/urls.py

from blog.views import (
    blog_post_create_view,
)

urlpatterns = [
    ..
    path('blog-new', blog_post_create_view),
    ..
]

mysite/templates/form.html

{% extends "base.html" %}

{% block content %}

{% if title %}

{{ title }}

{% endif %}

<form method='POST' action='.'> {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Send</button>
</form>

{% endblock %}

Body:
You need to point to right url in action attribute of form.

<form action="/blog-new/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

I think it's not necessary in your case but you could also refactor your view to match the docs.

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import SomeForm

def some_view(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = SomeForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = SomeForm()

    return render(request, 'template_name.html', {'form': form})


问:
What is a UML profile diagram and when is it used?
I have been reading about the UML Profile Diagram but I don't understand it. I want to mainly understand when it can used.

答:
A profile is a special kind of package that allows you to extend UML. The profile diagram is a structural diagram that explains these extensions using meta-classes, so the classes that are used to define UML itself.

Look for example, how the standard profile defines the stereotypes of a component diagram:

You will certainly remark the black arrow, which looks like a generalization but with a filled head.  They mean an extension of an UML metaclass.  So, here an UML component can be extended with a stereotype «Entity». Like all UML diagrams, the diagram doesn't show it all.  So you'd have some definition of what the stereotype is.

You can find an practical example in this profile diagram that defines EJB stereotypes, which can be useful if you model a lot of EJB based designs.  You can in the same way define a more specialised profile if you do specialised modelling.

Another example of use for UML profiles is to define the basic types of a programming language.  For example, if the UML primitive types Integer and Real are not what you want, you can very well define the following primitive types in your own profile:

Profiles even allow you to associate a graphical icon with an element.


问:
Can not find element in XPath with Selenium driver
Every time I load up python script the Xpath for the Facebook login button and popup button has to changed manually every time before I login. How do I change this so that I dont have to enter the XPath manually?

```<code>from selenium import webdriver
from time import sleep

class TinderBot():
    def __init__(self):
        self.driver = webdriver.Chrome()

    def login(self):
        self.driver.get('https://tinder.com')

        sleep(3)

        #fbxpath = //button[@type = 'button' and @aria-label = 'Log in with Facebook']

        fb_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div/main/div/div[2]/div[2]/div/div/span/div[2]/button')
        fb_btn.click()

        base_window = self.driver.window_handles[0]
        self.driver.switch_to_window(self.driver.window_handles[1])
        fbemail = self.driver.find_element_by_xpath('//*[@id="email"]')
        fbemail.send_keys('ara_98425@yahoo.com')

        fbpass = self.driver.find_element_by_xpath('//*[@id="pass"]')
        fbpass.send_keys('BlackToast5')

        login_btn = self.driver.find_element_by_xpath('//*[@id="u_0_0"]')
        login_btn.click()

        self.driver.switch_to_window(base_window)

        popup1 = self.driver.find_element_by_xpath('//*[@id="modal-manager"]/div/div/div/div/div[3]/button[1]')
        popup1.click()

        popup2 = self.driver.find_element_by_xpath('//*[@id="modal-manager"]/div/div/div/div/div[3]/button[1]')
        popup2.click()

bot = TinderBot()
bot.login()
</code>```

This is the error I get:

```<code>File "tind_bt.py", line 16, in login
    fb_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div/main/div/div[2]/div[2]/div/div/span/div[2]/button')
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="content"]/div/div[1]/div/div/main/div/div[2]/div[2]/div/div/span/div[2]/button"}
  (Session info: chrome=80.0.3987.106)
</code>```

答:
You were close. To invoke click() on the element with text as Log in with Facebook you need to induce WebDriverWait for the element_to_be_clickable() reaching till the child  and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type = 'button'][aria-label = 'Log in with Facebook'] span"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@type = 'button' and @aria-label = 'Log in with Facebook']//span"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Browser Snapshot:

Reference

You can find a detailed relevant discussion in:

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

Body:
Every time I load up python script the Xpath for the Facebook login button and popup button has to changed manually every time before I login. How do I change this so that I dont have to enter the XPath manually?

from selenium import webdriver
from time import sleep

class TinderBot():
    def __init__(self):
        self.driver = webdriver.Chrome()

    def login(self):
        self.driver.get('https://tinder.com')

        sleep(3)

        #fbxpath = //button[@type = 'button' and @aria-label = 'Log in with Facebook']

        fb_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div/main/div/div[2]/div[2]/div/div/span/div[2]/button')
        fb_btn.click()

        base_window = self.driver.window_handles[0]
        self.driver.switch_to_window(self.driver.window_handles[1])
        fbemail = self.driver.find_element_by_xpath('//*[@id="email"]')
        fbemail.send_keys('ara_98425@yahoo.com')

        fbpass = self.driver.find_element_by_xpath('//*[@id="pass"]')
        fbpass.send_keys('BlackToast5')

        login_btn = self.driver.find_element_by_xpath('//*[@id="u_0_0"]')
        login_btn.click()

        self.driver.switch_to_window(base_window)

        popup1 = self.driver.find_element_by_xpath('//*[@id="modal-manager"]/div/div/div/div/div[3]/button[1]')
        popup1.click()

        popup2 = self.driver.find_element_by_xpath('//*[@id="modal-manager"]/div/div/div/div/div[3]/button[1]')
        popup2.click()

bot = TinderBot()
bot.login()

This is the error I get:

File "tind_bt.py", line 16, in login
    fb_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div/main/div/div[2]/div[2]/div/div/span/div[2]/button')
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="content"]/div/div[1]/div/div/main/div/div[2]/div[2]/div/div/span/div[2]/button"}
  (Session info: chrome=80.0.3987.106)

Body:
You were close. To invoke click() on the element with text as Log in with Facebook you need to induce WebDriverWait for the element_to_be_clickable() reaching till the child <span> and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type = 'button'][aria-label = 'Log in with Facebook'] span"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@type = 'button' and @aria-label = 'Log in with Facebook']//span"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Browser Snapshot:

Reference

You can find a detailed relevant discussion in:

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome


问:
Clang and CMake on Windows - clang.exe broken, program not executable
I've set up Clang and CMake on Windows and when running cmake-gui on the OpenSceneGraph project source (configure step), the process fails with Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe -- broken.

Following the whole output:

```<code>The C compiler identification is unknown
The CXX compiler identification is unknown
Found Eclipse version 4.3 ()
Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe
Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe -- broken
CMake Error at C:/Program Files (x86)/CMake/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:61 (message):
  The C compiler "C:/Program Files (x86)/LLVM/bin/clang.exe" is not able to
  compile a simple test program.

  It fails with the following output:

   Change Dir: C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp

  Run Build Command:C:/PROGRA~2/GnuWin32/bin/make.exe
  "cmTryCompileExec2091697540/fast"

  C:/PROGRA~2/GnuWin32/bin/make.exe -f
  CMakeFiles/cmTryCompileExec2091697540.dir/build.make
  CMakeFiles/cmTryCompileExec2091697540.dir/build

  make.exe[1]: Entering directory
  `C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp'

  "C:/Program Files (x86)/CMake/bin/cmake.exe" -E cmake_progress_report
  C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp/CMakeFiles
  1

  "Building C object
  CMakeFiles/cmTryCompileExec2091697540.dir/testCCompiler.c.obj"

  "C:/Program Files (x86)/LLVM/bin/clang.exe" -o
  CMakeFiles/cmTryCompileExec2091697540.dir/testCCompiler.c.obj -c
  C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp/testCCompiler.c

  clang.exe: error: unable to execute command: program not executable

  clang.exe: error: assembler (via gcc) command failed with exit code 1 (use
  -v to see invocation)

  make.exe[1]: ***
  [CMakeFiles/cmTryCompileExec2091697540.dir/testCCompiler.c.obj] Fehler 1

  make.exe[1]: Leaving directory
  `C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp'

  make.exe: *** [cmTryCompileExec2091697540/fast] Fehler 2

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:47 (PROJECT)

Configuring incomplete, errors occurred!
See also "C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeOutput.log".
See also "C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeError.log".
</code>```

What can be the reason for this? Is there an incompatibility between the programs, or are there environment variables missing?

答:
As mentioned in this link, clang on Windows must be able to find link.exe.

I tested it with an old Visual Studio Express edition linker, and it worked just fine.

Body:
I've set up Clang and CMake on Windows and when running cmake-gui on the OpenSceneGraph project source (configure step), the process fails with Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe -- broken.

Following the whole output:

The C compiler identification is unknown
The CXX compiler identification is unknown
Found Eclipse version 4.3 ()
Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe
Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe -- broken
CMake Error at C:/Program Files (x86)/CMake/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:61 (message):
  The C compiler "C:/Program Files (x86)/LLVM/bin/clang.exe" is not able to
  compile a simple test program.

  It fails with the following output:

   Change Dir: C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp

  Run Build Command:C:/PROGRA~2/GnuWin32/bin/make.exe
  "cmTryCompileExec2091697540/fast"

  C:/PROGRA~2/GnuWin32/bin/make.exe -f
  CMakeFiles/cmTryCompileExec2091697540.dir/build.make
  CMakeFiles/cmTryCompileExec2091697540.dir/build

  make.exe[1]: Entering directory
  `C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp'

  "C:/Program Files (x86)/CMake/bin/cmake.exe" -E cmake_progress_report
  C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp/CMakeFiles
  1

  "Building C object
  CMakeFiles/cmTryCompileExec2091697540.dir/testCCompiler.c.obj"

  "C:/Program Files (x86)/LLVM/bin/clang.exe" -o
  CMakeFiles/cmTryCompileExec2091697540.dir/testCCompiler.c.obj -c
  C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp/testCCompiler.c

  clang.exe: error: unable to execute command: program not executable

  clang.exe: error: assembler (via gcc) command failed with exit code 1 (use
  -v to see invocation)

  make.exe[1]: ***
  [CMakeFiles/cmTryCompileExec2091697540.dir/testCCompiler.c.obj] Fehler 1

  make.exe[1]: Leaving directory
  `C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeTmp'

  make.exe: *** [cmTryCompileExec2091697540/fast] Fehler 2

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:47 (PROJECT)

Configuring incomplete, errors occurred!
See also "C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeOutput.log".
See also "C:/Users/Adam/Desktop/OpenSceneGraph-3.2.1-rc3/build/CMakeFiles/CMakeError.log".

What can be the reason for this? Is there an incompatibility between the programs, or are there environment variables missing?


问:
How to Call Partial View with Asp.Net Mvc
I need to search on the database, and load only the View, and not refresh the entire page. A function in Js calls my method on the controller, when clicking on search, and the controller returns the View.

```<code>function Pesquisa()
{
  let campo = document.getElementsByName("campo");
  let pesquisa = document.getElementsByName("EdtPesquisa");
  let condicao = document.getElementsByName("pesquisa");

  let scampo = Array();
  let spesquisa = Array();
  let scondicao = Array();

  let sNomeGrid = ($(this).find("a").text());

  for (var indice = 0; indice < pesquisa.length; indice++)
  {
    string = pesquisa[indice].value;

    if (string.trim() != "")
    {
        scampo[indice] = campo[indice].id;
        scondicao[indice] = condicao[indice].value;
        spesquisa[indice] = pesquisa[indice].value;
    }
  }

window.location.href = "/MenuPrincipal/RetornarView?sNomeGrid=" + "Unidade" + "&listacampo=" + scampo + "&listacondicao=" + scondicao + "&listapesquisa=" + spesquisa;
</code>```

Controller

```<code>public IActionResult RetornarView(string sNomeGrid, List<string> listacampo, List<string> listacondicao, List<string> listapesquisa)
{
    var sWhere = "";

    if (listacampo.Count > 0)
    {
        Pesquisa _Pesquisa = new Pesquisa();

        sWhere = _Pesquisa.Pesquisar(listacampo, listacondicao, listapesquisa);
    }

    if (sNomeGrid == "Unidade")
    {
        var listaunidade = _UnidadeRepositorio.ListarMenu(sWhere);

        return View("Unidade", listaunidade);
    }

    return View("MenuPrincipal");
}
</code>```

View

```<code>@model IEnumerable<ApesWeb.Models.Classes.Unidade>

<div class="tabela-responsive">
<table id="tabela" class="tabela tabela-hover"
       data-toggle="table">
    <thead>
        <tr>
            <th id="idunidade" name="campo">@Html.DisplayNameFor(model => model.idunidade)</th>
            <th id="sdescricao" name="campo">@Html.DisplayNameFor(model => model.sdescricao)</th>
            <th id="sunidade" name="campo">@Html.DisplayNameFor(model => model.sunidade)</th>
            <th id="sdigitavolume" name="campo">@Html.DisplayNameFor(model => model.sdigitavolume)</th>
            <th id="spadraosistema" name="campo">@Html.DisplayNameFor(model => model.spadraosistema)</th>
        </tr>
        <tr>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa"/>
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var Unidade in Model)
        {
        <tr>
            <td>
                @Html.DisplayFor(modelitem => Unidade.idunidade)
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.sdescricao)
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.sunidade)
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.sdigitavolume)
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.spadraosistema)
            </td>
        </tr>
        }
    </tbody>
</table>
</code>```

Returns the View with the list to fill the Table, but in this process the entire page is refreshed.

答:
You can use one of the following methods according to your needs:

Method I: If you want to use ViewData, try this:

```<code>@Html.Partial("~/PathToYourView.cshtml", null,
    new ViewDataDictionary { { "VariableName", "some value" } })
</code>```

And to retrieve the passed in values:

```<code>@{
    string valuePassedIn = this.ViewData.ContainsKey("VariableName") ?
        this.ViewData["VariableName"].ToString() : string.Empty;
}
</code>```

Method II: If you just render a partial with just the partial name:

```<code>@Html.Partial("_SomePartial", Model)
</code>```

Method II: Render PartialView using jQuery Ajax call:

Firstly wrap your body content in a div and assign any id to it in _Layout page:

```<code><div id="div-page-content" class="page-content">
    @RenderBody()
</div>
</code>```

Here is the menu item used for rendering PartialView in _Layout page:

```<code><ul class="sub-menu">
    <li class="nav-item  ">
        <a href="#" onclick="renderPartial(event, 'Account', '_Register')" class="nav-link">
            <span class="title">Create New User</span>
        </a>
    </li>
</ul>
</code>```

Define the javascript function for click event in _Layout page:

```<code>function renderPartial(e, controller, action) {
    e.preventDefault();
    e.stopPropagation();

    var controllerName = controller;
    var actionName = action;

    if (String(actionName).trim() == '') {
        return false;
    }
    if (typeof (controllerName) == "undefined") {
        return false;
    }

    var url = "/" + controllerName + "/" + actionName;

    ////Open url in new tab with ctrl key press
    //if (e.ctrlKey) {
    //    window.open(url, '_blank');
    //    e.stopPropagation();
    //    return false;
    //}

    $.ajax({
        url: url,
        data: { /* additional parameters */ },
        cache: false,
        type: "POST",
        dataType: "html",

        success: function (data) {
            var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
            if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
                requestedUrl = window.location.href;
            }

            // if the url is the same, replace the state
            if (typeof (history.pushState) != "undefined") {
                if (window.location.href == requestedUrl) {
                    history.replaceState({ html: '' }, document.title, requestedUrl);
                }
                else {
                    history.pushState({ html: '' }, document.title, requestedUrl);
                }
            }

            $("#div-page-content").html(data);
        },
        error: function (data) { onError(data); }
    });
};
</code>```

Define your PartialView as shown below:

```<code><div>
    ... partial view content goes here >
</div>
</code>```

Add the Action metdod to the Controller as shown below:

```<code>[HttpPost]
[AllowAnonymous]
public PartialViewResult _Register(/* additional parameters */)
{
    return PartialView();
}
</code>```

Body:
I need to search on the database, and load only the View, and not refresh the entire page. A function in Js calls my method on the controller, when clicking on search, and the controller returns the View.

function Pesquisa()
{
  let campo = document.getElementsByName("campo");
  let pesquisa = document.getElementsByName("EdtPesquisa");
  let condicao = document.getElementsByName("pesquisa");

  let scampo = Array();
  let spesquisa = Array();
  let scondicao = Array();

  let sNomeGrid = ($(this).find("a").text());

  for (var indice = 0; indice < pesquisa.length; indice++)
  {
    string = pesquisa[indice].value;

    if (string.trim() != "")
    {
        scampo[indice] = campo[indice].id;
        scondicao[indice] = condicao[indice].value;
        spesquisa[indice] = pesquisa[indice].value;
    }
  }

window.location.href = "/MenuPrincipal/RetornarView?sNomeGrid=" + "Unidade" + "&listacampo=" + scampo + "&listacondicao=" + scondicao + "&listapesquisa=" + spesquisa;

Controller

public IActionResult RetornarView(string sNomeGrid, List<string> listacampo, List<string> listacondicao, List<string> listapesquisa)
{
    var sWhere = "";

    if (listacampo.Count > 0)
    {
        Pesquisa _Pesquisa = new Pesquisa();

        sWhere = _Pesquisa.Pesquisar(listacampo, listacondicao, listapesquisa);
    }

    if (sNomeGrid == "Unidade")
    {
        var listaunidade = _UnidadeRepositorio.ListarMenu(sWhere);

        return View("Unidade", listaunidade);
    }

    return View("MenuPrincipal");
}

View

@model IEnumerable<ApesWeb.Models.Classes.Unidade>

            @Html.DisplayNameFor(model => model.idunidade)
            @Html.DisplayNameFor(model => model.sdescricao)
            @Html.DisplayNameFor(model => model.sunidade)
            @Html.DisplayNameFor(model => model.sdigitavolume)
            @Html.DisplayNameFor(model => model.spadraosistema)

                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>

                    <select name="pesquisa"/>
                    <input type="text" name="EdtPesquisa"/>

                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>

                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>

                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>

        @foreach (var Unidade in Model)
        {

                @Html.DisplayFor(modelitem => Unidade.idunidade)

                @Html.DisplayFor(modelitem => Unidade.sdescricao)

                @Html.DisplayFor(modelitem => Unidade.sunidade)

                @Html.DisplayFor(modelitem => Unidade.sdigitavolume)

                @Html.DisplayFor(modelitem => Unidade.spadraosistema)

        }

Returns the View with the list to fill the Table, but in this process the entire page is refreshed.

Body:
You can use one of the following methods according to your needs:

Method I: If you want to use ViewData, try this:

@Html.Partial("~/PathToYourView.cshtml", null,
    new ViewDataDictionary { { "VariableName", "some value" } })

And to retrieve the passed in values:

@{
    string valuePassedIn = this.ViewData.ContainsKey("VariableName") ?
        this.ViewData["VariableName"].ToString() : string.Empty;
}

Method II: If you just render a partial with just the partial name:

@Html.Partial("_SomePartial", Model)

Method II: Render PartialView using jQuery Ajax call:

Firstly wrap your body content in a div and assign any id to it in _Layout page:

<div id="div-page-content" class="page-content">
    @RenderBody()
</div>

Here is the menu item used for rendering PartialView in _Layout page:

<ul class="sub-menu">
    <li class="nav-item  ">
        <a href="#" onclick="renderPartial(event, 'Account', '_Register')" class="nav-link">
            <span class="title">Create New User</span>
        </a>
    </li>
</ul>

Define the javascript function for click event in _Layout page:

function renderPartial(e, controller, action) {
    e.preventDefault();
    e.stopPropagation();

    var controllerName = controller;
    var actionName = action;

    if (String(actionName).trim() == '') {
        return false;
    }
    if (typeof (controllerName) == "undefined") {
        return false;
    }

    var url = "/" + controllerName + "/" + actionName;

    ////Open url in new tab with ctrl key press
    //if (e.ctrlKey) {
    //    window.open(url, '_blank');
    //    e.stopPropagation();
    //    return false;
    //}

    $.ajax({
        url: url,
        data: { /* additional parameters */ },
        cache: false,
        type: "POST",
        dataType: "html",

        success: function (data) {
            var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
            if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
                requestedUrl = window.location.href;
            }

            // if the url is the same, replace the state
            if (typeof (history.pushState) != "undefined") {
                if (window.location.href == requestedUrl) {
                    history.replaceState({ html: '' }, document.title, requestedUrl);
                }
                else {
                    history.pushState({ html: '' }, document.title, requestedUrl);
                }
            }

            $("#div-page-content").html(data);
        },
        error: function (data) { onError(data); }
    });
};

Define your PartialView as shown below:

<div>
    ... partial view content goes here >
</div>

Add the Action metdod to the Controller as shown below:

[HttpPost]
[AllowAnonymous]
public PartialViewResult _Register(/* additional parameters */)
{
    return PartialView();
}


问:
How to mock a Vuex store in VueJS test-utils parentComponent
I'm using Jest with vue-test-utils trying to test if a child component reacts to an $emit event in the parent component.

VueJS test-utils library provides a parentComponent option to be passed when mounting/shallow mounting the component.

Everything is working fine except that even though I instantiate the component with a mocked Vuex store, the parent component throws a

TypeError: Cannot read property 'state' of undefined

on a this.$store.state.something.here piece of code in the parent component.

How can I mock the Vuex store there?

The component mount looks like this:

```<code>const wrapper = shallowMount(ChildComponent, {
  store,
  localVue,
  parentComponent: ParentComponent,
  mocks: {
    $t: msg => msg,
  },
});
</code>```

Any ideas on how to solve this?

答:
it may not be the complete answer to OP questions, but since I had been debugging around for the last 2h and finally found MY problem, I would like to posted here to help someone in the future.

I was trying to mock and mount the following component:

```<code><template>
<div test="object-list-div">
  <h1 test="component-title">{{ objectName }}</h1>
  <table class="table">
    <thead>
        <tr test="table-row-title">
            <th scope="col" test="table-column-title" v-for="(value, name, index) in objectData[0]" :key="index">{{ name }}</th>
        </tr>
    </thead>
    <tbody>
      <tr test="table-row-data" v-for="(ivalue, iname, i) in objectData" :key="i">
        <td test="table-cell-data" v-for="(jvalue, jname, j) in ivalue" :key="j">{{ jvalue }}</td>
      </tr>
    </tbody>
  </table>
</div>
</code>```

```<code>export default  {

    props: [
        'objectName',
        'objectData'
    ],
    computed: {
      visibleColums() {
        return this.$store.state.Config_ShowColumn;
      }
    }
}
</code>```

with the following wrapper code

```<code> wrapper = shallowMount(ObjectList, {
    mocks: {
      $store: {
        state: {
          Config_ShowColumn: [
            "Field1",
            "Field2",
            "Field3",
            "Field4",
            "Field5",
          ]
        }
      }
    }
  });
</code>```

I got OP error, but in my case the component was expecting two Props at the moment of creation. Since it did not receive this, it got stuck.

This is working now:

```<code>import { shallowMount } from "@vue/test-utils";
import { expect } from "chai";
import ObjectList from "@/components/Object-List.vue";

wrapper = shallowMount(ObjectList, {
    propsData: {
      objectName: "Ticket",
      objectData: [
        {
          Field1: "Field1",
          Field2: "Field2",
          Field3: "Field3",
          Field4: "Field4",
          Field5: "Field5",
        },
      ]
    },
    mocks: {
      $store: {
        state: {
          Config_ShowColumn: [
            "Field1",
            "Field2",
            "Field3",
            "Field4",
            "Field5",
          ]
        }
      }
    }
  });
</code>```

Hope it helps someone.

Body:
I'm using Jest with vue-test-utils trying to test if a child component reacts to an $emit event in the parent component.

VueJS test-utils library provides a parentComponent option to be passed when mounting/shallow mounting the component.

Everything is working fine except that even though I instantiate the component with a mocked Vuex store, the parent component throws a

TypeError: Cannot read property 'state' of undefined

on a this.$store.state.something.here piece of code in the parent component.

How can I mock the Vuex store there?

The component mount looks like this:

const wrapper = shallowMount(ChildComponent, {
  store,
  localVue,
  parentComponent: ParentComponent,
  mocks: {
    $t: msg => msg,
  },
});

Any ideas on how to solve this?

Body:
it may not be the complete answer to OP questions, but since I had been debugging around for the last 2h and finally found MY problem, I would like to posted here to help someone in the future.

I was trying to mock and mount the following component:

<template>
<div test="object-list-div">
  <h1 test="component-title">{{ objectName }}</h1>
  <table class="table">
    <thead>
        <tr test="table-row-title">
            <th scope="col" test="table-column-title" v-for="(value, name, index) in objectData[0]" :key="index">{{ name }}</th>
        </tr>
    </thead>
    <tbody>
      <tr test="table-row-data" v-for="(ivalue, iname, i) in objectData" :key="i">
        <td test="table-cell-data" v-for="(jvalue, jname, j) in ivalue" :key="j">{{ jvalue }}</td>
      </tr>
    </tbody>
  </table>
</div>

export default  {

    props: [
        'objectName',
        'objectData'
    ],
    computed: {
      visibleColums() {
        return this.$store.state.Config_ShowColumn;
      }
    }
}

with the following wrapper code

 wrapper = shallowMount(ObjectList, {
    mocks: {
      $store: {
        state: {
          Config_ShowColumn: [
            "Field1",
            "Field2",
            "Field3",
            "Field4",
            "Field5",
          ]
        }
      }
    }
  });

I got OP error, but in my case the component was expecting two Props at the moment of creation. Since it did not receive this, it got stuck.

This is working now:

import { shallowMount } from "@vue/test-utils";
import { expect } from "chai";
import ObjectList from "@/components/Object-List.vue";

wrapper = shallowMount(ObjectList, {
    propsData: {
      objectName: "Ticket",
      objectData: [
        {
          Field1: "Field1",
          Field2: "Field2",
          Field3: "Field3",
          Field4: "Field4",
          Field5: "Field5",
        },
      ]
    },
    mocks: {
      $store: {
        state: {
          Config_ShowColumn: [
            "Field1",
            "Field2",
            "Field3",
            "Field4",
            "Field5",
          ]
        }
      }
    }
  });

Hope it helps someone.


问:
Angular how to subtract time from current time
I am fetching data from firebase i need to know how can i check difference between the fetch time and current time

Example

```<code>if(this.data.time - current time <= (less or equal) 3 hours) {
  console.log('Please wait till difference')
}
</code>```

What i need if data.time - current time is less then or equal to 3 hours then i need to console the time left in 3 hours.

I have time in second and nanoseconds.

Let me clear more. For example data time is 2.30AM and current time is 3.30AM So its not completed 3 hours till now so i need time left which is 2 hours left. and if time completed like current time is 6.30 so simple console time exceed.

Working with this code but showing error Type 'string' is not assignable to type 'number'.

```<code>secondsToHHMMSS(totalSeconds: any): string { // from https://stackoverflow.com/a/1322798/6513921
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // if you want strings with leading zeroes:
  minutes = String(minutes).padStart(2, "0"); //here showing error of String
  hours = String(hours).padStart(2, "0"); //here showing error of String
  seconds = String(seconds).padStart(2, "0"); //here showing error of String

  return (hours + ":" + minutes + ":" + seconds);
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log('3 hours hasn\'t elapsed yet.');
  console.log('Time remaining: ' + this.secondsToHHMMSS(timeDiff));
}
</code>```

答:
Your timestamp lastLogin.seconds is in Epoch time.

So subtract your current timestamp Math.floor(Date.now() / 1000) from your timestamp and check if it's less than 10800 seconds (3 hours). The following code should do

```<code>secondsToHHMMSS(totalSeconds: any): string { // https://stackoverflow.com/a/1322798/6513921
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // if you want strings with leading zeroes:
  minutes = String(minutes).padStart(2, "0");
  hours = String(hours).padStart(2, "0");
  seconds = String(seconds).padStart(2, "0");

  return (hours + ":" + minutes + ":" + seconds);
}

secondsToHHMMSSRegex(seconds: any): any { // https://stackoverflow.com/a/17781037/6513921
    const date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log('3 hours hasn\'t elapsed yet.');
  console.log('Time remaining: ' + this.secondsToHHMMSSRegex(timeDiff));
}
</code>```

Note: the reverse conversion contains multiple division operators. Division operator usually incurs high latency. As a result, your result might be a second or two delayed than you expect.

Body:
I am fetching data from firebase i need to know how can i check difference between the fetch time and current time

Example

if(this.data.time - current time <= (less or equal) 3 hours) {
  console.log('Please wait till difference')
}

What i need if data.time - current time is less then or equal to 3 hours then i need to console the time left in 3 hours.

I have time in second and nanoseconds.

Let me clear more. For example data time is 2.30AM and current time is 3.30AM So its not completed 3 hours till now so i need time left which is 2 hours left. and if time completed like current time is 6.30 so simple console time exceed.

Working with this code but showing error Type 'string' is not assignable to type 'number'.

secondsToHHMMSS(totalSeconds: any): string { // from https://stackoverflow.com/a/1322798/6513921
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // if you want strings with leading zeroes:
  minutes = String(minutes).padStart(2, "0"); //here showing error of String
  hours = String(hours).padStart(2, "0"); //here showing error of String
  seconds = String(seconds).padStart(2, "0"); //here showing error of String

  return (hours + ":" + minutes + ":" + seconds);
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log('3 hours hasn\'t elapsed yet.');
  console.log('Time remaining: ' + this.secondsToHHMMSS(timeDiff));
}

Body:
Your timestamp lastLogin.seconds is in Epoch time.

So subtract your current timestamp Math.floor(Date.now() / 1000) from your timestamp and check if it's less than 10800 seconds (3 hours). The following code should do

secondsToHHMMSS(totalSeconds: any): string { // https://stackoverflow.com/a/1322798/6513921
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // if you want strings with leading zeroes:
  minutes = String(minutes).padStart(2, "0");
  hours = String(hours).padStart(2, "0");
  seconds = String(seconds).padStart(2, "0");

  return (hours + ":" + minutes + ":" + seconds);
}

secondsToHHMMSSRegex(seconds: any): any { // https://stackoverflow.com/a/17781037/6513921
    const date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log('3 hours hasn\'t elapsed yet.');
  console.log('Time remaining: ' + this.secondsToHHMMSSRegex(timeDiff));
}

Note: the reverse conversion contains multiple division operators. Division operator usually incurs high latency. As a result, your result might be a second or two delayed than you expect.


问:
Lagom Serialization for Static Assets
I'm developing a Lagom microservice. In addition to its meat, it has a few static files to serve (index.html, *.css, *.js, and favicon.ico). I know how to set the response's Content-Type header using Lagom's ServerServiceCall[Req, Res]. However, if if specify String as the response parameter type, Content-Type is overwritten as "text/plain" regardless of what I set in the service call's body. If I use akka.util.ByteString, then Content-Type becomes "application/octet-stream".

I figure this must be because this is what the serializers of String and ByteString demand. So, my question is: which response types should I do to obtain "text/html", "text/css", "application/javascript", and "image/vnd.microsoft.icon"? Or is there a more generic way to serve static assets in Lagom? The documentation is surprisingly sparse on this.

Would something like this work:

```<code>import akka.util.ByteString
import com.lightbend.lagom.scaladsl.api.transport.MessageProtocol
import com.lightbend.lagom.scaladsl.api.deser.MessageSerializer.NegotiatedSerializer

class ContentTypeSerializer(contentType: String, charset: String) extends NegotiatedSerializer[String, ByteString] {
  override val protocol = MessageProtocol(Some(contentType), Some(charset))
  def serialize(body: String) = ByteString.fromString(body, charset)
}
</code>```

答:
Yup, this takes care of it:</p>

```<code>import akka.util.ByteString
import play.api.libs.json.Json
import scala.collection.immutable
import scala.util.control.NonFatal
import com.lightbend.lagom.scaladsl.api.transport._
import com.lightbend.lagom.scaladsl.api.deser.StrictMessageSerializer
import com.lightbend.lagom.scaladsl.api.deser.MessageSerializer.{NegotiatedDeserializer, NegotiatedSerializer}

class ContentTypeSerializer(contentType: String, charset: String) extends NegotiatedSerializer[String, ByteString] {
  override val protocol = MessageProtocol(Some(contentType), Some(charset))
  def serialize(body: String) = ByteString.fromString(body, charset)
}

object ContentTypeSerializer {
  val Json = "application/json"
  val Js = "application/javascript"
  val Icon = "image/vnd.microsoft.icon"
  val Html = "text/html"
  val Css = "text/css"

  val JsonSerializer = new ContentTypeSerializer(ContentTypeSerializer.Json, "utf-8")
}

class JsonTextDeserializer extends NegotiatedDeserializer[String, ByteString] {
  def deserialize(bytes: ByteString) =
    try {
      Json.parse(bytes.iterator.asInputStream).as[String]
    } catch {
      case NonFatal(e) => throw DeserializationException(e)
    }
}

object ResponseSerializer extends StrictMessageSerializer[String] {
  override val acceptResponseProtocols = List(
    MessageProtocol(Some(ContentTypeSerializer.Json)),
    MessageProtocol(Some(ContentTypeSerializer.Html)),
    MessageProtocol(Some(ContentTypeSerializer.Icon)),
    MessageProtocol(Some(ContentTypeSerializer.Css)),
    MessageProtocol(Some(ContentTypeSerializer.Js))
  )

  val serializerForRequest = ContentTypeSerializer.JsonSerializer

  def deserializer(protocol: MessageProtocol) = protocol.contentType match {
    case Some(ContentTypeSerializer.Json) | None =>
      new JsonTextDeserializer
    case _ =>
      throw UnsupportedMediaType(protocol, MessageProtocol(Some("text/plain")))
  }

  def serializerForResponse(accepted: immutable.Seq[MessageProtocol]) = accepted match {
    case Nil => ContentTypeSerializer.JsonSerializer
    case protocols => protocols.collectFirst {
      case MessageProtocol(Some(ContentTypeSerializer.Json), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Json, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Html), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Html, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Icon), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Icon, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Css), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Css, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Js), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Js, charset.getOrElse("utf-8"))
    }.getOrElse {
      throw NotAcceptable(accepted, MessageProtocol(Some("text/plain")))
    }
  }
}
</code>```

Title: Lagom Serialization for Static Assets

Body:
I'm developing a Lagom microservice. In addition to its meat, it has a few static files to serve (index.html, *.css, *.js, and favicon.ico). I know how to set the response's Content-Type header using Lagom's ServerServiceCall[Req, Res]. However, if if specify String as the response parameter type, Content-Type is overwritten as "text/plain" regardless of what I set in the service call's body. If I use akka.util.ByteString, then Content-Type becomes "application/octet-stream".

I figure this must be because this is what the serializers of String and ByteString demand. So, my question is: which response types should I do to obtain "text/html", "text/css", "application/javascript", and "image/vnd.microsoft.icon"? Or is there a more generic way to serve static assets in Lagom? The documentation is surprisingly sparse on this.

Would something like this work:

import akka.util.ByteString
import com.lightbend.lagom.scaladsl.api.transport.MessageProtocol
import com.lightbend.lagom.scaladsl.api.deser.MessageSerializer.NegotiatedSerializer

class ContentTypeSerializer(contentType: String, charset: String) extends NegotiatedSerializer[String, ByteString] {
  override val protocol = MessageProtocol(Some(contentType), Some(charset))
  def serialize(body: String) = ByteString.fromString(body, charset)
}

Body:
Yup, this takes care of it:

import akka.util.ByteString
import play.api.libs.json.Json
import scala.collection.immutable
import scala.util.control.NonFatal
import com.lightbend.lagom.scaladsl.api.transport._
import com.lightbend.lagom.scaladsl.api.deser.StrictMessageSerializer
import com.lightbend.lagom.scaladsl.api.deser.MessageSerializer.{NegotiatedDeserializer, NegotiatedSerializer}

class ContentTypeSerializer(contentType: String, charset: String) extends NegotiatedSerializer[String, ByteString] {
  override val protocol = MessageProtocol(Some(contentType), Some(charset))
  def serialize(body: String) = ByteString.fromString(body, charset)
}

object ContentTypeSerializer {
  val Json = "application/json"
  val Js = "application/javascript"
  val Icon = "image/vnd.microsoft.icon"
  val Html = "text/html"
  val Css = "text/css"

  val JsonSerializer = new ContentTypeSerializer(ContentTypeSerializer.Json, "utf-8")
}

class JsonTextDeserializer extends NegotiatedDeserializer[String, ByteString] {
  def deserialize(bytes: ByteString) =
    try {
      Json.parse(bytes.iterator.asInputStream).as[String]
    } catch {
      case NonFatal(e) => throw DeserializationException(e)
    }
}

object ResponseSerializer extends StrictMessageSerializer[String] {
  override val acceptResponseProtocols = List(
    MessageProtocol(Some(ContentTypeSerializer.Json)),
    MessageProtocol(Some(ContentTypeSerializer.Html)),
    MessageProtocol(Some(ContentTypeSerializer.Icon)),
    MessageProtocol(Some(ContentTypeSerializer.Css)),
    MessageProtocol(Some(ContentTypeSerializer.Js))
  )

  val serializerForRequest = ContentTypeSerializer.JsonSerializer

  def deserializer(protocol: MessageProtocol) = protocol.contentType match {
    case Some(ContentTypeSerializer.Json) | None =>
      new JsonTextDeserializer
    case _ =>
      throw UnsupportedMediaType(protocol, MessageProtocol(Some("text/plain")))
  }

  def serializerForResponse(accepted: immutable.Seq[MessageProtocol]) = accepted match {
    case Nil => ContentTypeSerializer.JsonSerializer
    case protocols => protocols.collectFirst {
      case MessageProtocol(Some(ContentTypeSerializer.Json), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Json, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Html), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Html, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Icon), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Icon, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Css), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Css, charset.getOrElse("utf-8"))
      case MessageProtocol(Some(ContentTypeSerializer.Js), charset, _) =>
        new ContentTypeSerializer(ContentTypeSerializer.Js, charset.getOrElse("utf-8"))
    }.getOrElse {
      throw NotAcceptable(accepted, MessageProtocol(Some("text/plain")))
    }
  }
}


问:
How to slice a string in a nested element inside of an array with Javascript?
I need to slice a string element that is nested inside of a JSON file formatted as an array using JS.

```<code>"fields": {
            "title": "Jameson Library 12th Floor",
            "slug": "Jameson-12th-floor",
            "shortDescription": "[All Jameson Library Floors](/jameson-floor-maps \"All Jameson Library Floors\")",
            "building": {
</code>```

The filteredFloors array is passed into the component as data and mapped to a table.

```<code>{data.map(item => (
          <tr key={item.sys.id}>
            {columns.map(column =>
              <td role='cell' key={this.createKey(item, column)}>{this.renderCell(item, column)}</td>)
</code>```

I'm trying to return an array that omits the first 17 spaces of the title so all that remains is the floor (i.e. "12th Floor"). Any ideas?

答:
Once you're able to pull the title data, you can use slice against it.

```<code>// this will slice the first 16 characters and return "12th Floor"
// remember whitespace is counted, not just characters
"Jameson Library 12th Floor".slice(16);
</code>```

Body:
I need to slice a string element that is nested inside of a JSON file formatted as an array using JS.

"fields": {
            "title": "Jameson Library 12th Floor",
            "slug": "Jameson-12th-floor",
            "shortDescription": "[All Jameson Library Floors](/jameson-floor-maps \"All Jameson Library Floors\")",
            "building": {

The filteredFloors array is passed into the component as data and mapped to a table.

{data.map(item => (

            {columns.map(column =>
              {this.renderCell(item, column)}	)

I'm trying to return an array that omits the first 17 spaces of the title so all that remains is the floor (i.e. "12th Floor"). Any ideas?

Body:
Once you're able to pull the title data, you can use slice against it.

// this will slice the first 16 characters and return "12th Floor"
// remember whitespace is counted, not just characters
"Jameson Library 12th Floor".slice(16);