问:
Why does fseek have "long int offset" instead of "long long int offset"?
C2x, 7.21.9.2 The fseek function:

Synopsis

```<code>#include <stdio.h>
int fseek(FILE *stream, long int offset, int whence);
</code>```

Why does fseek have long int offset instead of long long int offset?

It seems that on operating systems with data model LLP64 or ILP32 (e.g. Microsoft Windows) the 2147483647 (2 GB) may be insufficient.

Note: POSIX's lseek has off_t offset, where off_t "isn't very rigorously defined".

答:
The C Standard was formalized in 1990 when most hard drives were smaller than 2 GB.  The prototype for fseek() was already in broad use with a long type offset and 32 bits seemed large enough for all purposes, especially since the corresponding system call used the same API already. They did add fgetpos() and fsetpos() for exotic file systems where a simple long offset did not carry all the necessary information for seeking, but kept the fpos_t type opaque.

After a few years, when 64-bit offsets became necessary, many operating systems added 64-bit versions of the system calls and POSIX introduced fseeko() and ftello() to provide a high level interface for larger offsets. These extensions are not necessary anymore for 64-bit versions of common operating systems (linux, OS/X) but Microsoft decided to keep it's long, or more precisely LONG, type at 32-bits, solidifying this issue and other ones too such as size_t being larger than unsigned long.  This very unfortunate decision plagues C developers on Win64 platforms ever since and forces them to use non portable APIs for large files.

Changing fseek and ftell prototypes would create more problems with existing software as it would break compatibility, so it will not happen.

Some other historical shortcomings are even more surprising, such as the prototype for fgets:

```<code>char *fgets(char * restrict s, int n, FILE * restrict stream);
</code>```

Why did they use int instead of size_t is a mystery: back in 1990, int and size_t had the same size on most platforms and it did not make sense to pass a negative value anyway.  Again, this inconsistent API is here to stay.

Body:
C2x, 7.21.9.2 The fseek function:

Synopsis

#include <stdio.h>
int fseek(FILE *stream, long int offset, int whence);

Why does fseek have long int offset instead of long long int offset?

It seems that on operating systems with data model LLP64 or ILP32 (e.g. Microsoft Windows) the 2147483647 (2 GB) may be insufficient.

Note: POSIX's lseek has off_t offset, where off_t "isn't very rigorously defined".

Body:
The C Standard was formalized in 1990 when most hard drives were smaller than 2 GB.  The prototype for fseek() was already in broad use with a long type offset and 32 bits seemed large enough for all purposes, especially since the corresponding system call used the same API already. They did add fgetpos() and fsetpos() for exotic file systems where a simple long offset did not carry all the necessary information for seeking, but kept the fpos_t type opaque.

After a few years, when 64-bit offsets became necessary, many operating systems added 64-bit versions of the system calls and POSIX introduced fseeko() and ftello() to provide a high level interface for larger offsets. These extensions are not necessary anymore for 64-bit versions of common operating systems (linux, OS/X) but Microsoft decided to keep it's long, or more precisely LONG, type at 32-bits, solidifying this issue and other ones too such as size_t being larger than unsigned long.  This very unfortunate decision plagues C developers on Win64 platforms ever since and forces them to use non portable APIs for large files.

Changing fseek and ftell prototypes would create more problems with existing software as it would break compatibility, so it will not happen.

Some other historical shortcomings are even more surprising, such as the prototype for fgets:

char *fgets(char * restrict s, int n, FILE * restrict stream);

Why did they use int instead of size_t is a mystery: back in 1990, int and size_t had the same size on most platforms and it did not make sense to pass a negative value anyway.  Again, this inconsistent API is here to stay.


来源: stackexchange

问:
html: Best way to create table of contents from h1 & h2 elements?
I have an html files with h1 and h2 elements.

What is the best way and how to create a Table of Contents in this file using these elements?

Any way to automate the process or I have to settle for creating the TOC manually?

Thanks.

答:
I would do this on the server side using any language of your choice, and then cache the results and display them every time. Don't bother doing this in javascript because it will be work that needs to be repeated everytime.

The better approach might even be to parse the file, put in a database and the just display the TOC with an easy SELECT statement.

ContentLicense: CC BY-SA 3.0


问:
application cannot get the running AppImage path
In my application, sometimes I need to find out the path of the application executable. I use QApplication::applicationFilePath() and it works fine. But when I distribute my application as AppImage on Linux, this breaks. It returns the path where the running AppImage was mounted, e.g. /tmp/.mount_MyAppxyzabc/MyApp. But I would need to get the path of the AppImage itself, e.g. /home/vlad/MyApp/MyApp.AppImage. Is this possible to obtain from inside the running application?

答:
The code above doesn't work for me.  appImagePath is set to an empty QString.  Also, the following:

```<code>QProcessEnvironment env(QProcessEnvironment::systemEnvironment());
QStringList tt = env.keys();
QFile outFile("./debug.txt");
outFile.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&outFile);
for (QStringList::iterator it = tt.begin(); it != tt.end(); ++it)
    out << *it << " " << env.value(*it) << endl;
outFile.close();
</code>```

works for me in my release build, but doesn't in the appImage

This is on Linux.

Thanks.

ContentLicense: CC BY-SA 4.0

Body:
The code above doesn't work for me.  appImagePath is set to an empty QString.  Also, the following:

QProcessEnvironment env(QProcessEnvironment::systemEnvironment());
QStringList tt = env.keys();
QFile outFile("./debug.txt");
outFile.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&outFile);
for (QStringList::iterator it = tt.begin(); it != tt.end(); ++it)
    out << *it << " " << env.value(*it) << endl;
outFile.close();

works for me in my release build, but doesn't in the appImage

This is on Linux.

Thanks.


问:
Have custom options and databound items in html select
I am currently trying to have a select contain a default value in the options section, while also databinding it using a sqldatasource. I know that asp:Dropdowns have the appenddatabounditems attribute, but was curious if select controls also have something similar. Or if there is any way to do this at all.</p>
```<code><select id="ddlRFC" runat="server" datasourceid="dsRFC" DataTextField="ControlDescription" DataValueField="ControlValue" class="form-control">
      <option selected>Choose...</option>
</select>
</code>```

答:
It doesn't. Looking at the source, any existing items are always cleared when the HtmlSelect control is data-bound:

```<code>/* Copyright (c) Microsoft Corporation.  All rights reserved. */

// create items using the datasource
if (dataSource != null) {
    ...
    Items.Clear();
</code>```

Body:
I am currently trying to have a select contain a default value in the options section, while also databinding it using a sqldatasource. I know that asp:Dropdowns have the appenddatabounditems attribute, but was curious if select controls also have something similar. Or if there is any way to do this at all.

<select id="ddlRFC" runat="server" datasourceid="dsRFC" DataTextField="ControlDescription" DataValueField="ControlValue" class="form-control">
      <option selected>Choose...</option>
</select>

Body:
It doesn't. Looking at the source, any existing items are always cleared when the HtmlSelect control is data-bound:

/* Copyright (c) Microsoft Corporation.  All rights reserved. */

// create items using the datasource
if (dataSource != null) {
    ...
    Items.Clear();


问:
State not updating when using React state hook within setInterval
I'm trying out the new React Hooks and have a Clock component with a time value which is supposed to increase every second. However, the value does not increase beyond one.

function Clock() {
  const [time, setTime] = React.useState(0);
  React.useEffect(() => {
    const timer = window.setInterval(() => {
      setTime(time + 1);
    }, 1000);
    return () => {
      window.clearInterval(timer);
    };
  }, []);

  return (

Seconds: {time}

  );
}

ReactDOM.render(<Clock />, document.querySelector('#app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div></code>```

答:
For those looking for a minimalist solution for:

Stop interval after N seconds, and

Be able to reset it multiple times again on button click.

(I am not a React expert by any means my coworker asked to help out, I wrote this up and thought someone else might find it useful.)

```<code>
  const [disabled, setDisabled] = useState(true)
  const [inter, setInter] = useState(null)
  const [seconds, setSeconds] = useState(0)

  const startCounting = () => {
    setSeconds(0)
    setDisabled(true)
    setInter(window.setInterval(() => {
        setSeconds(seconds => seconds + 1)
    }, 1000))
  }

  useEffect(() => {
      startCounting()
  }, [])

  useEffect(() => {
    if (seconds >= 3) {
        setDisabled(false)
        clearInterval(inter)
    }
  }, [seconds])

  return (<button style = {{fontSize:'64px'}}
      onClick={startCounting}
      disabled = {disabled}>{seconds}</button>)
}
</code>```

Body:
For those looking for a minimalist solution for:

Stop interval after N seconds, and

Be able to reset it multiple times again on button click.

(I am not a React expert by any means my coworker asked to help out, I wrote this up and thought someone else might find it useful.)

  const [disabled, setDisabled] = useState(true)
  const [inter, setInter] = useState(null)
  const [seconds, setSeconds] = useState(0)

  const startCounting = () => {
    setSeconds(0)
    setDisabled(true)
    setInter(window.setInterval(() => {
        setSeconds(seconds => seconds + 1)
    }, 1000))
  }

  useEffect(() => {
      startCounting()
  }, [])

  useEffect(() => {
    if (seconds >= 3) {
        setDisabled(false)
        clearInterval(inter)
    }
  }, [seconds])

  return (<button style = {{fontSize:'64px'}}
      onClick={startCounting}
      disabled = {disabled}>{seconds}</button>)
}


问:
What is the equivalent of the Bash ` (backquote/backtick) in Windows PowerShell?
I need the result of a command to be taken as a parameter in another command.

```<code>command /opt <another command output>
</code>```

On Bash Linux I would do

```<code>command /opt `another command`
</code>```

What is the equivalent of the ` symbol that works in Windows Terminal?

In particular, I am using the command

```<code>'C:\Program Files\Display\display64.exe' /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}
</code>```

where findstr is the windows equivalent to grep and the final command in the pipe is the equivalent to sed. The output of this command will be 1, 2 or 3, and I need this to be passed to the %HERE in the following line

```<code>'C:\Program Files\Display\display64.exe' /device %HERE /rotate 90
</code>```

The following minimal example, does not work:

```<code>FOR /F %a in ('"C:\Program Files\Display\display64.exe"  /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}') do echo "%a"
</code>```

What I am doing wrong? (I am new in Windows).

答:
Use (...), the grouping operator to pass output from a command as an argument to another command:

```<code>'C:\Program Files\Display\display64.exe' /device (
  'C:\Program Files\Display\display64.exe' /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}
) /rotate 90
</code>```

Note: $(...), the subexpression operator, works too, but (...) is usually sufficient and has no side effects; you only need $(...) for multiple (;-separated) statements - see this answer for details.

As for what you tried:

In POSIX-compatible shells such as Bash, `...` is the legacy form of a command substitution whose modern syntax is $(...) - while PowerShell supports $(...) too, (...) is usually preferable, as noted.

In PowerShell, ` serves as the escape character (only), analogous to \ in POSIX-compatible shells - see the conceptual about_Special_Characters help topic.

Your attempts to use FOR /F %a in ... and %HERE (which should be %HERE%) relate to the legacy cmd.exe shell on Windows, not to its successor, PowerShell, whose syntax differs fundamentally.

Body:
I need the result of a command to be taken as a parameter in another command.

command /opt <another command output>

On Bash Linux I would do

command /opt `another command`

What is the equivalent of the ` symbol that works in Windows Terminal?

In particular, I am using the command

'C:\Program Files\Display\display64.exe' /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}

where findstr is the windows equivalent to grep and the final command in the pipe is the equivalent to sed. The output of this command will be 1, 2 or 3, and I need this to be passed to the %HERE in the following line

'C:\Program Files\Display\display64.exe' /device %HERE /rotate 90

The following minimal example, does not work:

FOR /F %a in ('"C:\Program Files\Display\display64.exe"  /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}') do echo "%a"

What I am doing wrong? (I am new in Windows).

Body:
Use (...), the grouping operator to pass output from a command as an argument to another command:

'C:\Program Files\Display\display64.exe' /device (
  'C:\Program Files\Display\display64.exe' /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}
) /rotate 90

Note: $(...), the subexpression operator, works too, but (...) is usually sufficient and has no side effects; you only need $(...) for multiple (;-separated) statements - see this answer for details.

As for what you tried:

In POSIX-compatible shells such as Bash, `...` is the legacy form of a command substitution whose modern syntax is $(...) - while PowerShell supports $(...) too, (...) is usually preferable, as noted.

In PowerShell, ` serves as the escape character (only), analogous to \ in POSIX-compatible shells - see the conceptual about_Special_Characters help topic.

Your attempts to use FOR /F %a in ... and %HERE (which should be %HERE%) relate to the legacy cmd.exe shell on Windows, not to its successor, PowerShell, whose syntax differs fundamentally.


问:
Does Appcelerator Titanium have option to develop both iPad and Android Galaxy application?
I am newbie to Appcelerator Titanium, My requirement is, develop mobile application for both iPad and Android Galaxy tab. But when I start the Titanium , it asks Mobile, iPad and desktop type of apps. Can you please help me how to develop app for both iPad and tablet.

Regards
Sri

答: From what I know Appcelerator supports the ability to make an iPhone / iPad combination apps (as i have done it).  I have previously worked on a prototype that was iPhone / Android in a single build / version.  You should be able to do this by going the mobile route and detecting the os, and screen dimensions. Also, there are lots of calls not supported by iPhone / Android and it's pretty tricky to make anything very complicated for both in a single project.</p>


问:
Pandas groupby and lambda functions to compare strings across columns
I have the following dataframe:

```<code>  A         B           C           D            E           F
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson
1001    S. Jackson  J. Smith    P. Jones    S. Jackson  P. Peterson
1001    P. Jones    J. Smith    P. Jones    S. Jackson  P. Peterson
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones
1002    J. Smith    S. Jackson  J. Smith    P. Peterson P. Jones
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones
1002    J. Smith    S. Jackson  J. Smith    P. Peterson P. Jones
</code>```

I am trying to generate the below dataframe based upon the following criteria:

Groupby column A;

If the entry in column C exists within the column B (post-groupby of column A), return 1 in new column G, otherwise return 0;

The process at step 2 is then repeated for columns C vs D, C vs E etc.

.

```<code> A          B           C           D             E           F     G   H   I   J
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1001    S. Jackson  J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1001    P. Jones    J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1
1002    P. Jones    S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1
1002    P. Peterson S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1
</code>```

I have researched and attempted to use lambda functions, np.where and combinations of boolean indexing from this forum but have been unsuccessful. For example, a lot of the lambda function questions seem to relate to comparing string versus string.

I am trying to compare a string in one cell, versus an entire column of values. My attempt seems logical but I'm not sure how to rectify this to achieve the above.

```<code>df['G'] = df.groupby(['A']).apply(lambda x: 1 if x['B'] == x['C'] else 0)
</code>```

I have also tried some less traditional approaches such as the below. Here, column Z is a column of 1s: if B and C do not match, replace the value in column z with a 0. Still, this does not achieve the desired outcome as above.

```<code>df['Y'] = (
    df['Z'].where(df['B'] == df['C'],other=0)
    .groupby([df['A']])
    .transform('count')
)

df['G'] = df['Y'] / df['Y']
</code>```

答:
For each group, you could use numpy broadcasting to return a matrix where each column is one of C, D, E and F, and where each value is True if it's in B, False otherwise. Then just use any(axis=1) to convert the matrix into a list of booleans where each value is True if at least one value in the column it represents was True, False otherwise:

```<code>values = dfe['A'].map(dfe.groupby('A').apply(lambda x: (x['B'].to_numpy()[:, None] == x.drop(['A', 'B'], axis=1).to_numpy()).any(axis=0).astype(int)))
df[['G', 'H', 'I', 'J']] = pd.DataFrame(values.tolist())
</code>```

Output:

```<code>>>> df
      A           B           C         D            E            F  G  H  I  J
0  1001    J. Smith    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
1  1001    J. Smith    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
2  1001  S. Jackson    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
3  1001    P. Jones    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
4  1002  S. Jackson  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0
5  1002    J. Smith  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0
6  1002  S. Jackson  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0
7  1002    J. Smith  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0
</code>```

Body:
I have the following dataframe:

  A         B           C           D            E           F
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson
1001    S. Jackson  J. Smith    P. Jones    S. Jackson  P. Peterson
1001    P. Jones    J. Smith    P. Jones    S. Jackson  P. Peterson
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones
1002    J. Smith    S. Jackson  J. Smith    P. Peterson P. Jones
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones
1002    J. Smith    S. Jackson  J. Smith    P. Peterson P. Jones

I am trying to generate the below dataframe based upon the following criteria:

Groupby column A;

If the entry in column C exists within the column B (post-groupby of column A), return 1 in new column G, otherwise return 0;

The process at step 2 is then repeated for columns C vs D, C vs E etc.

.

 A          B           C           D             E           F     G   H   I   J
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1001    J. Smith    J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1001    S. Jackson  J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1001    P. Jones    J. Smith    P. Jones    S. Jackson  P. Peterson 1   1   1   0
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1
1002    P. Jones    S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1
1002    S. Jackson  S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1
1002    P. Peterson S. Jackson  J. Smith    P. Peterson P. Jones    1   0   1   1

I have researched and attempted to use lambda functions, np.where and combinations of boolean indexing from this forum but have been unsuccessful. For example, a lot of the lambda function questions seem to relate to comparing string versus string.

I am trying to compare a string in one cell, versus an entire column of values. My attempt seems logical but I'm not sure how to rectify this to achieve the above.

df['G'] = df.groupby(['A']).apply(lambda x: 1 if x['B'] == x['C'] else 0)

I have also tried some less traditional approaches such as the below. Here, column Z is a column of 1s: if B and C do not match, replace the value in column z with a 0. Still, this does not achieve the desired outcome as above.

df['Y'] = (
    df['Z'].where(df['B'] == df['C'],other=0)
    .groupby([df['A']])
    .transform('count')
)

df['G'] = df['Y'] / df['Y']

Body:
For each group, you could use numpy broadcasting to return a matrix where each column is one of C, D, E and F, and where each value is True if it's in B, False otherwise. Then just use any(axis=1) to convert the matrix into a list of booleans where each value is True if at least one value in the column it represents was True, False otherwise:

values = dfe['A'].map(dfe.groupby('A').apply(lambda x: (x['B'].to_numpy()[:, None] == x.drop(['A', 'B'], axis=1).to_numpy()).any(axis=0).astype(int)))
df[['G', 'H', 'I', 'J']] = pd.DataFrame(values.tolist())

Output:

>>> df
      A           B           C         D            E            F  G  H  I  J
0  1001    J. Smith    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
1  1001    J. Smith    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
2  1001  S. Jackson    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
3  1001    P. Jones    J. Smith  P. Jones   S. Jackson  P. Peterson  1  1  1  0
4  1002  S. Jackson  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0
5  1002    J. Smith  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0
6  1002  S. Jackson  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0
7  1002    J. Smith  S. Jackson  J. Smith  P. Peterson     P. Jones  1  1  0  0


问:
How to get the browser viewport dimensions?
I want to provide my visitors the ability to see images in high quality, is there any way I can detect the window size?

Or better yet, the viewport size of the browser with JavaScript? See green area here:

答:
It  should be

let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;
```

understand viewport: https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts

shorthand for link above: viewport.moz.one

I've built a site for testing on devices: https://vp.moz.one

Body:
It  should be

let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;

understand viewport: https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts

shorthand for link above: viewport.moz.one

I've built a site for testing on devices: https://vp.moz.one


问:
script/command to add extra space before stating of selected/each line in a paragraph
I need to update my cpp source files header by adding extra one space before starting of the below lines in header information -

```<code>This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.
</code>```

Present Header format:

```<code>/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/
</code>```

Expected:

```<code>/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/
</code>```

Query:
Is there any command or script available to do that changes.
I have total 270 files with few files with proper space added and majority files with no space added.

答:
This might work for you (GNU sed):

```<code>sed -i '/FileHeaderBegin/{:a;n;s/^\S/ &/;/FileHeaderEnd/!ba}' file1 ... filen
</code>```

Turn on edit inplace option -i

Insert a space at the front of any line that begins with a non-space character between the lines containing FileHeaderBegin and FileHeaderEnd.

Alternative solution:

```<code>sed -i '/FileHeaderBegin/,/FileHeaderEnd/s/^\S/ &/' file1 ... filen
</code>```

Body:
I need to update my cpp source files header by adding extra one space before starting of the below lines in header information -

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

Present Header format:

/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/

Expected:

/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/

Query:
Is there any command or script available to do that changes.
I have total 270 files with few files with proper space added and majority files with no space added.

Body:
This might work for you (GNU sed):

sed -i '/FileHeaderBegin/{:a;n;s/^\S/ &/;/FileHeaderEnd/!ba}' file1 ... filen

Turn on edit inplace option -i

Insert a space at the front of any line that begins with a non-space character between the lines containing FileHeaderBegin and FileHeaderEnd.

Alternative solution:

sed -i '/FileHeaderBegin/,/FileHeaderEnd/s/^\S/ &/' file1 ... filen


问:
How memory address of list in Python work?
Simple code

```<code>c=[1]
print (c is [1])
#return false while if c = 1 integer then it would be true
</code>```

I check the id then turn out

```<code>print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
#2523446278656 same id but diffrent from id(c)
#2523446278656 same id
#2523446278656 same id
#2523446278848
</code>```

All the freaking lists values have the same id?? (now I understand that each time I call the print function the id is reset)

And when I just add a simple code

```<code>d=c[:]
</code>```

All the id MAGICALLY CHANGE except id(c), also id(d) is pointed back to the id([1]) above

```<code>print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
print(id(d))
#2523446278592 diffrent id than aboved
#2523446278592 diffrent id than aboved
#2523446278592 diffrent id than aboved
#2523446278848 the same id as id(c) aboved
#2523446278656 now id(d) is somehow the same with id[1],[1,2],[1,2,3] above
</code>```

Note that if I just typed 'c[:]' instead of 'd=c[:]' they will still be the same id. Also, my whole code above is on the same script and executed once.

Edit for gaining back asking privileges: Now I understand that there is a Garbage Collector in Python, and every time I assign the value to a variable, the Garbage Collector will come and take the old id, then next time I assign it will use that id again

答:
[1] does not always exist at 2523446278592 (for example) memory is assigned and reassigned all the time. So, for print(id([1])) it assigns [1] to an id so that it can be evaluated, stored, etc. but after it is used in that line it is no longer needed so the space at 2523446278592 is now free again so the next line print(id([2])) can now assign [2] to the id 2523446278592 since it is empty. However, print(id(c)) does not use 2523446278592 (although it is available) because c is already stored at a different location (which is printed instead). Then since d = c[:] creates a new list (not at id(c)) it can then use the open space represented by 2523446278592.

But also notice the difference here:

```<code>c = [1]
print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
d = c[:]
print(id(d))
</code>```

This prints as you say because d takes the next free id (the on freed up after the prints)

whereas:

```<code>c = [1]
d = c[:]
print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
print(id(d))
</code>```

this works differently because d is assigned before the prints so the print lines cannot use the id of d for [1] etc. since it is not free so it is different. The output of this case is:

```<code>2346573042880
2346573042880
2346573042880
2346568705216
2346568705408 #d is different from the print lines
</code>```

Body:
Simple code

c=[1]
print (c is [1])
#return false while if c = 1 integer then it would be true

I check the id then turn out

print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
#2523446278656 same id but diffrent from id(c)
#2523446278656 same id
#2523446278656 same id
#2523446278848

All the freaking lists values have the same id?? (now I understand that each time I call the print function the id is reset)

And when I just add a simple code

d=c[:]

All the id MAGICALLY CHANGE except id(c), also id(d) is pointed back to the id([1]) above

print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
print(id(d))
#2523446278592 diffrent id than aboved
#2523446278592 diffrent id than aboved
#2523446278592 diffrent id than aboved
#2523446278848 the same id as id(c) aboved
#2523446278656 now id(d) is somehow the same with id[1],[1,2],[1,2,3] above

Note that if I just typed 'c[:]' instead of 'd=c[:]' they will still be the same id. Also, my whole code above is on the same script and executed once.

Edit for gaining back asking privileges: Now I understand that there is a Garbage Collector in Python, and every time I assign the value to a variable, the Garbage Collector will come and take the old id, then next time I assign it will use that id again

Body:
[1] does not always exist at 2523446278592 (for example) memory is assigned and reassigned all the time. So, for print(id([1])) it assigns [1] to an id so that it can be evaluated, stored, etc. but after it is used in that line it is no longer needed so the space at 2523446278592 is now free again so the next line print(id([2])) can now assign [2] to the id 2523446278592 since it is empty. However, print(id(c)) does not use 2523446278592 (although it is available) because c is already stored at a different location (which is printed instead). Then since d = c[:] creates a new list (not at id(c)) it can then use the open space represented by 2523446278592.

But also notice the difference here:

c = [1]
print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
d = c[:]
print(id(d))

This prints as you say because d takes the next free id (the on freed up after the prints)

whereas:

c = [1]
d = c[:]
print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
print(id(d))

this works differently because d is assigned before the prints so the print lines cannot use the id of d for [1] etc. since it is not free so it is different. The output of this case is:

2346573042880
2346573042880
2346573042880
2346568705216
2346568705408 #d is different from the print lines


问:
Why the unary * operator does not have a constraint "the operand shall not be a pointer to void"?
C2x, 6.5.3.2 Address and indirection operators, Constraints, 2:

The operand of the unary * operator shall have pointer type.

Why there is no constraint "the operand shall not be a pointer to void"?

Though it can be deduced from:

C2x, 6.5.3.2 Address and indirection operators, Semantics, 4:

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.

C2x, 6.3.2.1 Lvalues, arrays, and function designators, 1:

An lvalue is an expression (with an object type other than void) that potentially designates an object; ...

答:
One possible (though somewhat contrived, I'll admit) case where adding your 'suggested' constraint would break code is where the & and * operators are concatenated. In such cases, an expression such as a = &*p, where p is a void* type, is allowed.

From this Draft Standard, immediately following the section in your first citation (bold emphasis mine):

Semantics

3     The unary & operator yields the address of its
operand. If the operand has type ‘‘type’’, the result has type
‘‘pointer to type’’. If the operand is the result of a unary *
operator, neither that operator nor the & operator is evaluated
and the result is as if both were omitted, except that the
constraints on the operators still apply and the result is not an
lvalue. …

I can't, currently, think of a use-case for that &* combination (on a void* or any other pointer type) – but it may occur in code that is "auto-generated" and/or uses conditional macro expansion(s).


问:
Can not Login with credentials of any other user than the one created at first place Mongodb and react
I am facing this issue in react that when I create user other than the first one the users gets created in the mongodb but when I try to login with the credentials of any other users I get this internal node error 464 in terminal with the message of wrong password in postman and the API crashes also if the password for the first registered user is wrong the API crashes in same manner. Also the login request doesn't verify the username it only cares about the password. I have no idea what is causing this issue. I checked my code but it seems fine to me. Can someone please assist who may have faced and solved this problem? Any help will be highly appreciated. Thank you in advance.

My code for auth is:

```<code>const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");

//REGISTER
router.post("/register", async (req, res) => {
  const newUser = new User({
    username: req.body.username,
    email: req.body.email,
    password: CryptoJS.AES.encrypt(
      req.body.password,
      process.env.PASS_SEC
    ).toString(),
  });

  try {
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
  } catch (err) {
    res.status(500).json(err);
  }
});

//LOGIN

router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne(
            {
                userName: req.body.user_name
            }
        );

        !user && res.status(401).json("Wrong User Name");

        const hashedPassword = CryptoJS.AES.decrypt(
            user.password,
            process.env.PASS_SEC
        );

        const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

        const inputPassword = req.body.password;

        originalPassword != inputPassword &&
            res.status(401).json("Wrong Password");

        const accessToken = jwt.sign(
        {
            id: user._id,
            isAdmin: user.isAdmin,
        },
        process.env.JWT_SEC,
            {expiresIn:"3d"}
        );

        const { password, ...others } = user._doc;
        res.status(200).json({...others, accessToken});

    }catch(err){
        res.status(500).json(err);
    }

});

module.exports = router;

</code>```

And the error that I get in the terminal is

```<code>node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (D:\Shop Api Test\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (D:\Shop Api Test\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (D:\Shop Api Test\node_modules\express\lib\response.js:267:15)
    at D:\Shop Api Test\routes\auth.js:63:25
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
</code>```

答:
the error

Cannot set headers after they are sent to the client

usually happens when you send response again while you already sent response back to client.
so i think when user send wrong pass you send res.status(401).json("Wrong Password"); and since you're not returning, the function still runs and execute codes after that so the second res.status().json() will call and cause the error

change your code like this and always retrun if you don't wanna do anything after sending response back

```<code>router.post('/login', async (req, res) => {
  try {
    const user = await User.findOne({
      userName: req.body.user_name
    });

    if (!user) {
      return res.status(401).json("Wrong User Name");
    }

    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );

    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

    const inputPassword = req.body.password;

    if (originalPassword != inputPassword) {
        return res.status(401).json("Wrong Password");
    }

    const accessToken = jwt.sign({
        id: user._id,
        isAdmin: user.isAdmin,
      },
      process.env.JWT_SEC, {
        expiresIn: "3d"
      }
    );

    const { password, others } = user._doc;
    return res.status(200).json({ ...others, accessToken });

  } catch (err) {
    res.status(500).json(err);
  }

});
</code>```

Body:
I am facing this issue in react that when I create user other than the first one the users gets created in the mongodb but when I try to login with the credentials of any other users I get this internal node error 464 in terminal with the message of wrong password in postman and the API crashes also if the password for the first registered user is wrong the API crashes in same manner. Also the login request doesn't verify the username it only cares about the password. I have no idea what is causing this issue. I checked my code but it seems fine to me. Can someone please assist who may have faced and solved this problem? Any help will be highly appreciated. Thank you in advance.

My code for auth is:

const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");

//REGISTER
router.post("/register", async (req, res) => {
  const newUser = new User({
    username: req.body.username,
    email: req.body.email,
    password: CryptoJS.AES.encrypt(
      req.body.password,
      process.env.PASS_SEC
    ).toString(),
  });

  try {
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
  } catch (err) {
    res.status(500).json(err);
  }
});

//LOGIN

router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne(
            {
                userName: req.body.user_name
            }
        );

        !user && res.status(401).json("Wrong User Name");

        const hashedPassword = CryptoJS.AES.decrypt(
            user.password,
            process.env.PASS_SEC
        );

        const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

        const inputPassword = req.body.password;

        originalPassword != inputPassword &&
            res.status(401).json("Wrong Password");

        const accessToken = jwt.sign(
        {
            id: user._id,
            isAdmin: user.isAdmin,
        },
        process.env.JWT_SEC,
            {expiresIn:"3d"}
        );

        const { password, ...others } = user._doc;
        res.status(200).json({...others, accessToken});

    }catch(err){
        res.status(500).json(err);
    }

});

module.exports = router;

And the error that I get in the terminal is

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (D:\Shop Api Test\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (D:\Shop Api Test\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (D:\Shop Api Test\node_modules\express\lib\response.js:267:15)
    at D:\Shop Api Test\routes\auth.js:63:25
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

Body:
the error

Cannot set headers after they are sent to the client

usually happens when you send response again while you already sent response back to client.
so i think when user send wrong pass you send res.status(401).json("Wrong Password"); and since you're not returning, the function still runs and execute codes after that so the second res.status().json() will call and cause the error

change your code like this and always retrun if you don't wanna do anything after sending response back

router.post('/login', async (req, res) => {
  try {
    const user = await User.findOne({
      userName: req.body.user_name
    });

    if (!user) {
      return res.status(401).json("Wrong User Name");
    }

    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );

    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

    const inputPassword = req.body.password;

    if (originalPassword != inputPassword) {
        return res.status(401).json("Wrong Password");
    }

    const accessToken = jwt.sign({
        id: user._id,
        isAdmin: user.isAdmin,
      },
      process.env.JWT_SEC, {
        expiresIn: "3d"
      }
    );

    const { password, others } = user._doc;
    return res.status(200).json({ ...others, accessToken });

  } catch (err) {
    res.status(500).json(err);
  }

});


问:
How to delete messages EFFICIENTLY with Discord bot
I want have a Discord Music Bot that when it leaves the voice channel it clears the text channel from commands and logs. But the problem is that it takes too much time (up to 1-3 mins). I have seen other that other bots are able to do the same in much lower time, so how can I make my code better?

Here is my code, that it does work, but I would like to make the bot delete messages faster:

```<code>} else if (msg.content.trim().toLowerCase() == _CMD_LEAVE) {
        const channel = msg.channel;
        const messageManager = channel.messages;
        messageManager.fetch({ limit: 100 }).then((messages) => {
             messages.forEach((message) => {
                 if ((message.author.id == 0123456789) || (message.content.startsWith(PREFIX))) {
                     message.delete();
                 }
             });
        });

        if (guildMap.has(mapKey)) {

            let val = guildMap.get(mapKey);
            if (val.voice_Channel) val.voice_Channel.leave()
            if (val.voice_Connection) val.voice_Connection.disconnect()
            if (val.musicYTStream) val.musicYTStream.destroy()
                guildMap.delete(mapKey)
            msg.reply("Disconnected.")

        } else {
            msg.reply("Cannot leave because not connected.")
        }
    }
</code>```

答:
Discord.js has a feature to prune a large number of messages.

First, you fetch all messages in the channel up to a certain point (e.g. the latest 100 messages), then filter them depending on your criteria.
Afterwards, you use channel.bulkDelete(messages) to immediately delete all of them.
This only works for messages younger than 14 days sadly, but it's much more efficient than manually deleting them.
The code could look somewhat like this:

//fetch 100 most recent messages
channel.messages.fetch({limit: 100}).then(messages => {
    //filter the messages to only delete messages by a certain user
    messages = messages.filter(m => m.author.id === useridhere)

    //bulk delete the messages
    channel.bulkDelete(messages)

})
```

Body:
I want have a Discord Music Bot that when it leaves the voice channel it clears the text channel from commands and logs. But the problem is that it takes too much time (up to 1-3 mins). I have seen other that other bots are able to do the same in much lower time, so how can I make my code better?

Here is my code, that it does work, but I would like to make the bot delete messages faster:

} else if (msg.content.trim().toLowerCase() == _CMD_LEAVE) {
        const channel = msg.channel;
        const messageManager = channel.messages;
        messageManager.fetch({ limit: 100 }).then((messages) => {
             messages.forEach((message) => {
                 if ((message.author.id == 0123456789) || (message.content.startsWith(PREFIX))) {
                     message.delete();
                 }
             });
        });

        if (guildMap.has(mapKey)) {

            let val = guildMap.get(mapKey);
            if (val.voice_Channel) val.voice_Channel.leave()
            if (val.voice_Connection) val.voice_Connection.disconnect()
            if (val.musicYTStream) val.musicYTStream.destroy()
                guildMap.delete(mapKey)
            msg.reply("Disconnected.")

        } else {
            msg.reply("Cannot leave because not connected.")
        }
    }


问:
Cucumber runner file is not running any Tests
I have checked the related questions, but couldn't find any answer for my problem.
I am trying to set up cucumber framework from scratch.

I set up the POM, test runner, a feature file and related step definitions.

But when I run the test, there is no error but none of the test runs. I tried giving glue also in my runner file. Its not running from intellij as well as from command line.

Giving all the files for reference. Please see if anybody is able to point the error I am making?

POM

```<code><?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.demo</groupId>
    <artifactId>TestCucumber</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>TestCucumber</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <cucumber.version>7.2.3</cucumber.version>
        <maven-cucumber-reporting.version>5.6.1</maven-cucumber-reporting.version>
        <project.name>TestCucumber</project.name>

    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>${maven-cucumber-reporting.version}</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.4.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>net.masterthought</groupId>
                <artifactId>maven-cucumber-reporting</artifactId>
                <version>${maven-cucumber-reporting.version}</version>
                <executions>
                    <execution>
                        <id>execution-dwp-employment-income-api</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <!-- report generation is happening at this phase, so please dont change-->
                        <phase>integration-test</phase>
                        <configuration>
                            <projectName>${project.name}</projectName>
                            <skip>false</skip>
                            <!-- output directory for the generated report -->
                            <outputDirectory>${project.build.directory}/jsonReports/reports</outputDirectory>
                            <!-- optional, defaults to outputDirectory if not specified -->
                            <inputDirectory>${project.build.directory}/jsonReports</inputDirectory>
                            <jsonFiles>
                                <!-- supports wildcard or name pattern -->
                                <param>**/*.json</param>
                            </jsonFiles>
                            <mergeFeaturesById>false</mergeFeaturesById>
                            <!-- optional, set true to get a final report with latest results of the same test from different test runs -->
                            <mergeFeaturesWithRetest>false</mergeFeaturesWithRetest>
                            <!-- optional, set true to fail build on test failures -->
                            <checkBuildResult>false</checkBuildResult>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Runner File

```<code>import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/resources/features",
        tags = "@Test",
        monochrome = true,
       plugin = {"json:target/cucumber.json"}
)
public class CucumberTestDebugger {
}
</code>```

Feature file

```<code>@Test
Feature: As user I want to Validate the feature
  Scenario : Scenario 1 for the Feature
    Given A sample record is present
</code>```

Step definition

```<code>import io.cucumber.java.en.Given;

public class Feature1Step {
    @Given("A sample record is present")
    public void aSampleScenario() {
        System.out.println("RECORD IS PRESENT");
    }
}
</code>```

Even if I just run the feature file for which step definition is not defined, that scenario also doesn't run. Usually it should give error for undefined steps in feature. It just shows -

```<code>C:\Users\myname\Java\jdk8\bin\java.exe -C:/Users/myname/IdeaProjects/TestCucumber/src/test/resources/features/Validate.feature
    Testing started at 16:34 ...

    0 Scenarios
    0 Steps
    0m0.324s
</code>```

Thanks in advance!!!

答:
Aggghhhhh..... I had an extra space after Scenario.
Silly mistake !!! Took hours</p>
```<code>  **Before**
    Scenario : Scenario 1 for the Feature
  **After**
     Scenario: Scenario 1 for the Feature
</code>```

Body:
I have checked the related questions, but couldn't find any answer for my problem.
I am trying to set up cucumber framework from scratch.

I set up the POM, test runner, a feature file and related step definitions.

But when I run the test, there is no error but none of the test runs. I tried giving glue also in my runner file. Its not running from intellij as well as from command line.

Giving all the files for reference. Please see if anybody is able to point the error I am making?

POM

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.demo</groupId>
    <artifactId>TestCucumber</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>TestCucumber</name>

    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <cucumber.version>7.2.3</cucumber.version>
        <maven-cucumber-reporting.version>5.6.1</maven-cucumber-reporting.version>
        <project.name>TestCucumber</project.name>

    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>${maven-cucumber-reporting.version}</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.4.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>net.masterthought</groupId>
                <artifactId>maven-cucumber-reporting</artifactId>
                <version>${maven-cucumber-reporting.version}</version>
                <executions>
                    <execution>
                        <id>execution-dwp-employment-income-api</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>

                        <phase>integration-test</phase>
                        <configuration>
                            <projectName>${project.name}</projectName>
                            <skip>false</skip>

                            <outputDirectory>${project.build.directory}/jsonReports/reports</outputDirectory>

                            <inputDirectory>${project.build.directory}/jsonReports</inputDirectory>
                            <jsonFiles>

                                <param>**/*.json</param>
                            </jsonFiles>
                            <mergeFeaturesById>false</mergeFeaturesById>

                            <mergeFeaturesWithRetest>false</mergeFeaturesWithRetest>

                            <checkBuildResult>false</checkBuildResult>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Runner File

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/resources/features",
        tags = "@Test",
        monochrome = true,
       plugin = {"json:target/cucumber.json"}
)
public class CucumberTestDebugger {
}

Feature file

@Test
Feature: As user I want to Validate the feature
  Scenario : Scenario 1 for the Feature
    Given A sample record is present

Step definition

import io.cucumber.java.en.Given;

public class Feature1Step {
    @Given("A sample record is present")
    public void aSampleScenario() {
        System.out.println("RECORD IS PRESENT");
    }
}

Even if I just run the feature file for which step definition is not defined, that scenario also doesn't run. Usually it should give error for undefined steps in feature. It just shows -

C:\Users\myname\Java\jdk8\bin\java.exe -C:/Users/myname/IdeaProjects/TestCucumber/src/test/resources/features/Validate.feature
    Testing started at 16:34 ...

    0 Scenarios
    0 Steps
    0m0.324s

Thanks in advance!!!

Body:
Aggghhhhh..... I had an extra space after Scenario.
Silly mistake !!! Took hours

  **Before**
    Scenario : Scenario 1 for the Feature
  **After**
     Scenario: Scenario 1 for the Feature


问:
How to convert to 1-dimensional list a list of a string that is list that contains int elements
Can't figure out how to make a proper 1-dimensional list out of

```<code>a = ['[2,5911,3391,10687,9796,15870,11533]']
a[1:-1]

</code>```

i want to get
[2,5911,3391,10687,9796,15870,11533]

Slices don't seem to work there

Is there any elegant way to do it without writing 2 for loops
Appreciate all the help

Body:
Can't figure out how to make a proper 1-dimensional list out of

a = ['[2,5911,3391,10687,9796,15870,11533]']
a[1:-1]

i want to get
[2,5911,3391,10687,9796,15870,11533]

Slices don't seem to work there

Is there any elegant way to do it without writing 2 for loops
Appreciate all the help

Body:
import ast
a = ['[2,5911,3391,10687,9796,15870,11533]']
ast.literal_eval(a[0])

Output:

[2, 5911, 3391, 10687, 9796, 15870, 11533]


问:
How to read data from Firebase Realtime Database conditionally
Assume that I have the following structure in my Firebase Realtime database:

```<code>- users
  - g123
    - john
      - age: 30
      - active: 1
    - mike
      - age: 20
      - active: 0
    - johanna
      - age: 30
      - active: 1
  - g456
    - jake
      - age: 20
      - active: 1
    - maria
      - age: 20
      - active: 0
  - g789
    - elli
      - age: 20
      - active: 0
    - joe
      - age: 20
      - active: 0
</code>```

I need to get the list of child:s where there is at least 1 user with active set to 1.

So, in the example above, there are 2 active users in g123 and 1 active user in g456. And there is no active user in g789.

How do I build a query to Firebase Realtime database (preferably with Python) that will return g123 and g456?

答:
Firebase Realtime Database queries work on a flat list of nodes, and the value to order/filter on must be at a fixed path under each direct child node. So the sort of query you want, is not possible on this data structure.

A common workaround is to store the activeCount under each direct child node, and update that upon each write.

```<code>- users
  - g123
    activeCount: 3
    - john
      - age: 30
      - active: 1
    - mike
      - age: 20
      - active: 0
    - johanna
      - age: 30
      - active: 1
  - g456
    activeCount: 0
    - jake
      - age: 20
      - active: 1
    - maria
      - age: 20
      - active: 0
  - g789
    activeCount: 3
    - elli
      - age: 20
      - active: 0
    - joe
      - age: 20
      - active: 0
</code>```

You can then order/filter on this activeCount.

Also see:

Firebase Query Double Nested

Firebase query if child of child contains a value

Many to Many relationship in Firebase

Body:
Assume that I have the following structure in my Firebase Realtime database:

- users
  - g123
    - john
      - age: 30
      - active: 1
    - mike
      - age: 20
      - active: 0
    - johanna
      - age: 30
      - active: 1
  - g456
    - jake
      - age: 20
      - active: 1
    - maria
      - age: 20
      - active: 0
  - g789
    - elli
      - age: 20
      - active: 0
    - joe
      - age: 20
      - active: 0

I need to get the list of child:s where there is at least 1 user with active set to 1.

So, in the example above, there are 2 active users in g123 and 1 active user in g456. And there is no active user in g789.

How do I build a query to Firebase Realtime database (preferably with Python) that will return g123 and g456?

Body:
Firebase Realtime Database queries work on a flat list of nodes, and the value to order/filter on must be at a fixed path under each direct child node. So the sort of query you want, is not possible on this data structure.

A common workaround is to store the activeCount under each direct child node, and update that upon each write.

- users
  - g123
    activeCount: 3
    - john
      - age: 30
      - active: 1
    - mike
      - age: 20
      - active: 0
    - johanna
      - age: 30
      - active: 1
  - g456
    activeCount: 0
    - jake
      - age: 20
      - active: 1
    - maria
      - age: 20
      - active: 0
  - g789
    activeCount: 3
    - elli
      - age: 20
      - active: 0
    - joe
      - age: 20
      - active: 0

You can then order/filter on this activeCount.

Also see:

Firebase Query Double Nested

Firebase query if child of child contains a value

Many to Many relationship in Firebase


问:
pdf as outlook attachment into logic app from azure storage
I am trying to add one or several attachments into an automated email stream. The pdfs are coming from a file storage and should be attached as pdf format into the "send an email" workflow. However this does not work.

```<code>"Send_an_email_(V2)": {
            "inputs": {
                "body": {
                    "Attachments": [
                        {
                            "ContentBytes": "{@base64(body('Get_file_content'))}",
                            "Name": "test"
                        }
                    ],
                    "Body": "<p>t</p>",
                    "Subject": "t",
                    "To": " "
                },
</code>```

The above gives me the following error: "Cannot convert the literal '{@base64(body('Get_file_content'))}' to the expected type 'Edm.Binary'."

How do I get the pdfs which are setting in the file storage AS A PDF attached into an automated mailing stream please?

答: Any reason why you are trying to convert the file content to base64 encoding? There is no need to do this. Just change the name of the file to test.pdf and set the content to "Get_file_content" as shown in the snapshot.

Body:
I am trying to add one or several attachments into an automated email stream. The pdfs are coming from a file storage and should be attached as pdf format into the "send an email" workflow. However this does not work.

"Send_an_email_(V2)": {
            "inputs": {
                "body": {
                    "Attachments": [
                        {
                            "ContentBytes": "{@base64(body('Get_file_content'))}",
                            "Name": "test"
                        }
                    ],
                    "Body": "
t
",
                    "Subject": "t",
                    "To": " "
                },

The above gives me the following error: "Cannot convert the literal '{@base64(body('Get_file_content'))}' to the expected type 'Edm.Binary'."

How do I get the pdfs which are setting in the file storage AS A PDF attached into an automated mailing stream please?


问:
Format like KSQL long timestamp in ABAP?
How to create an KSQL Timestamp in ABAP ?

ISO Extended is not enough.

"timestamp":"2022-02-07T08:35:02,4595190",

I need this ..

"timestamp": "2021-03-23T14:00:04.893888792Z",

Who has an idea ?

答:
"timestamp":"2022-02-07T08:35:02,4595190"

I assume that is a typo. Looks like json output and  The SAP Standard JSON conversion of TZNTSTMPL uses decimal point.

You may also have fun dealing with time fields and initial dates.
I had to write converters to handle the output.

If you are using the identity transformation approach,
something like this,

```<code>   " get a JSON writer
    lo_writer = cl_sxml_string_writer=>create(
                  type = if_sxml=>co_xt_json
                  no_empty_elements  = i_suppress_initial ).

    CALL TRANSFORMATION id  SOURCE json_root_node = myAbapStru
                            RESULT XML lo_writer

    l_xstring  = lo_writer->get_output( ).

   lo_converter   = cl_abap_conv_in_ce=>create(
                          input = l_xstring
                          encoding = 'UTF-8'  ).

    lo_converter->read( EXPORTING   n    = lv_length
                       IMPORTING    data = r_string ).
</code>```

Then you get the output in SAPs interpretation of JSON Standard.
Which is unfortunately valid in ISO8601.   Since ALL timestamps in sap are in UTC the Z can be dropped :(

You may need to parse/fix the resulting JSON string before sending it.
I ended up fixing the result at the other end.
In c# using NetwonSoft Datatype converters

EDIT: for class /UI2/CL_JSON.
using the old ABAP parser, there is an option to do this as user @ALEZHU points out.

```<code>data: begin of test,
      ts type timestampl,
      END OF test,
      l_json type string.
get time STAMP FIELD test-ts.

l_json = /ui2/cl_json=>serialize( EXPORTING data             = test
                                   ts_as_iso8601    = 'X' ).
write: /  l_json.
</code>```

produces: {"TS":"2022-02-10T06:27:13.8734110Z"}

Body:
"timestamp":"2022-02-07T08:35:02,4595190"

I assume that is a typo. Looks like json output and  The SAP Standard JSON conversion of TZNTSTMPL uses decimal point.

You may also have fun dealing with time fields and initial dates.
I had to write converters to handle the output.

If you are using the identity transformation approach,
something like this,

   " get a JSON writer
    lo_writer = cl_sxml_string_writer=>create(
                  type = if_sxml=>co_xt_json
                  no_empty_elements  = i_suppress_initial ).

    CALL TRANSFORMATION id  SOURCE json_root_node = myAbapStru
                            RESULT XML lo_writer

    l_xstring  = lo_writer->get_output( ).

   lo_converter   = cl_abap_conv_in_ce=>create(
                          input = l_xstring
                          encoding = 'UTF-8'  ).

    lo_converter->read( EXPORTING   n    = lv_length
                       IMPORTING    data = r_string ).

Then you get the output in SAPs interpretation of JSON Standard.
Which is unfortunately valid in ISO8601.   Since ALL timestamps in sap are in UTC the Z can be dropped :(

You may need to parse/fix the resulting JSON string before sending it.
I ended up fixing the result at the other end.
In c# using NetwonSoft Datatype converters

EDIT: for class /UI2/CL_JSON.
using the old ABAP parser, there is an option to do this as user @ALEZHU points out.

data: begin of test,
      ts type timestampl,
      END OF test,
      l_json type string.
get time STAMP FIELD test-ts.

l_json = /ui2/cl_json=>serialize( EXPORTING data             = test
                                   ts_as_iso8601    = 'X' ).
write: /  l_json.

produces: {"TS":"2022-02-10T06:27:13.8734110Z"}


问:
Nested RecyclerView OnclickListener

I have nested RecyclerView (MainRecyclerview and ChildRecyclerview) with two Adapters(MainRecyclerviewAdapter and ChildRecyclerviewAdapter), i create an interface to handle click for childRecyclerview, but i can only access that click in MainRecyclerviewAdapter.
I want to know how to handle click for items in childRecyclerview in MainActivity, thanks.

Here is my code:

//MainActivity

public class MainActivity extends AppCompatActivity {

```<code>List<Section> sectionList = new ArrayList<>();
RecyclerView mainRecyclerView;
LinearLayoutManager layoutManager;
MainRecyclerAdapter mainRecyclerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile_properties);

    initData();
    initRecyclerView();

}
</code>```

}

//ChildRecyclerAdapter

public class ChildRecyclerAdapter extends RecyclerView.Adapter<ChildRecyclerAdapter.ChildViewHolder> {

```<code>private final List<String> items;
private OnItemClickListener mListener;

public ChildRecyclerAdapter(List<String> items) {
    this.items = items;
}

public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}

@NonNull
@Override
public ChildViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
    return new ChildViewHolder(view, mListener);
}

@Override
public void onBindViewHolder(@NonNull ChildViewHolder holder, int position) {
    holder.itemTextView.setText(items.get(position));
}

@Override
public int getItemCount() {
    return items.size();
}

public class ChildViewHolder extends RecyclerView.ViewHolder {

    TextView itemTextView;

    ChildViewHolder(final View itemView, OnItemClickListener listener) {
        super(itemView);
        itemTextView = itemView.findViewById(R.id.txt_item_view);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    int position = getBindingAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        String item = items.get(position);
                        listener.onItemClick(item);
                    }
                }
            }
        });
    }
}
</code>```

}

//MainRecyclerAdapter

public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {

```<code>List<Section> sectionList;

public MainRecyclerAdapter(List<Section> sectionList) {
    this.sectionList = sectionList;
}

@NonNull
@Override
public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.section_row, parent, false);
    return new MainViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {

    Section section = sectionList.get(position);
    String sectionName = section.getSectionName();
    List<String> items = section.getSectionItems();

    holder.sectionNameTextView.setText(sectionName);
    ChildRecyclerAdapter childRecyclerAdapter = new ChildRecyclerAdapter(items);
    holder.recyclerChild.setAdapter(childRecyclerAdapter);
    childRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(String item) {
            // TODO: 07/02/2022 handle click

        }
    });

}

@Override
public int getItemCount() {
    return sectionList.size();
}

public static class MainViewHolder extends RecyclerView.ViewHolder {

    TextView sectionNameTextView;
    RecyclerView recyclerChild;

    public MainViewHolder(final View itemView) {
        super(itemView);

        sectionNameTextView = itemView.findViewById(R.id.txt_section_name);
        recyclerChild = itemView.findViewById(R.id.child_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(itemView.getContext());
        recyclerChild.setLayoutManager(layoutManager);

    }
}
</code>```

}

//OnItemClickListener

public interface OnItemClickListener {

```<code>void onItemClick(String item);
</code>```

}

答:
You can simple make one more interface and call it in nested adapter's onclick method.

So it will pass that data from adapter to the activity when you click any adapter items.

Like this :

1. Create an interface for getting the child recyclerview item click in the activity or fragment.

First, you need to change your child adapter's click listener from this

```<code>public interface OnItemClickListener {
    void onItemClick(String item);
}
</code>```

to this :

```<code>public interface OnItemClickListener {
    void onItemClick(int childPosition);
}
</code>```

then pass the adapter position of child recyclerview instead of string value.

Now, make a new interface to get both the parent and child item clicks in the activity or fragment.

```<code>public interface RvItemClickListener {
    void onChildItemClick(int parentPosition, int childPosition, String item);
}
</code>```

2. Define the listener and call it on child item click in parent recyclerview adapter :

```<code>RvItemClickListener rvItemClickListener;

public void setRvItemClickListener(RvItemClickListener rvItemClickListener){
    this.rvItemClickListener = rvItemClickListener;
}
</code>```

3. Call it on child item click :

```<code>childRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int childPosition) {
                    String item = items.get(childPosition);
                    rvItemClickListener.onChildItemClick(getAdapterPosition(), childPosition, item);
                  }
               });
</code>```

4. The last step is to override the method in your activity or fragment as you do it normally :

```<code>@Override
public void onItemClick(int parentPosition, int childPosition, String item) {

}
</code>```

I hope it's enough for you to understand what I am trying to say.

It's just an example. Do make changes as per your needs.

Title: Nested RecyclerView OnclickListener

Body:
I have nested RecyclerView (MainRecyclerview and ChildRecyclerview) with two Adapters(MainRecyclerviewAdapter and ChildRecyclerviewAdapter), i create an interface to handle click for childRecyclerview, but i can only access that click in MainRecyclerviewAdapter.
I want to know how to handle click for items in childRecyclerview in MainActivity, thanks.

Here is my code:

//MainActivity

public class MainActivity extends AppCompatActivity {

List
 sectionList = new ArrayList<>();
RecyclerView mainRecyclerView;
LinearLayoutManager layoutManager;
MainRecyclerAdapter mainRecyclerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile_properties);

    initData();
    initRecyclerView();

}

}

//ChildRecyclerAdapter

public class ChildRecyclerAdapter extends RecyclerView.Adapter<ChildRecyclerAdapter.ChildViewHolder> {

private final List<String> items;
private OnItemClickListener mListener;

public ChildRecyclerAdapter(List<String> items) {
    this.items = items;
}

public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}

@NonNull
@Override
public ChildViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
    return new ChildViewHolder(view, mListener);
}

@Override
public void onBindViewHolder(@NonNull ChildViewHolder holder, int position) {
    holder.itemTextView.setText(items.get(position));
}

@Override
public int getItemCount() {
    return items.size();
}

public class ChildViewHolder extends RecyclerView.ViewHolder {

    TextView itemTextView;

    ChildViewHolder(final View itemView, OnItemClickListener listener) {
        super(itemView);
        itemTextView = itemView.findViewById(R.id.txt_item_view);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    int position = getBindingAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        String item = items.get(position);
                        listener.onItemClick(item);
                    }
                }
            }
        });
    }
}

}

//MainRecyclerAdapter

public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {

List
 sectionList;

public MainRecyclerAdapter(List
 sectionList) {
    this.sectionList = sectionList;
}

@NonNull
@Override
public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.section_row, parent, false);
    return new MainViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {

    Section section = sectionList.get(position);
    String sectionName = section.getSectionName();
    List<String> items = section.getSectionItems();

    holder.sectionNameTextView.setText(sectionName);
    ChildRecyclerAdapter childRecyclerAdapter = new ChildRecyclerAdapter(items);
    holder.recyclerChild.setAdapter(childRecyclerAdapter);
    childRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(String item) {
            // TODO: 07/02/2022 handle click

        }
    });

}

@Override
public int getItemCount() {
    return sectionList.size();
}

public static class MainViewHolder extends RecyclerView.ViewHolder {

    TextView sectionNameTextView;
    RecyclerView recyclerChild;

    public MainViewHolder(final View itemView) {
        super(itemView);

        sectionNameTextView = itemView.findViewById(R.id.txt_section_name);
        recyclerChild = itemView.findViewById(R.id.child_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(itemView.getContext());
        recyclerChild.setLayoutManager(layoutManager);

    }
}

}

//OnItemClickListener

public interface OnItemClickListener {

void onItemClick(String item);

}

Body:
You can simple make one more interface and call it in nested adapter's onclick method.

So it will pass that data from adapter to the activity when you click any adapter items.

Like this :

1. Create an interface for getting the child recyclerview item click in the activity or fragment.

First, you need to change your child adapter's click listener from this

public interface OnItemClickListener {
    void onItemClick(String item);
}

to this :

public interface OnItemClickListener {
    void onItemClick(int childPosition);
}

then pass the adapter position of child recyclerview instead of string value.

Now, make a new interface to get both the parent and child item clicks in the activity or fragment.

public interface RvItemClickListener {
    void onChildItemClick(int parentPosition, int childPosition, String item);
}

2. Define the listener and call it on child item click in parent recyclerview adapter :

RvItemClickListener rvItemClickListener;

public void setRvItemClickListener(RvItemClickListener rvItemClickListener){
    this.rvItemClickListener = rvItemClickListener;
}

3. Call it on child item click :

childRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int childPosition) {
                    String item = items.get(childPosition);
                    rvItemClickListener.onChildItemClick(getAdapterPosition(), childPosition, item);
                  }
               });

4. The last step is to override the method in your activity or fragment as you do it normally :

@Override
public void onItemClick(int parentPosition, int childPosition, String item) {

}

I hope it's enough for you to understand what I am trying to say.

It's just an example. Do make changes as per your needs.


问:
How to align a picture,name and the post with css like facebook does?
I am trying to align  a full name,picture and the post just like they do in most social networks (linked-in or facebook).But i cant align them the well.Can anybody please try to fill the gaps with necessary css commands?Thank you in advance.

```<code><div>
 <span class="picture"> <img src="/assets/images/rails.png"/></span>
  <a  href="#" class="user-name">user-full-name</a>
 <span class="post"></span>
 </div>
</code>```

css

```<code> .picture{height:40px;
         width:40px;
         }

  .user-name{
         margin-bottom:35px;
            }
   .post{     }
</code>```

答: Here's a basic example: http://jsfiddle.net/GU2aM/ to get you started.</p>

Body:
I am trying to align  a full name,picture and the post just like they do in most social networks (linked-in or facebook).But i cant align them the well.Can anybody please try to fill the gaps with necessary css commands?Thank you in advance.

  user-full-name

css

 .picture{height:40px;
         width:40px;
         }

  .user-name{
         margin-bottom:35px;
            }
   .post{     }


问:
Can't compile Android project with gradle after adding a library
Before adding a library to my Android project the layout was like this:

MyappProject

Myapp

build.gradle

settings.gradle

build.gradle

The top level build.gradle has always been empty, with the settings.gradle file containing only:

```<code>include ':Myapp'
</code>```

I obtained a library project which I was able to import successfully into Android Studio, so I presume that the gradle files within it were fine. I now have the following structure:

MyappProject

Myapp

build.gradle

libraries

Library

LibrarySubProject1

build.gradle

....

build.gradle

settings.gradle

build.gradle

...and the top level settings gradle now looks like:

```<code>include ':Myapp'
include ':libraries:Library'
</code>```

I've also updated Myapp's build.gradle so it includes the extra last line in dependencies here:

```<code>dependencies {
    compile 'com.android.support:support-v4:+'
    compile files('libs/commons-lang3-3.1.jar')
    compile files('libs/jsoup-1.7.3.jar')
    compile project(':libraries:Library')
}
</code>```

Unfortunately, any attempt to do anything with gradle (sync files, build etc.) now gets me the following:

```<code>Gradle 'MyappProject' project refresh failed:
     Configuration with name 'default' not found.
     Gradle settings
</code>```

Any changes to the settings appear to have no effect, and Android Studio keeps the settings set to "use default gradle wrapper".
From what I understand, that means that there is a problem with the top level build.gradle along the lines of this file not containing sufficient information to build the sub projects. But, perhaps I have misunderstood, as Myapp used to build and Library also seems fine. Removing the compile project(':libraries:Library') allows gradle file syncing again, but I would like to use that library...

Any suggestions as to how to fix this would be welcome.

Edited to add build.gradle from Library. Top level:

```<code>buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.9.+'
    }
}

allprojects {
    version = VERSION_NAME
    group = GROUP

    repositories {
        mavenCentral()
    }
}
</code>```

From the next level:

```<code>apply plugin: 'android-library'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 19
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

apply from: 'https://raw.github.com/chrisbanes/gradle-mvn-push/master/gradle-mvn-push.gradle'
</code>```

答:
I just commented out line:

apply from: rootProject.file('gradle/maven-push.gradle') in
build.gradle(:library) since I don't want to publish this project at all, but I need it just as a library.

Body:
Before adding a library to my Android project the layout was like this:

MyappProject

Myapp

build.gradle

settings.gradle

build.gradle

The top level build.gradle has always been empty, with the settings.gradle file containing only:

include ':Myapp'

I obtained a library project which I was able to import successfully into Android Studio, so I presume that the gradle files within it were fine. I now have the following structure:

MyappProject

Myapp

build.gradle

libraries

Library

LibrarySubProject1

build.gradle

....

build.gradle

settings.gradle

build.gradle

...and the top level settings gradle now looks like:

include ':Myapp'
include ':libraries:Library'

I've also updated Myapp's build.gradle so it includes the extra last line in dependencies here:

dependencies {
    compile 'com.android.support:support-v4:+'
    compile files('libs/commons-lang3-3.1.jar')
    compile files('libs/jsoup-1.7.3.jar')
    compile project(':libraries:Library')
}

Unfortunately, any attempt to do anything with gradle (sync files, build etc.) now gets me the following:

Gradle 'MyappProject' project refresh failed:
     Configuration with name 'default' not found.
     Gradle settings

Any changes to the settings appear to have no effect, and Android Studio keeps the settings set to "use default gradle wrapper".
From what I understand, that means that there is a problem with the top level build.gradle along the lines of this file not containing sufficient information to build the sub projects. But, perhaps I have misunderstood, as Myapp used to build and Library also seems fine. Removing the compile project(':libraries:Library') allows gradle file syncing again, but I would like to use that library...

Any suggestions as to how to fix this would be welcome.

Edited to add build.gradle from Library. Top level:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.9.+'
    }
}

allprojects {
    version = VERSION_NAME
    group = GROUP

    repositories {
        mavenCentral()
    }
}

From the next level:

apply plugin: 'android-library'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 19
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

apply from: 'https://raw.github.com/chrisbanes/gradle-mvn-push/master/gradle-mvn-push.gradle'


答:
Welcome to the world of temporary objects! When you write c == [1] you create a new list object ([1])and set a reference (c) on it. The lifetime of an object will be the one of its last reference.

But when you write id([1]) you do create a new object (hence a different id), but set no reference to keep it alive so it is immediately destroyed and its address is available for next created object...

BTW, with d = c you create a new reference on the very same object so they will have the same id.

And last but not least, the way the interpretor manages its memory and the object ids only depends on implementation details and you should not even try to guess it... And definitely never rely on any pattern!

Title: How memory address of list in Python work?

Body:
Simple code

c=[1]
print (c is [1])
#return false while if c = 1 integer then it would be true

I check the id then turn out

print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
#2523446278656 same id but diffrent from id(c)
#2523446278656 same id
#2523446278656 same id
#2523446278848

All the freaking lists values have the same id?? (now I understand that each time I call the print function the id is reset)

And when I just add a simple code

d=c[:]

All the id MAGICALLY CHANGE except id(c), also id(d) is pointed back to the id([1]) above

print(id([1]))
print(id([2]))
print(id([1,2,3]))
print(id(c))
print(id(d))
#2523446278592 diffrent id than aboved
#2523446278592 diffrent id than aboved
#2523446278592 diffrent id than aboved
#2523446278848 the same id as id(c) aboved
#2523446278656 now id(d) is somehow the same with id[1],[1,2],[1,2,3] above

Note that if I just typed 'c[:]' instead of 'd=c[:]' they will still be the same id. Also, my whole code above is on the same script and executed once.

Edit for gaining back asking privileges: Now I understand that there is a Garbage Collector in Python, and every time I assign the value to a variable, the Garbage Collector will come and take the old id, then next time I assign it will use that id again