问:
How to return an array for unit testing with JUnit and Mockito?
I am testing an application that will stop unless it can split a String into a String[]. I am using JUnit and Mockito to test the application. I set up a default value and the mock behavior as follows.

String[] exampleStringList = {"exampleElement", "exampleElement"};
when(example.Call()).thenReturn(exampleStringList);

This creates the error java: no suitable method found for thenReturn(java.Util.String[]). I tried to resolve the issue by substituting String[] with List<String> and then adding the necessary elements. This created the same error as above.

TL;DR; I need to return a String[] with elements using JUnit for testing purposes but thenReturn is not compatible. How can I use JUnit and Mockito to return a String[] array to the test?

答:
I have tried to recreate you scenario,

Service definition

```<code>public interface ExampleService {
boolean doSomething();
</code>```

}

Implementation

```<code>@Service
@RequiredArgsConstructor
public class ExampleServiceImpl implements ExampleService {
private final ExampleDependantService exampleDependantService;
 @Override
public boolean doSomething() {
String[] strings = exampleDependantService.call();
if(strings.length >0){
    return true;
}else{
    return false ;
}

 }
}
</code>```

Dependency

```<code>  @Component
  public class ExampleDependantService {
  public String[] call(){
   return new String[]{"exampleElement", "exampleElement"};
  }
  }
</code>```

4.Test

```<code>       @ExtendWith(SpringExtension.class)
       class ExampleDependantServiceImplTest {
       @Mock
       private ExampleDependantService exampleDependantService;
       @InjectMocks
       private ExampleServiceImpl exampleServiceImpl;

      @Test
      void doSomething_WhenCalled() {
      String[] exampleStringList = {"exampleElement", "exampleElement"};
      when(exampleDependantService.call()).thenReturn(exampleStringList);
      boolean b = exampleServiceImpl.doSomething();
       Assert.assertTrue(b);
      }
      }
</code>```

5.Output

Body:
I have tried to recreate you scenario,

Service definition

public interface ExampleService {
boolean doSomething();

}

Implementation

@Service
@RequiredArgsConstructor
public class ExampleServiceImpl implements ExampleService {
private final ExampleDependantService exampleDependantService;
 @Override
public boolean doSomething() {
String[] strings = exampleDependantService.call();
if(strings.length >0){
    return true;
}else{
    return false ;
}

 }
}

Dependency

  @Component
  public class ExampleDependantService {
  public String[] call(){
   return new String[]{"exampleElement", "exampleElement"};
  }
  }

4.Test

       @ExtendWith(SpringExtension.class)
       class ExampleDependantServiceImplTest {
       @Mock
       private ExampleDependantService exampleDependantService;
       @InjectMocks
       private ExampleServiceImpl exampleServiceImpl;

      @Test
      void doSomething_WhenCalled() {
      String[] exampleStringList = {"exampleElement", "exampleElement"};
      when(exampleDependantService.call()).thenReturn(exampleStringList);
      boolean b = exampleServiceImpl.doSomething();
       Assert.assertTrue(b);
      }
      }

5.Output


来源: stackexchange

问:
Many-to-one relationship using two unique keys
I have two tables which look like thiS:

```<code>uploads
________
id (primary key)
user_id
file_checksum
</code>```

```<code>upload_information
---------
upload_info_id (primary key)
file_checksum
metadata1
metdata2
</code>```

The "many to one" relationship I am trying to enforce is this:

Many uploads can have the same file checksum

However, the file checksum can only ever point to one upload_information record, thus making the unique constraint between file_checksum and upload_info_id mandatory in the upload_information table.

I am wondering how to alter these tables in Postgres in order to achieve this relationship.

```<code>CREATE TABLE uploads (
  id SERIAL NOT NULL PRIMARY KEY,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  user_id VARCHAR NOT NULL,
  file_checksum VARCHAR NOT NULL,
);
</code>```

```<code>CREATE TABLE upload_information (
  upload_info_id SERIAL NOT NULL PRIMARY KEY,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  file_checksum VARCHAR NOT NULL,
  file_name VARCHAR NOT NULL,
  source_file_url VARCHAR NOT NULL,
);
</code>```

答:
Add a unique index on file_checksum.

```<code>create unique index unique_checksum on upload_information(file_checksum)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two tables which look like thiS:

uploads
________
id (primary key)
user_id
file_checksum

upload_information
---------
upload_info_id (primary key)
file_checksum
metadata1
metdata2

The "many to one" relationship I am trying to enforce is this:

Many uploads can have the same file checksum

However, the file checksum can only ever point to one upload_information record, thus making the unique constraint between file_checksum and upload_info_id mandatory in the upload_information table.

I am wondering how to alter these tables in Postgres in order to achieve this relationship.

CREATE TABLE uploads (
  id SERIAL NOT NULL PRIMARY KEY,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  user_id VARCHAR NOT NULL,
  file_checksum VARCHAR NOT NULL,
);

CREATE TABLE upload_information (
  upload_info_id SERIAL NOT NULL PRIMARY KEY,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  file_checksum VARCHAR NOT NULL,
  file_name VARCHAR NOT NULL,
  source_file_url VARCHAR NOT NULL,
);

Body:
Add a unique index on file_checksum.

create unique index unique_checksum on upload_information(file_checksum)


问:
Jooq: Joining the same table twice across a three table join
So i have three tables

Parent_section(id)

Assessment_Question(id,parent_section_id)

Assessment_Answer(id,assessment_question_id)

I am trying to inner join parent_section and assessment_qestion, and left join assessment_question and assessment_Answer

So far joining parent_Section and assessment_question I have this, not sure how to do it for a third table?

```<code>    var queryResult= dsl.select()
    .from(PARENT_SECTION)
    .join(ASSESSMENT_QUESTION)
    .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
    .where(PARENT_SECTION.GATE_ID.eq(gateId))
    .fetch()
</code>```

答:
Just add another join where you would have added another join in plain SQL:

var queryResult = dsl.select()
    .from(PARENT_SECTION)
    .join(ASSESSMENT_QUESTION)
    .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
    .leftJoin(ASSESSMENT_ANSWER)
    .on(ASSESSMENT_QUESTION.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_QUESTION_ID))
    .where(PARENT_SECTION.GATE_ID.eq(gateId))
    .fetch()
```

Body:
So i have three tables

Parent_section(id)

Assessment_Question(id,parent_section_id)

Assessment_Answer(id,assessment_question_id)

I am trying to inner join parent_section and assessment_qestion, and left join assessment_question and assessment_Answer

So far joining parent_Section and assessment_question I have this, not sure how to do it for a third table?

    var queryResult= dsl.select()
    .from(PARENT_SECTION)
    .join(ASSESSMENT_QUESTION)
    .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID))
    .where(PARENT_SECTION.GATE_ID.eq(gateId))
    .fetch()


问:
int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here? I know how to find the size of array
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element. </p>

```<code>
int main()
{
    int array[10] = {1, 2, 0, 3, 4};

    printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array

    int i = 0;

    while(array[i] != 0  && i < 10) {
        i++;
    };

    printf("%d\n", i);

    return 0;
}```
</code>```

答:
You have several options:

You know how many elements are in the initializer, so you create another variable that stores that number:```<code>int array[10] = {1, 2, 0, 3, 4};
int num_items = 5;
</code>```

You'll need to update num_items as you "add" or "remove" items to the array.  If you treat the array as a stack (only add or remove at the highest index), then this is easy-ish:```<code>array[num_items++] = 7; // adds 7 after 4
...
x = array[--num_items]; // x gets 7, 7 is "removed" from the array, need special
                        // case logic for element 0
</code>```

You pick a value that isn't valid (say -1) and initialize the remaining elements explicitly:```<code>int array[10] = {1, 2, 0, 3, 4, -1, -1, -1, -1, -1 };</code>```

You size the array for the initializer, meaning it can only ever store that many elements:```<code>int array[] = {1, 2, 0, 3, 4};</code>```

Otherwise, you'll need to use a different data structure (such as a linked list) if you need a container that can grow or shrink as items are added or removed.

Body:
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element.

int main()
{
    int array[10] = {1, 2, 0, 3, 4};

    printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array

    int i = 0;

    while(array[i] != 0  && i < 10) {
        i++;
    };

    printf("%d\n", i);

    return 0;
}```

Body:
You have several options:

You know how many elements are in the initializer, so you create another variable that stores that number:
int array[10] = {1, 2, 0, 3, 4};
int num_items = 5;

You'll need to update num_items as you "add" or "remove" items to the array.  If you treat the array as a stack (only add or remove at the highest index), then this is easy-ish:
array[num_items++] = 7; // adds 7 after 4
...
x = array[--num_items]; // x gets 7, 7 is "removed" from the array, need special
                        // case logic for element 0

You pick a value that isn't valid (say -1) and initialize the remaining elements explicitly:
int array[10] = {1, 2, 0, 3, 4, -1, -1, -1, -1, -1 };

You size the array for the initializer, meaning it can only ever store that many elements:
int array[] = {1, 2, 0, 3, 4};

Otherwise, you'll need to use a different data structure (such as a linked list) if you need a container that can grow or shrink as items are added or removed.


问:
How to implement (char-ready?) in C
I'm currently implementing Scheme R5RS in C, and I am stuck trying to implement the (char-ready?) function.

I have the specs for the function quoted below. The function is guaranteed not to block. The standard C functions like fgetc() all block on input when called when there is no input ready.

Does anyone know if there is way to implement this in a nice simple way, without spawning a dedicated IO thread?

Edit:
My input stream type is a FILE*, which could be stdin or a file opened with fopen().

(char-ready?) procedure

(char-ready? port) procedure

Returns #t if a character is ready on the input port and returns #f otherwise. If char-ready returns #t then the next read-char operation on the given port is guaranteed not to hang. If the port is at end of file then char-ready? returns #t. Port may be omitted, in which case it defaults to the value returned by current-input-port.

Rationale:

Char-ready? exists to make it possible for a program to accept characters from interactive ports without getting stuck waiting for input. Any input editors associated with such ports must ensure that characters whose existence has been asserted by char-ready? cannot be rubbed out. If char-ready? were to return #f at end of file, a port at end of file would be indistinguishable from an interactive port that has no ready characters.

答: You will need to go below the stdio level. On UNIX, you can use fileno() to get the file descriptor associated with the stream, and then you can use select() and read() system calls to do non-blocking reads.

ContentLicense: CC BY-SA 3.0

Title: How to implement (char-ready?) in C


问:
Document and Window are not Defined Puppeteer Electron
I'm having an issue where I'm running a automated chrome session using puppeteer in the back end of my electron app, but I keep getting the error document is undefined. Here is the code:

```<code>const isDone = await this.page.evaluate(async () => await this.autoScroll);

...

async autoScroll() {
        return new Promise(resolve => {
            const timer = setInterval(() => {
                document.scrollingElement.scrollBy(0, 100);
                if (document.scrollingElement.scrollTop + window.innerHeight >= document.scrollingElement.scrollHeight) {
                    clearInterval(timer);
                    resolve(true);
                }
            }, 230);
        });
    }
</code>```

The code works an executes perfectly if I run it on its own in a different folder, but somehow it seems to error out when I run it in the app.

Any help is welcome.

Thanks.

答:
I was transforming my code with babel. Puppeteer page.evaluate calls autoScroll.toString() which results in an incomplete string when used with babel. Instead it worked with:

```<code>const isDone = await this.page.evaluate(`(async() => {
                return new Promise(resolve => {
                    const timer = setInterval(() => {
                        document.scrollingElement.scrollBy(0, 100);
                        if (document.scrollingElement.scrollTop + window.innerHeight >= document.scrollingElement.scrollHeight) {
                            clearInterval(timer);
                            resolve(true);
                        }
                    }, 230);
                });
             })()`);
</code>```

Just put it in a string so there aren't any issues with the toString.

Body:
I'm having an issue where I'm running a automated chrome session using puppeteer in the back end of my electron app, but I keep getting the error document is undefined. Here is the code:

const isDone = await this.page.evaluate(async () => await this.autoScroll);

...

async autoScroll() {
        return new Promise(resolve => {
            const timer = setInterval(() => {
                document.scrollingElement.scrollBy(0, 100);
                if (document.scrollingElement.scrollTop + window.innerHeight >= document.scrollingElement.scrollHeight) {
                    clearInterval(timer);
                    resolve(true);
                }
            }, 230);
        });
    }

The code works an executes perfectly if I run it on its own in a different folder, but somehow it seems to error out when I run it in the app.

Any help is welcome.

Thanks.

Body:
I was transforming my code with babel. Puppeteer page.evaluate calls autoScroll.toString() which results in an incomplete string when used with babel. Instead it worked with:

const isDone = await this.page.evaluate(`(async() => {
                return new Promise(resolve => {
                    const timer = setInterval(() => {
                        document.scrollingElement.scrollBy(0, 100);
                        if (document.scrollingElement.scrollTop + window.innerHeight >= document.scrollingElement.scrollHeight) {
                            clearInterval(timer);
                            resolve(true);
                        }
                    }, 230);
                });
             })()`);

Just put it in a string so there aren't any issues with the toString.


问:
pivot point auto refresh in live market in pine editor
I am making a code in pine editor of tradingview in which i want to calculate important pivot point on daily basis.These points are very critical for my strategies.

In after market, the code works perfectly fine with stable lines on daily basis as required.
Image of stable lines

But in live market these points keep on changing with passage of time.
image in live market

I am confused, what exactly is missing in my code. Pl help.

My code is a simple one:

```<code>// @version=4
strategy("RCR GCR", overlay=true)

/////////////////////////Pivot Points//////////////////////////////
// CPR
PP = (high + low + close ) / 3.0
tc = (high + low ) / 2.0
bc = (PP - tc) + PP

//Daily Pivot Range
dtime_pivot = security(syminfo.tickerid, 'D', PP)
dtime_bc = security(syminfo.tickerid, 'D', bc)
dtime_tc = security(syminfo.tickerid, 'D', tc)

plot(dtime_pivot, color=color.purple,linewidth=3)
plot(dtime_bc, color=color.blue,linewidth=3)
plot(dtime_tc, color=color.blue,linewidth=3)
</code>```

答:
That's because you are using values like close, high and low which change during the realtime bar. This way of calling security() tells it to use only confirmed prices, so your lines will only move in the realtime bar when a daily bar ends. See How to avoid repainting when using security() - PineCoders FAQ for more info.

```<code>// @version=4
strategy("RCR GCR", overlay=true)

/////////////////////////Pivot Points//////////////////////////////
// CPR
PP = (high + low + close ) / 3.0
tc = (high + low ) / 2.0
bc = (PP - tc) + PP

//Daily Pivot Range
dtime_pivot = security(syminfo.tickerid, 'D', PP[1], lookahead = barmerge.lookahead_on)
dtime_bc = security(syminfo.tickerid, 'D', bc[1], lookahead = barmerge.lookahead_on)
dtime_tc = security(syminfo.tickerid, 'D', tc[1], lookahead = barmerge.lookahead_on)

plot(dtime_pivot, color=color.purple,linewidth=3)
plot(dtime_bc, color=color.blue,linewidth=3)
plot(dtime_tc, color=color.blue,linewidth=3)
</code>```

Body:
I am making a code in pine editor of tradingview in which i want to calculate important pivot point on daily basis.These points are very critical for my strategies.

In after market, the code works perfectly fine with stable lines on daily basis as required.
Image of stable lines

But in live market these points keep on changing with passage of time.
image in live market

I am confused, what exactly is missing in my code. Pl help.

My code is a simple one:

// @version=4
strategy("RCR GCR", overlay=true)

/////////////////////////Pivot Points//////////////////////////////
// CPR
PP = (high + low + close ) / 3.0
tc = (high + low ) / 2.0
bc = (PP - tc) + PP

//Daily Pivot Range
dtime_pivot = security(syminfo.tickerid, 'D', PP)
dtime_bc = security(syminfo.tickerid, 'D', bc)
dtime_tc = security(syminfo.tickerid, 'D', tc)

plot(dtime_pivot, color=color.purple,linewidth=3)
plot(dtime_bc, color=color.blue,linewidth=3)
plot(dtime_tc, color=color.blue,linewidth=3)

Body:
That's because you are using values like close, high and low which change during the realtime bar. This way of calling security() tells it to use only confirmed prices, so your lines will only move in the realtime bar when a daily bar ends. See How to avoid repainting when using security() - PineCoders FAQ for more info.

// @version=4
strategy("RCR GCR", overlay=true)

/////////////////////////Pivot Points//////////////////////////////
// CPR
PP = (high + low + close ) / 3.0
tc = (high + low ) / 2.0
bc = (PP - tc) + PP

//Daily Pivot Range
dtime_pivot = security(syminfo.tickerid, 'D', PP[1], lookahead = barmerge.lookahead_on)
dtime_bc = security(syminfo.tickerid, 'D', bc[1], lookahead = barmerge.lookahead_on)
dtime_tc = security(syminfo.tickerid, 'D', tc[1], lookahead = barmerge.lookahead_on)

plot(dtime_pivot, color=color.purple,linewidth=3)
plot(dtime_bc, color=color.blue,linewidth=3)
plot(dtime_tc, color=color.blue,linewidth=3)


问:
Replacing columns with different Dataframe
I have two dataframes,namely 'df' and 'df1'

```<code>df
Out[14]:
      first country  Rating
0    Robert      US     100
1     Chris     Aus      99
2  Scarlett      US     100

df1
Out[17]:
        last        Role
0     Downey     IronMan
1  Hemsworth        Thor
2  Johansson  BlackWidow
</code>```

Expected output:

```<code>      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100
</code>```

I need to drop off the 'country' column and replace with another dataframe(ie. 'df1')

I understand,I can join dataframes and drop 'country' column,but I need columns exactly in this order.

答:
Could you give this a shot?

df1.join(df2, lsuffix='', rsuffix='r_')[["first", "last", "Role", "Rating"]]
```

<p>Output:</p>

```      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100
```

Body:
I have two dataframes,namely 'df' and 'df1'

df
Out[14]:
      first country  Rating
0    Robert      US     100
1     Chris     Aus      99
2  Scarlett      US     100

df1
Out[17]:
        last        Role
0     Downey     IronMan
1  Hemsworth        Thor
2  Johansson  BlackWidow

Expected output:

      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100

I need to drop off the 'country' column and replace with another dataframe(ie. 'df1')

I understand,I can join dataframes and drop 'country' column,but I need columns exactly in this order.

Body:
Could you give this a shot?

df1.join(df2, lsuffix='', rsuffix='r_')[["first", "last", "Role", "Rating"]]

Output:

      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100


问:
How to compare elements in a list without for loop?
I have a list: R = ['123', '1854', '000'] and I want to make sure that all the elements on it have the same length, but I don't want to use a for loop.

I tried this:

```<code>if R[::] !== R[::]:
   print('false')
</code>```

Obviously it does not work.

It's possible to do it without a for loop?

And How to put it as an AssertError like: assert ..., 'False'? if the list elements are length different then raise an AssertError.

答:
You should probably make a function and call that, but you could do something like this</p>

```<code>if len(set(map(len,R))) != 1:
    # Do something, there exists elements of different sizes
</code>```

Body:
I have a list: R = ['123', '1854', '000'] and I want to make sure that all the elements on it have the same length, but I don't want to use a for loop.

I tried this:

if R[::] !== R[::]:
   print('false')

Obviously it does not work.

It's possible to do it without a for loop?

And How to put it as an AssertError like: assert ..., 'False'? if the list elements are length different then raise an AssertError.

Body:
You should probably make a function and call that, but you could do something like this

if len(set(map(len,R))) != 1:
    # Do something, there exists elements of different sizes


问:
Using loadTable with correct types in typescript with p5js
I am loading a csv file using the p5.js function, loadTable. It seems that its not reading the csv file at all, maybe i am missing something in my approach.

```<code>  let data: p5.Table;

  p.preload = () => {
    let csv_file: string = "./sample.csv";
    let csv_type: string = "csv";
    let csv_header: string = "header";

    data = (p as any).loadTable(csv_file, csv_type, csv_header);

    console.log("data ", data.getRowCount());
  };
</code>```

It works fine in javascipt as below.

```<code>let data;

// preload table data
function preload() {
  data = loadTable(
    'sample.csv',
        'csv',
        'header');
}
</code>```

答:
ah, i figure it out. The issue was not related to typescript. It was browser cors policy.

Something like this works fine in typescript + p5.js,

```<code>p.preload = () => {
    data = (p as any).loadTable("http://127.0.0.1:34568/", "csv", "header");
  };
</code>```

Where i hosted my own csv on a local web server (http://127.0.0.1:34568/) using cpprestSDK. Or even host the file over some url like github and read from there while in development. That worked fine as well.

Other option i found was, browser-sync. https://github.com/processing/p5.js/wiki/Local-server#node-http-server-2nd-option. It did worked for some people, for me, chrome still gave cors error from browser-sync.

Body:
I am loading a csv file using the p5.js function, loadTable. It seems that its not reading the csv file at all, maybe i am missing something in my approach.

  let data: p5.Table;

  p.preload = () => {
    let csv_file: string = "./sample.csv";
    let csv_type: string = "csv";
    let csv_header: string = "header";

    data = (p as any).loadTable(csv_file, csv_type, csv_header);

    console.log("data ", data.getRowCount());
  };

It works fine in javascipt as below.

let data;

// preload table data
function preload() {
  data = loadTable(
    'sample.csv',
        'csv',
        'header');
}

Body:
ah, i figure it out. The issue was not related to typescript. It was browser cors policy.

Something like this works fine in typescript + p5.js,

p.preload = () => {
    data = (p as any).loadTable("http://127.0.0.1:34568/", "csv", "header");
  };

Where i hosted my own csv on a local web server (http://127.0.0.1:34568/) using cpprestSDK. Or even host the file over some url like github and read from there while in development. That worked fine as well.

Other option i found was, browser-sync. https://github.com/processing/p5.js/wiki/Local-server#node-http-server-2nd-option. It did worked for some people, for me, chrome still gave cors error from browser-sync.


问:
How to print stdout & stderr of failed job in GNU parallel?
I'm invoking GNU parallel on a bunch of commands using parallel --keep-order --line-buffer --halt 2. Every once in a while one of the commands fails, and GNU parallel prints:

```<code> parallel: This job failed:
    <failing command comes here>
</code>```

Is there any way to to print the stdout and stderr of ONLY the failed job whenever this happens?

答:
neno (no-error-no-output) does that:

```<code>neno 'echo stdout; echo stderr >&2; false'
neno 'echo stdout; echo stderr >&2; true'
</code>```

https://gitlab.com/ole.tange/tangetools/-/tree/master/neno

So:

```<code>parallel --halt 2 neno ...
</code>```

Body:
I'm invoking GNU parallel on a bunch of commands using parallel --keep-order --line-buffer --halt 2. Every once in a while one of the commands fails, and GNU parallel prints:

 parallel: This job failed:
    <failing command comes here>

Is there any way to to print the stdout and stderr of ONLY the failed job whenever this happens?

Body:
neno (no-error-no-output) does that:

neno 'echo stdout; echo stderr >&2; false'
neno 'echo stdout; echo stderr >&2; true'

https://gitlab.com/ole.tange/tangetools/-/tree/master/neno

So:

parallel --halt 2 neno ...


问:
Redis-cli - Selecting which instance?
I'm currently running multiple redis instances on one box. Each have their own config, init.d, and listen on different ports. My application(s) have no problem connecting via the redis clients, but I'd like to be able to connect to each one using redis-cli. I couldn't find any information on $:redis-cli [options] in either the redis-doc or on redis.io. Any ideas?</p>

答:
You can specify the server host and port using -h and -p parameters. E.g.:</p>

```<code>redis-cli -h 127.0.0.1 -p 6379
</code>```

Title: Redis-cli - Selecting which instance?

Body:
You can specify the server host and port using -h and -p parameters. E.g.:

redis-cli -h 127.0.0.1 -p 6379


问:
SQL query results are duplicating
Using below query

SELECT *
            FROM Customer, Orders, Orderline, Product

Results with 6500 rows as a result instead of 30 rows. I'm using SQL Server Management Studio

```<code>Customer

----------------------------------------
CustomerNo CustomerName CustomerAddress
----------------------------------------

1          Harry        19 mousemat

2          Potter       98a speakers

Orders
-------------------------------
OrderID CustomerNo OrderDate
-------------------------------

 1       1         12/3/1992

 2       2         13/5/1997

OrderLine
-----------------------------
OrderID ProductID ProductQty
-----------------------------
1       100       27

2       101       30

Products
-----------------------------------
ProductID ProductDesc ProductPrice
-----------------------------------

100       Blue        0.13

101       Yellow      1.21
</code>```

答:
In case the query is just SELECT * FROM Customer, Orders, Orderline, Product then you made an "implicit" CROSS JOIN or cartesian join in your query. When using multiple tables in your query you should specify JOIN - how you want to connect them.

```<code>SELECT *
FROM Customer as c
INNER JOIN Orders as o
ON c.CustomerNo = o.CustomerNo
INNER JOIN Orderline as ol
ON o.OrderID = ol.OrderID
INNER JOIN Product as p
ON ol.ProductID = p.ProductID
</code>```

Title: SQL query results are duplicating

Body:
Using below query

SELECT *
            FROM Customer, Orders, Orderline, Product

Results with 6500 rows as a result instead of 30 rows. I'm using SQL Server Management Studio

Customer

----------------------------------------
CustomerNo CustomerName CustomerAddress
----------------------------------------

1          Harry        19 mousemat

2          Potter       98a speakers

Orders
-------------------------------
OrderID CustomerNo OrderDate
-------------------------------

 1       1         12/3/1992

 2       2         13/5/1997

OrderLine
-----------------------------
OrderID ProductID ProductQty
-----------------------------
1       100       27

2       101       30

Products
-----------------------------------
ProductID ProductDesc ProductPrice
-----------------------------------

100       Blue        0.13

101       Yellow      1.21

Body:
In case the query is just SELECT * FROM Customer, Orders, Orderline, Product then you made an "implicit" CROSS JOIN or cartesian join in your query. When using multiple tables in your query you should specify JOIN - how you want to connect them.

SELECT *
FROM Customer as c
INNER JOIN Orders as o
ON c.CustomerNo = o.CustomerNo
INNER JOIN Orderline as ol
ON o.OrderID = ol.OrderID
INNER JOIN Product as p
ON ol.ProductID = p.ProductID


问:
Custom Database Type in ActiveRecord
I am using Rails 3.1.1 with PostgreSQL 9.1 and the earthdistance module.
To be able to calculate the distance between different locations properly, I have setup a column with the earth type in my branches table.

The problem I am experiencing now is that my Rails application that uses this table does not understand the earth type and thus I am getting this in my db/schema.rb:

```# Could not dump table "branches" because of following StandardError
#   Unknown type 'earth' for column 'location'```

This is problematic since now I can't create my test database from the schema.rb.

How can I add this type to AR or make it ignore that column?

答:
For anyones who comes to this page, someone has implemented this in a gem easy to use.

This is how your migration and model files will look like, respectively

```<code># migration
class CreatePerson < ActiveRecord::Migration
  def change
    create_enum :mood, %w(happy great never_better)

    create_table :person do |t|
      t.enum :person_mood, enum_name: :mood
    end
  end
end

# model
class Person < ActiveRecord::Base
  enum mood: { happy: 'happy', great: 'great', never_better: 'never_better' }
end
</code>```

https://github.com/bibendi/activerecord-postgres_enum

Title: Custom Database Type in ActiveRecord

Body:
I am using Rails 3.1.1 with PostgreSQL 9.1 and the earthdistance module.
To be able to calculate the distance between different locations properly, I have setup a column with the earth type in my branches table.

The problem I am experiencing now is that my Rails application that uses this table does not understand the earth type and thus I am getting this in my db/schema.rb:

# Could not dump table "branches" because of following StandardError
#   Unknown type 'earth' for column 'location'

This is problematic since now I can't create my test database from the schema.rb.

How can I add this type to AR or make it ignore that column?

Body:
For anyones who comes to this page, someone has implemented this in a gem easy to use.

This is how your migration and model files will look like, respectively

# migration
class CreatePerson < ActiveRecord::Migration
  def change
    create_enum :mood, %w(happy great never_better)

    create_table :person do |t|
      t.enum :person_mood, enum_name: :mood
    end
  end
end

# model
class Person < ActiveRecord::Base
  enum mood: { happy: 'happy', great: 'great', never_better: 'never_better' }
end

https://github.com/bibendi/activerecord-postgres_enum


问:
How to fix broken links wordpress web config rewrite index.php broke site links error 404
Background:  Website was created in WordPress 3.5.1 on Windows Server 2008 r2.  Original developer is no longer in business.

Website address is http://wordpress.sunwireless.co/wordpress/
Website addressing has always been awkward, but website worked until morning of May 22, 2020 when I made changes.
Objective: was to change the address link for a web-page on our website.  Public Sector/CTF address was to be changed from
http://wordpress.sunwireless.co/wordpress/?page_id=478,
to
http://wordpress.sunwireless.co/wordpress/ctf

Procedure I followed:
1.  Log in to Wordpress and change the link address using Permalink field, on Pages tab, for page CTF.
2.

Clicked UPDATE but wordpress gave error message including:  ““If the root directory of your site were writable, we could do this automatically, but it isn’t so this is the url rewrite rule you should have in your web.config file. Create a new file, called web.config in the root directory of your site. Click in the field and press CTRL + a to select all. Then insert this code into the web.config file.”
Wordpress recommended I use this code for web.config:

```<code><configuration>
    <system.webServer>
        <rewrite>
            <rules>
            <rule name="wordpress" patternSyntax="Wildcard">
                <match url="*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                <action type="Rewrite" url="index.php" />
            </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

Inserted code web.config file, with code above  in wwwroot directory on server.  Restarted server.

Website home page is still accessable, but all pages below home, ‘About us’, ‘CTF’, etc. respond with error 403 FORBIDDEN.

Searched on the error and found another web.config file recommendation, from 2015 on hostmysite, for wordpress sites hosted on Windows Server 2008:

Inserted this code above in web.config file, in wwwroot directory.

Website home page is still accessable, but all pages below home, ‘About us’, ‘CTF’, etc. respond with error 404 NOT FOUND.

Old web-site is not available.  How can I make the links work again?

Response to question asked below: "From where did you get that rule?".  The rule came from the WordPress content management system.

答:
I found this was caused by a configuration change I made in Wordpress, but had forgotten:
I had reconfigured from Default to Custom Structure Permalink Settings.

After reverting to Default Permalink Settings, and emptying the browser cache, the site links operated as expected.

Sorry for any confusion.

Body:
Background:  Website was created in WordPress 3.5.1 on Windows Server 2008 r2.  Original developer is no longer in business.

Website address is http://wordpress.sunwireless.co/wordpress/
Website addressing has always been awkward, but website worked until morning of May 22, 2020 when I made changes.
Objective: was to change the address link for a web-page on our website.  Public Sector/CTF address was to be changed from
http://wordpress.sunwireless.co/wordpress/?page_id=478,
to
http://wordpress.sunwireless.co/wordpress/ctf

Procedure I followed:
1.  Log in to Wordpress and change the link address using Permalink field, on Pages tab, for page CTF.
2.

Clicked UPDATE but wordpress gave error message including:  ““If the root directory of your site were writable, we could do this automatically, but it isn’t so this is the url rewrite rule you should have in your web.config file. Create a new file, called web.config in the root directory of your site. Click in the field and press CTRL + a to select all. Then insert this code into the web.config file.”
Wordpress recommended I use this code for web.config:

<configuration>
    <system.webServer>
        <rewrite>
            <rules>
            <rule name="wordpress" patternSyntax="Wildcard">
                <match url="*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                <action type="Rewrite" url="index.php" />
            </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Inserted code web.config file, with code above  in wwwroot directory on server.  Restarted server.

Website home page is still accessable, but all pages below home, ‘About us’, ‘CTF’, etc. respond with error 403 FORBIDDEN.

Searched on the error and found another web.config file recommendation, from 2015 on hostmysite, for wordpress sites hosted on Windows Server 2008:

Inserted this code above in web.config file, in wwwroot directory.

Website home page is still accessable, but all pages below home, ‘About us’, ‘CTF’, etc. respond with error 404 NOT FOUND.

Old web-site is not available.  How can I make the links work again?

Response to question asked below: "From where did you get that rule?".  The rule came from the WordPress content management system.


问:
Context Management in Bot Framework - Node JS
in the main dialog, I have used this to get the details of the user activity and session ID stepContext.context._activity
and I am able to store the data in JSON format,
I want to know how to use the previous text of the user for the next query if there is no entity present in that and it should work for multiple users, not for a single user.

答:
The location of the user's input varies depending on the option provided to them. Simple text input is available in the stepContext.context.activity.text field. However, the user's returned value could, for example, exist in:

stepContext.result, if a hero card is used

stepContext.options, if a value is forwarded on from a previous step or action

stepContext.context.activity.text, if a suggested action is used

stepContext.context.activity.value, if a postBack is returned

There are a few other possibilities. Referencing the docs is a good place to start as are the BotBuilder-Samples for getting a grasp on all the possibilities. Don't be averse to inspecting the stepContext to see how it is populated and with what.

async firstStep(stepContext) {
    await stepContext.context.sendActivity('Type something...');
    return { status: DialogTurnStatus.waiting };
}

async secondStep(stepContext) {
    const result = stepContext.context.activity.text;
    return await stepContext.context.sendActivity(`You said: ${ result }`);
```

Hope of help!

Body:
The location of the user's input varies depending on the option provided to them. Simple text input is available in the stepContext.context.activity.text field. However, the user's returned value could, for example, exist in:

stepContext.result, if a hero card is used

stepContext.options, if a value is forwarded on from a previous step or action

stepContext.context.activity.text, if a suggested action is used

stepContext.context.activity.value, if a postBack is returned

There are a few other possibilities. Referencing the docs is a good place to start as are the BotBuilder-Samples for getting a grasp on all the possibilities. Don't be averse to inspecting the stepContext to see how it is populated and with what.

async firstStep(stepContext) {
    await stepContext.context.sendActivity('Type something...');
    return { status: DialogTurnStatus.waiting };
}

async secondStep(stepContext) {
    const result = stepContext.context.activity.text;
    return await stepContext.context.sendActivity(`You said: ${ result }`);

Hope of help!


问:
Tensorflow | ValueError: No gradients provided for any variable
I am trying to do a time series prediction with Bitcoin. I loaded my data and scaled it. When I tried to fit the data. It returns this error. There are others questions regarding the same error, but it doesn't apply to me.

Code:

```<code>import tensorflow as tf
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler

# Load Data

df = pd.read_csv("exampledata.csv", header=None, names=[
                 'Date', 'Close'], parse_dates=['Date'])
print(df.head())
print(df.shape)

# The testing data
test = df.shift(-4)

# Preprocessing Data

target = df.pop('Date')

scaler = MinMaxScaler(feature_range=(0, 1))
print(scaler.fit_transform(df))

# Creating The Model

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(50, activation='relu', input_shape=(1,)))
# This is to reshape the output for LSTM
model.add(tf.keras.layers.Lambda(
    lambda x: tf.expand_dims(model.output, axis=-1)))
# I don't understand input_shape that much, I put 1 because I will give the model 1 column of input data
model.add(tf.keras.layers.LSTM(100, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=0.2))
model.add(tf.keras.layers.Dense(1, activation='relu'))
model.compile(optimizer='adam', loss='mean_absolute_error',
              metrics=['accuracy'])
model.summary()

# Training Model

model.fit(df, epochs=100)
</code>```

And here are the errors:

```<code>Traceback (most recent call last):
  File "example.py", line 39, in <module>
    model.fit(df, epochs=100)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 848, in fit
    tmp_logs = train_function(iterator)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 580, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 627, in _call
    self._initialize(args, kwds, add_initializers_to=initializers)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 506, in _initialize
    *args, **kwds))
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2446, in _get_concrete_function_internal_garbage_collected
    graph_function, _, _ = self._maybe_define_function(args, kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2777, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2667, in _create_graph_function
    capture_by_value=self._capture_by_value),
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 981, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 441, in wrapped_fn
    return weak_wrapped_fn().__wrapped__(*args, **kwds)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 968, in wrapper
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:541 train_step  **
        self.trainable_variables)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:1804 _minimize
        trainable_variables))
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py:521 _aggregate_gradients
        filtered_grads_and_vars = _filter_grads(grads_and_vars)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py:1219 _filter_grads
        ([v.name for _, v in grads_and_vars],))

    ValueError: No gradients provided for any variable: ['dense/kernel:0', 'dense/bias:0', 'lstm/lstm_cell/kernel:0', 'lstm/lstm_cell/recurrent_kernel:0', 'lstm/lstm_cell/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0'].
</code>```

Here is my data (partially) looks like (I scaled it):

```<code>[[0.29738429]
 [0.27614102]
 [0.39392314]
 [0.        ]
 [1.        ]
 [0.97227646]]
</code>```

答:
redefine your Lambda layer in this way

```<code>model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(50, activation='relu', input_shape=(1,)))
model.add(tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1))) # <======
model.add(tf.keras.layers.LSTM(100, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=0.2))
model.add(tf.keras.layers.Dense(1, activation='relu'))
model.compile(optimizer='adam', loss='mean_absolute_error')
model.summary()

model.fit(np.random.uniform(0,1, (100,1)), np.random.uniform(0,1, 100), epochs=10)
</code>```

I add a full example based on your question. we are using the value at time t to predict the value at time t+1

```<code># substitute this with your data
df = pd.DataFrame({'Date':np.random.randint(0,100, 100),
                   'Close':np.random.uniform(0,1, 100)})

len_train = int(len(df)*0.8) # train size
# split train test
X_train = df.Close.values[:len_train]
X_test = df.Close.values[len_train:]

scaler = MinMaxScaler(feature_range=(0, 1))
X_train = scaler.fit_transform(X_train.reshape(-1, 1))
X_test = scaler.transform(X_test.reshape(-1, 1))

# create target as the next day value
y_train = X_train[1:]
X_train = X_train[:-1]
y_test = X_test[1:]
X_test = X_test[:-1]

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(50, activation='relu', input_shape=(1,)))
model.add(tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1)))
model.add(tf.keras.layers.LSTM(100, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=0.2))
model.add(tf.keras.layers.Dense(1))
model.compile(optimizer='adam', loss='mean_absolute_error')
model.summary()

model.fit(X_train, y_train, epochs=10)

pred = model.predict(X_test)
</code>```

Body:
I am trying to do a time series prediction with Bitcoin. I loaded my data and scaled it. When I tried to fit the data. It returns this error. There are others questions regarding the same error, but it doesn't apply to me.

Code:

import tensorflow as tf
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler

# Load Data

df = pd.read_csv("exampledata.csv", header=None, names=[
                 'Date', 'Close'], parse_dates=['Date'])
print(df.head())
print(df.shape)

# The testing data
test = df.shift(-4)

# Preprocessing Data

target = df.pop('Date')

scaler = MinMaxScaler(feature_range=(0, 1))
print(scaler.fit_transform(df))

# Creating The Model

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(50, activation='relu', input_shape=(1,)))
# This is to reshape the output for LSTM
model.add(tf.keras.layers.Lambda(
    lambda x: tf.expand_dims(model.output, axis=-1)))
# I don't understand input_shape that much, I put 1 because I will give the model 1 column of input data
model.add(tf.keras.layers.LSTM(100, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=0.2))
model.add(tf.keras.layers.Dense(1, activation='relu'))
model.compile(optimizer='adam', loss='mean_absolute_error',
              metrics=['accuracy'])
model.summary()

# Training Model

model.fit(df, epochs=100)

And here are the errors:

Traceback (most recent call last):
  File "example.py", line 39, in <module>
    model.fit(df, epochs=100)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 848, in fit
    tmp_logs = train_function(iterator)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 580, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 627, in _call
    self._initialize(args, kwds, add_initializers_to=initializers)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 506, in _initialize
    *args, **kwds))
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2446, in _get_concrete_function_internal_garbage_collected
    graph_function, _, _ = self._maybe_define_function(args, kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2777, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2667, in _create_graph_function
    capture_by_value=self._capture_by_value),
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 981, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 441, in wrapped_fn
    return weak_wrapped_fn().__wrapped__(*args, **kwds)
  File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 968, in wrapper
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:541 train_step  **
        self.trainable_variables)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:1804 _minimize
        trainable_variables))
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py:521 _aggregate_gradients
        filtered_grads_and_vars = _filter_grads(grads_and_vars)
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py:1219 _filter_grads
        ([v.name for _, v in grads_and_vars],))

    ValueError: No gradients provided for any variable: ['dense/kernel:0', 'dense/bias:0', 'lstm/lstm_cell/kernel:0', 'lstm/lstm_cell/recurrent_kernel:0', 'lstm/lstm_cell/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0'].

Here is my data (partially) looks like (I scaled it):

[[0.29738429]
 [0.27614102]
 [0.39392314]
 [0.        ]
 [1.        ]
 [0.97227646]]

Body:
redefine your Lambda layer in this way

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(50, activation='relu', input_shape=(1,)))
model.add(tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1))) # <======
model.add(tf.keras.layers.LSTM(100, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=0.2))
model.add(tf.keras.layers.Dense(1, activation='relu'))
model.compile(optimizer='adam', loss='mean_absolute_error')
model.summary()

model.fit(np.random.uniform(0,1, (100,1)), np.random.uniform(0,1, 100), epochs=10)

I add a full example based on your question. we are using the value at time t to predict the value at time t+1

# substitute this with your data
df = pd.DataFrame({'Date':np.random.randint(0,100, 100),
                   'Close':np.random.uniform(0,1, 100)})

len_train = int(len(df)*0.8) # train size
# split train test
X_train = df.Close.values[:len_train]
X_test = df.Close.values[len_train:]

scaler = MinMaxScaler(feature_range=(0, 1))
X_train = scaler.fit_transform(X_train.reshape(-1, 1))
X_test = scaler.transform(X_test.reshape(-1, 1))

# create target as the next day value
y_train = X_train[1:]
X_train = X_train[:-1]
y_test = X_test[1:]
X_test = X_test[:-1]

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(50, activation='relu', input_shape=(1,)))
model.add(tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1)))
model.add(tf.keras.layers.LSTM(100, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=0.2))
model.add(tf.keras.layers.Dense(1))
model.compile(optimizer='adam', loss='mean_absolute_error')
model.summary()

model.fit(X_train, y_train, epochs=10)

pred = model.predict(X_test)


问:
Python Web Framework for Small Team
I have 4 days off and I will use this time to rewrite our RoR (Ruby on Rails) Application in a python web framework just for fun ;-] (and why not make the switch, RoR is great but keep changing all the time, can be exhausting.)

I don't know the python web framework very well, I've glad web.py, django, cherry.py, pylons/pyramid and few others. Our requirements are (put everything can be irrelevant) :

MVC (Strict or not)

Small Team (2-3 people included one designer)

Fun to use

REST support

Multilevel caching (DB query, page cache)

Nginx Support (X-Accel-Redirect File Download)

Heavy traffic (1,200,000 ~ views)

Urls rewrting (Multi-domains support not only subdomain)

Not a problem if it's not hype

Not a problem if there is no plugins

Either SQL or NOSQL (can be fun to try NOSQL)

So what you would advise ?

答: I would recommend DJANGO or TurboGears.</p>

Title: Python Web Framework for Small Team

Body: I would recommend DJANGO or TurboGears.


问:
Angular 9 -- Multiple Children inside Parent
Can someone explain to me, why the appropriate child switch won't update properly?
Click on the second child and the first child updates, but the console shows the correct method being called. Is it not possible to call the same child component in the parent like I am?

https://stackblitz.com/edit/angular-ivy-ch65ks

答:
https://stackblitz.com/edit/angular-ivy-ch65ks

Answer added here:
child.compontent.html

```<code><input type="checkbox" id="toggle-button-checkbox_{{inputId}}" [disabled]="isDisabled">
<label class="toggle-button-switch" for="toggle-button-checkbox_{{inputId}}" (click)="toggleCheck()"></label>
<div class="toggle-button-text">
    <div class="toggle-button-text-on">{{textOne}}</div>
    <div class="toggle-button-text-off">{{textTwo}}</div>
</div>
</code>```

child.component.ts

```<code>import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
   inputs: ['textOne', 'textTwo', 'checkedValue', 'isDisabled','inputId'],
  outputs: ['checkToEmit']
})
export class ChildComponent implements OnInit {
checkToEmit = new EventEmitter<boolean>();
  textOne: string;
  textTwo: string;
  inputId;
  checkedValue: boolean;
  isDisabled: boolean = false;
  constructor() { }
  ngOnInit(): void {
    console.log(this.checkedValue);
   }
  toggleCheck() {
    this.checkedValue = !this.checkedValue;
    this.checkToEmit.emit(this.checkedValue);
  }
}
</code>```

parent.component.html

```<code><app-child name="one" textOne="Yes" textTwo="No" [checkedValue]="test1" (checkToEmit)="test1Checked($event)" inputId="1">
</app-child>

<app-child name="two" textOne="Yes" textTwo="No" [checkedValue]="test2" (checkToEmit)="test2Checked($event)" inputId="2">
</app-child>
</code>```

Body:
https://stackblitz.com/edit/angular-ivy-ch65ks

Answer added here:
child.compontent.html

<input type="checkbox" id="toggle-button-checkbox_{{inputId}}" [disabled]="isDisabled">
<label class="toggle-button-switch" for="toggle-button-checkbox_{{inputId}}" (click)="toggleCheck()"></label>
<div class="toggle-button-text">
    <div class="toggle-button-text-on">{{textOne}}</div>
    <div class="toggle-button-text-off">{{textTwo}}</div>
</div>

child.component.ts

import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
   inputs: ['textOne', 'textTwo', 'checkedValue', 'isDisabled','inputId'],
  outputs: ['checkToEmit']
})
export class ChildComponent implements OnInit {
checkToEmit = new EventEmitter<boolean>();
  textOne: string;
  textTwo: string;
  inputId;
  checkedValue: boolean;
  isDisabled: boolean = false;
  constructor() { }
  ngOnInit(): void {
    console.log(this.checkedValue);
   }
  toggleCheck() {
    this.checkedValue = !this.checkedValue;
    this.checkToEmit.emit(this.checkedValue);
  }
}

parent.component.html

<app-child name="one" textOne="Yes" textTwo="No" [checkedValue]="test1" (checkToEmit)="test1Checked($event)" inputId="1">
</app-child>

<app-child name="two" textOne="Yes" textTwo="No" [checkedValue]="test2" (checkToEmit)="test2Checked($event)" inputId="2">
</app-child>


问:
PHP DOMDocument And DOMXpath
I am trying to find the last paragraph tag in a block of HTML using DOMDocument/DOMXpath but can't seem to figure it out.

```<code># Create DOMDocument Object
        $dom = new DOMDocument;
        # Load HTML into DomDocument Object
        $dom->loadHTML($data['component2']);

        # Creat DOMXPath Object and load DOMDocument Object into XPath for magical goodness
        $xpath = new DOMXPath($dom);

        # Loop through each comment node
        foreach($xpath->query('//p') as $node) {
            // krumo($node->parentNode);
            print_r($node->parentNode->lastChild);
        }
        exit();
</code>```

The print_r returns an empty DOMText Object ( )... any idea on how to find the last paragraph in a block of HTML using DOMDocument/DOMXPath?

Working Code:

```<code># Create DOMDocument Object
        $dom = new DOMDocument;
        $dom->preserveWhiteSpace = false;
        # Load HTML into DomDocument Object
        $dom->loadHTML($data['component2']);

        # Creat DOMXPath Object and load DOMDocument Object into XPath for magical goodness
        $xpath = new DOMXPath($dom);
        $q = $xpath->query('//div[@class="t_content"]/p[last()]');

        $data['component2'] = str_replace(utf8_decode($q->item(0)->nodeValue), "", $data['component2']);
</code>```

答:
Use this instead:</p>

```<code> print_r($node->parentNode->lastChild->nodeValue);
</code>```

Title: PHP DOMDocument And DOMXpath

Body:
I am trying to find the last paragraph tag in a block of HTML using DOMDocument/DOMXpath but can't seem to figure it out.

# Create DOMDocument Object
        $dom = new DOMDocument;
        # Load HTML into DomDocument Object
        $dom->loadHTML($data['component2']);

        # Creat DOMXPath Object and load DOMDocument Object into XPath for magical goodness
        $xpath = new DOMXPath($dom);

        # Loop through each comment node
        foreach($xpath->query('//p') as $node) {
            // krumo($node->parentNode);
            print_r($node->parentNode->lastChild);
        }
        exit();

The print_r returns an empty DOMText Object ( )... any idea on how to find the last paragraph in a block of HTML using DOMDocument/DOMXPath?

Working Code:

# Create DOMDocument Object
        $dom = new DOMDocument;
        $dom->preserveWhiteSpace = false;
        # Load HTML into DomDocument Object
        $dom->loadHTML($data['component2']);

        # Creat DOMXPath Object and load DOMDocument Object into XPath for magical goodness
        $xpath = new DOMXPath($dom);
        $q = $xpath->query('//div[@class="t_content"]/p[last()]');

        $data['component2'] = str_replace(utf8_decode($q->item(0)->nodeValue), "", $data['component2']);

Body:
Use this instead:

 print_r($node->parentNode->lastChild->nodeValue);


问:
Battleship game: place ships randomly in java
I am writing the code of the game. How can I do this board? </p>

```<code>It should be like this example.

  0 1 2 3 4 5 6 7 8 9
0 . . . . . . . . . .
1 . . o . . . . . . .
2 . . . . . . . o . .
3 . . . . . . . o . .
4 . . . o o . . o . .
5 . . . . . . . o . o
6 . . . . . . . . . o
7 . o o o . . . . . o
8 . . . . . . . . . o
9 . . . . . . . . . o
</code>```

答:
You may check this solution:

```<code>static int FIELD_SIZE = 10;

static void fillField() {
    Random random = new Random();
    int[][] field = new int[FIELD_SIZE][FIELD_SIZE];
    for (int i = 5; i > 0; i--) {
        //System.out.println("Placing ship with length: " + i);
        // start point of the ship and direction
        int x = random.nextInt(field.length);
        int y = random.nextInt(field.length);
        boolean vertical = random.nextBoolean();

        // correct start point so that the ship could fit in the field
        if (vertical) {
            if (y + i > FIELD_SIZE) {
                y -= i;
            }
        } else if (x + i > FIELD_SIZE) {
            x -= i;
        }
        //System.out.println("Start point: " + x + ", " + y + "; dir: " + (vertical ? "VERTICAL" : "HORIZONTAL"));
        boolean isFree = true;
        // check for free space
        if (vertical) {
            for (int m = y; m < y + i; m++) {
                if (field[m][x] != 0) {
                    //System.out.println("Neighbors found, " + x + ", " + m);
                    isFree = false;
                    break;
                }
            }
        } else {
            for (int n = x; n < x + i; n++) {
                if (field[y][n] != 0) {
                    //System.out.println("Neighbors found, " + n + ", " + y);
                    isFree = false;
                    break;
                }
            }
        }
        if (!isFree) {  // no free space found, retry
            i++;
            continue;
        }

        // fill in the adjacent cells
        if (vertical) {
            for (int m = Math.max(0, x - 1); m < Math.min(FIELD_SIZE, x + 2); m++) {
                for (int n = Math.max(0, y - 1); n < Math.min(FIELD_SIZE, y + i + 1); n++) {
                    field[n][m] = 9;
                }
            }
        } else {
            for (int m = Math.max(0, y - 1); m < Math.min(FIELD_SIZE, y + 2); m++) {
                for (int n = Math.max(0, x - 1); n < Math.min(FIELD_SIZE, x + i + 1); n++) {
                    field[m][n] = 9;
                }
            }
        }
        // fill in the ship cells
        for (int j = 0; j < i; j++) {
            field[y][x] = i;
            if (vertical) {
                y++;
            } else {
                x++;
            }
        }
    }
    // build char map
    char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
    for (int i = 0; i < FIELD_SIZE; i++) {
        for (int j = 0; j < FIELD_SIZE; j++) {
            map[i][j] = field[i][j] == 0 || field[i][j] == 9 ? '.' : 'O';
        }
    }
    // print map
    Arrays.stream(map)
          .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
}

</code>```

Output (example):

```<code>[. O O O O O . . . .]
[. . . . . . . . . .]
[. . . . . . . . . .]
[. . O . . . . . . .]
[. . . . . . . . . .]
[. . . . . . . . O .]
[. O O O O . . . O .]
[. . . . . . O . . .]
[. . . . . . O . . .]
[. . . . . . O . . .]
</code>```

Body:
I am writing the code of the game. How can I do this board?

It should be like this example.

  0 1 2 3 4 5 6 7 8 9
0 . . . . . . . . . .
1 . . o . . . . . . .
2 . . . . . . . o . .
3 . . . . . . . o . .
4 . . . o o . . o . .
5 . . . . . . . o . o
6 . . . . . . . . . o
7 . o o o . . . . . o
8 . . . . . . . . . o
9 . . . . . . . . . o

Body:
You may check this solution:

static int FIELD_SIZE = 10;

static void fillField() {
    Random random = new Random();
    int[][] field = new int[FIELD_SIZE][FIELD_SIZE];
    for (int i = 5; i > 0; i--) {
        //System.out.println("Placing ship with length: " + i);
        // start point of the ship and direction
        int x = random.nextInt(field.length);
        int y = random.nextInt(field.length);
        boolean vertical = random.nextBoolean();

        // correct start point so that the ship could fit in the field
        if (vertical) {
            if (y + i > FIELD_SIZE) {
                y -= i;
            }
        } else if (x + i > FIELD_SIZE) {
            x -= i;
        }
        //System.out.println("Start point: " + x + ", " + y + "; dir: " + (vertical ? "VERTICAL" : "HORIZONTAL"));
        boolean isFree = true;
        // check for free space
        if (vertical) {
            for (int m = y; m < y + i; m++) {
                if (field[m][x] != 0) {
                    //System.out.println("Neighbors found, " + x + ", " + m);
                    isFree = false;
                    break;
                }
            }
        } else {
            for (int n = x; n < x + i; n++) {
                if (field[y][n] != 0) {
                    //System.out.println("Neighbors found, " + n + ", " + y);
                    isFree = false;
                    break;
                }
            }
        }
        if (!isFree) {  // no free space found, retry
            i++;
            continue;
        }

        // fill in the adjacent cells
        if (vertical) {
            for (int m = Math.max(0, x - 1); m < Math.min(FIELD_SIZE, x + 2); m++) {
                for (int n = Math.max(0, y - 1); n < Math.min(FIELD_SIZE, y + i + 1); n++) {
                    field[n][m] = 9;
                }
            }
        } else {
            for (int m = Math.max(0, y - 1); m < Math.min(FIELD_SIZE, y + 2); m++) {
                for (int n = Math.max(0, x - 1); n < Math.min(FIELD_SIZE, x + i + 1); n++) {
                    field[m][n] = 9;
                }
            }
        }
        // fill in the ship cells
        for (int j = 0; j < i; j++) {
            field[y][x] = i;
            if (vertical) {
                y++;
            } else {
                x++;
            }
        }
    }
    // build char map
    char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
    for (int i = 0; i < FIELD_SIZE; i++) {
        for (int j = 0; j < FIELD_SIZE; j++) {
            map[i][j] = field[i][j] == 0 || field[i][j] == 9 ? '.' : 'O';
        }
    }
    // print map
    Arrays.stream(map)
          .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
}

Output (example):

[. O O O O O . . . .]
[. . . . . . . . . .]
[. . . . . . . . . .]
[. . O . . . . . . .]
[. . . . . . . . . .]
[. . . . . . . . O .]
[. O O O O . . . O .]
[. . . . . . O . . .]
[. . . . . . O . . .]
[. . . . . . O . . .]


问:
i have issues regarding react state
Hi i have been building a sorting algorithms visualization it works so far but i have a doubt regarding state object.
consider the below code:

```<code>import React,{Component} from 'react';
import getMergeSortAnimations from './Person/Person';
import bubbleSortAnimations from './Person/BubbleSort';
import './App.css';

class App extends Component{

    state = {
    array: [],
   bar_width:2
 };

componentDidMount() {

  this.generateArray();
}

generateArray = ()=> {
  const array = [];

 let val = document.querySelector('#size').value;

 if(val<=10)
 {
   this.setState({bar_width:8});
 }
 else if(val<=20 && val>10)
  this.setState({bar_width:7});
else if(val<=50 && val>20)
   this.setState({bar_width:6});
else if(val<=100 && val>50)
  this.setState({bar_width:5});
else if(val<=150 && val>100)
  this.setState({bar_width:3});
else
   this.setState({bar_width:2});

 for (let i = 0; i < val; i++) {
   array.push(this.randomIntFromInterval(5, 450));
   }
 this.setState({array});

  }

 randomIntFromInterval = (min, max)=> {

  return Math.floor(Math.random() * (max - min + 1) + min);
 }
 mergeSort = ()=>{
   let t ;
   console.log(this.state);

   const animations = getMergeSortAnimations(this.state.array);
   console.log(this.state);
   for (let i = 0; i < animations.length; i++) {

   const arrayBars = document.getElementsByClassName('element');

   const isColorChange = i % 3 !== 2;
   if (isColorChange) {
     const [barOneIdx, barTwoIdx] = animations[i];
     const barOneStyle = arrayBars[barOneIdx].style;
     const barTwoStyle = arrayBars[barTwoIdx].style;
     const color = i % 3 === 0 ? 'red' : '#007bff';
     setTimeout(() => {
       barOneStyle.backgroundColor = color;
       barTwoStyle.backgroundColor = color;
     }, i*10);
   } else {
     setTimeout(() => {
       const [barOneIdx, newHeight] = animations[i];
       const barOneStyle = arrayBars[barOneIdx].style;
       barOneStyle.height = `${newHeight}px`;
     }, i*10);
   }

 }

}

render() {

 return (
  <div>
   <header>
      <input className="slider" onChange={this.generateArray}  type="range" min="5" max="200"
 id='size'/>
      <nav>
       <ul>
         <li><button onClick={this.generateArray} id="new"  >New array</button></li>
         <li><button onClick={this.mergeSort} id="mergesort" >Merge Sort</button></li>
         <li><button onClick={this.bubbleSort} id="bubbleSort" >Bubble sort</button></li>
       </ul>
     </nav>
    </header>

   <div className="container">
   <br></br>
     {this.state.array.map((value, idx) => (
       <div
         className="element"
         key={idx}
         style={{
           width:`${this.state.bar_width}px`,
           height:`${value}px`
         }}></div>
     ))}

   </div>
   </div>
 );
  }
}
</code>```

Merge sort Code:

```<code>   export default function getMergeSortAnimations(array) {

  const animations = [];
  mergeSort(array, 0, array.length - 1,animations);
  return animations;
  }

function mergeSort(array,low, high,animations) {
 if(low<high)
  {
    const mid = Math.floor((low + high) / 2);
     mergeSort(array, low, mid,animations);
     mergeSort(array, mid + 1, high,animations);
    merge(array, low, high,animations);
  }
 }

 function merge(array,low,high,animations) {
     let a = [];
    let k = low;
    let i = low;
   let mid = Math.floor((low+high)/2);
    let j = mid + 1;
   while (i <= mid && j <= high) {
     animations.push([i, j]);

    animations.push([i, j]);
     if (array[i] <= array[j]) {
      animations.push([k, array[i]]);
      a[k++] = array[i++];
    } else {
     animations.push([k, array[j]]);
     a[k++] = array[j++];
   }
}
   while (i <= mid) {
    animations.push([i, i]);

   animations.push([i, i]);

    animations.push([k, array[i]]);
     a[k++] = array[i++];
   }
  while (j <= high) {
      animations.push([j, j]);

   animations.push([j, j]);

   animations.push([k, array[j]]);
   a[k++] = array[j++];
 }
 for(let o=low;o<k;o++)
 {
   array[o] = a[o];
 }
 }
</code>```

The merge sort function is under src->Person->Person as mentioned in the import section,it just returns animations array which i use for visualization.

Now the generateArray function generates an array and sets it to state using setSate() Method.When this is done the user can select mergesort and the code runs.But as you can see getMergesortAnimations() returns the animations array after the actual mergesort happens.But the question is:

"""When i console the state array before calling getMergesortAnimations() it displays a sorted array.It happens even before the mergesort is called and how is the state set to the sorted array without acutally using setState method?"""
This is very confusing to me ....
Thanks.
 // From Generate random number between two numbers in JavaScript

export default App;

答:
From a quick look at your code I can see that at the very end of your mergeSort function you are doing:

```<code>for(let o=low;o<k;o++)
{
  array[o] = a[o];
}
</code>```

Which is modifying the array in place. So after you in your component call:

```<code>const animations = getMergeSortAnimations(this.state.array);
</code>```

this.state.array will be modified in place. This is something you should not do in React, from React docs:

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

In order to fix this just fix the last couple lines of your mergeSort function so that it does not assign to array but rather creates a new array and returns that.

Title: i have issues regarding react state

Body:
Hi i have been building a sorting algorithms visualization it works so far but i have a doubt regarding state object.
consider the below code:

import React,{Component} from 'react';
import getMergeSortAnimations from './Person/Person';
import bubbleSortAnimations from './Person/BubbleSort';
import './App.css';

class App extends Component{

    state = {
    array: [],
   bar_width:2
 };

componentDidMount() {

  this.generateArray();
}

generateArray = ()=> {
  const array = [];

 let val = document.querySelector('#size').value;

 if(val<=10)
 {
   this.setState({bar_width:8});
 }
 else if(val<=20 && val>10)
  this.setState({bar_width:7});
else if(val<=50 && val>20)
   this.setState({bar_width:6});
else if(val<=100 && val>50)
  this.setState({bar_width:5});
else if(val<=150 && val>100)
  this.setState({bar_width:3});
else
   this.setState({bar_width:2});

 for (let i = 0; i < val; i++) {
   array.push(this.randomIntFromInterval(5, 450));
   }
 this.setState({array});

  }

 randomIntFromInterval = (min, max)=> {

  return Math.floor(Math.random() * (max - min + 1) + min);
 }
 mergeSort = ()=>{
   let t ;
   console.log(this.state);

   const animations = getMergeSortAnimations(this.state.array);
   console.log(this.state);
   for (let i = 0; i < animations.length; i++) {

   const arrayBars = document.getElementsByClassName('element');

   const isColorChange = i % 3 !== 2;
   if (isColorChange) {
     const [barOneIdx, barTwoIdx] = animations[i];
     const barOneStyle = arrayBars[barOneIdx].style;
     const barTwoStyle = arrayBars[barTwoIdx].style;
     const color = i % 3 === 0 ? 'red' : '#007bff';
     setTimeout(() => {
       barOneStyle.backgroundColor = color;
       barTwoStyle.backgroundColor = color;
     }, i*10);
   } else {
     setTimeout(() => {
       const [barOneIdx, newHeight] = animations[i];
       const barOneStyle = arrayBars[barOneIdx].style;
       barOneStyle.height = `${newHeight}px`;
     }, i*10);
   }

 }

}

render() {

 return (

      <input className="slider" onChange={this.generateArray}  type="range" min="5" max="200"
 id='size'/>

<button onClick={this.generateArray} id="new"  >New array</button>

<button onClick={this.mergeSort} id="mergesort" >Merge Sort</button>

<button onClick={this.bubbleSort} id="bubbleSort" >Bubble sort</button>

     {this.state.array.map((value, idx) => (
       <div
         className="element"
         key={idx}
         style={{
           width:`${this.state.bar_width}px`,
           height:`${value}px`
         }}>

     ))}

 );
  }
}

Merge sort Code:

   export default function getMergeSortAnimations(array) {

  const animations = [];
  mergeSort(array, 0, array.length - 1,animations);
  return animations;
  }

function mergeSort(array,low, high,animations) {
 if(low<high)
  {
    const mid = Math.floor((low + high) / 2);
     mergeSort(array, low, mid,animations);
     mergeSort(array, mid + 1, high,animations);
    merge(array, low, high,animations);
  }
 }

 function merge(array,low,high,animations) {
     let a = [];
    let k = low;
    let i = low;
   let mid = Math.floor((low+high)/2);
    let j = mid + 1;
   while (i <= mid && j <= high) {
     animations.push([i, j]);

    animations.push([i, j]);
     if (array[i] <= array[j]) {
      animations.push([k, array[i]]);
      a[k++] = array[i++];
    } else {
     animations.push([k, array[j]]);
     a[k++] = array[j++];
   }
}
   while (i <= mid) {
    animations.push([i, i]);

   animations.push([i, i]);

    animations.push([k, array[i]]);
     a[k++] = array[i++];
   }
  while (j <= high) {
      animations.push([j, j]);

   animations.push([j, j]);

   animations.push([k, array[j]]);
   a[k++] = array[j++];
 }
 for(let o=low;o<k;o++)
 {
   array[o] = a[o];
 }
 }

The merge sort function is under src->Person->Person as mentioned in the import section,it just returns animations array which i use for visualization.

Now the generateArray function generates an array and sets it to state using setSate() Method.When this is done the user can select mergesort and the code runs.But as you can see getMergesortAnimations() returns the animations array after the actual mergesort happens.But the question is:

"""When i console the state array before calling getMergesortAnimations() it displays a sorted array.It happens even before the mergesort is called and how is the state set to the sorted array without acutally using setState method?"""
This is very confusing to me ....
Thanks.
 // From Generate random number between two numbers in JavaScript

export default App;

Body:
From a quick look at your code I can see that at the very end of your mergeSort function you are doing:

for(let o=low;o<k;o++)
{
  array[o] = a[o];
}

Which is modifying the array in place. So after you in your component call:

const animations = getMergeSortAnimations(this.state.array);

this.state.array will be modified in place. This is something you should not do in React, from React docs:

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

In order to fix this just fix the last couple lines of your mergeSort function so that it does not assign to array but rather creates a new array and returns that.


问:
c# + autocad mirror command
```<code>var commandString = string.Format("_.mirror _C\r{0}\r{1}\r {2}\r{3} _n\r",
                pEnd.ToString2D(), pStart.ToString2D(), axialPStart.ToString2D(), axialPEnd.ToString2D());
            _acadCurrentDocument.SendCommand(commandString);
</code>```

does not work, i believe it is because \r.
How to pass trough this situation?

答: Replace the spaces in your expression with \r and check that osmode is at zero because the two points of your capture can be the same</p>

Title: c# + autocad mirror command

Body:
var commandString = string.Format("_.mirror _C\r{0}\r{1}\r {2}\r{3} _n\r",
                pEnd.ToString2D(), pStart.ToString2D(), axialPStart.ToString2D(), axialPEnd.ToString2D());
            _acadCurrentDocument.SendCommand(commandString);

does not work, i believe it is because \r.
How to pass trough this situation?


问:
Docker / PHP / Apache - File permissions lost when created inside container
i'm trying to set up a docker app with Apache and Php stack.
But when i create a new file inside my project container, the permissions losted because root user is connected by default.
How can I connect my host user ?

docker-compose.yml

```<code>version: '3'
services:
  web:
    container_name: web
    build:
      context: docker/web
    volumes:
      - ./app/:/var/www/app
      - ./docker/web/apache/log:/var/log/apache2/app
    working_dir: /var/www/app
    ports:
      - 80:80
</code>```

dockerfile

```<code>FROM php:7.4-apache

ENV APACHE_DOCUMENT_ROOT /var/www

RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libpng-dev \
        libzip-dev \
        git \
        zip \
        unzip \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install zip pdo pdo_mysql opcache \
    && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

COPY php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY apache/app.conf /etc/apache2/sites-available/000-default.conf

RUN groupadd dev -g 1000
RUN useradd dev -g dev -d /home/dev -m
RUN echo '%dev ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
</code>```

I tried to create a dev user in my Dockerfile but not working.

答:
And how about this?</p>

```<code># Add www-data to the '1000-group'
RUN usermod -u 1000 www-data
</code>```

Body:
i'm trying to set up a docker app with Apache and Php stack.
But when i create a new file inside my project container, the permissions losted because root user is connected by default.
How can I connect my host user ?

docker-compose.yml

version: '3'
services:
  web:
    container_name: web
    build:
      context: docker/web
    volumes:
      - ./app/:/var/www/app
      - ./docker/web/apache/log:/var/log/apache2/app
    working_dir: /var/www/app
    ports:
      - 80:80

dockerfile

FROM php:7.4-apache

ENV APACHE_DOCUMENT_ROOT /var/www

RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libpng-dev \
        libzip-dev \
        git \
        zip \
        unzip \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install zip pdo pdo_mysql opcache \
    && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

COPY php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY apache/app.conf /etc/apache2/sites-available/000-default.conf

RUN groupadd dev -g 1000
RUN useradd dev -g dev -d /home/dev -m
RUN echo '%dev ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

I tried to create a dev user in my Dockerfile but not working.

Body:
And how about this?

# Add www-data to the '1000-group'
RUN usermod -u 1000 www-data


问:
Where to add axios interceptors code in vue js
I am using vue js as frontend with laravel. I am using laravel passport for auth, now i wants to show some error message once received 401 unauthentic error message that mostly occurs when my token expired. so to do this i am using axios interceptors my code is like

axios.interceptors.response.use(function (response) {
      return response
    }, function (error) {
      // const { config, response: { status } } = error
      const { config, response } = error
      const originalRequest = config
      if (response && response.status === 401) {
           //notication or redirection
            this.$vs.notify({
            title: 'Error',
            text: response.data['message'],
            iconPack: 'feather',
            icon: 'icon-check-circle',
            color: 'danger'
            })
      }
      return Promise.reject(error)
    })

Now Question is that where i put this code in vue js so that it call after every request & so an error message shown & redirect to login once get 401 unauthorized..

Any Suggestion from anyone.

Thanks in advance!!

答: app.js or add them to separate file and include in app.js. There is post about this https://medium.com/@yaob/how-to-globally-use-axios-instance-and-interceptors-e28f351bb794</p>


问:
Template function to return containers of unrelated types
I have several containers of unrelated types. I would like to write a templated function to process input values and insert them into the corresponding containers. This is my best try so far:

```<code>#include <iostream>
#include <set>

struct A {
  // Must have operator< or std::less to insert into a std::set
  // Probably a bad idea to do it by memory address
  bool operator<(A const& other) const { return this < &other; }
};
struct B {
  bool operator<(B const& other) const { return this < &other; }
};
struct C {
  bool operator<(C const& other) const { return this < &other; }
};

std::set<A> aSet;
std::set<B> bSet;
std::set<C> cSet;

template
<typename T>
std::set<T>& getSet();

template
<>
std::set<A>& getSet<A>() { return aSet; }

template
<>
std::set<B>& getSet<B>() { return bSet; }

template
<>
std::set<C>& getSet<C>() { return cSet; }

template
<typename T>
void process(T const& value) {
  std::set<T>& specializedSet(getSet<T>());
  specializedSet.insert(value);
}

int main()
{
  // do stuff
  process(A()); process(A()); process(A());
  process(B()); process(B());
  process(C());

  std::cout<<"Set has "<<getSet<A>().size()<<" element(s)\n"
           <<"Set has "<<getSet<B>().size()<<" element(s)\n"
           <<"Set has "<<getSet<C>().size()<<" element(s)"<<std::endl;
}
</code>```

It produces the expected output:

```<code>Set has 3 element(s)
Set has 2 element(s)
Set has 1 element(s)
</code>```

I would strongly prefer not to have to specialize getSet() for every type (I actually have 10), though it's worth it to be able to templatize process(). Ideally I wouldn't even need to declare separate containers aSet, bSet, etc. I could make all these types pointers if that's helpful, though I'd like to stay away from set::set<void*> or similar opaque coding if possible. If this is a duplicate, I apologize, it's a bit tricky to search for.

答:
You could probably use the following code:

template<typename T>
std::set<T>& getSet()
{
    static std::set<T> s;
    return s;
}
```

This will create a new std::set for the type T, the first time getSet<T>() is called.

Body:
I have several containers of unrelated types. I would like to write a templated function to process input values and insert them into the corresponding containers. This is my best try so far:

#include <iostream>
#include <set>

struct A {
  // Must have operator< or std::less to insert into a std::set
  // Probably a bad idea to do it by memory address
  bool operator<(A const& other) const { return this < &other; }
};
struct B {
  bool operator<(B const& other) const { return this < &other; }
};
struct C {
  bool operator<(C const& other) const { return this < &other; }
};

std::set aSet;
std::set bSet;
std::set<C> cSet;

template
<typename T>
std::set<T>& getSet();

template
<>
std::set& getSet() { return aSet; }

template
<>
std::set& getSet() { return bSet; }

template
<>
std::set<C>& getSet<C>() { return cSet; }

template
<typename T>
void process(T const& value) {
  std::set<T>& specializedSet(getSet<T>());
  specializedSet.insert(value);
}

int main()
{
  // do stuff
  process(A()); process(A()); process(A());
  process(B()); process(B());
  process(C());

  std::cout<<"Set has "<<getSet().size()<<" element(s)\n"
           <<"Set has "<<getSet().size()<<" element(s)\n"
           <<"Set has "<<getSet<C>().size()<<" element(s)"<<std::endl;
}

It produces the expected output:

Set has 3 element(s)
Set has 2 element(s)
Set has 1 element(s)

I would strongly prefer not to have to specialize getSet() for every type (I actually have 10), though it's worth it to be able to templatize process(). Ideally I wouldn't even need to declare separate containers aSet, bSet, etc. I could make all these types pointers if that's helpful, though I'd like to stay away from set::set<void*> or similar opaque coding if possible. If this is a duplicate, I apologize, it's a bit tricky to search for.

Body:
You could probably use the following code:

template<typename T>
std::set<T>& getSet()
{
    static std::set<T> s;
    return s;
}

This will create a new std::set for the type T, the first time getSet<T>() is called.


问:
What is the purpose of this check in this PUT method of ASP.NET Core WebAPI with Entity Framework Core?
I have an ASP.NET Core WebAPI application with Entity Framework Core.

I have the following model class:

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}
</code>```

and scaffolded an "API Controller with actions, using Entity Framework", which has the following method:

```<code>    [HttpPut("{id}")]
    public async Task<IActionResult> PutItem(long id, Item item)
    {
        if (id != item.Id)
        {
            return BadRequest();
        }

        _context.Entry(item).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ItemExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }
</code>```

I don't understand the if (id != item.Id) check. The Id property is set to be DatabaseGenerated because I want it to be my primary key, autoincrementing and NOT provided by the client, so the client can just PUT a {"name":"item1"} object and be successful.

So why is there this check? Is it a fault of the auto code generator? Can I safely remove it?

Furthermore, if the ID wasn't database generated, is this check to ensure that the user passes an object that has the same ID as the one he is trying to update?

答:
The id value is coming from the URL route:

```<code>[HttpPut("{id}")]
</code>```

And the item.Id value is coming from the posted model.  One may consider it redundant to have both, but the former is part of a standard RESTful API and the latter is likely just for completeness of the model in the request body.

The intent here is just a defensive programming check to make sure both are the same.  If someone submitted two different values then semantically it would look like an attempt to modify the ID of a record, which should certainly not be allowed.  This is just a sanity check against that.

and NOT provided by the client

The client would have to provide one of the two in order for you to identify the record to update.  You can generally ignore the item.Id if you want and just use the id value from the URL route to identify the record.  However, if you do that then you'd need to also do one of two things:

Add a line of code to set item.Id = id; before trying to attach it to the DB context, or

Instead of adding the model directly to the DB context, fetch the record by its id as a separate object and manually update the fields you want to update.

After all, if item.Id isn't provided by the client then it's going to default to 0 and Entity Framework won't be able to attach that object directly without an Id value.  The above options would supply that value either by setting it directly on the object or by using the existing one on a re-fetched object.

Body:
I have an ASP.NET Core WebAPI application with Entity Framework Core.

I have the following model class:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}

and scaffolded an "API Controller with actions, using Entity Framework", which has the following method:

    [HttpPut("{id}")]
    public async Task<IActionResult> PutItem(long id, Item item)
    {
        if (id != item.Id)
        {
            return BadRequest();
        }

        _context.Entry(item).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ItemExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

I don't understand the if (id != item.Id) check. The Id property is set to be DatabaseGenerated because I want it to be my primary key, autoincrementing and NOT provided by the client, so the client can just PUT a {"name":"item1"} object and be successful.

So why is there this check? Is it a fault of the auto code generator? Can I safely remove it?

Furthermore, if the ID wasn't database generated, is this check to ensure that the user passes an object that has the same ID as the one he is trying to update?

Body:
The id value is coming from the URL route:

[HttpPut("{id}")]

And the item.Id value is coming from the posted model.  One may consider it redundant to have both, but the former is part of a standard RESTful API and the latter is likely just for completeness of the model in the request body.

The intent here is just a defensive programming check to make sure both are the same.  If someone submitted two different values then semantically it would look like an attempt to modify the ID of a record, which should certainly not be allowed.  This is just a sanity check against that.

and NOT provided by the client

The client would have to provide one of the two in order for you to identify the record to update.  You can generally ignore the item.Id if you want and just use the id value from the URL route to identify the record.  However, if you do that then you'd need to also do one of two things:

Add a line of code to set item.Id = id; before trying to attach it to the DB context, or

Instead of adding the model directly to the DB context, fetch the record by its id as a separate object and manually update the fields you want to update.

After all, if item.Id isn't provided by the client then it's going to default to 0 and Entity Framework won't be able to attach that object directly without an Id value.  The above options would supply that value either by setting it directly on the object or by using the existing one on a re-fetched object.


答: Normally roles field store in database like serialized array. In your case it should be a:1:{i:0;s:9:"ROLE_USER";}.

Title: Symfony: "Array to string conversion" error on Roles management

Body:
I've started exploring security on Symfony 4.4.7. User creation works and I can see its params saved on DB:

MariaDB [(symfony)]> desc user;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(180) | NO   | UNI | NULL    |                |
| roles    | longtext     | NO   |     | NULL    |                |
| password | varchar(255) | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
4 rows in set (0.106 sec)

MariaDB [symfony]> select * from user;
+----+---------------+---------------+---------------------------------------------------------------------------------------------------+
| id | username      | roles         | password                                                                                |
+----+---------------+---------------+---------------------------------------------------------------------------------------------------+
| 13 | administrator | ["ROLE_USER"] | $argon2id$v=19$m=65536,t=4,p=1$rDxNxYso7afyYiTaTnuL9A$kW+fMWykrEUHVzPMFvZSvPwENohmKakk9iymvJRhu98 |
+----+---------------+---------------+---------------------------------------------------------------------------------------------------+
1 row in set (0.001 sec)

But when I try to login I get an error: "Notice: Array to string conversion"
Error points to this line of code:         return array_unique($roles);

On log I have:

[2020-05-28 10:28:44] request.CRITICAL: Uncaught PHP Exception ErrorException: "Notice: Array to string conversion" at /var/www/symfony/src/Entity/User.php line 68 {"exception":"[object] (ErrorException(code: 0): Notice: Array to string conversion at /var/www/symfony/src/Entity/User.php:68)"} []

What is wrong here?

Thanks for your help


答: POST is typically used to create an object.  PUT is often for an update.  And to update it, you need to know its identity.  Most likely long id is part of the URL or query string.  And Item item is from the body.  That check ensures the entity supplied in the body matches the one specified by the URL.

Title: What is the purpose of this check in this PUT method of ASP.NET Core WebAPI with Entity Framework Core?


问:
NiFi to Zookeeper SSL Connection
I have a requirement to secure the connection between NiFi and a (non-embedded) Zookeeper cluster. From the documentation here it mentions that it is being worked on in Zookeeper version 3.5.x. However, we are now on version 3.6.1 and I have got SSL working between Zookeeper and Kafka so I know it works.

It seems that the issue was that, according to this post, the Zookeeper client code in NiFi was not built on a version supporting SSL.

However, the post is now over 2 years old and Zookeeper 3.5.x has been and gone. My question is; has the Zookeeper client code in NiFi been updated to a version that supports SSL and, if yes, how can I implement it?

Thank you in advance,

Harry

答:
There are multiple Jiras related to this and some PRs open for this work.

NIFI-7203 - Add support for Zookeeper TLS

NIFI-7401 - Add Zookeeper client TLS to CuratorLeaderElectionManager

NIFI-7357 - Make Zookeeper TLS properties available via nifi.properties

NIFI-7356 - Enable TLS for embedded Zookeeper when NiFi has TLS enabled

NIFI-7124 - Improve experience configuring Zookeeper to support TLS

NIFI-7115 - Add Zookeeper TLS configuration to Administration Guide

I think the short answer to your question is that the complete functionality is not available in an integrated way out of the box right now, but through a combination of setting Java arguments, you should be able to achieve this on a recent version of NiFi (see PR 4092 for instructions via the rendered Admin Guide doc changes). You can follow the specific Jiras above to be kept apprised of new developments.

Title: NiFi to Zookeeper SSL Connection