问:
How to prevent unnecessary renders in a Component using useContext?
I would like to know how can I avoid unnecessary updates on a child component that does not receive props, but uses useContext.

I've added React.memo to the Child2 component for me to make some demo tests.

As you can see, when I change the input value which uses context to pass the data to child1, Child2 does not re-render, as React.memo prevents this behavior.

How can I prevent unnecessary renders in Child1 as well? I know that React.memo won't work as it needs props, and with context this will not happen, as no props are being passed down to this component

App.js

```<code>import React, {useState} from 'react';
import './App.css';
import Child1 from "./Child1";
import Child2 from "./Child2";
import SillyContext from './context'

function App() {
    const [name, setName] = useState('Radha');
    const [count, setCount] = useState(0)

    const increaseCount = () => {
        setCount(prevState => prevState + 1)
    }

    return (
        <div className="App">
            <Child2 count={count}/>
            <button onClick={increaseCount}>Increase</button>
            <input type="text" value={name} onChange={(event => setName(event.target.value))}/>
            <SillyContext.Provider value={{name}}>
                <Child1/>
            </SillyContext.Provider>
        </div>
    );
}

export default App;
</code>```

Child1

```<code>import React, {useContext} from "react";
import SillyContext from './context'

export default function Child1() {
    const sillyContext = useContext(SillyContext)
    console.log('[Child 1 ran]')
    return (
        <div>
            <div>[Child 1]: {sillyContext.name}</div>
        </div>
    )
}
</code>```

Child2

```<code>import React from 'react'

export default React.memo(function Child2(props) {
    console.log('[Child2 Ran!]')
    return <div>[Child2] - Count: {props.count}</div>
})
</code>```

答:
You can use useMemo inside Child1 component. It doesn't solve rerendering problem, but it is some kind of improvement.

Following snippet is third variant proposed by React core dev

we could make our code a bit more verbose but keep it in a
  single component by wrapping return value in useMemo and specifying
  its dependencies. Our component would still re-execute, but React
  wouldn't re-render the child tree if all useMemo inputs are the same.

const { useState, useEffect, createContext, useContext, useMemo } = React;

const SillyContext = createContext();

const Child2 = React.memo(({count}) => {
    return
Count: {count}

})

const Child1 = () => {
    const {name} = useContext(SillyContext);

    return useMemo(() => {
    console.log('Child1');
      return

Child 1: {name}

}, [name])
}

const App = () => {
  const [count, setCount] = useState(0);

  const increaseCount = () => {
        setCount(prevState => prevState + 1)
  }

return

  <Child2 count={count}/>
   <button onClick={increaseCount}>Increase</button>
  <Child1/>

}

ReactDOM.render(
    <SillyContext.Provider value={{name: 'test'}}>
      <App />
    </SillyContext.Provider>,
    document.getElementById('root')
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div></code>```

Body:
I would like to know how can I avoid unnecessary updates on a child component that does not receive props, but uses useContext.

I've added React.memo to the Child2 component for me to make some demo tests.

As you can see, when I change the input value which uses context to pass the data to child1, Child2 does not re-render, as React.memo prevents this behavior.

How can I prevent unnecessary renders in Child1 as well? I know that React.memo won't work as it needs props, and with context this will not happen, as no props are being passed down to this component

App.js

import React, {useState} from 'react';
import './App.css';
import Child1 from "./Child1";
import Child2 from "./Child2";
import SillyContext from './context'

function App() {
    const [name, setName] = useState('Radha');
    const [count, setCount] = useState(0)

    const increaseCount = () => {
        setCount(prevState => prevState + 1)
    }

    return (

            <Child2 count={count}/>
            <button onClick={increaseCount}>Increase</button>
            <input type="text" value={name} onChange={(event => setName(event.target.value))}/>
            <SillyContext.Provider value={{name}}>
                <Child1/>
            </SillyContext.Provider>

    );
}

export default App;

Child1

import React, {useContext} from "react";
import SillyContext from './context'

export default function Child1() {
    const sillyContext = useContext(SillyContext)
    console.log('[Child 1 ran]')
    return (

[Child 1]: {sillyContext.name}

    )
}

Child2

import React from 'react'

export default React.memo(function Child2(props) {
    console.log('[Child2 Ran!]')
    return
[Child2] - Count: {props.count}

})

Body:
You can use useMemo inside Child1 component. It doesn't solve rerendering problem, but it is some kind of improvement.

Following snippet is third variant proposed by React core dev

we could make our code a bit more verbose but keep it in a
  single component by wrapping return value in useMemo and specifying
  its dependencies. Our component would still re-execute, but React
  wouldn't re-render the child tree if all useMemo inputs are the same.

const { useState, useEffect, createContext, useContext, useMemo } = React;

const SillyContext = createContext();

const Child2 = React.memo(({count}) => {
    return <div>Count: {count}</div>
})

const Child1 = () => {
    const {name} = useContext(SillyContext);

    return useMemo(() => {
    console.log('Child1');
      return <div>
        <div>Child 1: {name}</div>
      </div>}, [name])
}

const App = () => {
  const [count, setCount] = useState(0);

  const increaseCount = () => {
        setCount(prevState => prevState + 1)
  }

return <div>
  <Child2 count={count}/>
   <button onClick={increaseCount}>Increase</button>
  <Child1/>
</div>
}

ReactDOM.render(
    <SillyContext.Provider value={{name: 'test'}}>
      <App />
    </SillyContext.Provider>,
    document.getElementById('root')
  );

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>


来源: stackexchange

问:
Installing only single package via Composer without updating other packages
I need to install a single composer package into a project - maatwebsite/excel ~2.1.0. Each time composer updates, it updates all packages in composer.json. How can I avoid updating packages aside from the excel library?

I have tried the following commands but they don't seem to be working:

```<code>composer require maatwebsite/excel ~2.1.0
composer require vendor/maatwebsite/excel ~2.1.0
composer update maatwebsite/excel ~2.1.0
composer update vendor/maatwebsite/excel ~2.1.0
</code>```

I've also tried using the --lock attribute but that's also not working.

Can anybody tell me what I am doing wrong?

答:
To skip updates on any other package, simply add --no-update to your call. This instructs Composer to only require that new package and not update anything else.

The resulting call could then look like the following:

```<code>composer require maatwebsite/excel ~2.1.0 --no-update
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to install a single composer package into a project - maatwebsite/excel ~2.1.0. Each time composer updates, it updates all packages in composer.json. How can I avoid updating packages aside from the excel library?

I have tried the following commands but they don't seem to be working:

composer require maatwebsite/excel ~2.1.0
composer require vendor/maatwebsite/excel ~2.1.0
composer update maatwebsite/excel ~2.1.0
composer update vendor/maatwebsite/excel ~2.1.0

I've also tried using the --lock attribute but that's also not working.

Can anybody tell me what I am doing wrong?

Body:
To skip updates on any other package, simply add --no-update to your call. This instructs Composer to only require that new package and not update anything else.

The resulting call could then look like the following:

composer require maatwebsite/excel ~2.1.0 --no-update


问:
Java version of matlab's linspace
Is there a java version of matlab's colon operator or linspace? For instance, I'd like to make a for loop for evenly spaced numbers, but I don't want to bother with creating an array of those numbers manually.

For example to get all integers from 1 to 30, in matlab I would type:

```<code>1:30
</code>```

or

```<code>linspace(1,30)
</code>```

答:
For the two variable call, @x4u is correct.  The three variable call will be quite a bit harder to emulate.

For instance, i think that linspace(1,30,60) should produce values 1, 1.5, 2, 2.5, 3, 3.5..., or maybe that's the values for linspace(1,30,59)--either way, same problem.

With this format you'll have to do the calculations yourself--Personally I'd create a new object to do the whole thing for me and forget the for loop.

```<code>counter=new Linspace(1,30,60);
while(counter.hasNext()) {
    process(counter.getNextFloat())
}
</code>```

or simply

```<code>while(float f : new Linspace(1,30,60)) {
    process(f);
}
</code>```

if you have your Linspace object implement Iterable.

Then the inside of the counter object should be pretty obvious to implement and it will easily communicate to you what it is doing without obfuscating your code with a bunch of numeric calculations to figure out ratios.

An implementation might be something like this:
(NOTE: Untested and I'm pretty sure this would be vulnerable to edge cases and floating point errors!  It also probably won't handle end < start for backwards counting, it's just a suggestion to get you going.)

```<code>public class Linspace {
    private float current;
    private final float end;
    private final float step;
    public Linspace(float start, float end, float totalCount) {
        this.current=start;
        this.end=end;
        this.step=(end - start) / totalCount;
    }
    public boolean hasNext() {
        return current < (end + step/2); //MAY stop floating point error
    }
    public float getNextFloat() {
        current+=step;
        return current;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java version of matlab's linspace

Body:
Is there a java version of matlab's colon operator or linspace? For instance, I'd like to make a for loop for evenly spaced numbers, but I don't want to bother with creating an array of those numbers manually.

For example to get all integers from 1 to 30, in matlab I would type:

1:30

or

linspace(1,30)

Body:
For the two variable call, @x4u is correct.  The three variable call will be quite a bit harder to emulate.

For instance, i think that linspace(1,30,60) should produce values 1, 1.5, 2, 2.5, 3, 3.5..., or maybe that's the values for linspace(1,30,59)--either way, same problem.

With this format you'll have to do the calculations yourself--Personally I'd create a new object to do the whole thing for me and forget the for loop.

counter=new Linspace(1,30,60);
while(counter.hasNext()) {
    process(counter.getNextFloat())
}

or simply

while(float f : new Linspace(1,30,60)) {
    process(f);
}

if you have your Linspace object implement Iterable.

Then the inside of the counter object should be pretty obvious to implement and it will easily communicate to you what it is doing without obfuscating your code with a bunch of numeric calculations to figure out ratios.

An implementation might be something like this:
(NOTE: Untested and I'm pretty sure this would be vulnerable to edge cases and floating point errors!  It also probably won't handle end < start for backwards counting, it's just a suggestion to get you going.)

public class Linspace {
    private float current;
    private final float end;
    private final float step;
    public Linspace(float start, float end, float totalCount) {
        this.current=start;
        this.end=end;
        this.step=(end - start) / totalCount;
    }
    public boolean hasNext() {
        return current < (end + step/2); //MAY stop floating point error
    }
    public float getNextFloat() {
        current+=step;
        return current;
    }
}


问:
How to set tooltip ONLY on truncated cell dynamically
My goal is to display a tooltip on cells where the text is truncated at launch, but also during runtime, which means that if a column is resized, some tool tip may appear or dissapear.

In my cell factory, I thought there will be a property that I could bind or listen to, and simply link a tooltip to this, but I found none.

Here's my code that set a tool tip on every cell in the cell factory:

```<code>public void updateItem(T item, boolean empty) {
    super.updateItem(item, empty);

    if (empty || item == null) {
        setText(null);
        setGraphic(null);
    } else {
        setText(adapter.getCellContentParser().toString(item));
        setTooltip(new Tooltip(this.getText());
    }
}
</code>```

Please note that I look for every possible solution on the site, like these ones :
https://stackoverflow.com/questions/15683907/javafx-tableviews-cellvalue-is-not-enough-to-display-in-columns-it-will-be-cl#=

How to show tooltip only on those table cells which text is ellipsized (...)?

And they are perfectly fine when you launch your program, but don't work when you resizing your columns.

Is there something I'm missing ? I find it really strange that there is not an observableproperty for this kind of thing.

答:
This is a bit of a hack, but you can retrieve the child Text node in the cell by searching the scene graph below the cell after layout is performed, and then create a binding for the tooltip that checks if the cell's text is the same as the text's text. Note that we ignore any graphic set on the cell here, so this only searches for the Text node displaying the cell's text property:

```<code>setCellFactory(tc -> new TableCell<>() {
    private Text text ;
    private Tooltip tooltip = new Tooltip() ;

    {
        tooltip.textProperty().bind(textProperty());
    }

    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (item == null || empty) {
            setText("");
        } else {
            setText(item);
        }
    }

    @Override
    protected void layoutChildren() {
        super.layoutChildren();
        if (text == null) {
            text = findTextNode(this);
            bindTooltip();
        }
    }

    private void bindTooltip() {
        tooltipProperty().bind(Bindings.createObjectBinding(() -> {
            if (getItem()==null) return null ;
            if (getText().equals(text.getText())) return null ;
            return tooltip ;
        }, text.textProperty(), itemProperty(), textProperty()));
    }

    // recursively search through child node graph to find the Text node
    private Text findTextNode(Node root) {
        // Ignore the graphic and all its child nodes:
        if (root == getGraphic()) {
            return null ;
        }
        if (root instanceof Text) {
            return (Text) root ;
        }
        if (root instanceof Parent) {
            for (Node node : ((Parent)root).getChildrenUnmodifiable()) {
                Text text = findTextNode(node);
                if (text != null) return text ;
            }
        }
        return null ;
    }
});
</code>```

Here's a complete working example:

```<code>import java.util.Random;
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) {

        var table = new TableView<Item>();
        var itemCol = column("Item", Item::nameProperty);
        var valueCol = column("Value", Item::valueProperty);
        table.getColumns().add(itemCol);
        table.getColumns().add(valueCol);

        itemCol.setCellFactory(tc -> new TableCell<>() {
            private Text text ;
            private Tooltip tooltip = new Tooltip() ;

            {
                tooltip.textProperty().bind(textProperty());
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText("");
                } else {
                    setText(item);
                }
            }

            @Override
            protected void layoutChildren() {
                super.layoutChildren();
                if (text == null) {
                    text = findTextNode(this);
                    bindTooltip();
                }
            }

            private void bindTooltip() {
                tooltipProperty().bind(Bindings.createObjectBinding(() -> {
                    if (getItem()==null) return null ;
                    if (getText().equals(text.getText())) return null ;
                    return tooltip ;
                }, text.textProperty(), itemProperty(), textProperty()));
            }

            // recursively search through child node graph to find the Text node
            private Text findTextNode(Node root) {
                // Ignore the graphic and all its child nodes:
                if (root == getGraphic()) {
                    return null ;
                }
                if (root instanceof Text) {
                    return (Text) root ;
                }
                if (root instanceof Parent) {
                    for (Node node : ((Parent)root).getChildrenUnmodifiable()) {
                        Text text = findTextNode(node);
                        if (text != null) return text ;
                    }
                }
                return null ;
            }
        });

        var rng = new Random();
        for (int i = 1 ; i <= 40 ; i++) {
            table.getItems().add(new Item("Item "+i, rng.nextInt(100)));
        }

        var scene = new Scene(new BorderPane(table));
        stage.setScene(scene);
        stage.show();
    }

    public static <S,T>  TableColumn<S,T> column(String title, Function<S, Property<T>> prop) {
        TableColumn<S,T> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> prop.apply(cellData.getValue()));
        return col ;
    }

    public static class Item {
        private final StringProperty name = new SimpleStringProperty();
        private final IntegerProperty value = new SimpleIntegerProperty();
        public Item(String name, int value) {
            this.name.set(name);
            this.value.set(value);
        }

        public final StringProperty nameProperty() {
            return name ;
        }

        public final IntegerProperty valueProperty() {
            return value ;
        }
    }

    public static void main(String[] args) {
        launch();
    }

}
</code>```

Body:
My goal is to display a tooltip on cells where the text is truncated at launch, but also during runtime, which means that if a column is resized, some tool tip may appear or dissapear.

In my cell factory, I thought there will be a property that I could bind or listen to, and simply link a tooltip to this, but I found none.

Here's my code that set a tool tip on every cell in the cell factory:

public void updateItem(T item, boolean empty) {
    super.updateItem(item, empty);

    if (empty || item == null) {
        setText(null);
        setGraphic(null);
    } else {
        setText(adapter.getCellContentParser().toString(item));
        setTooltip(new Tooltip(this.getText());
    }
}

Please note that I look for every possible solution on the site, like these ones :
https://stackoverflow.com/questions/15683907/javafx-tableviews-cellvalue-is-not-enough-to-display-in-columns-it-will-be-cl#=

How to show tooltip only on those table cells which text is ellipsized (...)?

And they are perfectly fine when you launch your program, but don't work when you resizing your columns.

Is there something I'm missing ? I find it really strange that there is not an observableproperty for this kind of thing.

Body:
This is a bit of a hack, but you can retrieve the child Text node in the cell by searching the scene graph below the cell after layout is performed, and then create a binding for the tooltip that checks if the cell's text is the same as the text's text. Note that we ignore any graphic set on the cell here, so this only searches for the Text node displaying the cell's text property:

setCellFactory(tc -> new TableCell<>() {
    private Text text ;
    private Tooltip tooltip = new Tooltip() ;

    {
        tooltip.textProperty().bind(textProperty());
    }

    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (item == null || empty) {
            setText("");
        } else {
            setText(item);
        }
    }

    @Override
    protected void layoutChildren() {
        super.layoutChildren();
        if (text == null) {
            text = findTextNode(this);
            bindTooltip();
        }
    }

    private void bindTooltip() {
        tooltipProperty().bind(Bindings.createObjectBinding(() -> {
            if (getItem()==null) return null ;
            if (getText().equals(text.getText())) return null ;
            return tooltip ;
        }, text.textProperty(), itemProperty(), textProperty()));
    }

    // recursively search through child node graph to find the Text node
    private Text findTextNode(Node root) {
        // Ignore the graphic and all its child nodes:
        if (root == getGraphic()) {
            return null ;
        }
        if (root instanceof Text) {
            return (Text) root ;
        }
        if (root instanceof Parent) {
            for (Node node : ((Parent)root).getChildrenUnmodifiable()) {
                Text text = findTextNode(node);
                if (text != null) return text ;
            }
        }
        return null ;
    }
});

Here's a complete working example:

import java.util.Random;
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) {

        var table = new TableView<Item>();
        var itemCol = column("Item", Item::nameProperty);
        var valueCol = column("Value", Item::valueProperty);
        table.getColumns().add(itemCol);
        table.getColumns().add(valueCol);

        itemCol.setCellFactory(tc -> new TableCell<>() {
            private Text text ;
            private Tooltip tooltip = new Tooltip() ;

            {
                tooltip.textProperty().bind(textProperty());
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText("");
                } else {
                    setText(item);
                }
            }

            @Override
            protected void layoutChildren() {
                super.layoutChildren();
                if (text == null) {
                    text = findTextNode(this);
                    bindTooltip();
                }
            }

            private void bindTooltip() {
                tooltipProperty().bind(Bindings.createObjectBinding(() -> {
                    if (getItem()==null) return null ;
                    if (getText().equals(text.getText())) return null ;
                    return tooltip ;
                }, text.textProperty(), itemProperty(), textProperty()));
            }

            // recursively search through child node graph to find the Text node
            private Text findTextNode(Node root) {
                // Ignore the graphic and all its child nodes:
                if (root == getGraphic()) {
                    return null ;
                }
                if (root instanceof Text) {
                    return (Text) root ;
                }
                if (root instanceof Parent) {
                    for (Node node : ((Parent)root).getChildrenUnmodifiable()) {
                        Text text = findTextNode(node);
                        if (text != null) return text ;
                    }
                }
                return null ;
            }
        });

        var rng = new Random();
        for (int i = 1 ; i <= 40 ; i++) {
            table.getItems().add(new Item("Item "+i, rng.nextInt(100)));
        }

        var scene = new Scene(new BorderPane(table));
        stage.setScene(scene);
        stage.show();
    }

    public static <S,T>  TableColumn<S,T> column(String title, Function<S, Property<T>> prop) {
        TableColumn<S,T> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> prop.apply(cellData.getValue()));
        return col ;
    }

    public static class Item {
        private final StringProperty name = new SimpleStringProperty();
        private final IntegerProperty value = new SimpleIntegerProperty();
        public Item(String name, int value) {
            this.name.set(name);
            this.value.set(value);
        }

        public final StringProperty nameProperty() {
            return name ;
        }

        public final IntegerProperty valueProperty() {
            return value ;
        }
    }

    public static void main(String[] args) {
        launch();
    }

}


问:
Angular Material Table highlight row on mouse scroll
I am trying to highlight table row when user scroll mouse. By default I am showing first row highlighted.
I am using Hostlistener with mousewheel event to do this. Table rows are highlighing on scroll but it is moving very fast. I want to make it smooth.
Here is my code:

app.component.html

<mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container matColumnDef="position">
    <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="weight">
    <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="symbol">
    <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;  let i= index"
  [ngClass]="{'highlightTableColor': selectedRowIndex == i}"></mat-row>
</mat-table>
```

<p>app.component.ts</p>

<pre class="lang-js prettyprint-override"><code>import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
  selectedRowIndex: number = 0;

  @HostListener('mousewheel', ['$event'])
  handleScroll(event) {
    console.log('adadsdasda', event);
    this.selectedRowIndex++;
  }
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium Beryllium BerylliumBeryllium Beryllium Beryllium Beryllium Beryllium Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
  {position: 11, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 12, name: 'Helium Helium Helium Helium Helium Helium', weight: 4.0026, symbol: 'He'},
  {position: 13, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 14, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 15, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 16, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 17, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 18, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 19, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 20, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
  {position: 21, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 22, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 23, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 24, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 25, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 26, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 27, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 28, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 29, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 30, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];
</code>```

app.component.scss

mat-table {
  width: 100%;
  height: 300px;
  max-height: 300px;
  overflow: scroll
}

mat-row.highlightTableColor {
  background-color: #e2e2e2 !important;
}
```

you can check code here.
Height of each row can be different depends on data.

One Important thing - I can not do it using css only because on some event I need that currently selected row also, I have to send it to B/E.
Any help is appreciated.
Thanks

答:
Take a look at this to change the background color of row on hover,so whenever the user uses a mouse scroll, the row on which the mouse rests will be highlighted :</p>

```<code>.mat-row:hover {
  background-color: #e2e2e2; //required color
}
</code>```

Body:
I am trying to highlight table row when user scroll mouse. By default I am showing first row highlighted.
I am using Hostlistener with mousewheel event to do this. Table rows are highlighing on scroll but it is moving very fast. I want to make it smooth.
Here is my code:

app.component.html

<mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container matColumnDef="position">
    <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="weight">
    <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="symbol">
    <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;  let i= index"
  [ngClass]="{'highlightTableColor': selectedRowIndex == i}"></mat-row>
</mat-table>

app.component.ts

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
  selectedRowIndex: number = 0;

  @HostListener('mousewheel', ['$event'])
  handleScroll(event) {
    console.log('adadsdasda', event);
    this.selectedRowIndex++;
  }
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium Beryllium BerylliumBeryllium Beryllium Beryllium Beryllium Beryllium Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
  {position: 11, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 12, name: 'Helium Helium Helium Helium Helium Helium', weight: 4.0026, symbol: 'He'},
  {position: 13, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 14, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 15, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 16, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 17, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 18, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 19, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 20, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
  {position: 21, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 22, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 23, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 24, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 25, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 26, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 27, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 28, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 29, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 30, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

app.component.scss

mat-table {
  width: 100%;
  height: 300px;
  max-height: 300px;
  overflow: scroll
}

mat-row.highlightTableColor {
  background-color: #e2e2e2 !important;
}

you can check code here.
Height of each row can be different depends on data.

One Important thing - I can not do it using css only because on some event I need that currently selected row also, I have to send it to B/E.
Any help is appreciated.
Thanks

Body:
Take a look at this to change the background color of row on hover,so whenever the user uses a mouse scroll, the row on which the mouse rests will be highlighted :

.mat-row:hover {
  background-color: #e2e2e2; //required color
}


问:
how to send data from angular to node.js
i need to pass some data from angular to node.js server. this is my angular postlist component:
    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from "@angular/common/http";

```<code>@Component({
  selector: 'app-postlist',
  templateUrl: './postlist.component.html',
  styleUrls: ['./postlist.component.css']
})
export class PostlistComponent implements OnInit {

  constructor(private http: HttpClient) { }
  public data="test";
  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data);
  }

}
</code>```

my node.js server:

```<code>const express=require('express');
var app = express();
app.post('/api/book', function(req, res, next){
    var data = req.body.params;
    console.log(data);
 });
 app.listen(3000);
</code>```

i'm trying to console.log the data but nothing happens.

答:
If you are planning on printing the payload this.data, take req.body instead of req.body.params.
And also check if you have any cors errors in console, that can also be blocking your data from reaching your web server.

Body:
i need to pass some data from angular to node.js server. this is my angular postlist component:
    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from "@angular/common/http";

@Component({
  selector: 'app-postlist',
  templateUrl: './postlist.component.html',
  styleUrls: ['./postlist.component.css']
})
export class PostlistComponent implements OnInit {

  constructor(private http: HttpClient) { }
  public data="test";
  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data);
  }

}

my node.js server:

const express=require('express');
var app = express();
app.post('/api/book', function(req, res, next){
    var data = req.body.params;
    console.log(data);
 });
 app.listen(3000);

i'm trying to console.log the data but nothing happens.


问:
PHP EOF showing only one result

Possible Duplicate:

  PHP EOF shows only one result from loop

Hello

Seems like I can not find the solution for such problem.

I am using the following code.

it should display all the results given by the mySQL loop in the EOF.

But it is showing only the first results, nothing else.

What I am doing wrong?

Please help me

```<code>function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu .= "<div id=\"menu\" style=\"display:none;\"><li><a href=\"".$site['url'].$rowYiBmenu['linkHref']."\" onMouseOut=\"javascript: $('#menu').hide('9000');\"><img class=\"imgmenu\" src=\"".$site['url'].$rowYiBmenu['linkIcon']."\">".$rowYiBmenu['linkTitle']."</a></li></div>";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF
<div style="width:520px; background-color: #EEE; height:30px;">
{$menu}
</div>
EOF;
return $bannerCode;
}
</code>```

答:
I have tried helping in the other duplicate question.

i feel you need to implement (learn?) some basic debugging on the data coming from the database. This should be very simple to solve.

I suggest changing your while() code to something like this to help debug whats happening:

```<code>while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
    print "linkTitle: " . $rowYiBmenu['linkTitle'] ."<BR>";
    print "linkHref: " . $rowYiBmenu['linkHref'] ."<BR><BR>";
}
exit;
</code>```

You should see output of all results from the database (not just the first or last). After establishing that the correct data is being retrieved and looped through. you can get that $menu variable concatenation and $bannerCode + HereDoc EOF code sorted out.

Title: PHP EOF showing only one result

Body:
Possible Duplicate:

  PHP EOF shows only one result from loop

Hello

Seems like I can not find the solution for such problem.

I am using the following code.

it should display all the results given by the mySQL loop in the EOF.

But it is showing only the first results, nothing else.

What I am doing wrong?

Please help me

function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu .= "

".$rowYiBmenu['linkTitle']."

";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF

{$menu}

EOF;
return $bannerCode;
}

Body:
I have tried helping in the other duplicate question.

i feel you need to implement (learn?) some basic debugging on the data coming from the database. This should be very simple to solve.

I suggest changing your while() code to something like this to help debug whats happening:

while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
    print "linkTitle: " . $rowYiBmenu['linkTitle'] ."<BR>";
    print "linkHref: " . $rowYiBmenu['linkHref'] ."<BR><BR>";
}
exit;

You should see output of all results from the database (not just the first or last). After establishing that the correct data is being retrieved and looped through. you can get that $menu variable concatenation and $bannerCode + HereDoc EOF code sorted out.


问:
Gradient Button Crashed when Removing Gradient
So I'm new at learning Swift and I'm having trouble with removing the button gradient background, technically I am able to "remove" it but it's not stable and crashes if tapped multiple times. My guess it has something to do with the sublayer not being removed "safely" but I looked around and just can't figure it out.

```<code>@IBAction func button(_ sender: UIButton) {
    sender.setTitleColor(.systemBackground, for: .selected)
    sender.isSelected = !sender.isSelected
    if sender.isSelected {
        sender.layer.borderWidth = 0
        sender.applyGradient(colors: [ #colorLiteral(red: 0.5098039216, green: 0.8431372549, blue: 0.5254901961, alpha: 1) , #colorLiteral(red: 0.3058823529, green: 0.6941176471, blue: 0.3215686275, alpha: 1) ], radius: 10)
    } else {
        sender.layer.borderWidth = 1
        sender.layer.sublayers!.remove(at: 1)   // this not stable, cause crash if trigger repeatedly
    }
}
</code>```

```<code>extension UIButton {
    func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = CGPoint(x: 0.5, y: 0.0), endGradient: CGPoint = CGPoint(x: 0.5, y: 1.0)) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.cornerRadius = radius
        gradientLayer.colors = colors
        gradientLayer.startPoint = startGradient
        gradientLayer.endPoint = endGradient
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}
</code>```

答:
It's crashing because you are trying to remove something that's not present forcefuly, check if it's present and then try to remove it. Here's how:

@IBAction func button(_ sender: UIButton) {
    sender.setTitleColor(.systemBackground, for: .selected)

    sender.isSelected = !sender.isSelected
    if sender.isSelected {
        sender.layer.borderWidth = 0
        sender.applyGradient(colors: [ #colorLiteral(red: 0.5098039216, green: 0.8431372549, blue: 0.5254901961, alpha: 1) , #colorLiteral(red: 0.3058823529, green: 0.6941176471, blue: 0.3215686275, alpha: 1) ], radius: 10)
    } else {
        sender.layer.borderWidth = 1
        if sender.layer.sublayers?.count > 1 {
            sender.layer.sublayers?.remove(at: 1)
        }
    }
}
```

Body:
So I'm new at learning Swift and I'm having trouble with removing the button gradient background, technically I am able to "remove" it but it's not stable and crashes if tapped multiple times. My guess it has something to do with the sublayer not being removed "safely" but I looked around and just can't figure it out.

@IBAction func button(_ sender: UIButton) {
    sender.setTitleColor(.systemBackground, for: .selected)
    sender.isSelected = !sender.isSelected
    if sender.isSelected {
        sender.layer.borderWidth = 0
        sender.applyGradient(colors: [ #colorLiteral(red: 0.5098039216, green: 0.8431372549, blue: 0.5254901961, alpha: 1) , #colorLiteral(red: 0.3058823529, green: 0.6941176471, blue: 0.3215686275, alpha: 1) ], radius: 10)
    } else {
        sender.layer.borderWidth = 1
        sender.layer.sublayers!.remove(at: 1)   // this not stable, cause crash if trigger repeatedly
    }
}

extension UIButton {
    func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = CGPoint(x: 0.5, y: 0.0), endGradient: CGPoint = CGPoint(x: 0.5, y: 1.0)) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.cornerRadius = radius
        gradientLayer.colors = colors
        gradientLayer.startPoint = startGradient
        gradientLayer.endPoint = endGradient
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}


问:
Dynamically cast to a proper subclass from parent class in a method
I have a Java interface PlatformConfigurable. I also have two classes PlatformProducerConfig and PlatformConsumerConfig.

Later on, I need to add a common config to both that sets a property to an empty string:

```<code>    private PlatformConfigurable disableHostNameVerificationConfig(PlatformConfigurable platformConfig) {
        if (platformConfig instanceof PlatformProducerConfig) {
            PlatformProducerConfig oldConfig = (PlatformProducerConfig) platformConfig;
            Map<String, String> additionalConfig = oldConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        else if (platformConfig instanceof PlatformConsumerConfig) {
            PlatformConsumerConfig oldConfig = (PlatformConsumerConfig) platformConfig;
            Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        return platformConfig;
    }
</code>```

I am casting to producer or consumer config because the PlatformConfigurable interface doesn't have .toBuilder() or .build() methods declared in it, and I don't have access to modify the interface, as I can only implement it.

I would want to get rid of the duplicate code:

```<code>Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
</code>```

I was thinking of using lambdas, but I am not 100% sure how to do it.

答:
Taking Alex Rudenko's answer a bit further, using generics:

```<code>private <P extends PlatformConfigurable> P disableHostNameVerificationConfig(P platformConfig, BiFunction<P, Map<String, String>, P> appender) {
    Map<String, String> additionalConfig = platformConfig.additionalProperties();
    Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
    newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");

    return appender.apply(platformConfig, newConfig);
}
</code>```

This assumes that it is safe to do this for any subtype of PlatformConfigurable (and PlatformConfigurable itself).

Then invoke like:

```<code>disableHostNameVerificationConfig(
    platformProducerConfig,
    (p, config) -> p.toBuilder().setAdditionalConfig(config).build());

disableHostNameVerificationConfig(
    platformConsumerConfig,
    (p, config) -> p.toBuilder().setAdditionalConfig(config).build());
</code>```

If you like, create helper methods to hide the BiFunctions:

```<code>private PlatformProducerConfig disableHostNameVerificationConfig(PlatformProducerConfig config) {
  return disableHostNameVerificationConfig(
      platformConfigurable,
      (p, config) -> p.toBuilder().setAdditionalConfig(config).build());
}

private PlatformConsumerConfig disableHostNameVerificationConfig(PlatformConsumerConfig config) {
  return disableHostNameVerificationConfig(
      platformConfigurable,
      (p, config) -> p.toBuilder().setAdditionalConfig(config).build());
}
</code>```

Actually, I think a better way to do it would be without generics or lambdas: write a method which creates an updated map:

```<code>private static Map<String, String> newConfig(PlatformConfigurable platformConfig) {
  Map<String, String> additionalConfig = platformConfig.additionalProperties();
  Map<String, String> newConfig = additionalConfig != null ? new HashMap<>(additionalConfig) : new HashMap<>();

  newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
  return newConfig;
}
</code>```

and then just have two overloads:

```<code>private PlatformProducerConfig disableHostNameVerificationConfig(PlatformProducerConfig config) {
  return config.toBuilder().setAdditionalConfig(newConfig(config)).build();
}

private PlatformConsumerConfig disableHostNameVerificationConfig(PlatformConsumerConfig config) {
  return config.toBuilder().setAdditionalConfig(newConfig(config)).build();
}
</code>```

Body:
I have a Java interface PlatformConfigurable. I also have two classes PlatformProducerConfig and PlatformConsumerConfig.

Later on, I need to add a common config to both that sets a property to an empty string:

    private PlatformConfigurable disableHostNameVerificationConfig(PlatformConfigurable platformConfig) {
        if (platformConfig instanceof PlatformProducerConfig) {
            PlatformProducerConfig oldConfig = (PlatformProducerConfig) platformConfig;
            Map<String, String> additionalConfig = oldConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        else if (platformConfig instanceof PlatformConsumerConfig) {
            PlatformConsumerConfig oldConfig = (PlatformConsumerConfig) platformConfig;
            Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();
        }
        return platformConfig;
    }

I am casting to producer or consumer config because the PlatformConfigurable interface doesn't have .toBuilder() or .build() methods declared in it, and I don't have access to modify the interface, as I can only implement it.

I would want to get rid of the duplicate code:

Map<String, String> additionalConfig = platformConfig.additionalProperties();
            Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
            newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
            return oldConfig.toBuilder().additionalProperties(newConfig).build();

I was thinking of using lambdas, but I am not 100% sure how to do it.

Body:
Taking Alex Rudenko's answer a bit further, using generics:

private <P extends PlatformConfigurable> P disableHostNameVerificationConfig(P platformConfig, BiFunction<P, Map<String, String>, P> appender) {
    Map<String, String> additionalConfig = platformConfig.additionalProperties();
    Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
    newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");

    return appender.apply(platformConfig, newConfig);
}

This assumes that it is safe to do this for any subtype of PlatformConfigurable (and PlatformConfigurable itself).

Then invoke like:

disableHostNameVerificationConfig(
    platformProducerConfig,
    (p, config) -> p.toBuilder().setAdditionalConfig(config).build());

disableHostNameVerificationConfig(
    platformConsumerConfig,
    (p, config) -> p.toBuilder().setAdditionalConfig(config).build());

If you like, create helper methods to hide the BiFunctions:

private PlatformProducerConfig disableHostNameVerificationConfig(PlatformProducerConfig config) {
  return disableHostNameVerificationConfig(
      platformConfigurable,
      (p, config) -> p.toBuilder().setAdditionalConfig(config).build());
}

private PlatformConsumerConfig disableHostNameVerificationConfig(PlatformConsumerConfig config) {
  return disableHostNameVerificationConfig(
      platformConfigurable,
      (p, config) -> p.toBuilder().setAdditionalConfig(config).build());
}

Actually, I think a better way to do it would be without generics or lambdas: write a method which creates an updated map:

private static Map<String, String> newConfig(PlatformConfigurable platformConfig) {
  Map<String, String> additionalConfig = platformConfig.additionalProperties();
  Map<String, String> newConfig = additionalConfig != null ? new HashMap<>(additionalConfig) : new HashMap<>();

  newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
  return newConfig;
}

and then just have two overloads:

private PlatformProducerConfig disableHostNameVerificationConfig(PlatformProducerConfig config) {
  return config.toBuilder().setAdditionalConfig(newConfig(config)).build();
}

private PlatformConsumerConfig disableHostNameVerificationConfig(PlatformConsumerConfig config) {
  return config.toBuilder().setAdditionalConfig(newConfig(config)).build();
}


问:
How to retrieve Business Component rows in SIebel Open UI PM?
How can I get field values of BC from Presentation Model in Siebel Open UI?

I was trying:

```<code>SiebelApp.S_App.Model.GetBusObj("").GetBusComp("")
</code>```

but Model is not recognized. I also tried creating model with GetModel() function, but it didn't succeed.

答:
You can not access records of other business component using OpenUI.

OpenUI is for current View and available business components.

if you want to retrieve current row then you can use getrecordset or showselection.

Body:
How can I get field values of BC from Presentation Model in Siebel Open UI?

I was trying:

SiebelApp.S_App.Model.GetBusObj("").GetBusComp("")

but Model is not recognized. I also tried creating model with GetModel() function, but it didn't succeed.


问:
Install Qt for android development on Ubuntu
I want to develop android application with Qt on Ubuntu
now I want to know should I download Android version Qt for Linux from the qt.io site or I can install Qt development package from the Ubuntu repository and use it for develop android app too ?

I know I need some dependencies for develop for android and I have to download them (android sdk, ndk...)
The question is how to install the Qt Android kit on Ubuntu from the Ubuntu repository not to download the binary version from the Qt website?

答:
The question is how to install the Qt Android kit on Ubuntu from the Ubuntu repository [and] not to download the binary version from the Qt website?

The normal Ubuntu repositories provide only the "GCC 64 bit" version of Qt, which is not the one you need for developing for Android. To get the Android version, downloading from the Qt website (option 1 below) or via aqtinstall (option 2 below) are by far the simplest solutions and I'd recommend that. But anyway, here's the complete list of all the options you have in principle:

Option 1: Install Qt for Android from the Qt website

Download the Qt Online Installer from the Qt website and use that to install a version of Qt for Android.

This necessarily also installs Qt Creator. If you want to stick with the Qt Creator from the Ubuntu repositories, you can delete this one easily again: sudo rm -R /opt/Qt/Tools/QtCreator/.

The Qt Online Installer is basically the same as the Qt Maintenance Tool that you'll have now in /opt/Qt/MaintenanceTool. Use that Qt Maintenance Tool from now on to modify and extend your Qt installations. (It's not contained in the Ubuntu repository, otherwise we'd not need this whole process.)

Option 2: Install Qt for Android with aqtinstall

The tool aqtinstall ("Another Qt Installer") is an unofficial Qt installer that can be used to install any Qt version on any target platform, such as Qt for Android on a x86_64 desktop PC running Ubuntu Linux.

This option is probably my favourite. While it does not install from the Ubuntu repositories, it is a command line tool like apt, avoiding the use of the GUI-only "Qt Maintenance Tool".

Option 3: Compile Qt for Android from source

(I did not try this yet, but it's a possibility.) Qt for Android is basically just the normal Qt libraries compiled for the ARMv7 or ARMv8 processor architecture. You can cross-compile that from the Qt sources on a desktop computer following these instructions.

Option 4: Install Qt for Android from the armhf / arm64 packages

(I did not try this, so it's totally experimental and probably won't work.) All Ubuntu packages incl. Qt packages come in versions for different processor architectures (example). This includes the armhf (= ARMv7+) and arm64 (= ARMv8) processor architectures found in smartphones . So by installing from these, you might be able to install "Qt for Android" from the Ubuntu repositories:

```<code>sudo apt install qt5-default:armhf
</code>```

Body:
The question is how to install the Qt Android kit on Ubuntu from the Ubuntu repository [and] not to download the binary version from the Qt website?

The normal Ubuntu repositories provide only the "GCC 64 bit" version of Qt, which is not the one you need for developing for Android. To get the Android version, downloading from the Qt website (option 1 below) or via aqtinstall (option 2 below) are by far the simplest solutions and I'd recommend that. But anyway, here's the complete list of all the options you have in principle:

Option 1: Install Qt for Android from the Qt website

Download the Qt Online Installer from the Qt website and use that to install a version of Qt for Android.

This necessarily also installs Qt Creator. If you want to stick with the Qt Creator from the Ubuntu repositories, you can delete this one easily again: sudo rm -R /opt/Qt/Tools/QtCreator/.

The Qt Online Installer is basically the same as the Qt Maintenance Tool that you'll have now in /opt/Qt/MaintenanceTool. Use that Qt Maintenance Tool from now on to modify and extend your Qt installations. (It's not contained in the Ubuntu repository, otherwise we'd not need this whole process.)

Option 2: Install Qt for Android with aqtinstall

The tool aqtinstall ("Another Qt Installer") is an unofficial Qt installer that can be used to install any Qt version on any target platform, such as Qt for Android on a x86_64 desktop PC running Ubuntu Linux.

This option is probably my favourite. While it does not install from the Ubuntu repositories, it is a command line tool like apt, avoiding the use of the GUI-only "Qt Maintenance Tool".

Option 3: Compile Qt for Android from source

(I did not try this yet, but it's a possibility.) Qt for Android is basically just the normal Qt libraries compiled for the ARMv7 or ARMv8 processor architecture. You can cross-compile that from the Qt sources on a desktop computer following these instructions.

Option 4: Install Qt for Android from the armhf / arm64 packages

(I did not try this, so it's totally experimental and probably won't work.) All Ubuntu packages incl. Qt packages come in versions for different processor architectures (example). This includes the armhf (= ARMv7+) and arm64 (= ARMv8) processor architectures found in smartphones . So by installing from these, you might be able to install "Qt for Android" from the Ubuntu repositories:

sudo apt install qt5-default:armhf


问:
GD Library doesn't work in PHP 7.4.6 on Windows
When i try using the GD Library in PHP 7.4.6 on my Windows PC, it shows me this error:

```<code>Fatal error: Uncaught Error: Call to undefined function imagecreate() in C:\Users\user\Desktop\Site\index.php:11 Stack trace: #0 {main} thrown in C:\Users\user\Desktop\Site\index.php on line 11
</code>```

The line 11 is:

```<code> $image = imagecreate(200,20);
</code>```

The full PHP code is:

```<code><?php

    $image = imagecreate(200,20);
    $background = imagecolorallocate($image,0,0,0);
    $foreground = imagecolorallocate($image, 255,255,255);

    $imagestring($image,5,5,1,"Test",$foreground);

    $header("Content-type: image/jpeg");
    $imagejpeg($image);

?>
</code>```

I tried fixing this by following this guide, and i uncommented the GD line, but it still gives me this error.

Thanks in advance.

答: Do a php -m to see PHP modules. If you can't find gd there then you need to install and enable that extension. There a lot of tutorials in internet to doing so

Body:
When i try using the GD Library in PHP 7.4.6 on my Windows PC, it shows me this error:

Fatal error: Uncaught Error: Call to undefined function imagecreate() in C:\Users\user\Desktop\Site\index.php:11 Stack trace: #0 {main} thrown in C:\Users\user\Desktop\Site\index.php on line 11

The line 11 is:

 $image = imagecreate(200,20);

The full PHP code is:

<?php

    $image = imagecreate(200,20);
    $background = imagecolorallocate($image,0,0,0);
    $foreground = imagecolorallocate($image, 255,255,255);

    $imagestring($image,5,5,1,"Test",$foreground);

    $header("Content-type: image/jpeg");
    $imagejpeg($image);

?>

I tried fixing this by following this guide, and i uncommented the GD line, but it still gives me this error.

Thanks in advance.


问:
Can a java class object be a state variable in another class?
Let's say I have a Car class in Java and then I make another class called ElectricCar. Can a Car object be a state variable in my ElectricCar class?</p>

答:
Simply put: yes. Try it:</p>

```<code>class Car {
}

class ElectricCar {
    Car myCar = new Car();
}
</code>```

Body:
Simply put: yes. Try it:

class Car {
}

class ElectricCar {
    Car myCar = new Car();
}


问:
Kubernetes in-cluster authentication
it seems that my AKS cluster is unable to perform basic requests to the k8s api, i.e. using the in-cluster token for the pods. Everything works fine when I use the same code from my local machine, i.e. with config.load_kube_config .

I am using the python k8s client 11.0.0, and I am loading the configuration through config.load_incluster_config(). I get the following error:

HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}

when trying to simply list my pods (using client.list_namespaced_pod). I also tried to perform a raw get request, but same result.

I tried to extend the cluster role to specifically access the resources, here my clusterrole and clusterrolebinding:

```<code>apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: clusterrolename
rules:
- apiGroups:
  - ""
  resources:
  - pods
  - namespaces
  verbs:
  - get
  - list
- apiGroups:
  - metrics.k8s.io
  resources:
  - '*'
  verbs:
  - get
  - list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: clusterrolebindingname
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: clusterrolename
subjects:
- kind: ServiceAccount
  name: default
  namespace: mynamespace
</code>```

but I have always the same result.

The same approach does not work equally on linux and windows nodes.

The use of the very same approach was successful before on linux machine (pure linux cluster).

Could it be related to the SDK version?
Could it be something different in the cluster?
Does anyone know how I could retrieve a list of the authorisation for any specific ServiceAccount?

答:
You can check specific permission of a service account in a specific namespace using below command

```<code>kubectl auth can-i get pods --as=system:serviceaccount:mynamespace:default -n mynamespace
</code>```

If the above command returns no that means the service account does not have right RBAC.

To list all permission of a service account use

```<code>kubectl auth can-i --list --as=system:serviceaccount:mynamespace:default
</code>```

To know more use kubectl auth can-i -h

Title: Kubernetes in-cluster authentication

Body:
it seems that my AKS cluster is unable to perform basic requests to the k8s api, i.e. using the in-cluster token for the pods. Everything works fine when I use the same code from my local machine, i.e. with config.load_kube_config .

I am using the python k8s client 11.0.0, and I am loading the configuration through config.load_incluster_config(). I get the following error:

HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}

when trying to simply list my pods (using client.list_namespaced_pod). I also tried to perform a raw get request, but same result.

I tried to extend the cluster role to specifically access the resources, here my clusterrole and clusterrolebinding:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: clusterrolename
rules:
- apiGroups:
  - ""
  resources:
  - pods
  - namespaces
  verbs:
  - get
  - list
- apiGroups:
  - metrics.k8s.io
  resources:
  - '*'
  verbs:
  - get
  - list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: clusterrolebindingname
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: clusterrolename
subjects:
- kind: ServiceAccount
  name: default
  namespace: mynamespace

but I have always the same result.

The same approach does not work equally on linux and windows nodes.

The use of the very same approach was successful before on linux machine (pure linux cluster).

Could it be related to the SDK version?
Could it be something different in the cluster?
Does anyone know how I could retrieve a list of the authorisation for any specific ServiceAccount?

Body:
You can check specific permission of a service account in a specific namespace using below command

kubectl auth can-i get pods --as=system:serviceaccount:mynamespace:default -n mynamespace

If the above command returns no that means the service account does not have right RBAC.

To list all permission of a service account use

kubectl auth can-i --list --as=system:serviceaccount:mynamespace:default

To know more use kubectl auth can-i -h


问:
Advantages of using Fat Jars over Containers
I wanna know the difference between the two and also which one is currently used more according to industry standards. I tried finding resources online but the content about Fat Jars is very less and also almost no contrast is shown between the two anywhere.</p>

答:
It seems not a big deal at a first glance. The reason for that is that the Java packaging system is really mature and grew strong over many years. Many other ecosystems do not benefit from this and can benefit greatly from being packaged into a container image. But containers are not only about packaging. Packaging could almost be considered a side-effect of it.

Amongst others, some benefits of using containers over simple Fat JARS are:

Simplified infrastructure

For a big (or mid-sized) enterprise built around microservices, chances are that not all of them are using the same languages and tools. A container provides a predictable way of deploying all those different things in the same manner, so it greatly simplifies the infrastructure, thus dramatically reducing company costs with it. This becomes even more important when deploying into the cloud, especially in multi-cloud-provider scenarios, and in that case, container orchestration provided by software like Kubernetes help a great deal without much effort.

Consistency

Another benefit of containers over regular JARs is consistency across environments. Imagine for instance that you deploy your JAR into DEV (running Java 8) and then into PROD (running Java 10). For some reason the JVM behaves differently, either because of default Garbage Collector or something else, making your program behave differently in both environments. When you deploy through a container image, the same image will be used across different environments, and thus the same Java version will be always used, making it less error-prone.

Resource isolation

Yet another benefit is resource isolation. Containers can make sure that your application "see" only a predetermined amount of memory and CPUs. Actually, there were some improvements in Java 10 regarding this matter, you can read more about it here.

Hope this provides with a better point of view regarding this matter.


问:
trying to do a replace method in linked list but program replaces only the first element
My current code only replaces the first element of the linked list. I am trying to create a replace method with two parameters but failing. My current logic shows that I am trying to replace the element with my new input but I am assuming I am failing to traverse through the list as only the first one gets replaced.</p>

```<code>public class ListOfNVersion03PartA
{
    private int thisNumber;              // the number stored in this node
    private ListOfNVersion03PartA next;  // forms a linked list of objects
    private int []list;
    private final int nodeID;            // a unique ID for each object in the list

    private static int nodeCount = 0;    // the number of list objects that have been created

    /**
     * @param  num   the value to be stored in this object
     */
    public ListOfNVersion03PartA(int num)
    {
        thisNumber = num;
        next = null;

        ++nodeCount;
        nodeID = nodeCount;

    }

 public ListOfNVersion03PartA(int [] num)
{

    this(num[0]);  // in this context, "this" invokes the other constructor
    list = new int[num.length];
    for (int i=1 ; i<num.length ; ++i)
        {
        insertLast(num[i]);
        }
}

 public int replaceAll(int replaceThis, int withThis)
        {
            int count = 0;
            int x = 0;

        for ( int i=0 ; i < nodeCount; ++i)
        {
            if ( thisNumber == replaceThis )
        {
            thisNumber = x;
            x = withThis;
            ++count;

        }
        }

        return count;
    }
</code>```

答:
Once you've evaluated the current node (aka this), then you should perform the evaluation of the next node until there are no more nodes to evaluate. Here's an example using your current code:

```<code>public int replaceAll(int replaceThis, int withThis) {
    int result = 0;
    if (thisNumer == replaceThis) {
        thisNumber = withThis;
        result = 1;
    }
    if (next != null) {
        result += next.replaceAll(replaceThis, withThis);
    }
    return result;
}
</code>```

Body:
My current code only replaces the first element of the linked list. I am trying to create a replace method with two parameters but failing. My current logic shows that I am trying to replace the element with my new input but I am assuming I am failing to traverse through the list as only the first one gets replaced.

public class ListOfNVersion03PartA
{
    private int thisNumber;              // the number stored in this node
    private ListOfNVersion03PartA next;  // forms a linked list of objects
    private int []list;
    private final int nodeID;            // a unique ID for each object in the list

    private static int nodeCount = 0;    // the number of list objects that have been created

    /**
     * @param  num   the value to be stored in this object
     */
    public ListOfNVersion03PartA(int num)
    {
        thisNumber = num;
        next = null;

        ++nodeCount;
        nodeID = nodeCount;

    }

 public ListOfNVersion03PartA(int [] num)
{

    this(num[0]);  // in this context, "this" invokes the other constructor
    list = new int[num.length];
    for (int i=1 ; i<num.length ; ++i)
        {
        insertLast(num[i]);
        }
}

 public int replaceAll(int replaceThis, int withThis)
        {
            int count = 0;
            int x = 0;

        for ( int i=0 ; i < nodeCount; ++i)
        {
            if ( thisNumber == replaceThis )
        {
            thisNumber = x;
            x = withThis;
            ++count;

        }
        }

        return count;
    }

Body:
Once you've evaluated the current node (aka this), then you should perform the evaluation of the next node until there are no more nodes to evaluate. Here's an example using your current code:

public int replaceAll(int replaceThis, int withThis) {
    int result = 0;
    if (thisNumer == replaceThis) {
        thisNumber = withThis;
        result = 1;
    }
    if (next != null) {
        result += next.replaceAll(replaceThis, withThis);
    }
    return result;
}


问:
Media queries - not responding on devices
```<code>@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
            display: block !important;
            overflow: hidden !important;
}
</code>```

another version

```<code>@media screen and (max-width: 750px) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
            display: block !important;
            overflow: hidden !important;
        }
</code>```

Hi all,

Above is my media queries for my code. This code is for a news letter and for some reason the media queries will have no effect went sent to a mobile device. Is there something that I am missing in the media queries? The phone I am using to test is an iPhone XR.

Thank you so much in advance!

Dom

答:
Please put this code and check.

@media only screen and (max-width: 751px) {
   div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
        display: block !important;
        overflow: hidden !important;
    }
}```
</div>
</div>
</p>

<p>And also check your header in html.
Is meta tag is there or not.
If not then please put it in your head.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0"></code>```

Body:
@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
            display: block !important;
            overflow: hidden !important;
}

another version

@media screen and (max-width: 750px) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
            display: block !important;
            overflow: hidden !important;
        }

Hi all,

Above is my media queries for my code. This code is for a news letter and for some reason the media queries will have no effect went sent to a mobile device. Is there something that I am missing in the media queries? The phone I am using to test is an iPhone XR.

Thank you so much in advance!

Dom

Body:
Please put this code and check.

@media only screen and (max-width: 751px) {
   div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
        display: block !important;
        overflow: hidden !important;
    }
}

And also check your header in html.
Is meta tag is there or not.
If not then please put it in your head.

<meta name="viewport" content="width=device-width, initial-scale=1.0">


问:
Cloud Functions not being uploaded - Firebase
I'm trying to deploy a Cloud Function for my Firebase project. It says that the deploy was successful but it never uploads nor appears in my Functions dashboard.
This is the log of the firebase deploy --only functions command:

```<code>=== Deploying to 'XXXXXXXXX'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint C:\Users\XXXXXX\CloudFunctions\functions
> eslint .

+  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
+  functions: required API cloudfunctions.googleapis.com is enabled
i  functions: preparing functions directory for uploading...

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/XXXXXX/overview
</code>```

I've tried several times, but it never seems to work. Could somebody please help me fix this? I've been trying for days...

答: The output of the CLI here does not show that you've actually deployed any functions.  Or, in other words, the output shows the you deployed 0 functions.  I would expect to see the names of the individual deployed functions in the output.  If you don't see the names of the functions here, that means you haven't actually exported them from your index.js. And without seeing your code, we can't know that you've done that correctly.  You will need to review your code and make sure you have exported at least one function correctly using the Firebase SDK to define it.</p>

Body:
I'm trying to deploy a Cloud Function for my Firebase project. It says that the deploy was successful but it never uploads nor appears in my Functions dashboard.
This is the log of the firebase deploy --only functions command:

=== Deploying to 'XXXXXXXXX'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint C:\Users\XXXXXX\CloudFunctions\functions
> eslint .

+  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
+  functions: required API cloudfunctions.googleapis.com is enabled
i  functions: preparing functions directory for uploading...

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/XXXXXX/overview

I've tried several times, but it never seems to work. Could somebody please help me fix this? I've been trying for days...


问:
Laravel Excel not downloading
This is what I have currently
Export class

```<code>class ReportExcel implements FromArray, withHeadings
{
use Exportable;

protected $items;

public function __construct(array $items)
{
    $this->items= $items;
}

public function headings(): array
{
    return ["Opcion 1", "Opcion 2", "Opcion 3", "Nombres", "Apellidos", "Telefono", "Correo",
        "Pais", "Pais Otro", "Edad", "Adventista", "Estudia la Biblia", "Peticion", "Fecha"];
}

public function array(): array
{
    return $this->items;
}
</code>```

}

method in my controller

```<code>public function downloadExcel(Request $request)
{
    if ($request->country == null) {
        $item = Form::get(['option_1', 'option_2', 'option_3', 'name', 'lastname', 'phone',
            'email', 'country_id', 'country_other', 'age', 'adventist', 'study', 'petition', 'date_answered']);
    } else {
        $item = Form::where('country_id', $request->country)->orderByDesc('created_at')
            ->get(['option_1', 'option_2', 'option_3', 'name', 'lastname', 'phone', 'email', 'country_id',
                'country_other', 'age', 'adventist', 'study', 'petition', 'date_answered']);
    }

    $items[] = $item;

//   return (new ReportExcel($items))->download('invoices.csv', Excel::CSV,
//            ['Content-Type' => 'text/csv']);
    return Excel::download(new ReportExcel($items), 'reporte.csv');
}
</code>```

I have tried both ways seen in my controller neither downloads anything I do see something like this, if I change the extension to xls or xlsx the data is unreadable as there are a ton on symbols that show up as well

What am I doing wrong? How can I get this to download an actual excel file?

答: The solution is to use a href=""/> to the route instead of using the method as it doesn't work when sending the request through vue. The other code is correct.

Title: Laravel Excel not downloading

Body:
This is what I have currently
Export class

class ReportExcel implements FromArray, withHeadings
{
use Exportable;

protected $items;

public function __construct(array $items)
{
    $this->items= $items;
}

public function headings(): array
{
    return ["Opcion 1", "Opcion 2", "Opcion 3", "Nombres", "Apellidos", "Telefono", "Correo",
        "Pais", "Pais Otro", "Edad", "Adventista", "Estudia la Biblia", "Peticion", "Fecha"];
}

public function array(): array
{
    return $this->items;
}

}

method in my controller

public function downloadExcel(Request $request)
{
    if ($request->country == null) {
        $item = Form::get(['option_1', 'option_2', 'option_3', 'name', 'lastname', 'phone',
            'email', 'country_id', 'country_other', 'age', 'adventist', 'study', 'petition', 'date_answered']);
    } else {
        $item = Form::where('country_id', $request->country)->orderByDesc('created_at')
            ->get(['option_1', 'option_2', 'option_3', 'name', 'lastname', 'phone', 'email', 'country_id',
                'country_other', 'age', 'adventist', 'study', 'petition', 'date_answered']);
    }

    $items[] = $item;

//   return (new ReportExcel($items))->download('invoices.csv', Excel::CSV,
//            ['Content-Type' => 'text/csv']);
    return Excel::download(new ReportExcel($items), 'reporte.csv');
}

I have tried both ways seen in my controller neither downloads anything I do see something like this, if I change the extension to xls or xlsx the data is unreadable as there are a ton on symbols that show up as well

What am I doing wrong? How can I get this to download an actual excel file?

Body: The solution is to use a <a href=""/> to the route instead of using the method as it doesn't work when sending the request through vue. The other code is correct.


问:
Google AMP AutoAds - No ad placements found
I have inserted the AMP adsense code property into my AMP page and I made sure the page is valid using the AMP debug but the AutoAds still don't show up.

I get this error in the console: (My code has the correct publisher ID)

"No ad placements found for publisher ID 'ca-pub-XXXXXXXXXXXX'. Check that the provided publisher ID is correct."

I have waited 48 hours to see if they showed up but no luck. I am using regular AutoAds on my non-AMP pages and it works fine.

Has anyone encountered this issue before?

答:
Two years later, the same issue still persist..and Google is saying nothing...

My site, AMP only ElectronicoCigarrillo.com


问:
SqlFunctions.IsNumeric question
I'vw just use SqlFunctions.IsNumeric.

Here you can see that it returns int?.
Why does SqlFunctions.IsNumeric returns int? and not bool?

答: To be on par with how ISNUMERIC  behaves in MS-SQL - it also returns an INT.

Title: SqlFunctions.IsNumeric question


问:
App Insights Performing a Heartbeat Check to Api Root
I have a .Net Core 3.1 web api.  I added App Insights instrumentation, and now every 15 minutes it is performing a GET to /, which throws a 404.

Is there a way to set this url in the instrumentation configuration in my startup, or is there an option in Azure?

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();
    ...
}
</code>```

I'd rather make it hit an endpoint I specifically stood up for heartbeat checks.

I do know from this document that I could just disable the heartbeat, but I'd rather configure it.

答:
I do not thing it is the Application Insights. Having the same problem, I identified to be the Always On setting in Web application.

Quoting Microsoft

With the Always On feature, you can’t control the endpoint. It always sends a request to the application root.

It gives a call to the root of your website to keep it always on. The problem is that when your app is turned off, it takes some time to spin up when a request is coming. This is the reason Always On is true by default.

You can disable it by going to the Configuration tab in your web app and disable the Always On option

But you have to have in mind that the first request coming in your application after a cold start will take longer to get a response.

Body:
I have a .Net Core 3.1 web api.  I added App Insights instrumentation, and now every 15 minutes it is performing a GET to /, which throws a 404.

Is there a way to set this url in the instrumentation configuration in my startup, or is there an option in Azure?

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();
    ...
}

I'd rather make it hit an endpoint I specifically stood up for heartbeat checks.

I do know from this document that I could just disable the heartbeat, but I'd rather configure it.


问:
Optimizing a while multi-conditional in Python
I have a condition like this:

```<code>while A != "fi" and A != "fa" and A != "foo" and A != "fe":
    # code
</code>```

Is there any way to optimize (simplify) that while?

答:
You could check if A is not in a set:

while A not in {"fi", "fa", "foo", "fe"}:
  # do something
```

Body:
I have a condition like this:

while A != "fi" and A != "fa" and A != "foo" and A != "fe":
    # code

Is there any way to optimize (simplify) that while?


答:
Use the following:</p>

```<code>while A not in ["fi","fa","foo","fe"]:
   #code
</code>```

Title: Optimizing a while multi-conditional in Python

Body:
Use the following:

while A not in ["fi","fa","foo","fe"]:
   #code


问:
How do you write tests for the argparse portion of a python module?
I have a Python module that uses the argparse library. How do I write tests for that section of the code base?</p>

答:
For testing CLI (command line interface), and not command output I did something like this

```<code>import pytest
from argparse import ArgumentParser, _StoreAction

ap = ArgumentParser(prog="cli")
ap.add_argument("cmd", choices=("spam", "ham"))
ap.add_argument("-a", "--arg", type=str, nargs="?", default=None, const=None)
...

def test_parser():
    assert isinstance(ap, ArgumentParser)
    assert isinstance(ap, list)
    args = {_.dest: _ for _ in ap._actions if isinstance(_, _StoreAction)}

    assert args.keys() == {"cmd", "arg"}
    assert args["cmd"] == ("spam", "ham")
    assert args["arg"].type == str
    assert args["arg"].nargs == "?"
    ...
</code>```

Body:
For testing CLI (command line interface), and not command output I did something like this

import pytest
from argparse import ArgumentParser, _StoreAction

ap = ArgumentParser(prog="cli")
ap.add_argument("cmd", choices=("spam", "ham"))
ap.add_argument("-a", "--arg", type=str, nargs="?", default=None, const=None)
...

def test_parser():
    assert isinstance(ap, ArgumentParser)
    assert isinstance(ap, list)
    args = {_.dest: _ for _ in ap._actions if isinstance(_, _StoreAction)}

    assert args.keys() == {"cmd", "arg"}
    assert args["cmd"] == ("spam", "ham")
    assert args["arg"].type == str
    assert args["arg"].nargs == "?"
    ...


问:
Multiple Image Upload PHP form with one input
I've been trying to make this work for quite some time now. But I can't seem to make it work. I wanted to have a multiple image upload form with only using one input.

this is my upload.php

```<code><?php
include("../include/session.php");

session_start();
$allowedExts = array("jpeg", "jpg", "png", "gif");
$extension = end(explode(".", $_FILES["upload"]["name"]));

if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {

        if (($_FILES["upload"]["name"] < 90000000000000000)
            && in_array($extension, $allowedExts)) {
                if ($_FILES["upload"]["error"] > 0)
                {
                    header('location: '.$error); die;
                }
                else
                {

                    if (file_exists("../icons/".$_SESSION["username"] ."/" . $_FILES["upload"]["name"]))
                    {
                    echo "error";
                    }
                    else
                    {
                        if(!is_dir("../icons/". $_SESSION["username"] ."/")) {
                            mkdir("../icons/". $_SESSION["username"] ."/");
                        }

                        $temp = explode(".",$_FILES["upload"]["name"]);
                        $file = rand(1,999999999999) . '.' .end($temp);

                        move_uploaded_file($_FILES["upload"]["tmp_name"], "../icons/". $_SESSION["username"] ."/". $file);
                    }
                }
            }
        } else {
            echo "yep error";
        }
    }
}
?>
</code>```

if i take out the lines

```<code>if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {
</code>```

With the corresponding closing bracket, it seems to work fine. The image is uploaded perfectly. But the thing is, it only allows me to upload one.

Please I really need your expertise. THank you

答:
```<code>$total = count($_FILES['txt_gallery']['name']);
            $filename_arr = [];
            $filename_arr1 = [];
            for( $i=0 ; $i < $total ; $i++ ) {
              $tmpFilePath = $_FILES['txt_gallery']['tmp_name'][$i];
              if ($tmpFilePath != ""){
                $newFilePath = "../uploaded/" .date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                $newFilePath1 = date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                if(move_uploaded_file($tmpFilePath, $newFilePath)) {
                  $filename_arr[] = $newFilePath;
                  $filename_arr1[] = $newFilePath1;

                }
              }
            }
            $file_names = implode(',', $filename_arr1);
            var_dump($file_names); exit;
</code>```

Body:
I've been trying to make this work for quite some time now. But I can't seem to make it work. I wanted to have a multiple image upload form with only using one input.

this is my upload.php

<?php
include("../include/session.php");

session_start();
$allowedExts = array("jpeg", "jpg", "png", "gif");
$extension = end(explode(".", $_FILES["upload"]["name"]));

if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {

        if (($_FILES["upload"]["name"] < 90000000000000000)
            && in_array($extension, $allowedExts)) {
                if ($_FILES["upload"]["error"] > 0)
                {
                    header('location: '.$error); die;
                }
                else
                {

                    if (file_exists("../icons/".$_SESSION["username"] ."/" . $_FILES["upload"]["name"]))
                    {
                    echo "error";
                    }
                    else
                    {
                        if(!is_dir("../icons/". $_SESSION["username"] ."/")) {
                            mkdir("../icons/". $_SESSION["username"] ."/");
                        }

                        $temp = explode(".",$_FILES["upload"]["name"]);
                        $file = rand(1,999999999999) . '.' .end($temp);

                        move_uploaded_file($_FILES["upload"]["tmp_name"], "../icons/". $_SESSION["username"] ."/". $file);
                    }
                }
            }
        } else {
            echo "yep error";
        }
    }
}
?>

if i take out the lines

if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {

With the corresponding closing bracket, it seems to work fine. The image is uploaded perfectly. But the thing is, it only allows me to upload one.

Please I really need your expertise. THank you


答: This is how ISNUMERIC function is defined in SQL. It returns int.</p>

Title: SqlFunctions.IsNumeric question

Body:
I'vw just use SqlFunctions.IsNumeric.

Here you can see that it returns int?.
Why does SqlFunctions.IsNumeric returns int? and not bool?


问:
form data not saving to chrome local storage
I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?

```<code>    function submit() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
}

function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

        document.write("passed value = " + name);
        document.write("passed value = " + email);
        document.write("passed value = " + feedback);

}
</code>```

HTML

```<code><form action="form.html" method="get" onsubmit="submit()">
            <fieldset style="width: 80%; margin: auto;">
                <legend>Feedback:</legend>
                <label for="name">Name:</label><br />
                <input type="text" id="name" name="name"><br><br>
                <label for="email">Email:</label><br />
                <input type="email" id="email" name="email"><br><br>
                <label for="feedback">Feedback:</label><br />
                <textarea id="feedback" name="feedback"></textarea><br>
                <input type="submit" value="Submit" onclick="submit()">
            </fieldset>
        </form>
    </section>
    <script src="form.js" type="text/javascript"></script>
</code>```

答:
I use a function for this so I can call it at any time.

```<code>// add to local storage
const addToLocalStorageObject = function (name, key, value) {
    // Get the existing data
    let existing = localStorage.getItem(name);
    // If no existing data, create an object
    // Otherwise, convert the localStorage string to an object
    existing = existing ? JSON.parse(existing) : {};
    // Add new data to localStorage object
    existing[key] = value;
    // Save back to localStorage via stringify
    localStorage.setItem(name, JSON.stringify(existing));
};

// retrieve from local storage
const retrieveFromLocalStorageObject = function (name) {
    let data = localStorage.getItem(name);
    // read the localStorage item and convert it to an object
    return data ? JSON.parse(data) : null;
};
</code>```

Then call addToLocalStorageObject('name', name);

And retrieveFromLocalStorageObject('name');

NB: I did not write the above functions but I have found them extremely useful.

Body:
I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?

    function submit() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
}

function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

        document.write("passed value = " + name);
        document.write("passed value = " + email);
        document.write("passed value = " + feedback);

}

HTML

<form action="form.html" method="get" onsubmit="submit()">
            <fieldset style="width: 80%; margin: auto;">
                <legend>Feedback:</legend>
                Name:

                <input type="text" id="name" name="name">

                Email:

                <input type="email" id="email" name="email">

                Feedback:

                <textarea id="feedback" name="feedback"></textarea>

                <input type="submit" value="Submit" onclick="submit()">
            </fieldset>
        </form>

Body:
I use a function for this so I can call it at any time.

// add to local storage
const addToLocalStorageObject = function (name, key, value) {
    // Get the existing data
    let existing = localStorage.getItem(name);
    // If no existing data, create an object
    // Otherwise, convert the localStorage string to an object
    existing = existing ? JSON.parse(existing) : {};
    // Add new data to localStorage object
    existing[key] = value;
    // Save back to localStorage via stringify
    localStorage.setItem(name, JSON.stringify(existing));
};

// retrieve from local storage
const retrieveFromLocalStorageObject = function (name) {
    let data = localStorage.getItem(name);
    // read the localStorage item and convert it to an object
    return data ? JSON.parse(data) : null;
};

Then call addToLocalStorageObject('name', name);

And retrieveFromLocalStorageObject('name');

NB: I did not write the above functions but I have found them extremely useful.