问:
How do I send data from Struts action to javascript?
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

```<code>List<MarkerClass> markers;
</code>```

MarkerClass is defined acoprding to belove:

```<code>final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}
</code>```

The action also includes a getter for markers:

```<code>public List<MarkerClass> getMarkers()
{
    return markers;
}
</code>```

In my jsp-file I have tried doing this:

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function initialize()
{
    var titel = "";
    for(var i, "${markers}")
    {
        titel = titel+ "${markers[i].street}";
    }
}
</code>```

The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass@37a4, se.fubar.test.MarkerClass@9ad97c]"

I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.

答:
You cannot just use a struts variable in a javascript function and expect it to work. Remember that the ${...} stuff gets processed before the HTML for the page is sent to the browser. By the time the javascript is rendered at the browser, you are only left with the textual representations. What you will need to do is something like (check the syntax, I haven't used this stuff i a while):

```<code>function initialize() {
    var title = "";
    <c:foreach var="marker" list="${markers}">
         title = title + "${marker.street}";
    </c:foreach>
}
</code>```

Something along those lines anyway... Basically the Javascript seen by your browser will look like

```<code>function initialize() {
    var title = "";
    title = title + "Street1";
    title = title + "Street2";
    title = title + "Street3";
    title = title + "Street4";
}
</code>```

I hope that makes sense and is related to what you were asking.
By the way, there are usually better ways of accomplishing this functionality that building dynamic js etc. Probably there are built in Struts 2 components that you can use?

Body:
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

List<MarkerClass> markers;

MarkerClass is defined acoprding to belove:

final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}

The action also includes a getter for markers:

public List<MarkerClass> getMarkers()
{
    return markers;
}

In my jsp-file I have tried doing this:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>

Body:
You cannot just use a struts variable in a javascript function and expect it to work. Remember that the ${...} stuff gets processed before the HTML for the page is sent to the browser. By the time the javascript is rendered at the browser, you are only left with the textual representations. What you will need to do is something like (check the syntax, I haven't used this stuff i a while):

function initialize() {
    var title = "";
    <c:foreach var="marker" list="${markers}">
         title = title + "${marker.street}";
    </c:foreach>
}

Something along those lines anyway... Basically the Javascript seen by your browser will look like

function initialize() {
    var title = "";
    title = title + "Street1";
    title = title + "Street2";
    title = title + "Street3";
    title = title + "Street4";
}

I hope that makes sense and is related to what you were asking.
By the way, there are usually better ways of accomplishing this functionality that building dynamic js etc. Probably there are built in Struts 2 components that you can use?


来源: stackexchange

问:
Using a base.html file but modifying more than just the body
First of all, I have no problems with my code. This question is more of a "Is this possible and if so/not what is the right way of doing it ?"

I have a website where every page has the same look, the differences between them are as follows:

The homepage has an interactive leaflet map (javascript)

The titles vary on every page

The elements in the head tags change from one page to another but not always

The background image doesn't change

Within the body tag, I have a div tag containing a page footer common to all pages

What I would like to know is if it is possible to use a base.html template for these pages knowing the above constraints and also, if it is, how I would go about modifying the said pages to do so.

As I said, the code isn't really an issue here but for clarity and for you to be able to see what changes from one page to another, here is the Github repository for the project. (The project is a university project and therefore some parts of the code is in French since my university is a french University)

https://github.com/MaxMichel2/PWEB

Don't hesitate to tell me if some clarifications are needed to understand my issue.

EDIT

All the Django tutorials I have seen and read online only explain/talk about the {% block content %} delimiters in the  tags but I haven't found any help on how the have different parts within the  section.

Is it simply the case of using a different {% block content %} delimiter to identify the parts of the base.html file that will have parts added/modified ?

If so would if be possible to have a basic example to see what I'm working towards ?

答:
There is {% include template %} which is somewhat the opposite of the base-extends, instead of having a base template and extending that, include allows you to add small re-usable parts of codes into your template as in

```<code>{% extends 'base.html' %}
{% block content %}
    <some unique html to the current page>
    {% include 'some_common_html' %}      <---- right here this part doesnt have to be in base.html
    this means that you can include this part anywhere in your templates, without having it inside the base
{% endblock %}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There is {% include template %} which is somewhat the opposite of the base-extends, instead of having a base template and extending that, include allows you to add small re-usable parts of codes into your template as in

{% extends 'base.html' %}
{% block content %}
    <some unique html to the current page>
    {% include 'some_common_html' %}      <---- right here this part doesnt have to be in base.html
    this means that you can include this part anywhere in your templates, without having it inside the base
{% endblock %}


问:
Individual column searching filter for js sourced data using DataTable.js with filter at the top
I am unable to place the filter selects at the top. How do I achive?

I stuck to initComplete option as it is triggered just once upon DataTable fully initialized and API methods can be called safely.

Also where exactly would I make the column drop down values unnique

const dataSet = [
      ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
      ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
      ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ];

    const dataTable = $('#example').DataTable({
        data: dataSet,
        dom: 't',
        columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
            title: header
          })),
        initComplete: function () {
          //purge existing
 if exists
          $('#example tfoot').remove();
          //append new footer to the table
          $('#example').append('

');
          //iterate through table columns
          this.api().columns().every(function () {
            //append <select> node to each column footer inserting
            //current column().index() as a "colindex" attribute
            $('#example tfoot tr').append(`<th><select colindex="${this.index()}"></select></th>`);
            //grab unique sorted column entries and translate those into <option> nodes
            const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '<option value=""></option>');
            //append options to corresponding <select>
            $(`#example tfoot th:eq(${this.index()}) select`).append(options);
          });
        }
      });

    $('#example').on('change', 'tfoot select', function (event) {
      //use "colindex" attribute value to search corresponding column for selected option value
      dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw();
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table></code>```

答:
You may replace default column().header() with your custom <select> node, like that:

const dataSet = [
 ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
 ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
 ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
];

const dataTable = $('#example').DataTable({
  data: dataSet,
  dom: 't',
    ordering: false,
  columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({title: header})),
    initComplete: function(){
      const table = this.api();
      table.columns().every(function(){
        //grab initial column title
        const title = $(this.header()).text();
        //replace header with <select> node
        $(this.header()).html(`<select><option value="">${title} (All)</option></select>`);
        //grab unique sorted column values into <option> nodes
        const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '');
        //population <select> with options
        $(this.header()).find('select').append(options);
      });
    }
});

//filter upon option select
$('#example').on('change', 'thead select', event => dataTable.column($(event.target).closest('th')).search($(event.target).val()).draw());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="example"></table>
</body>
</html></code>```

But it will affect sorting feature - you'll get column sorting order swapped each time you click/select option (like it can be seen in another answer to this question. Either it can be disabled, as it is done in mine. If that feature still needs to be functional, there's a workaround for that.

Body:
I am unable to place the filter selects at the top. How do I achive?

I stuck to initComplete option as it is triggered just once upon DataTable fully initialized and API methods can be called safely.

Also where exactly would I make the column drop down values unnique

const dataSet = [
      ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
      ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
      ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ];

    const dataTable = $('#example').DataTable({
        data: dataSet,
        dom: 't',
        columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
            title: header
          })),
        initComplete: function () {
          //purge existing
 if exists
          $('#example tfoot').remove();
          //append new footer to the table
          $('#example').append('

');
          //iterate through table columns
          this.api().columns().every(function () {
            //append <select> node to each column footer inserting
            //current column().index() as a "colindex" attribute
            $('#example tfoot tr').append(`<th><select colindex="${this.index()}"></select></th>`);
            //grab unique sorted column entries and translate those into <option> nodes
            const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '<option value=""></option>');
            //append options to corresponding <select>
            $(`#example tfoot th:eq(${this.index()}) select`).append(options);
          });
        }
      });

    $('#example').on('change', 'tfoot select', function (event) {
      //use "colindex" attribute value to search corresponding column for selected option value
      dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw();
    })

<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>

Body:
You may replace default column().header() with your custom <select> node, like that:

const dataSet = [
 ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
 ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
 ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
];

const dataTable = $('#example').DataTable({
  data: dataSet,
  dom: 't',
    ordering: false,
  columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({title: header})),
    initComplete: function(){
      const table = this.api();
      table.columns().every(function(){
        //grab initial column title
        const title = $(this.header()).text();
        //replace header with <select> node
        $(this.header()).html(`<select><option value="">${title} (All)</option></select>`);
        //grab unique sorted column values into <option> nodes
        const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '');
        //population <select> with options
        $(this.header()).find('select').append(options);
      });
    }
});

//filter upon option select
$('#example').on('change', 'thead select', event => dataTable.column($(event.target).closest('th')).search($(event.target).val()).draw());

<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="example"></table>
</body>
</html>

But it will affect sorting feature - you'll get column sorting order swapped each time you click/select option (like it can be seen in another answer to this question. Either it can be disabled, as it is done in mine. If that feature still needs to be functional, there's a workaround for that.


问:
C standard regarding pointer arithmetic outside arrays
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

```<code>char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))
</code>```

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

```<code>#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

</code>```

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?

答:
The C Standards Committee saw no need to forbid compilers from behaving in silly ways that would make them unsuitable for many purposes.  Indeed, according to the published Rationale, the Committee recognized that it would be possible for implementation to behave in a way that was conforming but useless, but judged that people seeking to produce quality implementations of the language the Standard was written to describe would refrain from such silliness.  Consider the program:

```<code>void byte_copy(unsigned char *dest, unsigned char *src, int len)
{
  while(len--) *dest++ = *src++;
}
unsigned char src[10][10], dest[100];
void test(int mode)
{
  if (mode == 0)
    byte_copy(dest, src[0], 11);
  else
    byte_copy(dest, (unsigned char*)src, 100);
}
</code>```

It might be useful for an implementation to trap on test if mode is zero, on the basis that the programmer was probably intending to copy elements from the first row of src, and the authors of the Standard probably didn't want to forbid that.  On the other hand, the language would be severely broken if code like that in the mode != 0 case couldn't be used to make a bytewise copy of objects of all types including multi-dimensional arrays, and the Committee likely recognized that.  Nonetheless, the Standard recognizes no distinction between the pointers passed in the two cases.

Such a distinction would only be necessary if one believed that the language would be broken by allowing implementations to behave in ways that would make them useless.  Since the authors of the Standard have said that they recognize that it allows implementations to behave uselessly, but do not believe that such a possibility breaks the language, that would suggest that they might not regard a failure to define behavior of all necessary constructs as a defect in cases where they expected that quality implementations of the language the Standard was written to describe would support such constructs anyway.

As to the question of whether people seeking to write quality implementations of the language the Standard was written to describe can be relied upon to refrain from such silliness, that may be hard to answer without knowing the motives of the people maintaining some compilers.

Body:
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?

Body:
The C Standards Committee saw no need to forbid compilers from behaving in silly ways that would make them unsuitable for many purposes.  Indeed, according to the published Rationale, the Committee recognized that it would be possible for implementation to behave in a way that was conforming but useless, but judged that people seeking to produce quality implementations of the language the Standard was written to describe would refrain from such silliness.  Consider the program:

void byte_copy(unsigned char *dest, unsigned char *src, int len)
{
  while(len--) *dest++ = *src++;
}
unsigned char src[10][10], dest[100];
void test(int mode)
{
  if (mode == 0)
    byte_copy(dest, src[0], 11);
  else
    byte_copy(dest, (unsigned char*)src, 100);
}

It might be useful for an implementation to trap on test if mode is zero, on the basis that the programmer was probably intending to copy elements from the first row of src, and the authors of the Standard probably didn't want to forbid that.  On the other hand, the language would be severely broken if code like that in the mode != 0 case couldn't be used to make a bytewise copy of objects of all types including multi-dimensional arrays, and the Committee likely recognized that.  Nonetheless, the Standard recognizes no distinction between the pointers passed in the two cases.

Such a distinction would only be necessary if one believed that the language would be broken by allowing implementations to behave in ways that would make them useless.  Since the authors of the Standard have said that they recognize that it allows implementations to behave uselessly, but do not believe that such a possibility breaks the language, that would suggest that they might not regard a failure to define behavior of all necessary constructs as a defect in cases where they expected that quality implementations of the language the Standard was written to describe would support such constructs anyway.

As to the question of whether people seeking to write quality implementations of the language the Standard was written to describe can be relied upon to refrain from such silliness, that may be hard to answer without knowing the motives of the people maintaining some compilers.


问:
2 same string are not equal in bash
I'm trying to test if the output of a program is equal to something, so that I can do something based on it. The console prints that the 2 values are equal, but the condition is not met.

Here's the code:

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

test_id=`clasp run testRunner`

function get_logs() {
  echo "trying to get logs for test id $test_id..."

  logs=`clasp logs`

  if logs_contain_test_id
  then
    print_logs
  else
    get_logs
  fi
}

function logs_contain_test_id() {
  IFS=$' '
  for log in $logs
  do
    echo $log
    echo $test_id
    if [[ "$log" == "$test_id" ]]
    then
      return 0
    fi
  done
  return 1
}

get_logs
</code>```

Note that this line echo "trying to get logs for test id $test_id..." only prints the id like "03443db8..." and not the full sentence.

Also the echo $log and echo $test_id log 03443db8 03443db8 on 2 separate lines so they should be equal.

How can I debug this? Seems like some hidden characters are part of $test_id

The condition print_logs never gets activated, even if both returns print equal to the console. I am on a mac if it makes any difference.

Here's the strange output I am getting:

```<code>tests,
03443db8
0
03443db8
failures,
03443db8
03443db8
03443db8
03443db8... <-- this should be "trying to get logs for test id 03443db8..."
</code>```

edit: after adding set -x I get these logs:

```<code>+ [[ failures, == \[\2\K\[\1\G\4\4\f\a\7\0\c\7 ]]
+ for log in '$logs'
+ echo 44fa70c7
44fa70c7
44fa70c7'
44fa70c7
+ [[ 44fa70c7 == \[\2\K\[\1\G\4\4\f\a\7\0\c\7 ]]
+ return 1
+ get_logs
44fa70c7...'
44fa70c7...
++ clasp logs
</code>```

答:
Add set -x to your script then you can trace it.  See Bash Manual: The Set Builtin for more details.  In your case the script would be:

```<code>#!/bin/bash
set -x
test_id=`clasp run testRunner`

function get_logs() {
  set -x
  echo "trying to get logs for test id $test_id..."

  logs=`clasp logs`

  if logs_contain_test_id
  then
    print_logs
  else
    get_logs
  fi
}

function logs_contain_test_id() {
  set -x
  IFS=$' '
  for log in $logs
  do
    echo $log
    echo $test_id
    if [[ "$log" == "$test_id" ]]
    then
      return 0
    fi
  done
  return 1
}

get_logs
</code>```

Title: 2 same string are not equal in bash

Body:
I'm trying to test if the output of a program is equal to something, so that I can do something based on it. The console prints that the 2 values are equal, but the condition is not met.

Here's the code:

#!/bin/bash

test_id=`clasp run testRunner`

function get_logs() {
  echo "trying to get logs for test id $test_id..."

  logs=`clasp logs`

  if logs_contain_test_id
  then
    print_logs
  else
    get_logs
  fi
}

function logs_contain_test_id() {
  IFS=$' '
  for log in $logs
  do
    echo $log
    echo $test_id
    if [[ "$log" == "$test_id" ]]
    then
      return 0
    fi
  done
  return 1
}

get_logs

Note that this line echo "trying to get logs for test id $test_id..." only prints the id like "03443db8..." and not the full sentence.

Also the echo $log and echo $test_id log 03443db8 03443db8 on 2 separate lines so they should be equal.

How can I debug this? Seems like some hidden characters are part of $test_id

The condition print_logs never gets activated, even if both returns print equal to the console. I am on a mac if it makes any difference.

Here's the strange output I am getting:

tests,
03443db8
0
03443db8
failures,
03443db8
03443db8
03443db8
03443db8... <-- this should be "trying to get logs for test id 03443db8..."

edit: after adding set -x I get these logs:

+ [[ failures, == \[\2\K\[\1\G\4\4\f\a\7\0\c\7 ]]
+ for log in '$logs'
+ echo 44fa70c7
44fa70c7
44fa70c7'
44fa70c7
+ [[ 44fa70c7 == \[\2\K\[\1\G\4\4\f\a\7\0\c\7 ]]
+ return 1
+ get_logs
44fa70c7...'
44fa70c7...
++ clasp logs

Body:
Add set -x to your script then you can trace it.  See Bash Manual: The Set Builtin for more details.  In your case the script would be:

#!/bin/bash
set -x
test_id=`clasp run testRunner`

function get_logs() {
  set -x
  echo "trying to get logs for test id $test_id..."

  logs=`clasp logs`

  if logs_contain_test_id
  then
    print_logs
  else
    get_logs
  fi
}

function logs_contain_test_id() {
  set -x
  IFS=$' '
  for log in $logs
  do
    echo $log
    echo $test_id
    if [[ "$log" == "$test_id" ]]
    then
      return 0
    fi
  done
  return 1
}

get_logs


问:
Singleton initialization
I implemented the Singleton design pattern in my code.

Suppose it is:

```<code>class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};
</code>```

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

```<code>SingletonPointer* SingletonClass::s (0);
</code>```

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir

答:
The best way you can use the Singleton pattern is to not use it at all.

A brief summary of why Singletons are bad:

They are globals with special restrictions.  Globals are bad enough for their own reasons; making them singletons just amplifies the badness.

If you really need only one instance of an object, then just make one.  If you need a special device to ensure you don't make more than one, then there's something wrong with the semantics of your code.  Making it a singleton doesn't fix the problem, it just papers over it with new problems.

Singletons don't play nice with threads.  Threads are hard enough.  Don't make them harder.

Using a Singleton doesn't solve any problem.  It just applies false semantics to existing code, makes future extensions of that code difficult or impossible (what if you need two tomorrow?), and adds new problems.  Long story short, just don't use them.

ContentLicense: CC BY-SA 3.0

Title: Singleton initialization

Body:
I implemented the Singleton design pattern in my code.

Suppose it is:

class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

SingletonPointer* SingletonClass::s (0);

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir


问:
Multi-client remote debugging using ChromeDriver and Chrome DevTools protocol
So with Chrome 63 there is now support for Multi-client remote debugging (https://developers.google.com/web/updates/2017/10/devtools-release-notes)

What I want to achieve is use the Chrome DevTools Protocol HeapProfiler with some selenium tests. I'm running version 64 Chrome dev channel and ChromeDriver 2.33.

```<code>ChromeOptions options = newChromeOptions();
options.addArguments("--remote-debugging-port=9222");
WebDriver driver = new ChromeDriver(options);
... selenium stuff
</code>```

A new chrome window will open and hang until it times out. I can confirm that the chrome window opened is chrome 64 by going to help > about google chrome to check the version.
I get this error which appears to be the the webdriver losing connection.

```<code>Exception in thread "main" org.openqa.selenium.WebDriverException: chrome not
reachable
</code>```

The DevTools Protocol is working because I am able to open http://localhost:9222 in another chrome window and see debugging interface.

Has anyone been able to get these two things to work together?

Thanks :)

答:
Selenium 4 release will have a user friendly API for Chrome DevTools protocol. I just finished implementing Network and Performance domains for the Selenium Java client. https://github.com/SeleniumHQ/selenium/pull/7212

In addition, there is a generic API for all domains in Java client that was merged a while ago. All those new features will be released probably in the next Alpha release.

This is a nice article on how to use Log:
https://codoid.com/selenium-4-chrome-devtools-log-entry-listeners/

Body:
So with Chrome 63 there is now support for Multi-client remote debugging (https://developers.google.com/web/updates/2017/10/devtools-release-notes)

What I want to achieve is use the Chrome DevTools Protocol HeapProfiler with some selenium tests. I'm running version 64 Chrome dev channel and ChromeDriver 2.33.

ChromeOptions options = newChromeOptions();
options.addArguments("--remote-debugging-port=9222");
WebDriver driver = new ChromeDriver(options);
... selenium stuff

A new chrome window will open and hang until it times out. I can confirm that the chrome window opened is chrome 64 by going to help > about google chrome to check the version.
I get this error which appears to be the the webdriver losing connection.

Exception in thread "main" org.openqa.selenium.WebDriverException: chrome not
reachable

The DevTools Protocol is working because I am able to open http://localhost:9222 in another chrome window and see debugging interface.

Has anyone been able to get these two things to work together?

Thanks :)


问:
How to know what events will trigger when doing specific operation in VIM?
I am studying VIM events, but I found some events may not working well like ##TabLeave won't be triggered when using gt/gT to switch between tabpages. What can I do to know what event has been triggered by VIM when I am doing a specific operation, like typing tabmove command to execute it? I am writing a plugin to make my VIM tabpage can source back to previously visited tabpage, but the problem is tabmove command won't trigger anything, anyone can help me on this?

```<code>function! catchSomeEventTriggerByTabmCmd()
let histCmd = histget('cmd', -1)
if match(histCmd, '^tabm') == 0
DoUpdateJumpQueue()
endif
endfunction
</code>```

答:
... I found some events may not working well like ##TabLeave won't be triggered when using 'gt/gT' to switch between tabpages.

gt/gT does trigger TabLeave. example:

```<code>:let g:foo = 1
:autocmd TabLeave * let g:foo = g:foo + 1 | echom "TabLeave Event " . g:foo
:tabnew
</code>```

Now do a few gt/gT's. You should get messages

What can I do to know what event has been triggered by VIM when I am doing a specific operation, like typing 'tabmove' command to execute it? I am writing a plugin to make my VIM tabpage can source back to previously visited tabpage, but the problem is 'tabmove' command won't trigger anything, anyone can help me on this?

I am not sure you can use an event/autocmd like TabLeave to capture anything from :tabmove. It probably is also going to be tricky to use tab page numbers as well, since :tabmove modifies them.

Luckily, Vim always has to focus a window, so instead of trying to have a history of tab pages, maybe have a history have window id's. You may be able to use win_getid() and win_gotoid() to accomplish your history behavior.

For more help see:

```<code>:h win_getid()
:h win_gotoid()
:h windowid
</code>```

Body:
I am studying VIM events, but I found some events may not working well like ##TabLeave won't be triggered when using gt/gT to switch between tabpages. What can I do to know what event has been triggered by VIM when I am doing a specific operation, like typing tabmove command to execute it? I am writing a plugin to make my VIM tabpage can source back to previously visited tabpage, but the problem is tabmove command won't trigger anything, anyone can help me on this?

function! catchSomeEventTriggerByTabmCmd()
let histCmd = histget('cmd', -1)
if match(histCmd, '^tabm') == 0
DoUpdateJumpQueue()
endif
endfunction

Body:
... I found some events may not working well like ##TabLeave won't be triggered when using 'gt/gT' to switch between tabpages.

gt/gT does trigger TabLeave. example:

:let g:foo = 1
:autocmd TabLeave * let g:foo = g:foo + 1 | echom "TabLeave Event " . g:foo
:tabnew

Now do a few gt/gT's. You should get messages

What can I do to know what event has been triggered by VIM when I am doing a specific operation, like typing 'tabmove' command to execute it? I am writing a plugin to make my VIM tabpage can source back to previously visited tabpage, but the problem is 'tabmove' command won't trigger anything, anyone can help me on this?

I am not sure you can use an event/autocmd like TabLeave to capture anything from :tabmove. It probably is also going to be tricky to use tab page numbers as well, since :tabmove modifies them.

Luckily, Vim always has to focus a window, so instead of trying to have a history of tab pages, maybe have a history have window id's. You may be able to use win_getid() and win_gotoid() to accomplish your history behavior.

For more help see:

:h win_getid()
:h win_gotoid()
:h windowid


问:
How to send a echo text to an open window?
So basically I'm trying to find how to echo "Stop" to an open Command window like command prompt for example. If you can't give the answer what specifically do I need to google to get headed in the right direction.

I have tried googling multiple different ways but my wording has to be wrong as I am only getting info how to send echo to a file.

@echo some text | Command Prompt

答:
This is called scripting or macros. You need to send input into a specific screen via automation (simulating a manual keyboard input). FYI, this is VERY fragile and tends to break a great deal.

This can be done by creating scripts. Example:

```<code>set shell = CreateObject("WScript.Shell")
shell.run"Sndvol"
WScript.Sleep 1500
shell.SendKeys"{TAB}"
shell.SendKeys" "
shell.SendKeys"%{F4}"
</code>```

Sendkeys from command prompt

vbs SendKeys only to specific window

Body:
This is called scripting or macros. You need to send input into a specific screen via automation (simulating a manual keyboard input). FYI, this is VERY fragile and tends to break a great deal.

This can be done by creating scripts. Example:

set shell = CreateObject("WScript.Shell")
shell.run"Sndvol"
WScript.Sleep 1500
shell.SendKeys"{TAB}"
shell.SendKeys" "
shell.SendKeys"%{F4}"

Sendkeys from command prompt

vbs SendKeys only to specific window


问:
Converting Crystal IF statements to SQL
I am converting a Crystal Report to a SQL query. Embedding in the Crystal Report are formulas.

I am trying to convert the Crystal IF statements to a SQL WHERE clause

This is the Crystal formula

```<code>if {loanview.LOAN_STATUS} in
["COMMITMENT","APPLICATION","PA_APPROVED","PRE_CLOSING","FUND_HOLD","GRANTSOURCE"] then "SHOW" else

if {loanview.LOAN_STATUS} in ["CURRENT","LATE+30","LATE+60","DELINQ+90","CLOSED"]
and {BILLINFO.REVOLVING_CR} = "" and {balview.GBOOK_VALUE_P} = 0 then "HIDE" else

if {loanview.LOAN_STATUS} in ["CURRENT","LATE+30","LATE+60","DELINQ+90","CLOSED"]
and {BILLINFO.REVOLVING_CR} = "" and {balview.GBOOK_VALUE_P} <> 0 then "SHOW" else
</code>```

It looks like I need a WHERE clause. My thought is the WHERE = the Crystal SHOW and then just omitting the Crystal HIDE part. Does this make sense?

```<code>WHERE
      (
          loanview.LOAN_STATUS IN ( 'COMMITMENT', 'APPLICATION', 'PA_APPROVED', 'PRE_CLOSING', 'FUND_HOLD',
                                    'GRANTSOURCE'
                                  )
          OR
          (
              loanview.LOAN_STATUS IN ( 'CURRENT', 'LATE+30', 'LATE+60', 'DELINQ+90', 'CLOSED' )
              AND BILLINFO.REVOLVING_CR = ''
              AND balview.GBOOK_VALUE_P <> 0
          )
</code>```

答:
Yes, it's fine.
Only point of failure could be if the formula is set to default values for null. That means that a null BILLINFO.REVOLVING_CR is automatically converted to empty string.
So a better way to write it just to be sure is:</p>

```<code>WHERE
      (
          loanview.LOAN_STATUS IN ( 'COMMITMENT', 'APPLICATION', 'PA_APPROVED', 'PRE_CLOSING', 'FUND_HOLD',
                                    'GRANTSOURCE'
                                  )
          OR
          (
              loanview.LOAN_STATUS IN ( 'CURRENT', 'LATE+30', 'LATE+60', 'DELINQ+90', 'CLOSED' )
              AND (BILLINFO.REVOLVING_CR = '' or BILLINFO.REVOLVING_CR IS NULL)
              AND balview.GBOOK_VALUE_P <> 0
          )
)
</code>```

Title: Converting Crystal IF statements to SQL

Body:
I am converting a Crystal Report to a SQL query. Embedding in the Crystal Report are formulas.

I am trying to convert the Crystal IF statements to a SQL WHERE clause

This is the Crystal formula

if {loanview.LOAN_STATUS} in
["COMMITMENT","APPLICATION","PA_APPROVED","PRE_CLOSING","FUND_HOLD","GRANTSOURCE"] then "SHOW" else

if {loanview.LOAN_STATUS} in ["CURRENT","LATE+30","LATE+60","DELINQ+90","CLOSED"]
and {BILLINFO.REVOLVING_CR} = "" and {balview.GBOOK_VALUE_P} = 0 then "HIDE" else

if {loanview.LOAN_STATUS} in ["CURRENT","LATE+30","LATE+60","DELINQ+90","CLOSED"]
and {BILLINFO.REVOLVING_CR} = "" and {balview.GBOOK_VALUE_P} <> 0 then "SHOW" else

It looks like I need a WHERE clause. My thought is the WHERE = the Crystal SHOW and then just omitting the Crystal HIDE part. Does this make sense?

WHERE
      (
          loanview.LOAN_STATUS IN ( 'COMMITMENT', 'APPLICATION', 'PA_APPROVED', 'PRE_CLOSING', 'FUND_HOLD',
                                    'GRANTSOURCE'
                                  )
          OR
          (
              loanview.LOAN_STATUS IN ( 'CURRENT', 'LATE+30', 'LATE+60', 'DELINQ+90', 'CLOSED' )
              AND BILLINFO.REVOLVING_CR = ''
              AND balview.GBOOK_VALUE_P <> 0
          )

Body:
Yes, it's fine.
Only point of failure could be if the formula is set to default values for null. That means that a null BILLINFO.REVOLVING_CR is automatically converted to empty string.
So a better way to write it just to be sure is:

WHERE
      (
          loanview.LOAN_STATUS IN ( 'COMMITMENT', 'APPLICATION', 'PA_APPROVED', 'PRE_CLOSING', 'FUND_HOLD',
                                    'GRANTSOURCE'
                                  )
          OR
          (
              loanview.LOAN_STATUS IN ( 'CURRENT', 'LATE+30', 'LATE+60', 'DELINQ+90', 'CLOSED' )
              AND (BILLINFO.REVOLVING_CR = '' or BILLINFO.REVOLVING_CR IS NULL)
              AND balview.GBOOK_VALUE_P <> 0
          )
)


问:
ICheck plugin not working with sublist in Knockout.js
I have a Knockout model containing a bool observable and a list of objects that contain a bool observable.

I have custom binding iCheckedSys, for the bool in the model, to work with iCheck, and custom binding iCheckedPrimary to work with iCheck on the bool in the objects in the model's list.

iCheckedSys functions correctly, and valueAccessor() returns observable.
However in the list, valueAccessor() returns false in iCheckedPrimary.

If I just use checkbox for the list objects, it works just fine.

How can I have iCheck work with the list objects?
Thanks much.

      <input type="checkbox" data-bind="iChecked: IsSysAdmin">

      <input type="checkbox" data-bind="checked: IsPrimary" />

```

```
```

答:
I realized that regardless of with record I changed iCheckedPri in, only the last record in viewModel.RolesList was being passed in valueAccessor. So the current record and it's value wasn't being accessed.

I don't know if this is the proper way...
but instead of the value, I passed iCheck with the record object itself and updated it with the current checkbox value, and updated iCheck (check/uncheck) with the object value.

<input type="checkbox" data-bind="iCheckedPri: $rawData">
```

```ko.bindingHandlers.iCheckedPri = {

        $(element).on('ifChanged', function (event) {
            var observable = valueAccessor();
            observable = $(element)[0].checked;
            valueAccessor().IsPrimary = this.checked;
        });
    },
    update: function (element, valueAccessor) {
        var value = ko.unwrap(valueAccessor());
        if (value.IsPrimary) {
            $(element).iCheck('check');
        } else {
            $(element).iCheck('uncheck');
        }
    }
};
```

Body:
I realized that regardless of with record I changed iCheckedPri in, only the last record in viewModel.RolesList was being passed in valueAccessor. So the current record and it's value wasn't being accessed.

I don't know if this is the proper way...
but instead of the value, I passed iCheck with the record object itself and updated it with the current checkbox value, and updated iCheck (check/uncheck) with the object value.

<td><input type="checkbox" data-bind="iCheckedPri: $rawData"></td>

ko.bindingHandlers.iCheckedPri = {

        $(element).on('ifChanged', function (event) {
            var observable = valueAccessor();
            observable = $(element)[0].checked;
            valueAccessor().IsPrimary = this.checked;
        });
    },
    update: function (element, valueAccessor) {
        var value = ko.unwrap(valueAccessor());
        if (value.IsPrimary) {
            $(element).iCheck('check');
        } else {
            $(element).iCheck('uncheck');
        }
    }
};


问:
Polymer not loading ts web component with polymer serve
Following the LitElement guide here: https://lit-element.polymer-project.org/guide/start

I'm literally following it by the books and then running
polymer serve in the root directory of the project.

I even copy/pasted over every file from their example stackblitz pages. Am I not supposed to use polymer serve or something?

All I get is blank page, and it seems to not recognize the customElement

my-element.ts:

```<code>import { LitElement, html, customElement, property } from 'lit-element';

@customElement('my-element')
export class MyElement extends LitElement {
  @property()
  foo = 'foo';

  render() {
    return html`
      <p>hi!</p>
    `;
  }
}
</code>```

index.ts:

```<code>import './my-element.ts';
</code>```

index.html:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="/node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
    <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>

    <title>lit-element code sample</title>
  </head>
  <body>
    <my-element></my-element>
  </body>
</html>
</code>```

package.json:

```<code>{
  "name": "my-app",
  "version": "1.0.0",
  "license": "ISC",
  "dependencies": {
    "@webcomponents/webcomponentsjs": "^2.2.10",
    "lit-element": "^2.1.0"
  }
}
</code>```

答:
I even copy/pasted over every file from their example stackblitz pages

Actually Stackblitz TS projects follow a particular structure in which index.ts is treated as the entry point of the TypeScript code, automatically compiled and imported in the final result.

The local scenario is pretty different: you have to choose a build tool to compile TS files and import the result in index.html:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <!-- ... -->
    <!-- This may differ depending on your build configuration -->
    <script src="./path/to/my-element.js" type="module"></script>
  </head>
  <body>
    <my-element></my-element>
  </body>
</html>
</code>```

You can use tsc directly or a module bundler such as Webpack + ts-loader or Rollup + rollup-plugin-typescript2. This really depends on the complexity and requirements of your projects and what browsers you want to support.

Body:
Following the LitElement guide here: https://lit-element.polymer-project.org/guide/start

I'm literally following it by the books and then running
polymer serve in the root directory of the project.

I even copy/pasted over every file from their example stackblitz pages. Am I not supposed to use polymer serve or something?

All I get is blank page, and it seems to not recognize the customElement

my-element.ts:

import { LitElement, html, customElement, property } from 'lit-element';

@customElement('my-element')
export class MyElement extends LitElement {
  @property()
  foo = 'foo';

  render() {
    return html`

hi!

    `;
  }
}

index.ts:

import './my-element.ts';

index.html:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title>lit-element code sample</title>

    <my-element></my-element>

package.json:

{
  "name": "my-app",
  "version": "1.0.0",
  "license": "ISC",
  "dependencies": {
    "@webcomponents/webcomponentsjs": "^2.2.10",
    "lit-element": "^2.1.0"
  }
}

Body:
I even copy/pasted over every file from their example stackblitz pages

Actually Stackblitz TS projects follow a particular structure in which index.ts is treated as the entry point of the TypeScript code, automatically compiled and imported in the final result.

The local scenario is pretty different: you have to choose a build tool to compile TS files and import the result in index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- ... -->
    <!-- This may differ depending on your build configuration -->
    <script src="./path/to/my-element.js" type="module"></script>
  </head>
  <body>
    <my-element></my-element>
  </body>
</html>

You can use tsc directly or a module bundler such as Webpack + ts-loader or Rollup + rollup-plugin-typescript2. This really depends on the complexity and requirements of your projects and what browsers you want to support.


问:
Is there a way to check when something is added to a list like "a=[]"
I want to print something whenever something is added to a list that I've defined earlier in the code. How do I go about doing this?

a = []
```

Couldn't find anything on Google about this

答:
There's no built-in way to do this, but you can very easily make your list a user-defined class inheriting from list and hook into the append method:

```<code>class MyList(list):
    def append(self, item):
        print(f'item {item} will be appended to {str(self)}')
        return_value = super().append(item)
        print(f'append succeeded -> list is now {str(self)}')
        return return_value

mylist = MyList('abc')

print(mylist)
# output:
# ['a', 'b', 'c']

mylist.append('d')
# output:
# item d will be appended to ['a', 'b', 'c']
# append succeeded -> list is now ['a', 'b', 'c', 'd']

print(mylist)
# output:
# ['a', 'b', 'c', 'd']
</code>```

Body:
I want to print something whenever something is added to a list that I've defined earlier in the code. How do I go about doing this?

a = []

Couldn't find anything on Google about this

Body:
There's no built-in way to do this, but you can very easily make your list a user-defined class inheriting from list and hook into the append method:

class MyList(list):
    def append(self, item):
        print(f'item {item} will be appended to {str(self)}')
        return_value = super().append(item)
        print(f'append succeeded -> list is now {str(self)}')
        return return_value

mylist = MyList('abc')

print(mylist)
# output:
# ['a', 'b', 'c']

mylist.append('d')
# output:
# item d will be appended to ['a', 'b', 'c']
# append succeeded -> list is now ['a', 'b', 'c', 'd']

print(mylist)
# output:
# ['a', 'b', 'c', 'd']


问:
How to extract text following a keyword in UNIX
I have a text file (file.txt) that contains a wall of results (no newlines, whitespaces etc) that I received from an external source.  From this file, I need to find all mentions of the word serId, and then print out the alpha-numeric sequence following it.  The alpha-numeric sequence is of any length but will end with the character ,.  How can I extract these alpha-numeric sequences?

I've tried finding scripts/code using sed / awk but the results seem to revolve around a known sequence to find, rather than an unknown sequence.

For example, I would like to extract 28655784-EE from the following sample text:

```<code>{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU
</code>```

答:
Based on the short sample you posted in a comment, I have two suggestions:

If the file is a well-formed json, try to understand its structure and use jq.

If it is malformed and can only be interpreted as a bunch of text, use the following Perl:

```<code>perl -lne '@m=/"serId":"([^"]+)"/g; print "@m"' file.txt
</code>```

Test run:

```<code>$ cat file.txt
{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU

$ perl -lne '@m=/"serId":"([^"]+)"/g; print "@m"' file.txt
28655784-EE 28655784-EE
</code>```

Body:
I have a text file (file.txt) that contains a wall of results (no newlines, whitespaces etc) that I received from an external source.  From this file, I need to find all mentions of the word serId, and then print out the alpha-numeric sequence following it.  The alpha-numeric sequence is of any length but will end with the character ,.  How can I extract these alpha-numeric sequences?

I've tried finding scripts/code using sed / awk but the results seem to revolve around a known sequence to find, rather than an unknown sequence.

For example, I would like to extract 28655784-EE from the following sample text:

{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU

Body:
Based on the short sample you posted in a comment, I have two suggestions:

If the file is a well-formed json, try to understand its structure and use jq.

If it is malformed and can only be interpreted as a bunch of text, use the following Perl:

perl -lne '@m=/"serId":"([^"]+)"/g; print "@m"' file.txt

Test run:

$ cat file.txt
{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU

$ perl -lne '@m=/"serId":"([^"]+)"/g; print "@m"' file.txt
28655784-EE 28655784-EE


问:
Binding the List items to this.state
I have a Recact component defined as:

export default class App extends React.Component<AppProps, Items>

The Items class is defined as:

export default class Items extends Array<Item>

and the Item is just a class with a bunch of properties.

If in render() I bind a list to my Items object directly ie.

<List items={myItems} onRenderCell={this._onRenderCell} />

the list is displayed correctly, however if I this.setState(myItems) and then try to get the list binded to the state:

<List items={this.state} onRenderCell={this._onRenderCell} />

I get the compile-time error:

Type 'Readonly' is missing the following properties from type 'any[]': [Symbol.iterator], [Symbol.unscopables]

How do I fix this?

答:
I found an easy solution to this... I created a new type:

```<code>type ItemsState = {
    items: Items
}
</code>```

then changed my component to use that as a state instead: export default class App extends React.Component<AppProps, ItemsState>

Title: Binding the List items to this.state

Body:
I found an easy solution to this... I created a new type:

type ItemsState = {
    items: Items
}

then changed my component to use that as a state instead: export default class App extends React.Component<AppProps, ItemsState>


答:
First, I want to point out that React's patterns discourage inheritance and prefer composition

Moreover you are extending an Array while React expect an Object.

Another misconception is "bind a function to the state". You are binding this context, not to variables.

Finally, state must be serializable and you should put in it only objects and arrays or primitives.

Try to refactor your components following this guidelines or post complete code for a more comprehensive solution.

Title: Binding the List items to this.state

Body:
I have a Recact component defined as:

export default class App extends React.Component<AppProps, Items>

The Items class is defined as:

export default class Items extends Array<Item>

and the Item is just a class with a bunch of properties.

If in render() I bind a list to my Items object directly ie.

<List items={myItems} onRenderCell={this._onRenderCell} />

the list is displayed correctly, however if I this.setState(myItems) and then try to get the list binded to the state:

<List items={this.state} onRenderCell={this._onRenderCell} />

I get the compile-time error:

Type 'Readonly' is missing the following properties from type 'any[]': [Symbol.iterator], [Symbol.unscopables]

How do I fix this?


问:
Replace guava Fluent Iterables with Streams
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

```<code>public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}
</code>```

I tried with this solution:

```<code>public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}
</code>```

how to do that without casting the return Stream?

答:
Another thing you can do (though it's probably a bit less efficient than doing it in two steps) is to define something like this:

public static <T> Function<Object, Stream<T>> instancesOf(Class<T> c) {
  return o -> c.isInstance(o) ? Stream.of(c.cast(o)) : Stream.empty();
}
```

<p>and then use it like this:</p>

<pre class="lang-java prettyprint-override"><code>return filter.stream()
    .flatMap(instancesOf(classType))
    .collect(toList());
</code>```

Body:
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}

I tried with this solution:

public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}

how to do that without casting the return Stream?

Body:
Another thing you can do (though it's probably a bit less efficient than doing it in two steps) is to define something like this:

public static <T> Function<Object, Stream<T>> instancesOf(Class<T> c) {
  return o -> c.isInstance(o) ? Stream.of(c.cast(o)) : Stream.empty();
}

and then use it like this:

return filter.stream()
    .flatMap(instancesOf(classType))
    .collect(toList());


问:
Bash for loop remove commas and redirect output to same file names
I am attempting to run a shell script that loops through all files in a directory that I specify when executing the shell script, removes all commas in the file, and saves it as the same filename.

The problem is that it's deleting everything in each file, and I'm unsure why, but believe it has to do with "$filename";. I've tried putting it in brackets too, but I'm new to Bash.

I run it like so:
NaN$ ./remove_commas.sh /path/to/dir

./remove_commas.sh

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

dir="$@"

for filename in $dir/*; do
    echo "$filename"

    cat "$filename" | tr -d ',' > "$filename";
done
</code>```

答:
You can do it with sed, which has an option to write the result back to the input file.

```<code>sed -i 's/,//g' "$dir/*"
</code>```

Body:
I am attempting to run a shell script that loops through all files in a directory that I specify when executing the shell script, removes all commas in the file, and saves it as the same filename.

The problem is that it's deleting everything in each file, and I'm unsure why, but believe it has to do with "$filename";. I've tried putting it in brackets too, but I'm new to Bash.

I run it like so:
NaN$ ./remove_commas.sh /path/to/dir

./remove_commas.sh

#!/bin/bash

dir="$@"

for filename in $dir/*; do
    echo "$filename"

    cat "$filename" | tr -d ',' > "$filename";
done

Body:
You can do it with sed, which has an option to write the result back to the input file.

sed -i 's/,//g' "$dir/*"


问:
Declare object into a switch statement
obj not recognized after declaring in switch statement

```<code>switch (var){
        case "YES" : {
              Object1 obj = new Object1();
              break;
       }
        default: {
              Object2 obj = new Object2();
       }

     }

NewObject newObject = obj.objToNewObject(param);
</code>```

My problem is that "obj" is not recognized
-> "Error java: cannot find symbol"

I was thinking that with "default" i will work but no.
Any help ?

答:
The object obj in your code is a local variable of the switch statement, so it cannot be accessed outside this scope. Also, to be able to use obj as two different classes you will have to use Polymorphism, so you will have to declare a base class (I will use A to illustrate) and two different classes (B and C) that extends class A.

```<code>class A {
    public NewObject(param) {
        return new NewObject();
    }
}

</code>```

```<code>class B extends A{
    @Override
    public NewObject(param) {
        return new NewObject();
    }
}

</code>```

```<code>class C extends A {
    @Override
    public NewObject(param) {
        return new NewObject();
    }
}

</code>```

```<code>A obj = null;
switch (var){
        case "YES" : {
              obj = new B();
              break;
       }
        case "NO": {
              obj = new C();
       }
        default: {
              obj = new B();
       }

     }
NewObject newObject = obj.objToNewObject(param);
</code>```

Note that the classes B and C will have to override the method objToNewObject from class A for this to work

Title: Declare object into a switch statement

Body:
obj not recognized after declaring in switch statement

switch (var){
        case "YES" : {
              Object1 obj = new Object1();
              break;
       }
        default: {
              Object2 obj = new Object2();
       }

     }

NewObject newObject = obj.objToNewObject(param);

My problem is that "obj" is not recognized
-> "Error java: cannot find symbol"

I was thinking that with "default" i will work but no.
Any help ?

Body:
The object obj in your code is a local variable of the switch statement, so it cannot be accessed outside this scope. Also, to be able to use obj as two different classes you will have to use Polymorphism, so you will have to declare a base class (I will use A to illustrate) and two different classes (B and C) that extends class A.

class A {
    public NewObject(param) {
        return new NewObject();
    }
}

class B extends A{
    @Override
    public NewObject(param) {
        return new NewObject();
    }
}

class C extends A {
    @Override
    public NewObject(param) {
        return new NewObject();
    }
}

A obj = null;
switch (var){
        case "YES" : {
              obj = new B();
              break;
       }
        case "NO": {
              obj = new C();
       }
        default: {
              obj = new B();
       }

     }
NewObject newObject = obj.objToNewObject(param);

Note that the classes B and C will have to override the method objToNewObject from class A for this to work


问:
Create rotation animation for UIBezierPath
I have a CAShapeLayer that is a circle centered in the middle of the main View of my View Controller.

It looks like this:

The Problem I have is, that if I try to animate a rotation with the following code, it does not rotate around the center of the circle but somewhere else.

```<code>import UIKit

extension UIView {
    func addCircle(centerOfCircle: CGPoint, radius: CGFloat, startAngle: CGFloat?, endAngle: CGFloat?) {
        let circlePath = UIBezierPath(arcCenter: centerOfCircle, radius: radius, startAngle: startAngle ?? 0, endAngle: endAngle ?? CGFloat(Double.pi * 2), clockwise: true)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath

        //change the fill color
        shapeLayer.fillColor = UIColor.clear.cgColor
        //you can change the stroke color
        shapeLayer.strokeColor = UIColor.red.cgColor

        shapeLayer.lineDashPattern = [1, 10]
        shapeLayer.lineCap = .round
        //you can change the line width
        shapeLayer.lineWidth = 3.0

        shapeLayer.anchorPoint = centerOfCircle

        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.toValue = NSNumber(value: Double.pi * 2)
        rotation.duration = 2
        rotation.isCumulative = true
        rotation.repeatCount = Float.greatestFiniteMagnitude

        shapeLayer.add(rotation, forKey: "rotationAnimation")

        self.layer.addSublayer(shapeLayer)
    }
}
</code>```

What I get then is the following:

Any help would be highly appreciated!

答:
Instead of animating the rotation, animate lineDashPhase property of the CAShapeLayer

```<code>extension UIView {
    func addDashedCircle() {
        let circleLayer = CAShapeLayer()
        circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2),
                                        radius: frame.size.width/2,
                                        startAngle: 0,
                                        endAngle: .pi * 2,
                                        clockwise: true).cgPath
        circleLayer.lineWidth = 3.0
        circleLayer.strokeColor =  UIColor.red.cgColor
        circleLayer.fillColor = UIColor.white.cgColor
        circleLayer.lineJoin = .round
        circleLayer.lineDashPattern = [1,10]

        let animation = CABasicAnimation(keyPath: "lineDashPhase")
        animation.fromValue = 0
        animation.toValue = -11//1+10
        animation.duration = 1
        animation.repeatCount = .infinity
        circleLayer.add(animation, forKey: "line")

        layer.addSublayer(circleLayer)
    }
}
</code>```

Body:
I have a CAShapeLayer that is a circle centered in the middle of the main View of my View Controller.

It looks like this:

The Problem I have is, that if I try to animate a rotation with the following code, it does not rotate around the center of the circle but somewhere else.

import UIKit

extension UIView {
    func addCircle(centerOfCircle: CGPoint, radius: CGFloat, startAngle: CGFloat?, endAngle: CGFloat?) {
        let circlePath = UIBezierPath(arcCenter: centerOfCircle, radius: radius, startAngle: startAngle ?? 0, endAngle: endAngle ?? CGFloat(Double.pi * 2), clockwise: true)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath

        //change the fill color
        shapeLayer.fillColor = UIColor.clear.cgColor
        //you can change the stroke color
        shapeLayer.strokeColor = UIColor.red.cgColor

        shapeLayer.lineDashPattern = [1, 10]
        shapeLayer.lineCap = .round
        //you can change the line width
        shapeLayer.lineWidth = 3.0

        shapeLayer.anchorPoint = centerOfCircle

        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.toValue = NSNumber(value: Double.pi * 2)
        rotation.duration = 2
        rotation.isCumulative = true
        rotation.repeatCount = Float.greatestFiniteMagnitude

        shapeLayer.add(rotation, forKey: "rotationAnimation")

        self.layer.addSublayer(shapeLayer)
    }
}

What I get then is the following:

Any help would be highly appreciated!

Body:
Instead of animating the rotation, animate lineDashPhase property of the CAShapeLayer

extension UIView {
    func addDashedCircle() {
        let circleLayer = CAShapeLayer()
        circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2),
                                        radius: frame.size.width/2,
                                        startAngle: 0,
                                        endAngle: .pi * 2,
                                        clockwise: true).cgPath
        circleLayer.lineWidth = 3.0
        circleLayer.strokeColor =  UIColor.red.cgColor
        circleLayer.fillColor = UIColor.white.cgColor
        circleLayer.lineJoin = .round
        circleLayer.lineDashPattern = [1,10]

        let animation = CABasicAnimation(keyPath: "lineDashPhase")
        animation.fromValue = 0
        animation.toValue = -11//1+10
        animation.duration = 1
        animation.repeatCount = .infinity
        circleLayer.add(animation, forKey: "line")

        layer.addSublayer(circleLayer)
    }
}


问:
Using a base.html file but modifying more than just the body
First of all, I have no problems with my code. This question is more of a "Is this possible and if so/not what is the right way of doing it ?"

I have a website where every page has the same look, the differences between them are as follows:

The homepage has an interactive leaflet map (javascript)

The titles vary on every page

The elements in the head tags change from one page to another but not always

The background image doesn't change

Within the body tag, I have a div tag containing a page footer common to all pages

What I would like to know is if it is possible to use a base.html template for these pages knowing the above constraints and also, if it is, how I would go about modifying the said pages to do so.

As I said, the code isn't really an issue here but for clarity and for you to be able to see what changes from one page to another, here is the Github repository for the project. (The project is a university project and therefore some parts of the code is in French since my university is a french University)

https://github.com/MaxMichel2/PWEB

Don't hesitate to tell me if some clarifications are needed to understand my issue.

EDIT

All the Django tutorials I have seen and read online only explain/talk about the {% block content %} delimiters in the  tags but I haven't found any help on how the have different parts within the  section.

Is it simply the case of using a different {% block content %} delimiter to identify the parts of the base.html file that will have parts added/modified ?

If so would if be possible to have a basic example to see what I'm working towards ?

答:
Keep those thing in base.html which is common for every page.
Then suppose a specific styles sheet or JavaScript or page title required for specific page not every page then you follow something like this

base.html

```<code><html>
    <head>
    <--! common style sheets -->
    {% block page_specific_style %}
    {% endblock %}

    <title>
        {% block title %}
        {% endblock %}
    </title>
    </head>
    <body>
        {% block content %}
        {% endblock %}

        {% block page_specific_js %}
        {% endblock %}
    </body>
</html>
</code>```

Lets say you need to add a new style sheet to contact.html, not any other page

contact.html

```<code>{% load static %}
{% extends 'base.html' %}

{% block page_specific_style %}
    <link href="{% static 'some.css' %}">
{% endblock %}

{% block title %}
    This is contact page title
{% endblock %}

{% block content %}
    content of contact page
{% endblock %}
</code>```

Body:
Keep those thing in base.html which is common for every page.
Then suppose a specific styles sheet or JavaScript or page title required for specific page not every page then you follow something like this

base.html

<html>
    <head>
    <--! common style sheets -->
    {% block page_specific_style %}
    {% endblock %}

    <title>
        {% block title %}
        {% endblock %}
    </title>
    </head>
    <body>
        {% block content %}
        {% endblock %}

        {% block page_specific_js %}
        {% endblock %}
    </body>
</html>

Lets say you need to add a new style sheet to contact.html, not any other page

contact.html

{% load static %}
{% extends 'base.html' %}

{% block page_specific_style %}
    <link href="{% static 'some.css' %}">
{% endblock %}

{% block title %}
    This is contact page title
{% endblock %}

{% block content %}
    content of contact page
{% endblock %}


问:
Efficient way to search inside list of json based on its key containment
I have some variables and JSON from api, let say

```<code>var airlines = "Airasia";
var hotel = "Hyatt";
var tourType = "holiday";
var result = JSON.parse(data);
</code>```

the json structure is following:

```<code>    [ { id: 1,
        departure_month: 'September - November 2019',
        program: '9 Days',
        package_name: 'Example package 1',
        tour_type: 'holiday',
        airlines: 'Lion',
        hotel: 'Hyatt'
      },
      { id: 2,
        departure_month: 'September - November 2019',
        program: '15 Days',
        package_name: 'Example package 2',
        tour_type: 'pilgrimage',
        airlines: 'Saudia',
        hotel: 'pullman'
       },
      { id: 3,
        departure_month: 'September - November 2019',
        program: '10 Days',
        package_name: 'Example package 3',
        tour_type: 'holiday',
        airlines: 'Airasia',
        hotel: 'Hyatt'
       }
    ]
</code>```

I want to efficiently search if one or more of the parameters (ex: airline, hotel, tourType) are exist or not and the code will return the json that match with those keys

so for example if alirlines = "Saudia" and hotel = "pullman" and the rest is empty, then the code will only return corresponding parameters

```<code>{ id: 2,
    departure_month: 'September - November 2019',
    program: '15 Days',
    package_name: 'Example package 2',
    tour_type: 'pilgrimage',
    airlines: 'Saudia',
    hotel: 'pullman'
   }
</code>```

答:
create a function that takes array of keys, and use includes and filter to filter on those values.

const json = [ { id: 1,
        departure_month: 'September - November 2019',
        program: '9 Days',
        package_name: 'Example package 1',
        tour_type: 'holiday',
        airlines: 'Lion',
        hotel: 'Hyatt'
      },
      { id: 2,
        departure_month: 'September - November 2019',
        program: '15 Days',
        package_name: 'Example package 2',
        tour_type: 'pilgrimage',
        airlines: 'Saudia',
        hotel: 'pullman'
       },
      { id: 3,
        departure_month: 'September - November 2019',
        program: '10 Days',
        package_name: 'Example package 3',
        tour_type: 'holiday',
        airlines: 'Airasia',
        hotel: 'Hyatt'
       }
    ]

function searchJson(array, keys) {

  return array.filter(item => {
    const string = item && typeof item === 'object' && JSON.stringify(item).toLowerCase();

    return keys.filter(key => string && string.includes(key.toLowerCase())).length === keys.length;
  })
}

console.log(searchJson(json, ['Saudia', 'pullman']))```

Body:
I have some variables and JSON from api, let say

var airlines = "Airasia";
var hotel = "Hyatt";
var tourType = "holiday";
var result = JSON.parse(data);

the json structure is following:

    [ { id: 1,
        departure_month: 'September - November 2019',
        program: '9 Days',
        package_name: 'Example package 1',
        tour_type: 'holiday',
        airlines: 'Lion',
        hotel: 'Hyatt'
      },
      { id: 2,
        departure_month: 'September - November 2019',
        program: '15 Days',
        package_name: 'Example package 2',
        tour_type: 'pilgrimage',
        airlines: 'Saudia',
        hotel: 'pullman'
       },
      { id: 3,
        departure_month: 'September - November 2019',
        program: '10 Days',
        package_name: 'Example package 3',
        tour_type: 'holiday',
        airlines: 'Airasia',
        hotel: 'Hyatt'
       }
    ]

I want to efficiently search if one or more of the parameters (ex: airline, hotel, tourType) are exist or not and the code will return the json that match with those keys

so for example if alirlines = "Saudia" and hotel = "pullman" and the rest is empty, then the code will only return corresponding parameters

{ id: 2,
    departure_month: 'September - November 2019',
    program: '15 Days',
    package_name: 'Example package 2',
    tour_type: 'pilgrimage',
    airlines: 'Saudia',
    hotel: 'pullman'
   }


问:
Rendering templated HtmlHelper with MVC3/Razor
I have a HtmlHelper that renders a grid as a table, in MVC2 I would call it from the view using the following syntax...

```<code><%=
    Html.MyLibrary().Grid<MyGridItem>()
        .Name("MyGrid")
        .Width("100%")
        .Render()
%>
</code>```

Notice it uses templates. In MVC3 with Razor it won't compile, seemingly because the left angle bracket '<' is being confused for html. To get around this I can enclose it in curly braces...

```<code>@{Html.MyLibrary().Grid<MyGridItem>()
        .Name("MyGrid")
        .Width("100%")
        .Render();}
</code>```

but now the problem is that the string returned from .Render() doesn't get put in the output stream!

Any help solving this would be much appreciated.

答:
You should use Html.Raw() Method. </p>

```<code>@Html.Raw(Html.MyLibrary().Grid<MyGridItem>()
        .Name("MyGrid")
        .Width("100%")
        .Render())
</code>```

<p>The @{...} server side block does not get rendered because it's simple server side code. Same if you wrote </p>

```<code>@{ "renderedstring".ToString(); }
</code>```

Body:
I have a HtmlHelper that renders a grid as a table, in MVC2 I would call it from the view using the following syntax...

<%=
    Html.MyLibrary().Grid<MyGridItem>()
        .Name("MyGrid")
        .Width("100%")
        .Render()
%>

Notice it uses templates. In MVC3 with Razor it won't compile, seemingly because the left angle bracket '<' is being confused for html. To get around this I can enclose it in curly braces...

@{Html.MyLibrary().Grid<MyGridItem>()
        .Name("MyGrid")
        .Width("100%")
        .Render();}

but now the problem is that the string returned from .Render() doesn't get put in the output stream!

Any help solving this would be much appreciated.

Body:
You should use Html.Raw() Method.

@Html.Raw(Html.MyLibrary().Grid<MyGridItem>()
        .Name("MyGrid")
        .Width("100%")
        .Render())

The @{...} server side block does not get rendered because it's simple server side code. Same if you wrote

@{ "renderedstring".ToString(); }


问:
How to make, that the Rover drives to the left and stop
at the moment I'm using an L298 Motor Driver, an ultrasonic Sensor, and an ESP32. The goal is when the Ultrasonic Sensor(which is at the front of the Rover) detects an object, the Rover drives to the left and stops.
The problem is, that when the Sensor detects an object, the rover only stops without moving to the left. Otherwise, if I delete the Stop part of the code, my rover goes to the left. However, I do not know how I make, that he does both commands.

```<code>// defines Sensor pins

#define trigPin 12
#define echoPin 13

//Define Motor pins
#define motorIn3  16 //Input 3
#define motorIn1  17 //Input 1
#define motorIn4  18 //Input 4
#define motorIn2  19 //Input 2

// defines variables
long duration;
int distance;

// define ActivateDistance
double activateDistance = 20;

void setup()
{
  // Sets the trigPin as an Output
  pinMode(trigPin, OUTPUT);
  // Sets the echoPin as an Input
  pinMode(echoPin, INPUT);

  // sets the Motorpins  as outputs:
  pinMode(motorIn1, OUTPUT);
  pinMode(motorIn2, OUTPUT);
  pinMode(motorIn3, OUTPUT);
  pinMode(motorIn4, OUTPUT);

  Serial.begin(9600); // Starts the serial communication

}

void loop()
{

  //Moving Motor forward
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn4, HIGH);
  digitalWrite(motorIn3, LOW);
  digitalWrite(motorIn1, LOW);

  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

 // Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

 // Reads the echoPin, returns the sound wave travel time in microseconds
 duration = pulseIn(echoPin, HIGH);

 // Calculating the distance
 distance = duration * 0.034 / 2;

//when the distance is under 20, the motor should drives to the left and stopps.
 if (distance <= activateDistance)
 {
  //for loop using that the motor drives a specific amount to the left
  for(int i = 0; i<5;i++)
  {
 //Motor drives to left
  digitalWrite(motorIn1, LOW);
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn3, HIGH);
  digitalWrite(motorIn4, LOW);
//After drives to left, the motor should stop.
    if(i == 4)
    {
      //Moves forward
      digitalWrite(motorIn2, HIGH);
      digitalWrite(motorIn4, HIGH);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn1, LOW);
      delay(1000);
      //Motor Stops.
      digitalWrite(motorIn1, LOW);
      digitalWrite(motorIn2, LOW);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn4, LOW);
    }
  }

 }
  delay(1000);
}
</code>```

Sorry for my bad English.

答:
First, try to rewrite your code with functions that each one has its own purpose. This will give you more insight into what is going on and what the problem is. For example, you can create a function that calculates the distance and check it in your main loop, or creating a vehicle forward function with a duration as an argument.

Second, when you set your motor pins you need to put some delay to give enough time to your vehicle to move.

I rewrite your code with some functions and put some prints, just remember to calibrate the timings for better performance.

```<code>// defines Sensor pins

#define trigPin 12
#define echoPin 13

//Define Motor pins
#define motorIn3 16 //Input 3
#define motorIn1 17 //Input 1
#define motorIn4 18 //Input 4
#define motorIn2 19 //Input 2

// defines variables
long duration;
int distance;

// define ActivateDistance
const int activateDistance = 20;

void setup()
{
    // Sets the trigPin as an Output
    pinMode(trigPin, OUTPUT);
    // Sets the echoPin as an Input
    pinMode(echoPin, INPUT);
    // sets the Motorpins  as outputs:
    pinMode(motorIn1, OUTPUT);
    pinMode(motorIn2, OUTPUT);
    pinMode(motorIn3, OUTPUT);
    pinMode(motorIn4, OUTPUT);
    Serial.begin(9600); // Starts the serial communication
}

void stop()
{
    // stop motor without duration
    Serial.println("STOP");
    digitalWrite(motorIn1, LOW);
    digitalWrite(motorIn2, LOW);
    digitalWrite(motorIn3, LOW);
    digitalWrite(motorIn4, LOW);
}

void left(int duration)
{
    //Motor goes to left
    Serial.println("LEFT");
    digitalWrite(motorIn1, LOW);
    digitalWrite(motorIn2, HIGH);
    digitalWrite(motorIn3, HIGH);
    digitalWrite(motorIn4, LOW);
    delay(duration);
    stop();
}

void forward(int duration)
{
    //Motor goes forward
    Serial.println("FORWARD");
    digitalWrite(motorIn2, HIGH);
    digitalWrite(motorIn4, HIGH);
    digitalWrite(motorIn3, LOW);
    digitalWrite(motorIn1, LOW);
    delay(duration);
    stop();
}

long get_distance(void)
{
    //get distance from sensor
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance = duration * 0.034 / 2;
    return distance;
}

void loop()
{
    // check sensor
    if (get_distance() <= activateDistance)
    {
        Serial.println("Found an Obstacle!!!");
        // go left for 1 second
        left(1000);
        // go forward for 1 second
        forward(1000);
    }
    else
        // go forward for 1 second
        forward(1000);
}
</code>```

Body:
at the moment I'm using an L298 Motor Driver, an ultrasonic Sensor, and an ESP32. The goal is when the Ultrasonic Sensor(which is at the front of the Rover) detects an object, the Rover drives to the left and stops.
The problem is, that when the Sensor detects an object, the rover only stops without moving to the left. Otherwise, if I delete the Stop part of the code, my rover goes to the left. However, I do not know how I make, that he does both commands.

// defines Sensor pins

#define trigPin 12
#define echoPin 13

//Define Motor pins
#define motorIn3  16 //Input 3
#define motorIn1  17 //Input 1
#define motorIn4  18 //Input 4
#define motorIn2  19 //Input 2

// defines variables
long duration;
int distance;

// define ActivateDistance
double activateDistance = 20;

void setup()
{
  // Sets the trigPin as an Output
  pinMode(trigPin, OUTPUT);
  // Sets the echoPin as an Input
  pinMode(echoPin, INPUT);

  // sets the Motorpins  as outputs:
  pinMode(motorIn1, OUTPUT);
  pinMode(motorIn2, OUTPUT);
  pinMode(motorIn3, OUTPUT);
  pinMode(motorIn4, OUTPUT);

  Serial.begin(9600); // Starts the serial communication

}

void loop()
{

  //Moving Motor forward
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn4, HIGH);
  digitalWrite(motorIn3, LOW);
  digitalWrite(motorIn1, LOW);

  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

 // Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

 // Reads the echoPin, returns the sound wave travel time in microseconds
 duration = pulseIn(echoPin, HIGH);

 // Calculating the distance
 distance = duration * 0.034 / 2;

//when the distance is under 20, the motor should drives to the left and stopps.
 if (distance <= activateDistance)
 {
  //for loop using that the motor drives a specific amount to the left
  for(int i = 0; i<5;i++)
  {
 //Motor drives to left
  digitalWrite(motorIn1, LOW);
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn3, HIGH);
  digitalWrite(motorIn4, LOW);
//After drives to left, the motor should stop.
    if(i == 4)
    {
      //Moves forward
      digitalWrite(motorIn2, HIGH);
      digitalWrite(motorIn4, HIGH);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn1, LOW);
      delay(1000);
      //Motor Stops.
      digitalWrite(motorIn1, LOW);
      digitalWrite(motorIn2, LOW);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn4, LOW);
    }
  }

 }
  delay(1000);
}

Sorry for my bad English.

Body:
First, try to rewrite your code with functions that each one has its own purpose. This will give you more insight into what is going on and what the problem is. For example, you can create a function that calculates the distance and check it in your main loop, or creating a vehicle forward function with a duration as an argument.

Second, when you set your motor pins you need to put some delay to give enough time to your vehicle to move.

I rewrite your code with some functions and put some prints, just remember to calibrate the timings for better performance.

// defines Sensor pins

#define trigPin 12
#define echoPin 13

//Define Motor pins
#define motorIn3 16 //Input 3
#define motorIn1 17 //Input 1
#define motorIn4 18 //Input 4
#define motorIn2 19 //Input 2

// defines variables
long duration;
int distance;

// define ActivateDistance
const int activateDistance = 20;

void setup()
{
    // Sets the trigPin as an Output
    pinMode(trigPin, OUTPUT);
    // Sets the echoPin as an Input
    pinMode(echoPin, INPUT);
    // sets the Motorpins  as outputs:
    pinMode(motorIn1, OUTPUT);
    pinMode(motorIn2, OUTPUT);
    pinMode(motorIn3, OUTPUT);
    pinMode(motorIn4, OUTPUT);
    Serial.begin(9600); // Starts the serial communication
}

void stop()
{
    // stop motor without duration
    Serial.println("STOP");
    digitalWrite(motorIn1, LOW);
    digitalWrite(motorIn2, LOW);
    digitalWrite(motorIn3, LOW);
    digitalWrite(motorIn4, LOW);
}

void left(int duration)
{
    //Motor goes to left
    Serial.println("LEFT");
    digitalWrite(motorIn1, LOW);
    digitalWrite(motorIn2, HIGH);
    digitalWrite(motorIn3, HIGH);
    digitalWrite(motorIn4, LOW);
    delay(duration);
    stop();
}

void forward(int duration)
{
    //Motor goes forward
    Serial.println("FORWARD");
    digitalWrite(motorIn2, HIGH);
    digitalWrite(motorIn4, HIGH);
    digitalWrite(motorIn3, LOW);
    digitalWrite(motorIn1, LOW);
    delay(duration);
    stop();
}

long get_distance(void)
{
    //get distance from sensor
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance = duration * 0.034 / 2;
    return distance;
}

void loop()
{
    // check sensor
    if (get_distance() <= activateDistance)
    {
        Serial.println("Found an Obstacle!!!");
        // go left for 1 second
        left(1000);
        // go forward for 1 second
        forward(1000);
    }
    else
        // go forward for 1 second
        forward(1000);
}


问:
Fill <object> svg using jss
All I want is a fill color. The source file is #000, therefore no fill is specified in the svg code.

Here's the JSX:

```<code>import dashboardIcon from '../../images/icons/Dashboard-Icon.svg'

<object className={classes.navIcon} type="image/svg+xml" data={dashboardIcon}
alt='' />
</code>```

And the JSS:

```<code>navIcon: {
width: '24px',
paddingRight: '10px',
fill: '#F7F7F7'
}
</code>```

Thank you so much!

答:
Very late to the party, but I found your post when I was Googling the same thing and I found a solution for SVGs in JSS that modify the child elements. Posting for posterity:</p>

```<code>navIcon: {
   '& svg': {
    width: '24px',
    paddingRight: '10px',
   '& path': {
        fill: '#F7F7F7'
      }
    },
  }
</code>```

Title: Fill <object> svg using jss

Body:
All I want is a fill color. The source file is #000, therefore no fill is specified in the svg code.

Here's the JSX:

import dashboardIcon from '../../images/icons/Dashboard-Icon.svg'

<object className={classes.navIcon} type="image/svg+xml" data={dashboardIcon}
alt='' />

And the JSS:

navIcon: {
width: '24px',
paddingRight: '10px',
fill: '#F7F7F7'
}

Thank you so much!

Body:
Very late to the party, but I found your post when I was Googling the same thing and I found a solution for SVGs in JSS that modify the child elements. Posting for posterity:

navIcon: {
   '& svg': {
    width: '24px',
    paddingRight: '10px',
   '& path': {
        fill: '#F7F7F7'
      }
    },
  }