问:
How to pass the state true or false from a child to the parent- React
I have two components, one parent (Widgets) and another son (Telefono). The "Telefono" component has the notInCall status and with it I paint or not a certain part of the code.
On the other hand I have the showComponent() function that is in the parent with which I show or not the child component (Telefono) and two other components.
I need to recover from the parent, in the showComponent() function the current status (true or false) of notInCall but I do not know how to do it.

Edit: I think I have not explained well. In the child I use a conditional this.state.notInCall to show or not part of the code. I need to pass the true or false response to the parent. If {this.state.notInCall ? (some code) : (another code)}. If this.state.notInCallon the child is true do one thing and if it is false do another

This is my parent component (Widgets)

```<code>class Widgets extends Component {
    constructor(props) {
        super(props);
        this.state = {
            componente: 1,
            //notInCall: false,
        };
        this.showComponent = this.showComponent.bind(this);
    }

    showComponent(componentName) {
        /*this.setState({
            notInCall: false,
        });*/
        if(this.state.notInCall === false){
            this.setState({
                componente: Telefono,
                addActive: Telefono,
            });
            alert(this.state.notInCall + ' running? Componente:' + componentName);
            console.log(this.state.notInCall);
        }else{
            alert('verdad');
            this.setState({
                componente: componentName,
                addActive: componentName,
            });
        }
        console.log(this.state.notInCall);
    }

    renderComponent(){
        switch(this.state.componente) {
            case "ChatInterno":
                return <ChatInterno />
            case "HistorialLlamadas":
                return <HistorialLlamadas />
            case "Telefono":
            default:
                return <Telefono showComponent={this.showComponent}/>
        }
    }

    render(){
        return (
            <div id="bq-comunicacion">
                <nav>
                    <ul>
                        <li><button onClick={() => this.showComponent('Telefono')} id="mn-telefono" className={this.state.addActive === 'Telefono' ? 'active' : ''}><Icon icon="telefono" className='ico-telefono'/></button></li>
                        <li><button onClick={() => this.showComponent('ChatInterno')} id="mn-chat" className={this.state.addActive === 'ChatInterno' ? 'active' : ''}><Icon icon="chat-interno" className='ico-chat-interno'/></button></li>
                        <li><button onClick={() => this.showComponent('HistorialLlamadas')} id="mn-llamadas" className={this.state.addActive === 'HistorialLlamadas' ? 'active' : ''}><Icon icon="historial-llamadas" className='ico-historial-llamadas'/></button></li>
                    </ul>
                </nav>
                <div className="content">
                    { this.renderComponent() }
                </div>
            </div>
        );
    }
}
</code>```

This is my child component (Telefono)

```<code>class Telefono extends Component {
    constructor(props) {
        super(props);

        this.inputTelephone = React.createRef();

        ["update", "reset", "deleteClickNumber", "closeAlert", "handleKeyPress",].forEach((method) => {
            this[method] = this[method].bind(this);
        });

        this.state = this.initialState = {
            notInCall: true,
            isRunning: false,
        };
    }

    phoneCall(e){
        e.preventDefault();
        this.props.showComponent(this.state.notInCall);

        if(this.state.inputContent.length < 2){
            this.setState({
                warningEmptyPhone: true,
            });

            this.change = setTimeout(() => {
                this.setState({
                    warningEmptyPhone: false
                })
            }, 5000)
        }else if(this.state.inputContent.length >= 2 ){
            this.setState({
                notInCall: !this.state.notInCall,
                isRunning: !this.state.isRunning,
                componente: 'Telefono',
            },
                () => {
                    this.state.isRunning ? this.startTimer() : clearInterval(this.timer);
                    //console.log(this.componente);
                });
        }
    }

    render(){
        return(
            <div className="pad sb-content">
                {this.state.notInCall
                    ? (
                        <>
                        <div className="dial-pad">
                            <div className="digits">
                                <Numbers numbers={this.state.numbers}
                                />
                            </div>
                        </div>
                        <div className="btn-call call" onClick={this.phoneCall.bind(this)}>
                            <Icon icon="telefono" className='ico-telefono'/>
                            <span>LLAMAR</span>
                        </div>
                        </>
                    )
                    : (
                        <div className="call-pad">
                            <div id="ca-number" className="ca-number">{this.state.inputContent}</div>
                            <TimeElapsed id="timer" timeElapsed={timeElapsed}/>
                        </div>

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

Thanks for the help

答:
If I understood your problem correctly, the answer of Marcello Silva is correct.

Say you have this:

```<code>class Parent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            childAvailable: true,
        };
    }

    handleAvailability = status => {
        this.setState({ childAvailable: status });
    }

    render() {
        const { childAvailable } = this.state;

        if (!childAvailable) {
            return (...); // display whatever you want if children not available
        } else {
            return (
                <div>
                    {children.map(child => {
                        <Children
                            child={child}
                            statusHandler={this.handleAvailability}
                        />
                    }
                </div>
            );
        }
    }
}
</code>```

and

```<code>class Children extends React.Component {
    constructor(props) {
         super(props);

         this.state = {
             available: true,
         };
    }

    handleClick = e => {
        const status = !this.state.available;
        this.setState(prevState => { available: !prevState.available });

        // if you call the handler provided by the parent here, with the value
        // of status, it will change the state in the parent, hence
        // trigger a re render conditionned by your value
        this.props.statusHandler(status);
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick}>Click me to change status</button>
            </div>
        );
    }
}
</code>```

Doing this will call the function you passed as prop to your children in your parent. This function sets your state, and therefore triggers a re render once the state has been set, so you'll be rendering whatever you want considering the new value of childAvailable.

EDIT: After seeing the comment on said answer, I'd like to add that you can of course call your handleClick method from your conditions on this.state.notInCall.

Body:
I have two components, one parent (Widgets) and another son (Telefono). The "Telefono" component has the notInCall status and with it I paint or not a certain part of the code.
On the other hand I have the showComponent() function that is in the parent with which I show or not the child component (Telefono) and two other components.
I need to recover from the parent, in the showComponent() function the current status (true or false) of notInCall but I do not know how to do it.

Edit: I think I have not explained well. In the child I use a conditional this.state.notInCall to show or not part of the code. I need to pass the true or false response to the parent. If {this.state.notInCall ? (some code) : (another code)}. If this.state.notInCallon the child is true do one thing and if it is false do another

This is my parent component (Widgets)

class Widgets extends Component {
    constructor(props) {
        super(props);
        this.state = {
            componente: 1,
            //notInCall: false,
        };
        this.showComponent = this.showComponent.bind(this);
    }

    showComponent(componentName) {
        /*this.setState({
            notInCall: false,
        });*/
        if(this.state.notInCall === false){
            this.setState({
                componente: Telefono,
                addActive: Telefono,
            });
            alert(this.state.notInCall + ' running? Componente:' + componentName);
            console.log(this.state.notInCall);
        }else{
            alert('verdad');
            this.setState({
                componente: componentName,
                addActive: componentName,
            });
        }
        console.log(this.state.notInCall);
    }

    renderComponent(){
        switch(this.state.componente) {
            case "ChatInterno":
                return <ChatInterno />
            case "HistorialLlamadas":
                return <HistorialLlamadas />
            case "Telefono":
            default:
                return <Telefono showComponent={this.showComponent}/>
        }
    }

    render(){
        return (

<button onClick={() => this.showComponent('Telefono')} id="mn-telefono" className={this.state.addActive === 'Telefono' ? 'active' : ''}><Icon icon="telefono" className='ico-telefono'/></button>

<button onClick={() => this.showComponent('ChatInterno')} id="mn-chat" className={this.state.addActive === 'ChatInterno' ? 'active' : ''}><Icon icon="chat-interno" className='ico-chat-interno'/></button>

<button onClick={() => this.showComponent('HistorialLlamadas')} id="mn-llamadas" className={this.state.addActive === 'HistorialLlamadas' ? 'active' : ''}><Icon icon="historial-llamadas" className='ico-historial-llamadas'/></button>

                    { this.renderComponent() }

        );
    }
}

This is my child component (Telefono)

class Telefono extends Component {
    constructor(props) {
        super(props);

        this.inputTelephone = React.createRef();

        ["update", "reset", "deleteClickNumber", "closeAlert", "handleKeyPress",].forEach((method) => {
            this[method] = this[method].bind(this);
        });

        this.state = this.initialState = {
            notInCall: true,
            isRunning: false,
        };
    }

    phoneCall(e){
        e.preventDefault();
        this.props.showComponent(this.state.notInCall);

        if(this.state.inputContent.length < 2){
            this.setState({
                warningEmptyPhone: true,
            });

            this.change = setTimeout(() => {
                this.setState({
                    warningEmptyPhone: false
                })
            }, 5000)
        }else if(this.state.inputContent.length >= 2 ){
            this.setState({
                notInCall: !this.state.notInCall,
                isRunning: !this.state.isRunning,
                componente: 'Telefono',
            },
                () => {
                    this.state.isRunning ? this.startTimer() : clearInterval(this.timer);
                    //console.log(this.componente);
                });
        }
    }

    render(){
        return(

                {this.state.notInCall
                    ? (
                        <>

                                <Numbers numbers={this.state.numbers}
                                />

                            <Icon icon="telefono" className='ico-telefono'/>
                            LLAMAR

                        </>
                    )
                    : (

{this.state.inputContent}

                            <TimeElapsed id="timer" timeElapsed={timeElapsed}/>

                    )}

        );
    }
}

Thanks for the help

Body:
If I understood your problem correctly, the answer of Marcello Silva is correct.

Say you have this:

class Parent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            childAvailable: true,
        };
    }

    handleAvailability = status => {
        this.setState({ childAvailable: status });
    }

    render() {
        const { childAvailable } = this.state;

        if (!childAvailable) {
            return (...); // display whatever you want if children not available
        } else {
            return (
                <div>
                    {children.map(child => {
                        <Children
                            child={child}
                            statusHandler={this.handleAvailability}
                        />
                    }
                </div>
            );
        }
    }
}

and

class Children extends React.Component {
    constructor(props) {
         super(props);

         this.state = {
             available: true,
         };
    }

    handleClick = e => {
        const status = !this.state.available;
        this.setState(prevState => { available: !prevState.available });

        // if you call the handler provided by the parent here, with the value
        // of status, it will change the state in the parent, hence
        // trigger a re render conditionned by your value
        this.props.statusHandler(status);
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick}>Click me to change status</button>
            </div>
        );
    }
}

Doing this will call the function you passed as prop to your children in your parent. This function sets your state, and therefore triggers a re render once the state has been set, so you'll be rendering whatever you want considering the new value of childAvailable.

EDIT: After seeing the comment on said answer, I'd like to add that you can of course call your handleClick method from your conditions on this.state.notInCall.


来源: stackexchange

问:
Eloquent ORM filter the content after slash character
I'm trying fetch the data in the form like app/img.png. When i use Eloquent ORM, the result will get app (the content after slash will filter). However, I tried to use Query Builder, and it works! The result will show app/img.png. I have googled it, but nothing found. How should fix the problem if I want to use Eloquent ORM?

-- edit --

Eloquent

```<code>$images = Image::where('name', 'LIKE', '%' . $request->get('q') . '%')
                 ->select('name', 'URL')
                 ->get();
</code>```

QB

```<code>$images = \DB::table('images')
                 ->where('name', 'LIKE', '%' . $request->get('q') . '%')
                 ->select('name', 'URL')
                 ->get();
</code>```

答: Thanks for all of answers. After several of weeks, I found out I have set $primaryKey = 'URL' in the model, but I did not set $keyType = 'string'. After setting $keyType = 'string', and everything works!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying fetch the data in the form like app/img.png. When i use Eloquent ORM, the result will get app (the content after slash will filter). However, I tried to use Query Builder, and it works! The result will show app/img.png. I have googled it, but nothing found. How should fix the problem if I want to use Eloquent ORM?

-- edit --

Eloquent

$images = Image::where('name', 'LIKE', '%' . $request->get('q') . '%')
                 ->select('name', 'URL')
                 ->get();

QB

$images = \DB::table('images')
                 ->where('name', 'LIKE', '%' . $request->get('q') . '%')
                 ->select('name', 'URL')
                 ->get();


问:
How to code a BAT file to always run as admin mode?
I have this line inside my BAT file:

```<code>"Example1Server.exe"
</code>```

I would like to execute this in Administrator mode. How to modify the bat code to run this as admin?

Is this correct? Do I need to put the quotes?

```<code>runas /user:Administrator invis.vbs Example1Server.exe
</code>```

答:
My experimenting indicates that the runas command must include the admin user's domain (at least it does in my organization's environmental setup):

```<code>runas /user:AdminDomain\AdminUserName ExampleScript.bat
</code>```

If you don’t already know the admin user's domain, run an instance of Command Prompt as the admin user, and enter the following command:

```<code>echo %userdomain%
</code>```

The answers provided by both Kerrek SB and Ed Greaves will execute the target file under the admin user but, if the file is a Command script (.bat file) or VB script (.vbs file) which attempts to operate on the normal-login user’s environment (such as changing registry entries), you may not get the desired results because the environment under which the script actually runs will be that of the admin user, not the normal-login user!  For example, if the file is a script that operates on the registry’s HKEY_CURRENT_USER hive, the affected “current-user” will be the admin user, not the normal-login user.

ContentLicense: CC BY-SA 3.0

Body:
I have this line inside my BAT file:

"Example1Server.exe"

I would like to execute this in Administrator mode. How to modify the bat code to run this as admin?

Is this correct? Do I need to put the quotes?

runas /user:Administrator invis.vbs Example1Server.exe

Body:
My experimenting indicates that the runas command must include the admin user's domain (at least it does in my organization's environmental setup):

runas /user:AdminDomain\AdminUserName ExampleScript.bat

If you don’t already know the admin user's domain, run an instance of Command Prompt as the admin user, and enter the following command:

echo %userdomain%

The answers provided by both Kerrek SB and Ed Greaves will execute the target file under the admin user but, if the file is a Command script (.bat file) or VB script (.vbs file) which attempts to operate on the normal-login user’s environment (such as changing registry entries), you may not get the desired results because the environment under which the script actually runs will be that of the admin user, not the normal-login user!  For example, if the file is a script that operates on the registry’s HKEY_CURRENT_USER hive, the affected “current-user” will be the admin user, not the normal-login user.


问:
How to understand the path in DLE?
I would like to know how works the path in DataLife Engine

<source src="[xfvalue_videopath]" type="video/mp4"> </video>';

i have a slider with 4 videos, and this path direct this videos on slider, how can i change the path?

```<code>videopath|video path (dont touch!)|97|text||1|0|0|0
videopathimage|video preview (dont touch!)|97|text||1|0|0|0
</code>```

this is located in xfields.txt, as I understand this is the path

答: In admin panel, from additional fields section ( of news ), you can change the xfields:

Title: How to understand the path in DLE?

Body:
I would like to know how works the path in DataLife Engine

<source src="[xfvalue_videopath]" type="video/mp4"> </video>';

i have a slider with 4 videos, and this path direct this videos on slider, how can i change the path?

videopath|video path (dont touch!)|97|text||1|0|0|0
videopathimage|video preview (dont touch!)|97|text||1|0|0|0

this is located in xfields.txt, as I understand this is the path


问:
NSTableViewDataSource dealloc in objective-c
I'm currently learning objective-c and I'm currently training with NSTableView.

Here is my problem :

I have linked my tableview to my controller through Interface Builder so that it has a datasource, I have implemented NSTableViewDataSource protocol in my controller and I have implemented both -(NSInteger) numberOfRowsInTableView: and -(id) tableView:objectValueForTableColumn:row: methods.

I have created a raw business class ("person") and I succeeded to display its content into my NSTableView.

But then, I put some NSLog in my dealloc methods to see whether the memory was freed or not and it seems that my array as well as my "person" instances are never released.

here is my dealloc code in the controller:

```<code>-(void)dealloc
{
    NSLog(@"the array is about to be deleted. current retain : %d",[personnes retainCount]);

    [personnes release];
    [super dealloc];
}
</code>```

and in my "person" class

```<code>-(void) dealloc
{
    NSLog(@"%@ is about to be deleted. current retain : %d",[self prenom],[self retainCount]);

    [self->nom release];
    [self->prenom release];

    [super dealloc];
}
</code>```

When these deallocs are supposed to be called in the application lifecycle? Because I expected them to be called at the window closure, but it didn't.

In the hope of beeing clear enough,

Thanks :)

KiTe.

答:
I’m assuming you’re never releasing the window controller object that owns the (only) window. As such, the window controller and every top level object in the nib file are retained throughout the application lifecycle, including the window (and its views).

Since the window controller exists throughout the application lifecycle, it isn’t released, hence its -dealloc method is never called. And, since the controller -dealloc method is never called, its personnes array isn’t released.

The personnes array owns its elements. Since the array isn’t released, neither are its elements, hence the -dealloc method of the corresponding class/instances is never called.

Body:
I'm currently learning objective-c and I'm currently training with NSTableView.

Here is my problem :

I have linked my tableview to my controller through Interface Builder so that it has a datasource, I have implemented NSTableViewDataSource protocol in my controller and I have implemented both -(NSInteger) numberOfRowsInTableView: and -(id) tableView:objectValueForTableColumn:row: methods.

I have created a raw business class ("person") and I succeeded to display its content into my NSTableView.

But then, I put some NSLog in my dealloc methods to see whether the memory was freed or not and it seems that my array as well as my "person" instances are never released.

here is my dealloc code in the controller:

-(void)dealloc
{
    NSLog(@"the array is about to be deleted. current retain : %d",[personnes retainCount]);

    [personnes release];
    [super dealloc];
}

and in my "person" class

-(void) dealloc
{
    NSLog(@"%@ is about to be deleted. current retain : %d",[self prenom],[self retainCount]);

    [self->nom release];
    [self->prenom release];

    [super dealloc];
}

When these deallocs are supposed to be called in the application lifecycle? Because I expected them to be called at the window closure, but it didn't.

In the hope of beeing clear enough,

Thanks :)

KiTe.


问:
Using Python to read .CSV files and then compare the columns/rows
I am currently trying to develop a program that reads data from a text file, and returns the pair of employees that has worked the most time together. I decided to it in a .CSV format, as that is still a plain text format, but seperated with comas.

Example:

```<code>EmpID,ProjectID,DateFrom,DateTo
1,A,2014-11-01,2015-05-01
2,B,2013-12-06,2014-10-06
2,C,2014-01-07,2016-03-07
3,B,2015-06-04,2017-09-04
5,C,2014-10-01,2015-12-01
1,A,2013-03-07,2015-11-07
2,C,2015-07-09,2019-01-19
3,B,2013-11-13,2014-03-13
4,C,2016-02-14,NULL
5,D,2014-03-15,2015-11-09
</code>```

Now, I learned how to read .CSV files, but I am not sure on what is the best way for the thing after (the comparing of values, etc). For now, I decided that this is the cleanest option:

```<code>import csv

with open('data.csv', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)

print(your_list)
</code>```

I just want a piece of advice, if the best way to go would be with comparing indexes of the list. I was also thinking about dictionaries, but I am not sure, hence the reason I am asking here :) And SQL is not an option, even though it would be so easy with it. Sorry if this is a bad question, but I am currently learning Python and this is quite an important task for me. Thanks!

答:
As I understand from what you wrote, I think what you need is something like this:

```<code>#read csv, and split on "," the line
csv_file = csv.reader(open('data.csv', "rb"), delimiter=",")

for item in csv_file:
#do your work
</code>```

maybe you can look at Pandas too if you have large Data. It ll be more efficient to work with Pandas in that Case

Body:
I am currently trying to develop a program that reads data from a text file, and returns the pair of employees that has worked the most time together. I decided to it in a .CSV format, as that is still a plain text format, but seperated with comas.

Example:

EmpID,ProjectID,DateFrom,DateTo
1,A,2014-11-01,2015-05-01
2,B,2013-12-06,2014-10-06
2,C,2014-01-07,2016-03-07
3,B,2015-06-04,2017-09-04
5,C,2014-10-01,2015-12-01
1,A,2013-03-07,2015-11-07
2,C,2015-07-09,2019-01-19
3,B,2013-11-13,2014-03-13
4,C,2016-02-14,NULL
5,D,2014-03-15,2015-11-09

Now, I learned how to read .CSV files, but I am not sure on what is the best way for the thing after (the comparing of values, etc). For now, I decided that this is the cleanest option:

import csv

with open('data.csv', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)

print(your_list)

I just want a piece of advice, if the best way to go would be with comparing indexes of the list. I was also thinking about dictionaries, but I am not sure, hence the reason I am asking here :) And SQL is not an option, even though it would be so easy with it. Sorry if this is a bad question, but I am currently learning Python and this is quite an important task for me. Thanks!

Body:
As I understand from what you wrote, I think what you need is something like this:

#read csv, and split on "," the line
csv_file = csv.reader(open('data.csv', "rb"), delimiter=",")

for item in csv_file:
#do your work

maybe you can look at Pandas too if you have large Data. It ll be more efficient to work with Pandas in that Case


问:
Why align-self property doesn't work with a navigation bar while using flex?
This supposed to be a sticky navigation bar but never gets sticky. I've read that I must use align-self: flex-start; to fix this issue with flex but lamentably does not do it.

body { padding-bottom: 2000px;}
ul { list-style: none;}

.wrap {
 position: sticky;
 position: -webkit-sticky;
 top: 0;
 align-self: flex-start;
}
.nav-bar {
 display: flex;
 flex-direction: row;
 justify-content: flex-end;
 background-color: #00aae4;
 margin-bottom: 0;
 padding-right: 30px;
 height: 50px;
 margin-top:0;
}
.nav-link {
 padding-left: 0;
 padding-right: 0;
 background-color: #f1f1f1;
 width: 100px;
 text-align: center;
 font-size: 20px;
 margin-top: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<nav class="wrap">
          <ul class="nav-bar">
            <li class="nav-link">Luigis</li>
            <li class="nav-link">Menu</li>
            <li class="nav-link">Acerca de </li>
            <li class="nav-link">Contacto</li>
          </ul>
    </nav>
</body>
</html></code>```

I've tried changing the align-self property location into the ul's settings and made use of top. Also  tried to eliminate the list by just using div with clases but still no result.

答:
From the specification:

Intersection between the stickily positioned element and the bottom of the sticky-constraint rectangle limits movement in any direction, so the offset never pushes the stickily positioned element outside of its containing block. However, when the element is free to move within its containing block as the page is scrolled, it appears to be pinned to the relevant flow root edges, similarly to a fixed position element.

By default, your element is contained in the content-box and not the padding-box and in your case the content-box is defined by the sticky element so there is no sticky behavior if you add a big padding.

You can have a sticky behavior if you add a big height to increase the content-box.

body {
  height: 2000px;
}

ul {
  list-style: none;
}

.wrap {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
}

.nav-bar {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  background-color: #00aae4;
  margin-bottom: 0;
  padding-right: 30px;
  height: 50px;
  margin-top: 0;
}

.nav-link {
  padding-left: 0;
  padding-right: 0;
  background-color: #f1f1f1;
  width: 100px;
  text-align: center;
  font-size: 20px;
  margin-top: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="wrap">
    <ul class="nav-bar">
      <li class="nav-link">Luigis</li>
      <li class="nav-link">Menu</li>
      <li class="nav-link">Acerca de </li>
      <li class="nav-link">Contacto</li>
    </ul>
  </nav></code>```

For other elements, if the element's position is 'relative' or 'static', the containing block is formed by the content edge of the nearest block container ancestor box. ref

You are probably confusing with the containing block of an absolute positioned element that is the padding box:

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:

In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element. In CSS 2.1, if the inline element is split across multiple lines, the containing block is undefined.

Otherwise, the containing block is formed by the padding edge of the ancestor.

Body:
This supposed to be a sticky navigation bar but never gets sticky. I've read that I must use align-self: flex-start; to fix this issue with flex but lamentably does not do it.

body { padding-bottom: 2000px;}
ul { list-style: none;}

.wrap {
 position: sticky;
 position: -webkit-sticky;
 top: 0;
 align-self: flex-start;
}
.nav-bar {
 display: flex;
 flex-direction: row;
 justify-content: flex-end;
 background-color: #00aae4;
 margin-bottom: 0;
 padding-right: 30px;
 height: 50px;
 margin-top:0;
}
.nav-link {
 padding-left: 0;
 padding-right: 0;
 background-color: #f1f1f1;
 width: 100px;
 text-align: center;
 font-size: 20px;
 margin-top: 5px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Luigis

Menu

Acerca de

Contacto

I've tried changing the align-self property location into the ul's settings and made use of top. Also  tried to eliminate the list by just using div with clases but still no result.

Body:
From the specification:

Intersection between the stickily positioned element and the bottom of the sticky-constraint rectangle limits movement in any direction, so the offset never pushes the stickily positioned element outside of its containing block. However, when the element is free to move within its containing block as the page is scrolled, it appears to be pinned to the relevant flow root edges, similarly to a fixed position element.

By default, your element is contained in the content-box and not the padding-box and in your case the content-box is defined by the sticky element so there is no sticky behavior if you add a big padding.

You can have a sticky behavior if you add a big height to increase the content-box.

body {
  height: 2000px;
}

ul {
  list-style: none;
}

.wrap {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
}

.nav-bar {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  background-color: #00aae4;
  margin-bottom: 0;
  padding-right: 30px;
  height: 50px;
  margin-top: 0;
}

.nav-link {
  padding-left: 0;
  padding-right: 0;
  background-color: #f1f1f1;
  width: 100px;
  text-align: center;
  font-size: 20px;
  margin-top: 5px;
}

<nav class="wrap">
    <ul class="nav-bar">
      <li class="nav-link">Luigis</li>
      <li class="nav-link">Menu</li>
      <li class="nav-link">Acerca de </li>
      <li class="nav-link">Contacto</li>
    </ul>
  </nav>

For other elements, if the element's position is 'relative' or 'static', the containing block is formed by the content edge of the nearest block container ancestor box. ref

You are probably confusing with the containing block of an absolute positioned element that is the padding box:

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:

In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element. In CSS 2.1, if the inline element is split across multiple lines, the containing block is undefined.

Otherwise, the containing block is formed by the padding edge of the ancestor.


问:
String to date in Pervasive view
I created a view in Pervasive Control Center.
This view has a column "WeegDatum" which is a string (CHAR type) with a DDMMYYYY date.
I'm trying to convert this to a date.

My only experience with creating Pervasive views is selecting and filtering data.
I've tried all i could find over the last two days.
Mainly variations on "TO_DATE(,)" but nothing seems to work.

Just the (working) view:

```<code>CREATE VIEW "TEST2" AS SELECT "IORegHis" ."WeegDatum" FROM "IORegHis" "IORegHis"

View trying to convert to date:

CREATE VIEW "TEST2" AS SELECT TO_DATE('"IORegHis" ."WeegDatum"','DDMMYYYY') FROM "IORegHis" "IORegHis"
</code>```

This gives me "Error in expression: To_DATE"
I won't name all the syntax errors I have gotten the last days.

答:
Pervasive Date format is 'yyyy-mm-dd'.

You'll need to use something like this to convert your 'DDMMYYYY' to the Date format and then convert it to a SQL_DATE type:

```<code>select
CONVERT(right(WeegDatum,4) + '-'+
        right(left(WeegDatum,4),2) + '-' +
        left (WeegDatum,2), SQL_DATE)
from IORegHis
</code>```

Title: String to date in Pervasive view

Body:
I created a view in Pervasive Control Center.
This view has a column "WeegDatum" which is a string (CHAR type) with a DDMMYYYY date.
I'm trying to convert this to a date.

My only experience with creating Pervasive views is selecting and filtering data.
I've tried all i could find over the last two days.
Mainly variations on "TO_DATE(,)" but nothing seems to work.

Just the (working) view:

CREATE VIEW "TEST2" AS SELECT "IORegHis" ."WeegDatum" FROM "IORegHis" "IORegHis"

View trying to convert to date:

CREATE VIEW "TEST2" AS SELECT TO_DATE('"IORegHis" ."WeegDatum"','DDMMYYYY') FROM "IORegHis" "IORegHis"

This gives me "Error in expression: To_DATE"
I won't name all the syntax errors I have gotten the last days.

Body:
Pervasive Date format is 'yyyy-mm-dd'.

You'll need to use something like this to convert your 'DDMMYYYY' to the Date format and then convert it to a SQL_DATE type:

select
CONVERT(right(WeegDatum,4) + '-'+
        right(left(WeegDatum,4),2) + '-' +
        left (WeegDatum,2), SQL_DATE)
from IORegHis


问:
Write data to cloud firestore with flutter async
i am trying to write data in a firestore collection using async in my flutter app.

I do have this code, but it seems not to be working.

import 'package:location/location.dart';

Location _locationService = new Location();
  Future<void> setUserData() async {
    Map<String, dynamic> userData = <String, dynamic>{
      'email': this._emailController.text,
      'password': this._passwordController.text,
      'firstname': this._firstNameController.text,
      'familyname': this._familyNameController.text,
      'phonenumber': this._phoneNumberController.text,
      'neighbourhood': this._neighbourhoodController.text,
      'latitude': await _locationService.getLocation().latitude,
    };
    crudObj.addData(userData);
  }
```

crudObj.addData writes directly to my firestore collection.

What am i doing wrong  ?

答:
Looks like you haven't imported cloud_firestore to begin with.

```<code>Future<void> setUserData() async {
Firestore.instance.collection(*name of collection*).document(*name of document*).setData(
    {'email': this._emailController.text,
 'password': this._passwordController.text,
     'firstname': this._firstNameController.text,
    'familyname': this._familyNameController.text,
    'phonenumber': this._phoneNumberController.text,
    'neighbourhood': this._neighbourhoodController.text,
    'latitude': await _locationService.getLocation().latitude,});
</code>```

}

I hope you setup your project to connect to cloud firestore

Body:
i am trying to write data in a firestore collection using async in my flutter app.

I do have this code, but it seems not to be working.

import 'package:location/location.dart';

Location _locationService = new Location();
  Future<void> setUserData() async {
    Map<String, dynamic> userData = <String, dynamic>{
      'email': this._emailController.text,
      'password': this._passwordController.text,
      'firstname': this._firstNameController.text,
      'familyname': this._familyNameController.text,
      'phonenumber': this._phoneNumberController.text,
      'neighbourhood': this._neighbourhoodController.text,
      'latitude': await _locationService.getLocation().latitude,
    };
    crudObj.addData(userData);
  }

crudObj.addData writes directly to my firestore collection.

What am i doing wrong  ?

Body:
Looks like you haven't imported cloud_firestore to begin with.

Future<void> setUserData() async {
Firestore.instance.collection(*name of collection*).document(*name of document*).setData(
    {'email': this._emailController.text,
 'password': this._passwordController.text,
     'firstname': this._firstNameController.text,
    'familyname': this._familyNameController.text,
    'phonenumber': this._phoneNumberController.text,
    'neighbourhood': this._neighbourhoodController.text,
    'latitude': await _locationService.getLocation().latitude,});

}

I hope you setup your project to connect to cloud firestore


问:
Creating array from instance variables of a class
I have to create an array from teh instance variables of a class (the values, not the names). Currently my code simply uses getters for each variable but with 14 variables this is unsightly and not exactly code efficient. Is there any other way to do it more efficiently?</p>

答: You could make a method inside the class, like getInstanceVaribles, that returns an array with the instance variable values. So then you can use this.variable_names when assigning the values of the array instead of making and using getter methods, and this will add a layer of abstraction to your code, and simply the client code.


问:
Job queue with job affinity
I am currently facing a problem for which I am pretty sure there is an official name, but I don't know what to search the web for. I hope that if I describe the problem and the solution I have in mind, somebody is able to tell me the name of the design pattern (if there is one that matches what I am going to describe).

Basically, what I want to have is a job queue: I have multiple clients that create jobs (publishers), and a number of workers that process these jobs (consumers). Now I want to distribute the jobs created by the publishers to the various consumers, which is basically doable using almost any message queue with load balancing across a queue, e.g. using RabbitMQ or even MQTT 5.

However, now things get complicated... every job refers to an external entity, let's say a user. What I want is that the jobs for a single user get processed in order, but for multiple users in parallel. I do not have the requirement that the jobs for user X always go to worker Y, since they should be processed sequentially anyway.

Now I could solve this using RabbitMQ and its consistent hashing exchange, but then I have a data race when new workers enter the cluster, because RabbitMQ does not support re-locating the jobs that are already in a queue.

MQTT 5 does not support this either: Here this idea is known as "sticky shared subscriptions", but this is not official. It may be part of MQTT 6, or it may not. Who knows.

I have also taken a look at NSQ, NATS, and some other brokers. Most of them don't even support this very specific scenario, and those that do use consistent hashing, which has the previously mentioned data racing problem.

Now, the problem would be gone if the broker would not sort the jobs into queues, once the jobs arrive, but if it would track if a job for a specific user is already being processed: If so, it should delay all other jobs for this user, but all jobs for other users should still process. This is, AFAICS, not possible using RabbitMQ et al.

I am pretty sure that I am not the only person with a use case for that. I could e.g. think of users uploading videos to a video platform, and although uploaded videos are processed in parallel, all the videos uploaded by a single user are processed sequentially.

So, to cut a long story short: Is what I describe known under a common name? Something such as distributed job queue? Task dispatcher with task affinity? Or anything else? I have tried lots of terms, but didn't succeed. This may mean that there is no solution for this, but as said, it's hard to imagine that I'm the only person on the planet with this problem.

Any ideas what I could look for? And: Are there any tools that implement this? Any protocols?

PS: Just using a predefined routing key is not an option, since the user ids (which I just used as a made-up example here) are basically UUIDs, so there can be billions of it, so I need something more dynamic. Hence, consistent hashing is basically the correct approach, but as said, the distribution has to work piece by piece, not upfront, to avoid data races.

答: Kafka could help as it stores messages for a while, so you can poll them again</p>

Title: Job queue with job affinity


问:
Copying only non-empty cells into the HTML object which is being sent vie e-mail
I have a script that copies a table from a Google Sheet into an e-mail which is being sent automatically every day (there is a trigger). The table always starts in the cell K1 and it always has 6 columns, however, the number of rows is always different. I want to account for it and make it sorta dynamic. Here is the google script:

```<code>function CheckShare() {
  // Fetch the monthly sales
  var Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getRange("I2");
  var result = Range.getValue();
  var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getRange("K1:P10").getValues();

  var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'

  var htmltable = '<table ' + TABLEFORMAT +' ">';

for (row = 0; row<data.length; row++){

htmltable += '<tr>';

for (col = 0 ;col<data[row].length; col++){
  if (data[row][col] === "" || 0) {htmltable += '<td>' + 'None' + '</td>';}
  else
    if (row === 0)  {
      htmltable += '<th>' + data[row][col] + '</th>';
    }

  else {htmltable += '<td>' + data[row][col] + '</td>';}
}

     htmltable += '</tr>';
}

     htmltable += '</table>';
     Logger.log(data);
     Logger.log(htmltable);
  // Check totals sales
  if (result >0){
    // Fetch the email address
      var emailAddress = "reports@gmail.com";
    // Send Alert Email.
    var message = 'There are ' + result +' deviating metrics: https://docs.google.com/spreadsheets/d/1AQEBTt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698'
    + ' See the dashboard here: <link> ';
    var subject = 'Transaction Monitoring Alert: AA Share';
    MailApp.sendEmail(emailAddress, subject, message, {htmlBody:htmltable});
    }
}
</code>```

The current e-mail output looks likes this:

I want it to exclude rows with values "None" (empty cells)

答:
Use .getDataRange() rather than .getRange("K1:P10"), this should only return rows with actual data.

```<code>var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getDataRange().getValues();
</code>```

Edit:

Since you can't use .getDataRange() to achieve your goal. Try using .getLastRow() instead then passing that to your getRange(). The below code should get the range of K1:Px (x = however many rows of data you have).

```<code>var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share");
var lastRow = dataSheet.getLastRow();
var data = dataSheet.getRange(1, 11, lastRow, 6).getValues();
</code>```

Body:
I have a script that copies a table from a Google Sheet into an e-mail which is being sent automatically every day (there is a trigger). The table always starts in the cell K1 and it always has 6 columns, however, the number of rows is always different. I want to account for it and make it sorta dynamic. Here is the google script:

function CheckShare() {
  // Fetch the monthly sales
  var Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getRange("I2");
  var result = Range.getValue();
  var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getRange("K1:P10").getValues();

  var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'

  var htmltable = '
';

for (row = 0; row<data.length; row++){

htmltable += '
';

for (col = 0 ;col<data[row].length; col++){
  if (data[row][col] === "" || 0) {htmltable += '' + 'None' + '	';}
  else
    if (row === 0)  {
      htmltable += '' + data[row][col] + '	';
    }

  else {htmltable += '' + data[row][col] + '	';}
}

     htmltable += '
';
}

     htmltable += '
';
     Logger.log(data);
     Logger.log(htmltable);
  // Check totals sales
  if (result >0){
    // Fetch the email address
      var emailAddress = "reports@gmail.com";
    // Send Alert Email.
    var message = 'There are ' + result +' deviating metrics: https://docs.google.com/spreadsheets/d/1AQEBTt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698'
    + ' See the dashboard here: <link> ';
    var subject = 'Transaction Monitoring Alert: AA Share';
    MailApp.sendEmail(emailAddress, subject, message, {htmlBody:htmltable});
    }
}

The current e-mail output looks likes this:

I want it to exclude rows with values "None" (empty cells)

Body:
Use .getDataRange() rather than .getRange("K1:P10"), this should only return rows with actual data.

var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share").getDataRange().getValues();

Edit:

Since you can't use .getDataRange() to achieve your goal. Try using .getLastRow() instead then passing that to your getRange(). The below code should get the range of K1:Px (x = however many rows of data you have).

var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Daily AA Catergory Share");
var lastRow = dataSheet.getLastRow();
var data = dataSheet.getRange(1, 11, lastRow, 6).getValues();


问:
How do I apply headings to list items in Google Docs?
I am trying to apply the style "NORMAL" to a list item. While in the generated Google doc the list item's style is set to "NORMAL", the formatting is not the one set in the document's "NORMAL" style. Whereas, when I apply the style "NORMAL" to a paragraph, it works perfectly.

I've tried to use setHeading() and setAttributes().

```<code>var print = body.appendListItem(paragraph).setHeading(DocumentApp.ParagraphHeading.NORMAL);
print.setGlyphType(DocumentApp.GlyphType.BULLET);
</code>```

The style is rightly set but without the actual formatting.

答:
I create a style and then apply that style in one of my scripts and ti works fine

```<code>var replaceStyle = {};
replaceStyle[DocumentApp.Attribute.ITALIC] = true;
replaceStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = "#afeeee";
replaceStyle[DocumentApp.Attribute.STRIKETHROUGH] = false;
</code>```

And then later in the document

child.setAttributes(removeStyle);

this seems to work just fine for list items. Would that work or you?

Body:
I am trying to apply the style "NORMAL" to a list item. While in the generated Google doc the list item's style is set to "NORMAL", the formatting is not the one set in the document's "NORMAL" style. Whereas, when I apply the style "NORMAL" to a paragraph, it works perfectly.

I've tried to use setHeading() and setAttributes().

var print = body.appendListItem(paragraph).setHeading(DocumentApp.ParagraphHeading.NORMAL);
print.setGlyphType(DocumentApp.GlyphType.BULLET);

The style is rightly set but without the actual formatting.

Body:
I create a style and then apply that style in one of my scripts and ti works fine

var replaceStyle = {};
replaceStyle[DocumentApp.Attribute.ITALIC] = true;
replaceStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = "#afeeee";
replaceStyle[DocumentApp.Attribute.STRIKETHROUGH] = false;

And then later in the document

child.setAttributes(removeStyle);

this seems to work just fine for list items. Would that work or you?


问:
ml5 (ml5.js): How do I add my own data to the KNN classifier?
Trying to use the ml5 (ml5js.org) KNN classifier on a game I made. But I don't understand how to add my own data to it.

<!DOCTYPE html>

  <title>Getting Started with ml5.js</title>

```
</div>
</div>
</p>

<p>I expected that code to add to the classifier instead Im getting an error message: </p>

<blockquote>
  <p>"Uncaught TypeError: Cannot read property 'length' of undefined"</p>
</blockquote>

<p>The ml5 page has a KNN classifier example where they convert their data in the following way.</p>

```  // Convert poses results to a 2d array [[score0, x0, y0],...,[score16, x16, y16]]
  const poseArray = poses[0].pose.keypoints.map(p => [p.score, p.position.x, p.position.y]);
```

<p>Unsure but I think their data looks something like:</p>

```{
    "score": 0.32371445304906,
    "keypoints": [ { "position": { "x": 301.42237830162, "y": 177.69162777066 }, "score": 0.99799561500549 },...
    ]
  }
```

答:
Needed the last vertion, so change part of the link:
ml5@0.1.3
to
ml5@0.3.0

And it works.

Body:
Trying to use the ml5 (ml5js.org) KNN classifier on a game I made. But I don't understand how to add my own data to it.

<!DOCTYPE html>

  <title>Getting Started with ml5.js</title>

I expected that code to add to the classifier instead Im getting an error message:

"Uncaught TypeError: Cannot read property 'length' of undefined"

The ml5 page has a KNN classifier example where they convert their data in the following way.

  // Convert poses results to a 2d array [[score0, x0, y0],...,[score16, x16, y16]]
  const poseArray = poses[0].pose.keypoints.map(p => [p.score, p.position.x, p.position.y]);

Unsure but I think their data looks something like:

{
    "score": 0.32371445304906,
    "keypoints": [ { "position": { "x": 301.42237830162, "y": 177.69162777066 }, "score": 0.99799561500549 },...
    ]
  }


问:
IIS 6.0 suddenly shows directory listing instead of MVC 3 app
Over night an (internal, luckily) MVC web application has stopped working for me, without anything being changed as far as I know. The application itself absolutely hasn't been tinkered with in the last two days and the same goes for IIS.

The problem is that I get a directory listing of my www-folder instead of the applications default action (/Home/Index).

My www-folder contains the standard stuff:

```<code>bin
Content
Scripts
Views
Global.asax
Web.config
</code>```

I have tried:

setting a "Specific Page" as Start Action but it doesn't solve the problem.

restarting the web page in IIS

enable/disabled "default content page" in IIS. Doesn't help, but IIS does pick up on a Default.html if I place it in the www-folder.

Now, this has happened once before. At the time I was on vacation and it was solved by restarting the entire World Wide Web Publishing Service. While it might work this time as well, I'd rather figure out the root of the problem before temporarily fixing it just to have it happen again further down the road. So while a WWW Publishing Service restart might get the site running again I'd rather understand why it happened in the first place before fixing it this way.

Finally, note that I'm running other MVC apps on the same IIS server and have never gotten this problem with them.

答:
I had the same problem and here is how I resolved it.

I had a problem with the Global.asax file on the TFS server inheriting from the WebAPI project (and not the web project) although the web project was chosen as the startup project in Visual Studio. When I ran my build the Web API  was set as the start up project on the web server since it was deploying the version on the TFS server that was inheriting from the WebAPI project. To resolve this I set another project as the startup project and then changed the web project to be the startup project again in Visual studio. I had to do this since TFS complained that there were no pending changes when I tried to check the version I had on my machine into TFS. I then checked my code in and ran the build again. This resolved my issue.

Body:
Over night an (internal, luckily) MVC web application has stopped working for me, without anything being changed as far as I know. The application itself absolutely hasn't been tinkered with in the last two days and the same goes for IIS.

The problem is that I get a directory listing of my www-folder instead of the applications default action (/Home/Index).

My www-folder contains the standard stuff:

bin
Content
Scripts
Views
Global.asax
Web.config

I have tried:

setting a "Specific Page" as Start Action but it doesn't solve the problem.

restarting the web page in IIS

enable/disabled "default content page" in IIS. Doesn't help, but IIS does pick up on a Default.html if I place it in the www-folder.

Now, this has happened once before. At the time I was on vacation and it was solved by restarting the entire World Wide Web Publishing Service. While it might work this time as well, I'd rather figure out the root of the problem before temporarily fixing it just to have it happen again further down the road. So while a WWW Publishing Service restart might get the site running again I'd rather understand why it happened in the first place before fixing it this way.

Finally, note that I'm running other MVC apps on the same IIS server and have never gotten this problem with them.


问:
How to convert a list into a complex table with rearranged and individually named columns?
I have a list (called list) with 30 data frames that all have individual names (named after firms) and consist of the output of a regression. The data frames all look like this:

```<code>term         estimate std.error statistic p.value
(Intercept)  0.0012   0.000     2.84      0.00
x$Return     0.8119   0.055     14.49     1.08
x$ReturnDum  0.2989   0.083     0.10      0.05
</code>```

For my output, I need a (pdf or png) file with a regression table, that consists of all the outputs above. The table should look something like this:

```<code>Firm    (Intercept)  x$Return    x$ReturnDum
Firm1    0.0012       0.8119      0.2989
        (0.000)***   (0.055)     (0.083)**
Firm2    0.0242       0.2359      0.0239
        (0.000)***   (0.050)**   (0.909)
...
</code>```

Basically, it should contain four columns (called Firm, (Intercept), x$Return and x$ReturnDum) and 30 rows, one row for each firm. Each row should contain the firm name (under Firm), the value of the estimate and the value of the std.error for each remaining column (preferably together with the significance stars - 3 stars for a p.value < 0.01, 2 stars for a p.value < 0.05 and 1 star for a p.value < 0.1, no star for everything above).

I have not figured out how to transform my list into this kind of table and would appreciate any help as I am still a beginner with R! Thanks.

答:
We can use map from purrr to loop over the list, mutate the data.frame column 'std.error' to format into a string by concatenating "***" when the p.value is less than 0.25 or else return the column as a character type (case_when checks type), select the columns of interest, transpose (t), convert to data.frame, and create an id column 'Firm' based on the names of the list (by default, if there is no names, adds sequence number).  Note that map returns a list, while the suffix _df converts it to a single data.frame output by row binding the list elements

```<code>library(tidyverse)
map_df(lst1, ~
          .x  %>%
          mutate(std.error = case_when(p.value < 0.05 ~
                   str_c("(", std.error, ")", "***"),
                     TRUE ~ as.character(std.error)),
                 estimate = round(estimate, 3)) %>%
          select(estimate, std.error) %>%
          t %>%
           as.data.frame , .id = 'Firm')
</code>```

For multiple categories, an easier option is cut or findInterval

```<code>map_df(lst1, ~
     .x %>%
       mutate(std.error = str_c("(", round(std.error, 3), ")",
            c("****", "***", "**", "*")[findInterval(p.value,
            c(0.01, 0.05, 0.1))+1]),
            estimate = round(estimate, 3)) %>%
       select(estimate, std.error) %>%
       t %>%
       as.data.frame %>%
       rename_all(~ c("Intercept)",  "x$Return",    "x$ReturnDum")), .id = "Firm")
</code>```

Body:
I have a list (called list) with 30 data frames that all have individual names (named after firms) and consist of the output of a regression. The data frames all look like this:

term         estimate std.error statistic p.value
(Intercept)  0.0012   0.000     2.84      0.00
x$Return     0.8119   0.055     14.49     1.08
x$ReturnDum  0.2989   0.083     0.10      0.05

For my output, I need a (pdf or png) file with a regression table, that consists of all the outputs above. The table should look something like this:

Firm    (Intercept)  x$Return    x$ReturnDum
Firm1    0.0012       0.8119      0.2989
        (0.000)***   (0.055)     (0.083)**
Firm2    0.0242       0.2359      0.0239
        (0.000)***   (0.050)**   (0.909)
...

Basically, it should contain four columns (called Firm, (Intercept), x$Return and x$ReturnDum) and 30 rows, one row for each firm. Each row should contain the firm name (under Firm), the value of the estimate and the value of the std.error for each remaining column (preferably together with the significance stars - 3 stars for a p.value < 0.01, 2 stars for a p.value < 0.05 and 1 star for a p.value < 0.1, no star for everything above).

I have not figured out how to transform my list into this kind of table and would appreciate any help as I am still a beginner with R! Thanks.

Body:
We can use map from purrr to loop over the list, mutate the data.frame column 'std.error' to format into a string by concatenating "***" when the p.value is less than 0.25 or else return the column as a character type (case_when checks type), select the columns of interest, transpose (t), convert to data.frame, and create an id column 'Firm' based on the names of the list (by default, if there is no names, adds sequence number).  Note that map returns a list, while the suffix _df converts it to a single data.frame output by row binding the list elements

library(tidyverse)
map_df(lst1, ~
          .x  %>%
          mutate(std.error = case_when(p.value < 0.05 ~
                   str_c("(", std.error, ")", "***"),
                     TRUE ~ as.character(std.error)),
                 estimate = round(estimate, 3)) %>%
          select(estimate, std.error) %>%
          t %>%
           as.data.frame , .id = 'Firm')

For multiple categories, an easier option is cut or findInterval

map_df(lst1, ~
     .x %>%
       mutate(std.error = str_c("(", round(std.error, 3), ")",
            c("****", "***", "**", "*")[findInterval(p.value,
            c(0.01, 0.05, 0.1))+1]),
            estimate = round(estimate, 3)) %>%
       select(estimate, std.error) %>%
       t %>%
       as.data.frame %>%
       rename_all(~ c("Intercept)",  "x$Return",    "x$ReturnDum")), .id = "Firm")


问:
How to clone an Object by copy ByteArrayOutputStream into ByteArray, then call it by ByteArrayInputStream?
I try to clone an Object by 1) shoving it into a ByteArrayOutputStream 2) assigning the stream to a byte array 3) reading the byte array by ByteArrayInputStream. However, this won't work as I can not assign the OutputStream to the byte array, the line will just not execute.

Apporoach is based Java Serializable Object to Byte Array

```<code>public Bank clone() {
        Bank objektKopie = null;
        byte[] byteKopie = null;
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = null;
        try {
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);
            oo.writeObject(this);
            oo.flush() ;
            byteKopie = bo.toByteArray(); // THIS WILL NOT HAPPEN
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
               bo.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        ByteArrayInputStream bi = new ByteArrayInputStream(byteKopie); // byteKopie IS STILL NULL
        ObjectInputStream oi = null;
        try {
            oi = new ObjectInputStream(bi);
            objektKopie = (Bank) oi.readObject();
        } catch (Exception e) { System.out.println(e.getMessage()); }
        return objektKopie;
    }
</code>```

答: Your code is throwing "NotSerializable" exception, your class Bank NEEDS to implement Serializable</p>

Body:
I try to clone an Object by 1) shoving it into a ByteArrayOutputStream 2) assigning the stream to a byte array 3) reading the byte array by ByteArrayInputStream. However, this won't work as I can not assign the OutputStream to the byte array, the line will just not execute.

Apporoach is based Java Serializable Object to Byte Array

public Bank clone() {
        Bank objektKopie = null;
        byte[] byteKopie = null;
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = null;
        try {
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);
            oo.writeObject(this);
            oo.flush() ;
            byteKopie = bo.toByteArray(); // THIS WILL NOT HAPPEN
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
               bo.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        ByteArrayInputStream bi = new ByteArrayInputStream(byteKopie); // byteKopie IS STILL NULL
        ObjectInputStream oi = null;
        try {
            oi = new ObjectInputStream(bi);
            objektKopie = (Bank) oi.readObject();
        } catch (Exception e) { System.out.println(e.getMessage()); }
        return objektKopie;
    }


问:
How to make all the delete href tags make work with java scripts if clicked in Django
I have written a java script for the conformation box before deleting the comments. If user clicks delete, it should pop the box for delete conformation. If i have series of comments of same user, as i am printing the comments in loop the java script logic is staying with the first delete comment itself until i delete it. If i say no, and try to delete second comment, the java script logic is not function. Can any one help me with this issue. Should i need to place the java script logic some where else in the code. Does that recognize?</p>

```<code><div class="container">
<h2 class="text-center">User Comments</h2>

{% for comment in comments%}
   <p class="text-secondary text-center">{{ comment.created }}</p>
   <p> {{ comment.body }} </p>
   {% if comment.user == request.user.username %}
      <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'comment-update' comment.id %}">Update Comment</a>
      <a class="btn btn-danger btn-sm mt-1 mb-1"  id="delete-object" >Delete Comment
      <script type="text/javascript">
         document.getElementById("delete-object").onclick = function(){
            if (confirm('Delete the comment')){
                alert('hi');
                #Link to delete comment}}
      </script>

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

答:
You are assigning the same id to multiple a tags. The id must be unique in the document.

Try with someting like

```<code><div class="container">
<h2 class="text-center">User Comments</h2>

{% for comment in comments%}
   <p class="text-secondary text-center">{{ comment.created }}</p>
   <p> {{ comment.body }} </p>
   {% if comment.user == request.user.username %}
      <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'comment-update' comment.id %}">Update Comment</a>
      <a class="btn btn-danger btn-sm mt-1 mb-1"  data-action="delete-object" >Delete Comment
      <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            deleteLinks = document.querySelectorAll('[data-action="delete-object"]')
            deleteLinks.forEach(link => {
                link.addEventListener('click', function() {
                    if (confirm('Delete the comment')) {
                        alert('hi')
                        # link to the comment
                    }
                })
            })
        })
      </script>
    {% endif %}
{% endfor % }
</code>```

Body:
I have written a java script for the conformation box before deleting the comments. If user clicks delete, it should pop the box for delete conformation. If i have series of comments of same user, as i am printing the comments in loop the java script logic is staying with the first delete comment itself until i delete it. If i say no, and try to delete second comment, the java script logic is not function. Can any one help me with this issue. Should i need to place the java script logic some where else in the code. Does that recognize?

User Comments

{% for comment in comments%}

{{ comment.created }}

 {{ comment.body }}

   {% if comment.user == request.user.username %}
      Update Comment
      Delete Comment

    {% endif %}

Body:
You are assigning the same id to multiple a tags. The id must be unique in the document.

Try with someting like

<div class="container">
<h2 class="text-center">User Comments</h2>

{% for comment in comments%}
   <p class="text-secondary text-center">{{ comment.created }}</p>
   <p> {{ comment.body }} </p>
   {% if comment.user == request.user.username %}
      <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'comment-update' comment.id %}">Update Comment</a>
      <a class="btn btn-danger btn-sm mt-1 mb-1"  data-action="delete-object" >Delete Comment
      <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            deleteLinks = document.querySelectorAll('[data-action="delete-object"]')
            deleteLinks.forEach(link => {
                link.addEventListener('click', function() {
                    if (confirm('Delete the comment')) {
                        alert('hi')
                        # link to the comment
                    }
                })
            })
        })
      </script>
    {% endif %}
{% endfor % }


问:
Multiple lookups based on users
I'm trying to display a list of users who have broken rules in a system.
The data I'm working off is structured like:

```<code>TABLE_1:
USER | PRIVILEGE
 A    |  1
 A    |  2
 A    |  3
 B    |  1
 B    |  3
 C    |  2
 C    |  3
 C    |  4

TABLE_2:
RULE_ID | PRIVILEGE_1 | PRIVILEGE_2
    1   |       1     |       3
    2   |       2     |       3
</code>```

The goal is to find users that hold both PRIVILEGE_1 and PRIVILEGE_2 from the TABLE_2 and return them in a new table with the columns "USER" and "RULE_ID" to show which rules they have broken. For example...

```<code>TABLE_3:
USER  | RULE_ID
 A    |  1
 A    |  2
 B    |  1
 C    |  2
</code>```

Tried filtering and lookup values but haven't been able to find a solution yet. Any help appreciated!

答:
Ok, this is how I interpret your request: All "Rules" are composed of two privileges.  Find all users who are associated with both privileges in a rule.

I solved this using Power Query.

I used your sample data (I called Table1 "User" and Table2 "Rule") and created the result table User_Rule.  Here is the final M query from the Advanced Editor.

```<code>let
    Source = Rule,
    #"Merged Queries" = Table.NestedJoin(Source, {"PRIVILEGE_1"}, User, {"PRIVILEGE"}, "User", JoinKind.LeftOuter),
    #"Expanded User" = Table.ExpandTableColumn(#"Merged Queries", "User", {"USER"}, {"USER"}),
    #"Reordered Columns" = Table.ReorderColumns(#"Expanded User",{"USER", "RULE_ID", "PRIVILEGE_1", "PRIVILEGE_2"}),
    #"Merged Queries1" = Table.NestedJoin(#"Reordered Columns", {"PRIVILEGE_2", "USER"}, User, {"PRIVILEGE", "USER"}, "User", JoinKind.Inner),
    #"Removed Columns" = Table.RemoveColumns(#"Merged Queries1",{"PRIVILEGE_1", "PRIVILEGE_2", "User"})
in
    #"Removed Columns"
</code>```

As Applied Steps:

Create User_Rule as a reference to Rule

Do a Merge Queries to User on RULE.PRIVELEGE_1 and USER.PRIVILEGE.  Use a left join here.

Expand the 'User' column from the Merged Table

Reorder the columns

Do another merge queries to User.  Notice that this join is on two fields, and it is an inner join, not a left join.  Hold down the [ctrl] key to select more than one field from the merge queries dialog.  Make sure you select the fields in the same order (small numerals 1 and 2 will appear in the column headers to indicate the order).

Remove the unnecessary fields.

Hope it helps!

Title: Multiple lookups based on users

Body:
I'm trying to display a list of users who have broken rules in a system.
The data I'm working off is structured like:

TABLE_1:
USER | PRIVILEGE
 A    |  1
 A    |  2
 A    |  3
 B    |  1
 B    |  3
 C    |  2
 C    |  3
 C    |  4

TABLE_2:
RULE_ID | PRIVILEGE_1 | PRIVILEGE_2
    1   |       1     |       3
    2   |       2     |       3

The goal is to find users that hold both PRIVILEGE_1 and PRIVILEGE_2 from the TABLE_2 and return them in a new table with the columns "USER" and "RULE_ID" to show which rules they have broken. For example...

TABLE_3:
USER  | RULE_ID
 A    |  1
 A    |  2
 B    |  1
 C    |  2

Tried filtering and lookup values but haven't been able to find a solution yet. Any help appreciated!

Body:
Ok, this is how I interpret your request: All "Rules" are composed of two privileges.  Find all users who are associated with both privileges in a rule.

I solved this using Power Query.

I used your sample data (I called Table1 "User" and Table2 "Rule") and created the result table User_Rule.  Here is the final M query from the Advanced Editor.

let
    Source = Rule,
    #"Merged Queries" = Table.NestedJoin(Source, {"PRIVILEGE_1"}, User, {"PRIVILEGE"}, "User", JoinKind.LeftOuter),
    #"Expanded User" = Table.ExpandTableColumn(#"Merged Queries", "User", {"USER"}, {"USER"}),
    #"Reordered Columns" = Table.ReorderColumns(#"Expanded User",{"USER", "RULE_ID", "PRIVILEGE_1", "PRIVILEGE_2"}),
    #"Merged Queries1" = Table.NestedJoin(#"Reordered Columns", {"PRIVILEGE_2", "USER"}, User, {"PRIVILEGE", "USER"}, "User", JoinKind.Inner),
    #"Removed Columns" = Table.RemoveColumns(#"Merged Queries1",{"PRIVILEGE_1", "PRIVILEGE_2", "User"})
in
    #"Removed Columns"

As Applied Steps:

Create User_Rule as a reference to Rule

Do a Merge Queries to User on RULE.PRIVELEGE_1 and USER.PRIVILEGE.  Use a left join here.

Expand the 'User' column from the Merged Table

Reorder the columns

Do another merge queries to User.  Notice that this join is on two fields, and it is an inner join, not a left join.  Hold down the [ctrl] key to select more than one field from the merge queries dialog.  Make sure you select the fields in the same order (small numerals 1 and 2 will appear in the column headers to indicate the order).

Remove the unnecessary fields.

Hope it helps!